fs_internal.c 2.3 KB

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