summaryrefslogtreecommitdiffstats
path: root/scripts
diff options
context:
space:
mode:
authorSascha Hauer <s.hauer@pengutronix.de>2021-04-14 15:23:52 +0200
committerSascha Hauer <s.hauer@pengutronix.de>2021-04-14 15:46:48 +0200
commit2154de1cf36c0ac741f258f72de6895e8782ec79 (patch)
tree059eb2c27be8918d7edf26382912549ec4962e32 /scripts
parentcc9c2d3dd0ee72730dcdb6975da520b13d1ed75c (diff)
downloadbarebox-2154de1cf36c0ac741f258f72de6895e8782ec79.tar.gz
barebox-2154de1cf36c0ac741f258f72de6895e8782ec79.tar.xz
bareboximd: Use mmap when possibly
It's hard to believe but there are systems out there that are so sparse with memory that they can't afford 1MiB of RAM to read a file into. Use mmap when possible and fall back to reading into an allocated buffer otherwise. Signed-off-by: Sascha Hauer <s.hauer@pengutronix.de>
Diffstat (limited to 'scripts')
-rw-r--r--scripts/bareboximd.c53
1 files changed, 34 insertions, 19 deletions
diff --git a/scripts/bareboximd.c b/scripts/bareboximd.c
index 9558c77d1a..c3dcb4dcf0 100644
--- a/scripts/bareboximd.c
+++ b/scripts/bareboximd.c
@@ -15,6 +15,7 @@
#include <stdarg.h>
#include <linux/err.h>
#include <linux/kernel.h>
+#include <sys/mman.h>
#include "../include/image-metadata.h"
@@ -96,29 +97,35 @@ static int read_file_2(const char *filename, size_t *size, void **outbuf, size_t
goto close;
}
- buf = malloc(max_size);
- if (!buf) {
- fprintf(stderr, "Cannot allocate memory\n");
- ret = -ENOMEM;
- goto close;
- }
+ buf = mmap(NULL, max_size, PROT_READ, MAP_SHARED, fd, 0);
+ if (buf == MAP_FAILED ) {
+ buf = malloc(max_size);
+ if (!buf) {
+ fprintf(stderr, "Cannot allocate memory\n");
+ ret = -ENOMEM;
+ goto close;
+ }
- *outbuf = buf;
- while (*size < max_size) {
- rsize = read(fd, buf, max_size-*size);
- if (rsize == 0) {
- ret = -EIO;
- goto free;
- } else if (rsize < 0) {
- if (errno == EAGAIN)
- continue;
- else {
+ *outbuf = buf;
+
+ while (*size < max_size) {
+ rsize = read(fd, buf, max_size - *size);
+ if (rsize == 0) {
+ ret = -EIO;
+ goto free;
+ }
+
+ if (rsize < 0) {
ret = -errno;
goto free;
}
- } /* ret > 0 */
- buf += rsize;
- *size += rsize;
+
+ buf += rsize;
+ *size += rsize;
+ }
+ } else {
+ *outbuf = buf;
+ *size = max_size;
}
ret = 0;
@@ -131,6 +138,14 @@ close:
return ret;
}
+static inline void read_file_2_free(void *buf)
+{
+ /*
+ * Can't free() here because buffer might be mmapped. No need
+ * to do anything as we are exitting in a moment anyway.
+ */
+}
+
static unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
{
return strtoul(cp, endp, base);