2 * Copyright (C) 2013 Henrik Nordstrom <henrik@henriknordstrom.net>
4 * SPDX-License-Identifier: GPL-2.0+
12 #include <sandboxblockdev.h>
13 #include <asm/errno.h>
15 static struct host_block_dev host_devices[CONFIG_HOST_MAX_DEVICES];
17 static struct host_block_dev *find_host_device(int dev)
19 if (dev >= 0 && dev < CONFIG_HOST_MAX_DEVICES)
20 return &host_devices[dev];
25 static unsigned long host_block_read(struct blk_desc *block_dev,
26 unsigned long start, lbaint_t blkcnt,
29 int dev = block_dev->devnum;
30 struct host_block_dev *host_dev = find_host_device(dev);
35 if (os_lseek(host_dev->fd, start * block_dev->blksz, OS_SEEK_SET) ==
37 printf("ERROR: Invalid block %lx\n", start);
40 ssize_t len = os_read(host_dev->fd, buffer, blkcnt * block_dev->blksz);
42 return len / block_dev->blksz;
46 static unsigned long host_block_write(struct blk_desc *block_dev,
47 unsigned long start, lbaint_t blkcnt,
50 int dev = block_dev->devnum;
51 struct host_block_dev *host_dev = find_host_device(dev);
53 if (os_lseek(host_dev->fd, start * block_dev->blksz, OS_SEEK_SET) ==
55 printf("ERROR: Invalid block %lx\n", start);
58 ssize_t len = os_write(host_dev->fd, buffer, blkcnt * block_dev->blksz);
60 return len / block_dev->blksz;
64 int host_dev_bind(int dev, char *filename)
66 struct host_block_dev *host_dev = find_host_device(dev);
70 if (host_dev->blk_dev.priv) {
71 os_close(host_dev->fd);
72 host_dev->blk_dev.priv = NULL;
74 if (host_dev->filename)
75 free(host_dev->filename);
76 if (filename && *filename) {
77 host_dev->filename = strdup(filename);
79 host_dev->filename = NULL;
83 host_dev->fd = os_open(host_dev->filename, OS_O_RDWR);
84 if (host_dev->fd == -1) {
85 printf("Failed to access host backing file '%s'\n",
90 struct blk_desc *blk_dev = &host_dev->blk_dev;
91 blk_dev->if_type = IF_TYPE_HOST;
92 blk_dev->priv = host_dev;
94 blk_dev->lba = os_lseek(host_dev->fd, 0, OS_SEEK_END) / blk_dev->blksz;
95 blk_dev->block_read = host_block_read;
96 blk_dev->block_write = host_block_write;
97 blk_dev->devnum = dev;
98 blk_dev->part_type = PART_TYPE_UNKNOWN;
104 int host_get_dev_err(int devnum, struct blk_desc **blk_devp)
106 struct host_block_dev *host_dev = find_host_device(devnum);
111 if (!host_dev->blk_dev.priv)
114 *blk_devp = &host_dev->blk_dev;
118 struct blk_desc *host_get_dev(int dev)
120 struct blk_desc *blk_dev;
122 if (host_get_dev_err(dev, &blk_dev))