iPXE
int13.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License as
00006  * published by the Free Software Foundation; either version 2 of the
00007  * License, or any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful, but
00010  * WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012  * General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
00017  * 02110-1301, USA.
00018  *
00019  * You can also choose to distribute this program under the terms of
00020  * the Unmodified Binary Distribution Licence (as given in the file
00021  * COPYING.UBDL), provided that you have satisfied its requirements.
00022  */
00023 
00024 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
00025 
00026 #include <stdint.h>
00027 #include <stdlib.h>
00028 #include <limits.h>
00029 #include <byteswap.h>
00030 #include <errno.h>
00031 #include <assert.h>
00032 #include <ipxe/blockdev.h>
00033 #include <ipxe/io.h>
00034 #include <ipxe/acpi.h>
00035 #include <ipxe/sanboot.h>
00036 #include <ipxe/device.h>
00037 #include <ipxe/pci.h>
00038 #include <ipxe/eltorito.h>
00039 #include <realmode.h>
00040 #include <bios.h>
00041 #include <biosint.h>
00042 #include <bootsector.h>
00043 #include <int13.h>
00044 
00045 /** @file
00046  *
00047  * INT 13 emulation
00048  *
00049  * This module provides a mechanism for exporting block devices via
00050  * the BIOS INT 13 disk interrupt interface.  
00051  *
00052  */
00053 
00054 /** INT 13 SAN device private data */
00055 struct int13_data {
00056         /** BIOS natural drive number (0x00-0xff)
00057          *
00058          * This is the drive number that would have been assigned by
00059          * 'naturally' appending the drive to the end of the BIOS
00060          * drive list.
00061          *
00062          * If the emulated drive replaces a preexisting drive, this is
00063          * the drive number that the preexisting drive gets remapped
00064          * to.
00065          */
00066         unsigned int natural_drive;
00067 
00068         /** Number of cylinders
00069          *
00070          * The cylinder number field in an INT 13 call is ten bits
00071          * wide, giving a maximum of 1024 cylinders.  Conventionally,
00072          * when the 7.8GB limit of a CHS address is exceeded, it is
00073          * the number of cylinders that is increased beyond the
00074          * addressable limit.
00075          */
00076         unsigned int cylinders;
00077         /** Number of heads
00078          *
00079          * The head number field in an INT 13 call is eight bits wide,
00080          * giving a maximum of 256 heads.  However, apparently all
00081          * versions of MS-DOS up to and including Win95 fail with 256
00082          * heads, so the maximum encountered in practice is 255.
00083          */
00084         unsigned int heads;
00085         /** Number of sectors per track
00086          *
00087          * The sector number field in an INT 13 call is six bits wide,
00088          * giving a maximum of 63 sectors, since sector numbering
00089          * (unlike head and cylinder numbering) starts at 1, not 0.
00090          */
00091         unsigned int sectors_per_track;
00092 
00093         /** Address of El Torito boot catalog (if any) */
00094         unsigned int boot_catalog;
00095         /** Status of last operation */
00096         int last_status;
00097 };
00098 
00099 /** Vector for chaining to other INT 13 handlers */
00100 static struct segoff __text16 ( int13_vector );
00101 #define int13_vector __use_text16 ( int13_vector )
00102 
00103 /** Assembly wrapper */
00104 extern void int13_wrapper ( void );
00105 
00106 /** Dummy floppy disk parameter table */
00107 static struct int13_fdd_parameters __data16 ( int13_fdd_params ) = {
00108         /* 512 bytes per sector */
00109         .bytes_per_sector = 0x02,
00110         /* Highest sectors per track that we ever return */
00111         .sectors_per_track = 48,
00112 };
00113 #define int13_fdd_params __use_data16 ( int13_fdd_params )
00114 
00115 /**
00116  * Equipment word
00117  *
00118  * This is a cached copy of the BIOS Data Area equipment word at
00119  * 40:10.
00120  */
00121 static uint16_t equipment_word;
00122 
00123 /**
00124  * Number of BIOS floppy disk drives
00125  *
00126  * This is derived from the equipment word.  It is held in .text16 to
00127  * allow for easy access by the INT 13,08 wrapper.
00128  */
00129 static uint8_t __text16 ( num_fdds );
00130 #define num_fdds __use_text16 ( num_fdds )
00131 
00132 /**
00133  * Number of BIOS hard disk drives
00134  *
00135  * This is a cached copy of the BIOS Data Area number of hard disk
00136  * drives at 40:75.  It is held in .text16 to allow for easy access by
00137  * the INT 13,08 wrapper.
00138  */
00139 static uint8_t __text16 ( num_drives );
00140 #define num_drives __use_text16 ( num_drives )
00141 
00142 /**
00143  * Calculate SAN device capacity (limited to 32 bits)
00144  *
00145  * @v sandev            SAN device
00146  * @ret blocks          Number of blocks
00147  */
00148 static inline uint32_t int13_capacity32 ( struct san_device *sandev ) {
00149         uint64_t capacity = sandev_capacity ( sandev );
00150         return ( ( capacity <= 0xffffffffUL ) ? capacity : 0xffffffff );
00151 }
00152 
00153 /**
00154  * Test if SAN device is a floppy disk drive
00155  *
00156  * @v sandev            SAN device
00157  * @ret is_fdd          SAN device is a floppy disk drive
00158  */
00159 static inline int int13_is_fdd ( struct san_device *sandev ) {
00160         return ( ! ( sandev->drive & 0x80 ) );
00161 }
00162 
00163 /**
00164  * Parse El Torito parameters
00165  *
00166  * @v sandev            SAN device
00167  * @v scratch           Scratch area for single-sector reads
00168  * @ret rc              Return status code
00169  *
00170  * Reads and parses El Torito parameters, if present.
00171  */
00172 static int int13_parse_eltorito ( struct san_device *sandev, void *scratch ) {
00173         struct int13_data *int13 = sandev->priv;
00174         static const struct eltorito_descriptor_fixed boot_check = {
00175                 .type = ISO9660_TYPE_BOOT,
00176                 .id = ISO9660_ID,
00177                 .version = 1,
00178                 .system_id = "EL TORITO SPECIFICATION",
00179         };
00180         struct eltorito_descriptor *boot = scratch;
00181         int rc;
00182 
00183         /* Read boot record volume descriptor */
00184         if ( ( rc = sandev_read ( sandev, ELTORITO_LBA, 1,
00185                                   virt_to_user ( boot ) ) ) != 0 ) {
00186                 DBGC ( sandev, "INT13 drive %02x could not read El Torito boot "
00187                        "record volume descriptor: %s\n",
00188                        sandev->drive, strerror ( rc ) );
00189                 return rc;
00190         }
00191 
00192         /* Check for an El Torito boot catalog */
00193         if ( memcmp ( boot, &boot_check, sizeof ( boot_check ) ) == 0 ) {
00194                 int13->boot_catalog = boot->sector;
00195                 DBGC ( sandev, "INT13 drive %02x has an El Torito boot catalog "
00196                        "at LBA %08x\n", sandev->drive, int13->boot_catalog );
00197         } else {
00198                 DBGC ( sandev, "INT13 drive %02x has no El Torito boot "
00199                        "catalog\n", sandev->drive );
00200         }
00201 
00202         return 0;
00203 }
00204 
00205 /**
00206  * Guess INT 13 hard disk drive geometry
00207  *
00208  * @v sandev            SAN device
00209  * @v scratch           Scratch area for single-sector reads
00210  * @ret heads           Guessed number of heads
00211  * @ret sectors         Guessed number of sectors per track
00212  * @ret rc              Return status code
00213  *
00214  * Guesses the drive geometry by inspecting the partition table.
00215  */
00216 static int int13_guess_geometry_hdd ( struct san_device *sandev, void *scratch,
00217                                       unsigned int *heads,
00218                                       unsigned int *sectors ) {
00219         struct master_boot_record *mbr = scratch;
00220         struct partition_table_entry *partition;
00221         unsigned int i;
00222         unsigned int start_cylinder;
00223         unsigned int start_head;
00224         unsigned int start_sector;
00225         unsigned int end_head;
00226         unsigned int end_sector;
00227         int rc;
00228 
00229         /* Read partition table */
00230         if ( ( rc = sandev_read ( sandev, 0, 1, virt_to_user ( mbr ) ) ) != 0 ) {
00231                 DBGC ( sandev, "INT13 drive %02x could not read "
00232                        "partition table to guess geometry: %s\n",
00233                        sandev->drive, strerror ( rc ) );
00234                 return rc;
00235         }
00236         DBGC2 ( sandev, "INT13 drive %02x has MBR:\n", sandev->drive );
00237         DBGC2_HDA ( sandev, 0, mbr, sizeof ( *mbr ) );
00238         DBGC ( sandev, "INT13 drive %02x has signature %08x\n",
00239                sandev->drive, mbr->signature );
00240 
00241         /* Scan through partition table and modify guesses for
00242          * heads and sectors_per_track if we find any used
00243          * partitions.
00244          */
00245         *heads = 0;
00246         *sectors = 0;
00247         for ( i = 0 ; i < 4 ; i++ ) {
00248 
00249                 /* Skip empty partitions */
00250                 partition = &mbr->partitions[i];
00251                 if ( ! partition->type )
00252                         continue;
00253 
00254                 /* If partition starts on cylinder 0 then we can
00255                  * unambiguously determine the number of sectors.
00256                  */
00257                 start_cylinder = PART_CYLINDER ( partition->chs_start );
00258                 start_head = PART_HEAD ( partition->chs_start );
00259                 start_sector = PART_SECTOR ( partition->chs_start );
00260                 if ( ( start_cylinder == 0 ) && ( start_head != 0 ) ) {
00261                         *sectors = ( ( partition->start + 1 - start_sector ) /
00262                                      start_head );
00263                         DBGC ( sandev, "INT13 drive %02x guessing C/H/S "
00264                                "xx/xx/%d based on partition %d\n",
00265                                sandev->drive, *sectors, ( i + 1 ) );
00266                 }
00267 
00268                 /* If partition ends on a higher head or sector number
00269                  * than our current guess, then increase the guess.
00270                  */
00271                 end_head = PART_HEAD ( partition->chs_end );
00272                 end_sector = PART_SECTOR ( partition->chs_end );
00273                 if ( ( end_head + 1 ) > *heads ) {
00274                         *heads = ( end_head + 1 );
00275                         DBGC ( sandev, "INT13 drive %02x guessing C/H/S "
00276                                "xx/%d/xx based on partition %d\n",
00277                                sandev->drive, *heads, ( i + 1 ) );
00278                 }
00279                 if ( end_sector > *sectors ) {
00280                         *sectors = end_sector;
00281                         DBGC ( sandev, "INT13 drive %02x guessing C/H/S "
00282                                "xx/xx/%d based on partition %d\n",
00283                                sandev->drive, *sectors, ( i + 1 ) );
00284                 }
00285         }
00286 
00287         /* Default guess is xx/255/63 */
00288         if ( ! *heads )
00289                 *heads = 255;
00290         if ( ! *sectors )
00291                 *sectors = 63;
00292 
00293         return 0;
00294 }
00295 
00296 /** Recognised floppy disk geometries */
00297 static const struct int13_fdd_geometry int13_fdd_geometries[] = {
00298         INT13_FDD_GEOMETRY ( 40, 1, 8 ),
00299         INT13_FDD_GEOMETRY ( 40, 1, 9 ),
00300         INT13_FDD_GEOMETRY ( 40, 2, 8 ),
00301         INT13_FDD_GEOMETRY ( 40, 1, 9 ),
00302         INT13_FDD_GEOMETRY ( 80, 2, 8 ),
00303         INT13_FDD_GEOMETRY ( 80, 2, 9 ),
00304         INT13_FDD_GEOMETRY ( 80, 2, 15 ),
00305         INT13_FDD_GEOMETRY ( 80, 2, 18 ),
00306         INT13_FDD_GEOMETRY ( 80, 2, 20 ),
00307         INT13_FDD_GEOMETRY ( 80, 2, 21 ),
00308         INT13_FDD_GEOMETRY ( 82, 2, 21 ),
00309         INT13_FDD_GEOMETRY ( 83, 2, 21 ),
00310         INT13_FDD_GEOMETRY ( 80, 2, 22 ),
00311         INT13_FDD_GEOMETRY ( 80, 2, 23 ),
00312         INT13_FDD_GEOMETRY ( 80, 2, 24 ),
00313         INT13_FDD_GEOMETRY ( 80, 2, 36 ),
00314         INT13_FDD_GEOMETRY ( 80, 2, 39 ),
00315         INT13_FDD_GEOMETRY ( 80, 2, 40 ),
00316         INT13_FDD_GEOMETRY ( 80, 2, 44 ),
00317         INT13_FDD_GEOMETRY ( 80, 2, 48 ),
00318 };
00319 
00320 /**
00321  * Guess INT 13 floppy disk drive geometry
00322  *
00323  * @v sandev            SAN device
00324  * @ret heads           Guessed number of heads
00325  * @ret sectors         Guessed number of sectors per track
00326  * @ret rc              Return status code
00327  *
00328  * Guesses the drive geometry by inspecting the disk size.
00329  */
00330 static int int13_guess_geometry_fdd ( struct san_device *sandev,
00331                                       unsigned int *heads,
00332                                       unsigned int *sectors ) {
00333         unsigned int blocks = sandev_capacity ( sandev );
00334         const struct int13_fdd_geometry *geometry;
00335         unsigned int cylinders;
00336         unsigned int i;
00337 
00338         /* Look for a match against a known geometry */
00339         for ( i = 0 ; i < ( sizeof ( int13_fdd_geometries ) /
00340                             sizeof ( int13_fdd_geometries[0] ) ) ; i++ ) {
00341                 geometry = &int13_fdd_geometries[i];
00342                 cylinders = INT13_FDD_CYLINDERS ( geometry );
00343                 *heads = INT13_FDD_HEADS ( geometry );
00344                 *sectors = INT13_FDD_SECTORS ( geometry );
00345                 if ( ( cylinders * (*heads) * (*sectors) ) == blocks ) {
00346                         DBGC ( sandev, "INT13 drive %02x guessing C/H/S "
00347                                "%d/%d/%d based on size %dK\n", sandev->drive,
00348                                cylinders, *heads, *sectors, ( blocks / 2 ) );
00349                         return 0;
00350                 }
00351         }
00352 
00353         /* Otherwise, assume a partial disk image in the most common
00354          * format (1440K, 80/2/18).
00355          */
00356         *heads = 2;
00357         *sectors = 18;
00358         DBGC ( sandev, "INT13 drive %02x guessing C/H/S xx/%d/%d based on size "
00359                "%dK\n", sandev->drive, *heads, *sectors, ( blocks / 2 ) );
00360         return 0;
00361 }
00362 
00363 /**
00364  * Guess INT 13 drive geometry
00365  *
00366  * @v sandev            SAN device
00367  * @v scratch           Scratch area for single-sector reads
00368  * @ret rc              Return status code
00369  */
00370 static int int13_guess_geometry ( struct san_device *sandev, void *scratch ) {
00371         struct int13_data *int13 = sandev->priv;
00372         unsigned int guessed_heads;
00373         unsigned int guessed_sectors;
00374         unsigned int blocks;
00375         unsigned int blocks_per_cyl;
00376         int rc;
00377 
00378         /* Guess geometry according to drive type */
00379         if ( int13_is_fdd ( sandev ) ) {
00380                 if ( ( rc = int13_guess_geometry_fdd ( sandev, &guessed_heads,
00381                                                        &guessed_sectors )) != 0)
00382                         return rc;
00383         } else {
00384                 if ( ( rc = int13_guess_geometry_hdd ( sandev, scratch,
00385                                                        &guessed_heads,
00386                                                        &guessed_sectors )) != 0)
00387                         return rc;
00388         }
00389 
00390         /* Apply guesses if no geometry already specified */
00391         if ( ! int13->heads )
00392                 int13->heads = guessed_heads;
00393         if ( ! int13->sectors_per_track )
00394                 int13->sectors_per_track = guessed_sectors;
00395         if ( ! int13->cylinders ) {
00396                 /* Avoid attempting a 64-bit divide on a 32-bit system */
00397                 blocks = int13_capacity32 ( sandev );
00398                 blocks_per_cyl = ( int13->heads * int13->sectors_per_track );
00399                 assert ( blocks_per_cyl != 0 );
00400                 int13->cylinders = ( blocks / blocks_per_cyl );
00401                 if ( int13->cylinders > 1024 )
00402                         int13->cylinders = 1024;
00403         }
00404 
00405         return 0;
00406 }
00407 
00408 /**
00409  * Update BIOS drive count
00410  */
00411 static void int13_sync_num_drives ( void ) {
00412         struct san_device *sandev;
00413         struct int13_data *int13;
00414         uint8_t *counter;
00415         uint8_t max_drive;
00416         uint8_t required;
00417 
00418         /* Get current drive counts */
00419         get_real ( equipment_word, BDA_SEG, BDA_EQUIPMENT_WORD );
00420         get_real ( num_drives, BDA_SEG, BDA_NUM_DRIVES );
00421         num_fdds = ( ( equipment_word & 0x0001 ) ?
00422                      ( ( ( equipment_word >> 6 ) & 0x3 ) + 1 ) : 0 );
00423 
00424         /* Ensure count is large enough to cover all of our SAN devices */
00425         for_each_sandev ( sandev ) {
00426                 int13 = sandev->priv;
00427                 counter = ( int13_is_fdd ( sandev ) ? &num_fdds : &num_drives );
00428                 max_drive = sandev->drive;
00429                 if ( max_drive < int13->natural_drive )
00430                         max_drive = int13->natural_drive;
00431                 required = ( ( max_drive & 0x7f ) + 1 );
00432                 if ( *counter < required ) {
00433                         *counter = required;
00434                         DBGC ( sandev, "INT13 drive %02x added to drive count: "
00435                                "%d HDDs, %d FDDs\n",
00436                                sandev->drive, num_drives, num_fdds );
00437                 }
00438         }
00439 
00440         /* Update current drive count */
00441         equipment_word &= ~( ( 0x3 << 6 ) | 0x0001 );
00442         if ( num_fdds ) {
00443                 equipment_word |= ( 0x0001 |
00444                                     ( ( ( num_fdds - 1 ) & 0x3 ) << 6 ) );
00445         }
00446         put_real ( equipment_word, BDA_SEG, BDA_EQUIPMENT_WORD );
00447         put_real ( num_drives, BDA_SEG, BDA_NUM_DRIVES );
00448 }
00449 
00450 /**
00451  * Check number of drives
00452  */
00453 static void int13_check_num_drives ( void ) {
00454         uint16_t check_equipment_word;
00455         uint8_t check_num_drives;
00456 
00457         get_real ( check_equipment_word, BDA_SEG, BDA_EQUIPMENT_WORD );
00458         get_real ( check_num_drives, BDA_SEG, BDA_NUM_DRIVES );
00459         if ( ( check_equipment_word != equipment_word ) ||
00460              ( check_num_drives != num_drives ) ) {
00461                 int13_sync_num_drives();
00462         }
00463 }
00464 
00465 /**
00466  * INT 13, 00 - Reset disk system
00467  *
00468  * @v sandev            SAN device
00469  * @ret status          Status code
00470  */
00471 static int int13_reset ( struct san_device *sandev,
00472                          struct i386_all_regs *ix86 __unused ) {
00473         int rc;
00474 
00475         DBGC2 ( sandev, "Reset drive\n" );
00476 
00477         /* Reset SAN device */
00478         if ( ( rc = sandev_reset ( sandev ) ) != 0 )
00479                 return -INT13_STATUS_RESET_FAILED;
00480 
00481         return 0;
00482 }
00483 
00484 /**
00485  * INT 13, 01 - Get status of last operation
00486  *
00487  * @v sandev            SAN device
00488  * @ret status          Status code
00489  */
00490 static int int13_get_last_status ( struct san_device *sandev,
00491                                    struct i386_all_regs *ix86 __unused ) {
00492         struct int13_data *int13 = sandev->priv;
00493 
00494         DBGC2 ( sandev, "Get status of last operation\n" );
00495         return int13->last_status;
00496 }
00497 
00498 /**
00499  * Read / write sectors
00500  *
00501  * @v sandev            SAN device
00502  * @v al                Number of sectors to read or write (must be nonzero)
00503  * @v ch                Low bits of cylinder number
00504  * @v cl (bits 7:6)     High bits of cylinder number
00505  * @v cl (bits 5:0)     Sector number
00506  * @v dh                Head number
00507  * @v es:bx             Data buffer
00508  * @v sandev_rw         SAN device read/write method
00509  * @ret status          Status code
00510  * @ret al              Number of sectors read or written
00511  */
00512 static int int13_rw_sectors ( struct san_device *sandev,
00513                               struct i386_all_regs *ix86,
00514                               int ( * sandev_rw ) ( struct san_device *sandev,
00515                                                     uint64_t lba,
00516                                                     unsigned int count,
00517                                                     userptr_t buffer ) ) {
00518         struct int13_data *int13 = sandev->priv;
00519         unsigned int cylinder, head, sector;
00520         unsigned long lba;
00521         unsigned int count;
00522         userptr_t buffer;
00523         int rc;
00524 
00525         /* Validate blocksize */
00526         if ( sandev_blksize ( sandev ) != INT13_BLKSIZE ) {
00527                 DBGC ( sandev, "\nINT 13 drive %02x invalid blocksize (%zd) "
00528                        "for non-extended read/write\n",
00529                        sandev->drive, sandev_blksize ( sandev ) );
00530                 return -INT13_STATUS_INVALID;
00531         }
00532 
00533         /* Calculate parameters */
00534         cylinder = ( ( ( ix86->regs.cl & 0xc0 ) << 2 ) | ix86->regs.ch );
00535         head = ix86->regs.dh;
00536         sector = ( ix86->regs.cl & 0x3f );
00537         if ( ( cylinder >= int13->cylinders ) ||
00538              ( head >= int13->heads ) ||
00539              ( sector < 1 ) || ( sector > int13->sectors_per_track ) ) {
00540                 DBGC ( sandev, "C/H/S %d/%d/%d out of range for geometry "
00541                        "%d/%d/%d\n", cylinder, head, sector, int13->cylinders,
00542                        int13->heads, int13->sectors_per_track );
00543                 return -INT13_STATUS_INVALID;
00544         }
00545         lba = ( ( ( ( cylinder * int13->heads ) + head )
00546                   * int13->sectors_per_track ) + sector - 1 );
00547         count = ix86->regs.al;
00548         buffer = real_to_user ( ix86->segs.es, ix86->regs.bx );
00549 
00550         DBGC2 ( sandev, "C/H/S %d/%d/%d = LBA %08lx <-> %04x:%04x (count %d)\n",
00551                 cylinder, head, sector, lba, ix86->segs.es, ix86->regs.bx,
00552                 count );
00553 
00554         /* Read from / write to block device */
00555         if ( ( rc = sandev_rw ( sandev, lba, count, buffer ) ) != 0 ){
00556                 DBGC ( sandev, "INT13 drive %02x I/O failed: %s\n",
00557                        sandev->drive, strerror ( rc ) );
00558                 return -INT13_STATUS_READ_ERROR;
00559         }
00560 
00561         return 0;
00562 }
00563 
00564 /**
00565  * INT 13, 02 - Read sectors
00566  *
00567  * @v sandev            SAN device
00568  * @v al                Number of sectors to read (must be nonzero)
00569  * @v ch                Low bits of cylinder number
00570  * @v cl (bits 7:6)     High bits of cylinder number
00571  * @v cl (bits 5:0)     Sector number
00572  * @v dh                Head number
00573  * @v es:bx             Data buffer
00574  * @ret status          Status code
00575  * @ret al              Number of sectors read
00576  */
00577 static int int13_read_sectors ( struct san_device *sandev,
00578                                 struct i386_all_regs *ix86 ) {
00579 
00580         DBGC2 ( sandev, "Read: " );
00581         return int13_rw_sectors ( sandev, ix86, sandev_read );
00582 }
00583 
00584 /**
00585  * INT 13, 03 - Write sectors
00586  *
00587  * @v sandev            SAN device
00588  * @v al                Number of sectors to write (must be nonzero)
00589  * @v ch                Low bits of cylinder number
00590  * @v cl (bits 7:6)     High bits of cylinder number
00591  * @v cl (bits 5:0)     Sector number
00592  * @v dh                Head number
00593  * @v es:bx             Data buffer
00594  * @ret status          Status code
00595  * @ret al              Number of sectors written
00596  */
00597 static int int13_write_sectors ( struct san_device *sandev,
00598                                  struct i386_all_regs *ix86 ) {
00599 
00600         DBGC2 ( sandev, "Write: " );
00601         return int13_rw_sectors ( sandev, ix86, sandev_write );
00602 }
00603 
00604 /**
00605  * INT 13, 08 - Get drive parameters
00606  *
00607  * @v sandev            SAN device
00608  * @ret status          Status code
00609  * @ret ch              Low bits of maximum cylinder number
00610  * @ret cl (bits 7:6)   High bits of maximum cylinder number
00611  * @ret cl (bits 5:0)   Maximum sector number
00612  * @ret dh              Maximum head number
00613  * @ret dl              Number of drives
00614  */
00615 static int int13_get_parameters ( struct san_device *sandev,
00616                                   struct i386_all_regs *ix86 ) {
00617         struct int13_data *int13 = sandev->priv;
00618         unsigned int max_cylinder = int13->cylinders - 1;
00619         unsigned int max_head = int13->heads - 1;
00620         unsigned int max_sector = int13->sectors_per_track; /* sic */
00621 
00622         DBGC2 ( sandev, "Get drive parameters\n" );
00623 
00624         /* Validate blocksize */
00625         if ( sandev_blksize ( sandev ) != INT13_BLKSIZE ) {
00626                 DBGC ( sandev, "\nINT 13 drive %02x invalid blocksize (%zd) "
00627                        "for non-extended parameters\n",
00628                        sandev->drive, sandev_blksize ( sandev ) );
00629                 return -INT13_STATUS_INVALID;
00630         }
00631 
00632         /* Common parameters */
00633         ix86->regs.ch = ( max_cylinder & 0xff );
00634         ix86->regs.cl = ( ( ( max_cylinder >> 8 ) << 6 ) | max_sector );
00635         ix86->regs.dh = max_head;
00636         ix86->regs.dl = ( int13_is_fdd ( sandev ) ? num_fdds : num_drives );
00637 
00638         /* Floppy-specific parameters */
00639         if ( int13_is_fdd ( sandev ) ) {
00640                 ix86->regs.bl = INT13_FDD_TYPE_1M44;
00641                 ix86->segs.es = rm_ds;
00642                 ix86->regs.di = __from_data16 ( &int13_fdd_params );
00643         }
00644 
00645         return 0;
00646 }
00647 
00648 /**
00649  * INT 13, 15 - Get disk type
00650  *
00651  * @v sandev            SAN device
00652  * @ret ah              Type code
00653  * @ret cx:dx           Sector count
00654  * @ret status          Status code / disk type
00655  */
00656 static int int13_get_disk_type ( struct san_device *sandev,
00657                                  struct i386_all_regs *ix86 ) {
00658         uint32_t blocks;
00659 
00660         DBGC2 ( sandev, "Get disk type\n" );
00661 
00662         if ( int13_is_fdd ( sandev ) ) {
00663                 return INT13_DISK_TYPE_FDD;
00664         } else {
00665                 blocks = int13_capacity32 ( sandev );
00666                 ix86->regs.cx = ( blocks >> 16 );
00667                 ix86->regs.dx = ( blocks & 0xffff );
00668                 return INT13_DISK_TYPE_HDD;
00669         }
00670 }
00671 
00672 /**
00673  * INT 13, 41 - Extensions installation check
00674  *
00675  * @v sandev            SAN device
00676  * @v bx                0x55aa
00677  * @ret bx              0xaa55
00678  * @ret cx              Extensions API support bitmap
00679  * @ret status          Status code / API version
00680  */
00681 static int int13_extension_check ( struct san_device *sandev __unused,
00682                                    struct i386_all_regs *ix86 ) {
00683 
00684         if ( ix86->regs.bx == 0x55aa ) {
00685                 DBGC2 ( sandev, "INT13 extensions installation check\n" );
00686                 ix86->regs.bx = 0xaa55;
00687                 ix86->regs.cx = ( INT13_EXTENSION_LINEAR |
00688                                   INT13_EXTENSION_EDD |
00689                                   INT13_EXTENSION_64BIT );
00690                 return INT13_EXTENSION_VER_3_0;
00691         } else {
00692                 return -INT13_STATUS_INVALID;
00693         }
00694 }
00695 
00696 /**
00697  * Extended read / write
00698  *
00699  * @v sandev            SAN device
00700  * @v ds:si             Disk address packet
00701  * @v sandev_rw         SAN device read/write method
00702  * @ret status          Status code
00703  */
00704 static int int13_extended_rw ( struct san_device *sandev,
00705                                struct i386_all_regs *ix86,
00706                                int ( * sandev_rw ) ( struct san_device *sandev,
00707                                                      uint64_t lba,
00708                                                      unsigned int count,
00709                                                      userptr_t buffer ) ) {
00710         struct int13_disk_address addr;
00711         uint8_t bufsize;
00712         uint64_t lba;
00713         unsigned long count;
00714         userptr_t buffer;
00715         int rc;
00716 
00717         /* Extended reads are not allowed on floppy drives.
00718          * ELTORITO.SYS seems to assume that we are really a CD-ROM if
00719          * we support extended reads for a floppy drive.
00720          */
00721         if ( int13_is_fdd ( sandev ) )
00722                 return -INT13_STATUS_INVALID;
00723 
00724         /* Get buffer size */
00725         get_real ( bufsize, ix86->segs.ds,
00726                    ( ix86->regs.si + offsetof ( typeof ( addr ), bufsize ) ) );
00727         if ( bufsize < offsetof ( typeof ( addr ), buffer_phys ) ) {
00728                 DBGC2 ( sandev, "<invalid buffer size %#02x\n>\n", bufsize );
00729                 return -INT13_STATUS_INVALID;
00730         }
00731 
00732         /* Read parameters from disk address structure */
00733         memset ( &addr, 0, sizeof ( addr ) );
00734         copy_from_real ( &addr, ix86->segs.ds, ix86->regs.si, bufsize );
00735         lba = addr.lba;
00736         DBGC2 ( sandev, "LBA %08llx <-> ", ( ( unsigned long long ) lba ) );
00737         if ( ( addr.count == 0xff ) ||
00738              ( ( addr.buffer.segment == 0xffff ) &&
00739                ( addr.buffer.offset == 0xffff ) ) ) {
00740                 buffer = phys_to_user ( addr.buffer_phys );
00741                 DBGC2 ( sandev, "%08llx",
00742                         ( ( unsigned long long ) addr.buffer_phys ) );
00743         } else {
00744                 buffer = real_to_user ( addr.buffer.segment,
00745                                         addr.buffer.offset );
00746                 DBGC2 ( sandev, "%04x:%04x", addr.buffer.segment,
00747                         addr.buffer.offset );
00748         }
00749         if ( addr.count <= 0x7f ) {
00750                 count = addr.count;
00751         } else if ( addr.count == 0xff ) {
00752                 count = addr.long_count;
00753         } else {
00754                 DBGC2 ( sandev, " <invalid count %#02x>\n", addr.count );
00755                 return -INT13_STATUS_INVALID;
00756         }
00757         DBGC2 ( sandev, " (count %ld)\n", count );
00758 
00759         /* Read from / write to block device */
00760         if ( ( rc = sandev_rw ( sandev, lba, count, buffer ) ) != 0 ) {
00761                 DBGC ( sandev, "INT13 drive %02x extended I/O failed: %s\n",
00762                        sandev->drive, strerror ( rc ) );
00763                 /* Record that no blocks were transferred successfully */
00764                 addr.count = 0;
00765                 put_real ( addr.count, ix86->segs.ds,
00766                            ( ix86->regs.si +
00767                              offsetof ( typeof ( addr ), count ) ) );
00768                 return -INT13_STATUS_READ_ERROR;
00769         }
00770 
00771         return 0;
00772 }
00773 
00774 /**
00775  * INT 13, 42 - Extended read
00776  *
00777  * @v sandev            SAN device
00778  * @v ds:si             Disk address packet
00779  * @ret status          Status code
00780  */
00781 static int int13_extended_read ( struct san_device *sandev,
00782                                  struct i386_all_regs *ix86 ) {
00783 
00784         DBGC2 ( sandev, "Extended read: " );
00785         return int13_extended_rw ( sandev, ix86, sandev_read );
00786 }
00787 
00788 /**
00789  * INT 13, 43 - Extended write
00790  *
00791  * @v sandev            SAN device
00792  * @v ds:si             Disk address packet
00793  * @ret status          Status code
00794  */
00795 static int int13_extended_write ( struct san_device *sandev,
00796                                   struct i386_all_regs *ix86 ) {
00797 
00798         DBGC2 ( sandev, "Extended write: " );
00799         return int13_extended_rw ( sandev, ix86, sandev_write );
00800 }
00801 
00802 /**
00803  * INT 13, 44 - Verify sectors
00804  *
00805  * @v sandev            SAN device
00806  * @v ds:si             Disk address packet
00807  * @ret status          Status code
00808  */
00809 static int int13_extended_verify ( struct san_device *sandev,
00810                                    struct i386_all_regs *ix86 ) {
00811         struct int13_disk_address addr;
00812         uint64_t lba;
00813         unsigned long count;
00814 
00815         /* Read parameters from disk address structure */
00816         if ( DBG_EXTRA ) {
00817                 copy_from_real ( &addr, ix86->segs.ds, ix86->regs.si,
00818                                  sizeof ( addr ));
00819                 lba = addr.lba;
00820                 count = addr.count;
00821                 DBGC2 ( sandev, "Verify: LBA %08llx (count %ld)\n",
00822                         ( ( unsigned long long ) lba ), count );
00823         }
00824 
00825         /* We have no mechanism for verifying sectors */
00826         return -INT13_STATUS_INVALID;
00827 }
00828 
00829 /**
00830  * INT 13, 44 - Extended seek
00831  *
00832  * @v sandev            SAN device
00833  * @v ds:si             Disk address packet
00834  * @ret status          Status code
00835  */
00836 static int int13_extended_seek ( struct san_device *sandev,
00837                                  struct i386_all_regs *ix86 ) {
00838         struct int13_disk_address addr;
00839         uint64_t lba;
00840         unsigned long count;
00841 
00842         /* Read parameters from disk address structure */
00843         if ( DBG_EXTRA ) {
00844                 copy_from_real ( &addr, ix86->segs.ds, ix86->regs.si,
00845                                  sizeof ( addr ));
00846                 lba = addr.lba;
00847                 count = addr.count;
00848                 DBGC2 ( sandev, "Seek: LBA %08llx (count %ld)\n",
00849                         ( ( unsigned long long ) lba ), count );
00850         }
00851 
00852         /* Ignore and return success */
00853         return 0;
00854 }
00855 
00856 /**
00857  * Build device path information
00858  *
00859  * @v sandev            SAN device
00860  * @v dpi               Device path information
00861  * @ret rc              Return status code
00862  */
00863 static int int13_device_path_info ( struct san_device *sandev,
00864                                     struct edd_device_path_information *dpi ) {
00865         struct san_path *sanpath;
00866         struct device *device;
00867         struct device_description *desc;
00868         unsigned int i;
00869         uint8_t sum = 0;
00870         int rc;
00871 
00872         /* Reopen block device if necessary */
00873         if ( sandev_needs_reopen ( sandev ) &&
00874              ( ( rc = sandev_reopen ( sandev ) ) != 0 ) )
00875                 return rc;
00876         sanpath = sandev->active;
00877         assert ( sanpath != NULL );
00878 
00879         /* Get underlying hardware device */
00880         device = identify_device ( &sanpath->block );
00881         if ( ! device ) {
00882                 DBGC ( sandev, "INT13 drive %02x cannot identify hardware "
00883                        "device\n", sandev->drive );
00884                 return -ENODEV;
00885         }
00886 
00887         /* Fill in bus type and interface path */
00888         desc = &device->desc;
00889         switch ( desc->bus_type ) {
00890         case BUS_TYPE_PCI:
00891                 dpi->host_bus_type.type = EDD_BUS_TYPE_PCI;
00892                 dpi->interface_path.pci.bus = PCI_BUS ( desc->location );
00893                 dpi->interface_path.pci.slot = PCI_SLOT ( desc->location );
00894                 dpi->interface_path.pci.function = PCI_FUNC ( desc->location );
00895                 dpi->interface_path.pci.channel = 0xff; /* unused */
00896                 break;
00897         default:
00898                 DBGC ( sandev, "INT13 drive %02x unrecognised bus type %d\n",
00899                        sandev->drive, desc->bus_type );
00900                 return -ENOTSUP;
00901         }
00902 
00903         /* Get EDD block device description */
00904         if ( ( rc = edd_describe ( &sanpath->block, &dpi->interface_type,
00905                                    &dpi->device_path ) ) != 0 ) {
00906                 DBGC ( sandev, "INT13 drive %02x cannot identify block device: "
00907                        "%s\n", sandev->drive, strerror ( rc ) );
00908                 return rc;
00909         }
00910 
00911         /* Fill in common fields and fix checksum */
00912         dpi->key = EDD_DEVICE_PATH_INFO_KEY;
00913         dpi->len = sizeof ( *dpi );
00914         for ( i = 0 ; i < sizeof ( *dpi ) ; i++ )
00915                 sum += *( ( ( uint8_t * ) dpi ) + i );
00916         dpi->checksum -= sum;
00917 
00918         return 0;
00919 }
00920 
00921 /**
00922  * INT 13, 48 - Get extended parameters
00923  *
00924  * @v sandev            SAN device
00925  * @v ds:si             Drive parameter table
00926  * @ret status          Status code
00927  */
00928 static int int13_get_extended_parameters ( struct san_device *sandev,
00929                                            struct i386_all_regs *ix86 ) {
00930         struct int13_data *int13 = sandev->priv;
00931         struct int13_disk_parameters params;
00932         struct segoff address;
00933         size_t len = sizeof ( params );
00934         uint16_t bufsize;
00935         int rc;
00936 
00937         /* Get buffer size */
00938         get_real ( bufsize, ix86->segs.ds,
00939                    ( ix86->regs.si + offsetof ( typeof ( params ), bufsize )));
00940 
00941         DBGC2 ( sandev, "Get extended drive parameters to %04x:%04x+%02x\n",
00942                 ix86->segs.ds, ix86->regs.si, bufsize );
00943 
00944         /* Build drive parameters */
00945         memset ( &params, 0, sizeof ( params ) );
00946         params.flags = INT13_FL_DMA_TRANSPARENT;
00947         if ( ( int13->cylinders < 1024 ) &&
00948              ( sandev_capacity ( sandev ) <= INT13_MAX_CHS_SECTORS ) ) {
00949                 params.flags |= INT13_FL_CHS_VALID;
00950         }
00951         params.cylinders = int13->cylinders;
00952         params.heads = int13->heads;
00953         params.sectors_per_track = int13->sectors_per_track;
00954         params.sectors = sandev_capacity ( sandev );
00955         params.sector_size = sandev_blksize ( sandev );
00956         memset ( &params.dpte, 0xff, sizeof ( params.dpte ) );
00957         if ( ( rc = int13_device_path_info ( sandev, &params.dpi ) ) != 0 ) {
00958                 DBGC ( sandev, "INT13 drive %02x could not provide device "
00959                        "path information: %s\n",
00960                        sandev->drive, strerror ( rc ) );
00961                 len = offsetof ( typeof ( params ), dpi );
00962         }
00963 
00964         /* Calculate returned "buffer size" (which will be less than
00965          * the length actually copied if device path information is
00966          * present).
00967          */
00968         if ( bufsize < offsetof ( typeof ( params ), dpte ) )
00969                 return -INT13_STATUS_INVALID;
00970         if ( bufsize < offsetof ( typeof ( params ), dpi ) ) {
00971                 params.bufsize = offsetof ( typeof ( params ), dpte );
00972         } else {
00973                 params.bufsize = offsetof ( typeof ( params ), dpi );
00974         }
00975 
00976         DBGC ( sandev, "INT 13 drive %02x described using extended "
00977                "parameters:\n", sandev->drive );
00978         address.segment = ix86->segs.ds;
00979         address.offset = ix86->regs.si;
00980         DBGC_HDA ( sandev, address, &params, len );
00981 
00982         /* Return drive parameters */
00983         if ( len > bufsize )
00984                 len = bufsize;
00985         copy_to_real ( ix86->segs.ds, ix86->regs.si, &params, len );
00986 
00987         return 0;
00988 }
00989 
00990 /**
00991  * INT 13, 4b - Get status or terminate CD-ROM emulation
00992  *
00993  * @v sandev            SAN device
00994  * @v ds:si             Specification packet
00995  * @ret status          Status code
00996  */
00997 static int int13_cdrom_status_terminate ( struct san_device *sandev,
00998                                           struct i386_all_regs *ix86 ) {
00999         struct int13_cdrom_specification specification;
01000 
01001         DBGC2 ( sandev, "Get CD-ROM emulation status to %04x:%04x%s\n",
01002                 ix86->segs.ds, ix86->regs.si,
01003                 ( ix86->regs.al ? "" : " and terminate" ) );
01004 
01005         /* Fail if we are not a CD-ROM */
01006         if ( ! sandev->is_cdrom ) {
01007                 DBGC ( sandev, "INT13 drive %02x is not a CD-ROM\n",
01008                        sandev->drive );
01009                 return -INT13_STATUS_INVALID;
01010         }
01011 
01012         /* Build specification packet */
01013         memset ( &specification, 0, sizeof ( specification ) );
01014         specification.size = sizeof ( specification );
01015         specification.drive = sandev->drive;
01016 
01017         /* Return specification packet */
01018         copy_to_real ( ix86->segs.ds, ix86->regs.si, &specification,
01019                        sizeof ( specification ) );
01020 
01021         return 0;
01022 }
01023 
01024 
01025 /**
01026  * INT 13, 4d - Read CD-ROM boot catalog
01027  *
01028  * @v sandev            SAN device
01029  * @v ds:si             Command packet
01030  * @ret status          Status code
01031  */
01032 static int int13_cdrom_read_boot_catalog ( struct san_device *sandev,
01033                                            struct i386_all_regs *ix86 ) {
01034         struct int13_data *int13 = sandev->priv;
01035         struct int13_cdrom_boot_catalog_command command;
01036         unsigned int start;
01037         int rc;
01038 
01039         /* Read parameters from command packet */
01040         copy_from_real ( &command, ix86->segs.ds, ix86->regs.si,
01041                          sizeof ( command ) );
01042         DBGC2 ( sandev, "Read CD-ROM boot catalog to %08x\n", command.buffer );
01043 
01044         /* Fail if we have no boot catalog */
01045         if ( ! int13->boot_catalog ) {
01046                 DBGC ( sandev, "INT13 drive %02x has no boot catalog\n",
01047                        sandev->drive );
01048                 return -INT13_STATUS_INVALID;
01049         }
01050         start = ( int13->boot_catalog + command.start );
01051 
01052         /* Read from boot catalog */
01053         if ( ( rc = sandev_read ( sandev, start, command.count,
01054                                   phys_to_user ( command.buffer ) ) ) != 0 ) {
01055                 DBGC ( sandev, "INT13 drive %02x could not read boot catalog: "
01056                        "%s\n", sandev->drive, strerror ( rc ) );
01057                 return -INT13_STATUS_READ_ERROR;
01058         }
01059 
01060         return 0;
01061 }
01062 
01063 /**
01064  * INT 13 handler
01065  *
01066  */
01067 static __asmcall void int13 ( struct i386_all_regs *ix86 ) {
01068         int command = ix86->regs.ah;
01069         unsigned int bios_drive = ix86->regs.dl;
01070         struct san_device *sandev;
01071         struct int13_data *int13;
01072         int status;
01073 
01074         /* Check BIOS hasn't killed off our drive */
01075         int13_check_num_drives();
01076 
01077         for_each_sandev ( sandev ) {
01078 
01079                 int13 = sandev->priv;
01080                 if ( bios_drive != sandev->drive ) {
01081                         /* Remap any accesses to this drive's natural number */
01082                         if ( bios_drive == int13->natural_drive ) {
01083                                 DBGC2 ( sandev, "INT13,%02x (%02x) remapped to "
01084                                         "(%02x)\n", ix86->regs.ah,
01085                                         bios_drive, sandev->drive );
01086                                 ix86->regs.dl = sandev->drive;
01087                                 return;
01088                         } else if ( ( ( bios_drive & 0x7f ) == 0x7f ) &&
01089                                     ( command == INT13_CDROM_STATUS_TERMINATE )
01090                                     && sandev->is_cdrom ) {
01091                                 /* Catch non-drive-specific CD-ROM calls */
01092                         } else {
01093                                 continue;
01094                         }
01095                 }
01096                 
01097                 DBGC2 ( sandev, "INT13,%02x (%02x): ",
01098                         ix86->regs.ah, bios_drive );
01099 
01100                 switch ( command ) {
01101                 case INT13_RESET:
01102                         status = int13_reset ( sandev, ix86 );
01103                         break;
01104                 case INT13_GET_LAST_STATUS:
01105                         status = int13_get_last_status ( sandev, ix86 );
01106                         break;
01107                 case INT13_READ_SECTORS:
01108                         status = int13_read_sectors ( sandev, ix86 );
01109                         break;
01110                 case INT13_WRITE_SECTORS:
01111                         status = int13_write_sectors ( sandev, ix86 );
01112                         break;
01113                 case INT13_GET_PARAMETERS:
01114                         status = int13_get_parameters ( sandev, ix86 );
01115                         break;
01116                 case INT13_GET_DISK_TYPE:
01117                         status = int13_get_disk_type ( sandev, ix86 );
01118                         break;
01119                 case INT13_EXTENSION_CHECK:
01120                         status = int13_extension_check ( sandev, ix86 );
01121                         break;
01122                 case INT13_EXTENDED_READ:
01123                         status = int13_extended_read ( sandev, ix86 );
01124                         break;
01125                 case INT13_EXTENDED_WRITE:
01126                         status = int13_extended_write ( sandev, ix86 );
01127                         break;
01128                 case INT13_EXTENDED_VERIFY:
01129                         status = int13_extended_verify ( sandev, ix86 );
01130                         break;
01131                 case INT13_EXTENDED_SEEK:
01132                         status = int13_extended_seek ( sandev, ix86 );
01133                         break;
01134                 case INT13_GET_EXTENDED_PARAMETERS:
01135                         status = int13_get_extended_parameters ( sandev, ix86 );
01136                         break;
01137                 case INT13_CDROM_STATUS_TERMINATE:
01138                         status = int13_cdrom_status_terminate ( sandev, ix86 );
01139                         break;
01140                 case INT13_CDROM_READ_BOOT_CATALOG:
01141                         status = int13_cdrom_read_boot_catalog ( sandev, ix86 );
01142                         break;
01143                 default:
01144                         DBGC2 ( sandev, "*** Unrecognised INT13 ***\n" );
01145                         status = -INT13_STATUS_INVALID;
01146                         break;
01147                 }
01148 
01149                 /* Store status for INT 13,01 */
01150                 int13->last_status = status;
01151 
01152                 /* Negative status indicates an error */
01153                 if ( status < 0 ) {
01154                         status = -status;
01155                         DBGC ( sandev, "INT13,%02x (%02x) failed with status "
01156                                "%02x\n", ix86->regs.ah, sandev->drive, status );
01157                 } else {
01158                         ix86->flags &= ~CF;
01159                 }
01160                 ix86->regs.ah = status;
01161 
01162                 /* Set OF to indicate to wrapper not to chain this call */
01163                 ix86->flags |= OF;
01164 
01165                 return;
01166         }
01167 }
01168 
01169 /**
01170  * Hook INT 13 handler
01171  *
01172  */
01173 static void int13_hook_vector ( void ) {
01174         /* Assembly wrapper to call int13().  int13() sets OF if we
01175          * should not chain to the previous handler.  (The wrapper
01176          * clears CF and OF before calling int13()).
01177          */
01178         __asm__  __volatile__ (
01179                TEXT16_CODE ( "\nint13_wrapper:\n\t"
01180                              /* Preserve %ax and %dx for future reference */
01181                              "pushw %%bp\n\t"
01182                              "movw %%sp, %%bp\n\t"                           
01183                              "pushw %%ax\n\t"
01184                              "pushw %%dx\n\t"
01185                              /* Clear OF, set CF, call int13() */
01186                              "orb $0, %%al\n\t" 
01187                              "stc\n\t"
01188                              VIRT_CALL ( int13 )
01189                              /* Chain if OF not set */
01190                              "jo 1f\n\t"
01191                              "pushfw\n\t"
01192                              "lcall *%%cs:int13_vector\n\t"
01193                              "\n1:\n\t"
01194                              /* Overwrite flags for iret */
01195                              "pushfw\n\t"
01196                              "popw 6(%%bp)\n\t"
01197                              /* Fix up %dl:
01198                               *
01199                               * INT 13,15 : do nothing if hard disk
01200                               * INT 13,08 : load with number of drives
01201                               * all others: restore original value
01202                               */
01203                              "cmpb $0x15, -1(%%bp)\n\t"
01204                              "jne 2f\n\t"
01205                              "testb $0x80, -4(%%bp)\n\t"
01206                              "jnz 3f\n\t"
01207                              "\n2:\n\t"
01208                              "movb -4(%%bp), %%dl\n\t"
01209                              "cmpb $0x08, -1(%%bp)\n\t"
01210                              "jne 3f\n\t"
01211                              "testb $0x80, %%dl\n\t"
01212                              "movb %%cs:num_drives, %%dl\n\t"
01213                              "jnz 3f\n\t"
01214                              "movb %%cs:num_fdds, %%dl\n\t"
01215                              /* Return */
01216                              "\n3:\n\t"
01217                              "movw %%bp, %%sp\n\t"
01218                              "popw %%bp\n\t"
01219                              "iret\n\t" ) : : );
01220 
01221         hook_bios_interrupt ( 0x13, ( intptr_t ) int13_wrapper, &int13_vector );
01222 }
01223 
01224 /**
01225  * Unhook INT 13 handler
01226  */
01227 static void int13_unhook_vector ( void ) {
01228         unhook_bios_interrupt ( 0x13, ( intptr_t ) int13_wrapper,
01229                                 &int13_vector );
01230 }
01231 
01232 /**
01233  * Hook INT 13 SAN device
01234  *
01235  * @v drive             Drive number
01236  * @v uris              List of URIs
01237  * @v count             Number of URIs
01238  * @v flags             Flags
01239  * @ret drive           Drive number, or negative error
01240  *
01241  * Registers the drive with the INT 13 emulation subsystem, and hooks
01242  * the INT 13 interrupt vector (if not already hooked).
01243  */
01244 static int int13_hook ( unsigned int drive, struct uri **uris,
01245                         unsigned int count, unsigned int flags ) {
01246         struct san_device *sandev;
01247         struct int13_data *int13;
01248         unsigned int natural_drive;
01249         void *scratch;
01250         int need_hook = ( ! have_sandevs() );
01251         int rc;
01252 
01253         /* Calculate natural drive number */
01254         int13_sync_num_drives();
01255         natural_drive = ( ( drive & 0x80 ) ? ( num_drives | 0x80 ) : num_fdds );
01256 
01257         /* Use natural drive number if directed to do so */
01258         if ( ( drive & 0x7f ) == 0x7f )
01259                 drive = natural_drive;
01260 
01261         /* Allocate SAN device */
01262         sandev = alloc_sandev ( uris, count, sizeof ( *int13 ) );
01263         if ( ! sandev ) {
01264                 rc = -ENOMEM;
01265                 goto err_alloc;
01266         }
01267         int13 = sandev->priv;
01268         int13->natural_drive = natural_drive;
01269 
01270         /* Register SAN device */
01271         if ( ( rc = register_sandev ( sandev, drive, flags ) ) != 0 ) {
01272                 DBGC ( sandev, "INT13 drive %02x could not register: %s\n",
01273                        drive, strerror ( rc ) );
01274                 goto err_register;
01275         }
01276 
01277         /* Allocate scratch area */
01278         scratch = malloc ( sandev_blksize ( sandev ) );
01279         if ( ! scratch )
01280                 goto err_alloc_scratch;
01281 
01282         /* Parse parameters, if present */
01283         if ( sandev->is_cdrom &&
01284              ( ( rc = int13_parse_eltorito ( sandev, scratch ) ) != 0 ) )
01285                 goto err_parse_eltorito;
01286 
01287         /* Give drive a default geometry, if applicable */
01288         if ( ( sandev_blksize ( sandev ) == INT13_BLKSIZE ) &&
01289              ( ( rc = int13_guess_geometry ( sandev, scratch ) ) != 0 ) )
01290                 goto err_guess_geometry;
01291 
01292         DBGC ( sandev, "INT13 drive %02x (naturally %02x) registered with "
01293                "C/H/S geometry %d/%d/%d\n",
01294                sandev->drive, int13->natural_drive, int13->cylinders,
01295                int13->heads, int13->sectors_per_track );
01296 
01297         /* Hook INT 13 vector if not already hooked */
01298         if ( need_hook ) {
01299                 int13_hook_vector();
01300                 devices_get();
01301         }
01302 
01303         /* Update BIOS drive count */
01304         int13_sync_num_drives();
01305 
01306         free ( scratch );
01307         return drive;
01308 
01309  err_guess_geometry:
01310  err_parse_eltorito:
01311         free ( scratch );
01312  err_alloc_scratch:
01313         unregister_sandev ( sandev );
01314  err_register:
01315         sandev_put ( sandev );
01316  err_alloc:
01317         return rc;
01318 }
01319 
01320 /**
01321  * Unhook INT 13 SAN device
01322  *
01323  * @v drive             Drive number
01324  *
01325  * Unregisters the drive from the INT 13 emulation subsystem.  If this
01326  * is the last SAN device, the INT 13 vector is unhooked (if
01327  * possible).
01328  */
01329 static void int13_unhook ( unsigned int drive ) {
01330         struct san_device *sandev;
01331 
01332         /* Find drive */
01333         sandev = sandev_find ( drive );
01334         if ( ! sandev ) {
01335                 DBG ( "INT13 cannot find drive %02x\n", drive );
01336                 return;
01337         }
01338 
01339         /* Unregister SAN device */
01340         unregister_sandev ( sandev );
01341 
01342         /* Should adjust BIOS drive count, but it's difficult
01343          * to do so reliably.
01344          */
01345 
01346         DBGC ( sandev, "INT13 drive %02x unregistered\n", sandev->drive );
01347 
01348         /* Unhook INT 13 vector if no more drives */
01349         if ( ! have_sandevs() ) {
01350                 devices_put();
01351                 int13_unhook_vector();
01352         }
01353 
01354         /* Drop reference to drive */
01355         sandev_put ( sandev );
01356 }
01357 
01358 /**
01359  * Load and verify master boot record from INT 13 drive
01360  *
01361  * @v drive             Drive number
01362  * @v address           Boot code address to fill in
01363  * @ret rc              Return status code
01364  */
01365 static int int13_load_mbr ( unsigned int drive, struct segoff *address ) {
01366         uint16_t status;
01367         int discard_b, discard_c, discard_d;
01368         uint16_t magic;
01369 
01370         /* Use INT 13, 02 to read the MBR */
01371         address->segment = 0;
01372         address->offset = 0x7c00;
01373         __asm__ __volatile__ ( REAL_CODE ( "pushw %%es\n\t"
01374                                            "pushl %%ebx\n\t"
01375                                            "popw %%bx\n\t"
01376                                            "popw %%es\n\t"
01377                                            "stc\n\t"
01378                                            "sti\n\t"
01379                                            "int $0x13\n\t"
01380                                            "sti\n\t" /* BIOS bugs */
01381                                            "jc 1f\n\t"
01382                                            "xorw %%ax, %%ax\n\t"
01383                                            "\n1:\n\t"
01384                                            "popw %%es\n\t" )
01385                                : "=a" ( status ), "=b" ( discard_b ),
01386                                  "=c" ( discard_c ), "=d" ( discard_d )
01387                                : "a" ( 0x0201 ), "b" ( *address ),
01388                                  "c" ( 1 ), "d" ( drive ) );
01389         if ( status ) {
01390                 DBG ( "INT13 drive %02x could not read MBR (status %04x)\n",
01391                       drive, status );
01392                 return -EIO;
01393         }
01394 
01395         /* Check magic signature */
01396         get_real ( magic, address->segment,
01397                    ( address->offset +
01398                      offsetof ( struct master_boot_record, magic ) ) );
01399         if ( magic != INT13_MBR_MAGIC ) {
01400                 DBG ( "INT13 drive %02x does not contain a valid MBR\n",
01401                       drive );
01402                 return -ENOEXEC;
01403         }
01404 
01405         return 0;
01406 }
01407 
01408 /** El Torito boot catalog command packet */
01409 static struct int13_cdrom_boot_catalog_command __data16 ( eltorito_cmd ) = {
01410         .size = sizeof ( struct int13_cdrom_boot_catalog_command ),
01411         .count = 1,
01412         .buffer = 0x7c00,
01413         .start = 0,
01414 };
01415 #define eltorito_cmd __use_data16 ( eltorito_cmd )
01416 
01417 /** El Torito disk address packet */
01418 static struct int13_disk_address __bss16 ( eltorito_address );
01419 #define eltorito_address __use_data16 ( eltorito_address )
01420 
01421 /**
01422  * Load and verify El Torito boot record from INT 13 drive
01423  *
01424  * @v drive             Drive number
01425  * @v address           Boot code address to fill in
01426  * @ret rc              Return status code
01427  */
01428 static int int13_load_eltorito ( unsigned int drive, struct segoff *address ) {
01429         struct {
01430                 struct eltorito_validation_entry valid;
01431                 struct eltorito_boot_entry boot;
01432         } __attribute__ (( packed )) catalog;
01433         uint16_t status;
01434 
01435         /* Use INT 13, 4d to read the boot catalog */
01436         __asm__ __volatile__ ( REAL_CODE ( "stc\n\t"
01437                                            "sti\n\t"
01438                                            "int $0x13\n\t"
01439                                            "sti\n\t" /* BIOS bugs */
01440                                            "jc 1f\n\t"
01441                                            "xorw %%ax, %%ax\n\t"
01442                                            "\n1:\n\t" )
01443                                : "=a" ( status )
01444                                : "a" ( 0x4d00 ), "d" ( drive ),
01445                                  "S" ( __from_data16 ( &eltorito_cmd ) ) );
01446         if ( status ) {
01447                 DBG ( "INT13 drive %02x could not read El Torito boot catalog "
01448                       "(status %04x)\n", drive, status );
01449                 return -EIO;
01450         }
01451         copy_from_user ( &catalog, phys_to_user ( eltorito_cmd.buffer ), 0,
01452                          sizeof ( catalog ) );
01453 
01454         /* Sanity checks */
01455         if ( catalog.valid.platform_id != ELTORITO_PLATFORM_X86 ) {
01456                 DBG ( "INT13 drive %02x El Torito specifies unknown platform "
01457                       "%02x\n", drive, catalog.valid.platform_id );
01458                 return -ENOEXEC;
01459         }
01460         if ( catalog.boot.indicator != ELTORITO_BOOTABLE ) {
01461                 DBG ( "INT13 drive %02x El Torito is not bootable\n", drive );
01462                 return -ENOEXEC;
01463         }
01464         if ( catalog.boot.media_type != ELTORITO_NO_EMULATION ) {
01465                 DBG ( "INT13 drive %02x El Torito requires emulation "
01466                        "type %02x\n", drive, catalog.boot.media_type );
01467                 return -ENOTSUP;
01468         }
01469         DBG ( "INT13 drive %02x El Torito boot image at LBA %08x (count %d)\n",
01470               drive, catalog.boot.start, catalog.boot.length );
01471         address->segment = ( catalog.boot.load_segment ?
01472                              catalog.boot.load_segment : 0x7c0 );
01473         address->offset = 0;
01474         DBG ( "INT13 drive %02x El Torito boot image loads at %04x:%04x\n",
01475               drive, address->segment, address->offset );
01476 
01477         /* Use INT 13, 42 to read the boot image */
01478         eltorito_address.bufsize =
01479                 offsetof ( typeof ( eltorito_address ), buffer_phys );
01480         eltorito_address.count = catalog.boot.length;
01481         eltorito_address.buffer = *address;
01482         eltorito_address.lba = catalog.boot.start;
01483         __asm__ __volatile__ ( REAL_CODE ( "stc\n\t"
01484                                            "sti\n\t"
01485                                            "int $0x13\n\t"
01486                                            "sti\n\t" /* BIOS bugs */
01487                                            "jc 1f\n\t"
01488                                            "xorw %%ax, %%ax\n\t"
01489                                            "\n1:\n\t" )
01490                                : "=a" ( status )
01491                                : "a" ( 0x4200 ), "d" ( drive ),
01492                                  "S" ( __from_data16 ( &eltorito_address ) ) );
01493         if ( status ) {
01494                 DBG ( "INT13 drive %02x could not read El Torito boot image "
01495                       "(status %04x)\n", drive, status );
01496                 return -EIO;
01497         }
01498 
01499         return 0;
01500 }
01501 
01502 /**
01503  * Attempt to boot from an INT 13 drive
01504  *
01505  * @v drive             Drive number
01506  * @v filename          Filename (or NULL to use default)
01507  * @ret rc              Return status code
01508  *
01509  * This boots from the specified INT 13 drive by loading the Master
01510  * Boot Record to 0000:7c00 and jumping to it.  INT 18 is hooked to
01511  * capture an attempt by the MBR to boot the next device.  (This is
01512  * the closest thing to a return path from an MBR).
01513  *
01514  * Note that this function can never return success, by definition.
01515  */
01516 static int int13_boot ( unsigned int drive, const char *filename __unused ) {
01517         struct memory_map memmap;
01518         struct segoff address;
01519         int rc;
01520 
01521         /* Look for a usable boot sector */
01522         if ( ( ( rc = int13_load_mbr ( drive, &address ) ) != 0 ) &&
01523              ( ( rc = int13_load_eltorito ( drive, &address ) ) != 0 ) )
01524                 return rc;
01525 
01526         /* Dump out memory map prior to boot, if memmap debugging is
01527          * enabled.  Not required for program flow, but we have so
01528          * many problems that turn out to be memory-map related that
01529          * it's worth doing.
01530          */
01531         get_memmap ( &memmap );
01532 
01533         /* Jump to boot sector */
01534         if ( ( rc = call_bootsector ( address.segment, address.offset,
01535                                       drive ) ) != 0 ) {
01536                 DBG ( "INT13 drive %02x boot returned: %s\n",
01537                       drive, strerror ( rc ) );
01538                 return rc;
01539         }
01540 
01541         return -ECANCELED; /* -EIMPOSSIBLE */
01542 }
01543 
01544 /** Maximum size of boot firmware table(s) */
01545 #define XBFTAB_SIZE 768
01546 
01547 /** Alignment of boot firmware table entries */
01548 #define XBFTAB_ALIGN 16
01549 
01550 /** The boot firmware table(s) generated by iPXE */
01551 static uint8_t __bss16_array ( xbftab, [XBFTAB_SIZE] )
01552         __attribute__ (( aligned ( XBFTAB_ALIGN ) ));
01553 #define xbftab __use_data16 ( xbftab )
01554 
01555 /** Total used length of boot firmware tables */
01556 static size_t xbftab_used;
01557 
01558 /**
01559  * Install ACPI table
01560  *
01561  * @v acpi              ACPI description header
01562  * @ret rc              Return status code
01563  */
01564 static int int13_install ( struct acpi_header *acpi ) {
01565         struct segoff xbft_address;
01566         struct acpi_header *installed;
01567         size_t len;
01568 
01569         /* Check length */
01570         len = acpi->length;
01571         if ( len > ( sizeof ( xbftab ) - xbftab_used ) ) {
01572                 DBGC ( acpi, "INT13 out of space for %s table\n",
01573                        acpi_name ( acpi->signature ) );
01574                 return -ENOSPC;
01575         }
01576 
01577         /* Install table */
01578         installed = ( ( ( void * ) xbftab ) + xbftab_used );
01579         memcpy ( installed, acpi, len );
01580         xbft_address.segment = rm_ds;
01581         xbft_address.offset = __from_data16 ( installed );
01582 
01583         /* Fill in common parameters */
01584         strncpy ( installed->oem_id, "FENSYS",
01585                   sizeof ( installed->oem_id ) );
01586         strncpy ( installed->oem_table_id, "iPXE",
01587                   sizeof ( installed->oem_table_id ) );
01588 
01589         /* Fix checksum */
01590         acpi_fix_checksum ( installed );
01591 
01592         /* Update used length */
01593         xbftab_used = ( ( xbftab_used + len + XBFTAB_ALIGN - 1 ) &
01594                         ~( XBFTAB_ALIGN - 1 ) );
01595 
01596         DBGC ( acpi, "INT13 installed %s:\n",
01597                acpi_name ( installed->signature ) );
01598         DBGC_HDA ( acpi, xbft_address, installed, len );
01599         return 0;
01600 }
01601 
01602 /**
01603  * Describe SAN devices for SAN-booted operating system
01604  *
01605  * @ret rc              Return status code
01606  */
01607 static int int13_describe ( void ) {
01608         int rc;
01609 
01610         /* Clear tables */
01611         memset ( &xbftab, 0, sizeof ( xbftab ) );
01612         xbftab_used = 0;
01613 
01614         /* Install ACPI tables */
01615         if ( ( rc = acpi_install ( int13_install ) ) != 0 ) {
01616                 DBG ( "INT13 could not install ACPI tables: %s\n",
01617                       strerror ( rc ) );
01618                 return rc;
01619         }
01620 
01621         return 0;
01622 }
01623 
01624 PROVIDE_SANBOOT ( pcbios, san_hook, int13_hook );
01625 PROVIDE_SANBOOT ( pcbios, san_unhook, int13_unhook );
01626 PROVIDE_SANBOOT ( pcbios, san_boot, int13_boot );
01627 PROVIDE_SANBOOT ( pcbios, san_describe, int13_describe );