Skip to content

Instantly share code, notes, and snippets.

@bgilbert
Created March 27, 2012 23:12
Show Gist options
  • Save bgilbert/2221338 to your computer and use it in GitHub Desktop.
Save bgilbert/2221338 to your computer and use it in GitHub Desktop.
readme
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/fs.h>
#include <linux/fiemap.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#define SECTOR_OFFSET 4
int main(int argc, char **argv)
{
struct fiemap *fm;
int file;
int disk;
char obuf[512];
char ibuf[1024];
char expected[512];
unsigned char *ibufp = (unsigned char *) ((uint64_t) (ibuf + 512) & ~511ULL);
if (argc != 3) {
fprintf(stderr, "Usage: %s file block-device\n", argv[0]);
return 1;
}
fm = calloc(sizeof(struct fiemap) + sizeof(struct fiemap_extent), 1);
fm->fm_start = SECTOR_OFFSET;
fm->fm_length = 1;
fm->fm_extent_count = 1;
memset(obuf, 0xff, sizeof(obuf));
memset(expected, 0, sizeof(expected));
memset(expected, 0xff, SECTOR_OFFSET);
file = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0600);
if (file == -1) {
perror("Opening file");
return 1;
}
disk = open(argv[2], O_RDONLY | O_DIRECT);
if (disk == -1) {
perror("Opening disk");
return 1;
}
write(file, obuf, SECTOR_OFFSET);
while (1) {
uint64_t offset;
if (write(file, obuf, 512) != 512) {
fprintf(stderr, "Short write\n");
return 1;
}
fsync(file);
fm->fm_start += 512;
fm->fm_flags = 0;
if (ioctl(file, FS_IOC_FIEMAP, fm)) {
perror("ioctl failed");
return 1;
}
offset = fm->fm_extents[0].fe_physical + fm->fm_start -
fm->fm_extents[0].fe_logical;
//printf("%llu %llu\n", fm->fm_start, offset);
if (pread(disk, ibufp, 512, offset & ~511ULL) != 512) {
fprintf(stderr, "Short read\n");
return 1;
}
if (memcmp(ibufp, expected, sizeof(expected))) {
int i;
printf("fail %llu %llu\n", fm->fm_start, offset);
for (i = 0; i < 512; i++) {
printf("%02x ", ibufp[i]);
if (i % 16 == 15) {
printf("\n");
}
}
return 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment