fs_internal.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * 2017 by Marek Behun <marek.behun@nic.cz>
  4. *
  5. * Derived from code in ext4/dev.c, which was based on reiserfs/dev.c
  6. */
  7. #include <common.h>
  8. #include <blk.h>
  9. #include <compiler.h>
  10. #include <log.h>
  11. #include <part.h>
  12. #include <memalign.h>
  13. int fs_devread(struct blk_desc *blk, struct disk_partition *partition,
  14. lbaint_t sector, int byte_offset, int byte_len, char *buf)
  15. {
  16. unsigned block_len;
  17. int log2blksz;
  18. ALLOC_CACHE_ALIGN_BUFFER(char, sec_buf, (blk ? blk->blksz : 0));
  19. if (blk == NULL) {
  20. printf("** Invalid Block Device Descriptor (NULL)\n");
  21. return 0;
  22. }
  23. log2blksz = blk->log2blksz;
  24. /* Check partition boundaries */
  25. if ((sector + ((byte_offset + byte_len - 1) >> log2blksz))
  26. >= partition->size) {
  27. printf("%s read outside partition " LBAFU "\n", __func__,
  28. sector);
  29. return 0;
  30. }
  31. /* Get the read to the beginning of a partition */
  32. sector += byte_offset >> log2blksz;
  33. byte_offset &= blk->blksz - 1;
  34. debug(" <" LBAFU ", %d, %d>\n", sector, byte_offset, byte_len);
  35. if (byte_offset != 0) {
  36. int readlen;
  37. /* read first part which isn't aligned with start of sector */
  38. if (blk_dread(blk, partition->start + sector, 1,
  39. (void *)sec_buf) != 1) {
  40. printf(" ** %s read error **\n", __func__);
  41. return 0;
  42. }
  43. readlen = min((int)blk->blksz - byte_offset,
  44. byte_len);
  45. memcpy(buf, sec_buf + byte_offset, readlen);
  46. buf += readlen;
  47. byte_len -= readlen;
  48. sector++;
  49. }
  50. if (byte_len == 0)
  51. return 1;
  52. /* read sector aligned part */
  53. block_len = byte_len & ~(blk->blksz - 1);
  54. if (block_len == 0) {
  55. ALLOC_CACHE_ALIGN_BUFFER(u8, p, blk->blksz);
  56. block_len = blk->blksz;
  57. blk_dread(blk, partition->start + sector, 1,
  58. (void *)p);
  59. memcpy(buf, p, byte_len);
  60. return 1;
  61. }
  62. if (blk_dread(blk, partition->start + sector,
  63. block_len >> log2blksz, (void *)buf) !=
  64. block_len >> log2blksz) {
  65. printf(" ** %s read error - block\n", __func__);
  66. return 0;
  67. }
  68. block_len = byte_len & ~(blk->blksz - 1);
  69. buf += block_len;
  70. byte_len -= block_len;
  71. sector += block_len / blk->blksz;
  72. if (byte_len != 0) {
  73. /* read rest of data which are not in whole sector */
  74. if (blk_dread(blk, partition->start + sector, 1,
  75. (void *)sec_buf) != 1) {
  76. printf("* %s read error - last part\n", __func__);
  77. return 0;
  78. }
  79. memcpy(buf, sec_buf, byte_len);
  80. }
  81. return 1;
  82. }