fs_internal.c 2.3 KB

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