disk_common.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* This function performs three tasks:
  2. - Make sectors disk relative from partition relative.
  3. - Normalize offset to be less than the sector size.
  4. - Verify that the range is inside the partition. */
  5. static grub_err_t
  6. grub_disk_adjust_range (grub_disk_t disk, grub_disk_addr_t *sector,
  7. grub_off_t *offset, grub_size_t size)
  8. {
  9. grub_partition_t part;
  10. grub_disk_addr_t total_sectors;
  11. *sector += *offset >> GRUB_DISK_SECTOR_BITS;
  12. *offset &= GRUB_DISK_SECTOR_SIZE - 1;
  13. for (part = disk->partition; part; part = part->parent)
  14. {
  15. grub_disk_addr_t start;
  16. grub_uint64_t len;
  17. start = part->start;
  18. len = part->len;
  19. if (*sector >= len
  20. || len - *sector < ((*offset + size + GRUB_DISK_SECTOR_SIZE - 1)
  21. >> GRUB_DISK_SECTOR_BITS))
  22. return grub_error (GRUB_ERR_OUT_OF_RANGE,
  23. N_("attempt to read or write outside of partition"));
  24. *sector += start;
  25. }
  26. /* Transform total_sectors to number of 512B blocks. */
  27. total_sectors = disk->total_sectors << (disk->log_sector_size - GRUB_DISK_SECTOR_BITS);
  28. /*
  29. * Some drivers have problems with disks above reasonable sizes.
  30. * Clamp the size to GRUB_DISK_MAX_SECTORS. Just one condition is enough
  31. * since GRUB_DISK_SIZE_UNKNOWN is always above GRUB_DISK_MAX_SECTORS,
  32. * assuming a maximum 4 KiB sector size.
  33. */
  34. if (total_sectors > GRUB_DISK_MAX_SECTORS)
  35. total_sectors = GRUB_DISK_MAX_SECTORS;
  36. if ((total_sectors <= *sector
  37. || ((*offset + size + GRUB_DISK_SECTOR_SIZE - 1)
  38. >> GRUB_DISK_SECTOR_BITS) > total_sectors - *sector))
  39. return grub_error (GRUB_ERR_OUT_OF_RANGE,
  40. N_("attempt to read or write outside of disk `%s'"), disk->name);
  41. return GRUB_ERR_NONE;
  42. }
  43. static unsigned
  44. grub_disk_cache_get_index (unsigned long dev_id, unsigned long disk_id,
  45. grub_disk_addr_t sector)
  46. {
  47. return ((dev_id * 524287UL + disk_id * 2606459UL
  48. + ((unsigned) (sector >> GRUB_DISK_CACHE_BITS)))
  49. % GRUB_DISK_CACHE_NUM);
  50. }