| 1 |
/** @file |
| 2 |
* @brief Master Boot Record |
| 3 |
* |
| 4 |
* Based on http://thestarman.pcministry.com/asm/mbr/PartTables.htm |
| 5 |
*/ |
| 6 |
|
| 7 |
/* |
| 8 |
* Copyright (c) 2014 Flávio J. Saraiva <[email protected]> |
| 9 |
*/ |
| 10 |
|
| 11 |
#include "fs_mbr.h" |
| 12 |
|
| 13 |
/** Decode a CHS reference */ |
| 14 |
void mbr_get_chs(m_uint8_t chs[3], m_uint16_t *cyl, m_uint8_t *head, m_uint8_t *sect) |
| 15 |
{ |
| 16 |
if (head) *head = chs[0]; |
| 17 |
if (sect) *sect = (chs[1]&0x3F); |
| 18 |
if (cyl) *cyl = ((m_uint16_t)(chs[1]&0xC0)<<2) | (chs[2]); |
| 19 |
} |
| 20 |
|
| 21 |
/** Encode a CHS reference */ |
| 22 |
void mbr_set_chs(m_uint8_t chs[3], m_uint16_t cyl, m_uint8_t head, m_uint8_t sect) |
| 23 |
{ |
| 24 |
if (cyl > MBR_CYLINDER_MAX) { |
| 25 |
/* c=1023, h=254, s=63 */ |
| 26 |
chs[0] = 0xFE; |
| 27 |
chs[1] = 0xFF; |
| 28 |
chs[2] = 0xFF; |
| 29 |
} |
| 30 |
else { |
| 31 |
chs[0] = head; |
| 32 |
chs[1] = ((m_uint8_t)(cyl>>2)&0xC0) | (sect&0x3F); |
| 33 |
chs[2] = (m_uint8_t)(cyl&0xFF); |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
/** Write MBR data */ |
| 38 |
int mbr_write_fd(int fd, struct mbr_data *mbr) |
| 39 |
{ |
| 40 |
if (!mbr) { |
| 41 |
fprintf(stderr,"mbr_write_fd: null"); |
| 42 |
return(-1); |
| 43 |
} |
| 44 |
|
| 45 |
if (lseek(fd, MBR_OFFSET, SEEK_SET) != MBR_OFFSET) { |
| 46 |
perror("mbr_write_fd: lseek"); |
| 47 |
return(-1); |
| 48 |
} |
| 49 |
|
| 50 |
if (write(fd, mbr, sizeof(*mbr)) != sizeof(*mbr)) { |
| 51 |
perror("mbr_write_fd: write"); |
| 52 |
return(-1); |
| 53 |
} |
| 54 |
|
| 55 |
return(0); |
| 56 |
} |
| 57 |
|
| 58 |
/** Read MBR data */ |
| 59 |
int mbr_read_fd(int fd, struct mbr_data *mbr) |
| 60 |
{ |
| 61 |
if (!mbr) { |
| 62 |
fprintf(stderr,"mbr_read_fd: null"); |
| 63 |
return(-1); |
| 64 |
} |
| 65 |
|
| 66 |
if (lseek(fd, MBR_OFFSET, SEEK_SET) != MBR_OFFSET) { |
| 67 |
perror("mbr_read_fd: lseek"); |
| 68 |
return(-1); |
| 69 |
} |
| 70 |
|
| 71 |
if (read(fd, mbr, sizeof(*mbr)) != sizeof(*mbr)) { |
| 72 |
perror("mbr_read_fd: read"); |
| 73 |
return(-1); |
| 74 |
} |
| 75 |
|
| 76 |
return(0); |
| 77 |
} |