This function will be useful for the incoming loadable support, so factor
it out of file_to_sdram().

While at it, make it a bit safer as well: Only the first page needs to
be copied with zero_page_memcpy if at all, so copy at most one page if
the zero page is overlapped and then copy the rest as usual.

file_to_sdram() is intentionally left as-is as it's going to be removed
in a later commit.

Signed-off-by: Ahmad Fatoum <[email protected]>
---
 include/libfile.h |  1 +
 lib/libfile.c     | 29 +++++++++++++++++++++++++++++
 2 files changed, 30 insertions(+)

diff --git a/include/libfile.h b/include/libfile.h
index f44046fb0f7b..f61c45563c01 100644
--- a/include/libfile.h
+++ b/include/libfile.h
@@ -11,6 +11,7 @@ int pread_full(int fd, void *buf, size_t size, loff_t offset);
 int pwrite_full(int fd, const void *buf, size_t size, loff_t offset);
 int write_full(int fd, const void *buf, size_t size);
 int read_full(int fd, void *buf, size_t size);
+int __read_full_anywhere(int fd, void *buf, size_t size);
 int copy_fd(int in, int out, size_t size);
 
 ssize_t read_file_into_buf(const char *filename, void *buf, size_t size);
diff --git a/lib/libfile.c b/lib/libfile.c
index 3be410855d2e..966350674a83 100644
--- a/lib/libfile.c
+++ b/lib/libfile.c
@@ -798,6 +798,35 @@ int cache_file(const char *path, char **newpath)
        return 0;
 }
 
+/*
+ * __read_full_anywhere - read from filedescriptor, even into zero_page
+ *
+ * Like read_full, but this function will temporarily remap the zero
+ * page if data is to be placed there. You should not need to use this
+ * outside of boot code!
+ */
+int __read_full_anywhere(int fd, void *buf, size_t size)
+{
+       ssize_t now = 0;
+
+       if (unlikely(zero_page_contains((ulong)buf))) {
+               void *tmp = malloc(PAGE_SIZE);
+               if (!tmp)
+                       return -ENOMEM;
+
+               now = read_full(fd, tmp, min_t(size_t, size, PAGE_SIZE));
+               if (now > 0)
+                       zero_page_memcpy(buf, tmp, now);
+
+               free(tmp);
+
+               if (now <= 0)
+                       return now;
+       }
+
+       return now + read_full(fd, buf + now, size - now);
+}
+
 #define BUFSIZ (PAGE_SIZE * 32)
 
 struct resource *file_to_sdram(const char *filename, unsigned long adr,
-- 
2.47.3


Reply via email to