From 764bf12e00c840fa36ebb916d29aea76b7bd9537 Mon Sep 17 00:00:00 2001 From: Tomohiro Kusumi Date: Fri, 1 Dec 2023 00:01:23 -0800 Subject: [PATCH] usr.sbin/makefs/hammer2: Properly support block device for image creation Unlike regular file image, block device image creation fails if estimated image size exceeds the device size. Sparse file option is ignored. The block device blocks aren't zero cleared. --- usr.sbin/makefs/hammer2.c | 33 +++++++++++++++++++++++++++++++- usr.sbin/makefs/hammer2/hammer2_ondisk.c | 7 +++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/usr.sbin/makefs/hammer2.c b/usr.sbin/makefs/hammer2.c index aeb635c9cf..89bd27a2d0 100644 --- a/usr.sbin/makefs/hammer2.c +++ b/usr.sbin/makefs/hammer2.c @@ -839,6 +839,27 @@ hammer2_dump_fsinfo(fsinfo_t *fsopts) } static int +hammer2_setup_blkdev(const char *image, fsinfo_t *fsopts) +{ + hammer2_makefs_options_t *h2_opt = fsopts->fs_specific; + hammer2_off_t size; + + if ((fsopts->fd = open(image, O_RDWR)) == -1) { + warn("can't open `%s' for writing", image); + return -1; + } + + size = check_volume(fsopts->fd); + if (h2_opt->image_size > size) { + warnx("image size %lld exceeds %s size %lld", + (long long)h2_opt->image_size, image, (long long)size); + return -1; + } + + return 0; +} + +static int hammer2_create_image(const char *image, fsinfo_t *fsopts) { hammer2_makefs_options_t *h2_opt = fsopts->fs_specific; @@ -847,10 +868,20 @@ hammer2_create_image(const char *image, fsinfo_t *fsopts) char *buf; int i, bufsize, oflags; off_t bufrem; + struct stat st; assert(image != NULL); assert(fsopts != NULL); + /* check if image is blk or chr */ + if (stat(image, &st) == 0) { + if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) { + if (hammer2_setup_blkdev(image, fsopts)) + return -1; + goto done; + } + } + /* create image */ oflags = O_RDWR | O_CREAT; if (fsopts->offset == 0) @@ -901,7 +932,7 @@ hammer2_create_image(const char *image, fsinfo_t *fsopts) } if (buf) free(buf); - +done: /* make the file system */ if (debug & DEBUG_FS_CREATE_IMAGE) APRINTF("calling mkfs(\"%s\", ...)\n", image); diff --git a/usr.sbin/makefs/hammer2/hammer2_ondisk.c b/usr.sbin/makefs/hammer2/hammer2_ondisk.c index b70246e71d..66615d6f9b 100644 --- a/usr.sbin/makefs/hammer2/hammer2_ondisk.c +++ b/usr.sbin/makefs/hammer2/hammer2_ondisk.c @@ -464,6 +464,8 @@ hammer2_read_volume_header(struct m_vnode *devvp, const char *path, hammer2_volume_data_t *vd; struct m_buf *bp = NULL; hammer2_crc32_t crc0, crc1; + hammer2_off_t size = check_volume(devvp->fs->fd); + off_t blkoff; int zone = -1; int i; @@ -475,6 +477,11 @@ hammer2_read_volume_header(struct m_vnode *devvp, const char *path, * block device's EOF. */ for (i = 0; i < HAMMER2_NUM_VOLHDRS; ++i) { + /* ignore if blkoff is beyond media size */ + blkoff = (off_t)i * HAMMER2_ZONE_BYTES64; + if (blkoff >= (off_t)size) + continue; + if (breadx(devvp, i * HAMMER2_ZONE_BYTES64, HAMMER2_VOLUME_BYTES, &bp)) { brelse(bp); -- 2.11.4.GIT