add file read/write stuff
[tfsprogs.git] / utils.c
blob1304d10bafbd7bbedce66647d9e01437cd326009
1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 #include <sys/stat.h>
6 #include "tfs.h"
8 static int fd;
10 /*
11 * Open the fs image and return the size of the fs image
13 uint32_t open_fs(char *fs)
15 struct stat stat;
17 fd = open(fs, O_RDWR);
18 if (fd < 0) {
19 printf("open error\n");
20 return;
22 fstat(fd, &stat);
24 return stat.st_size;
28 * Set the bit and return it's original value
30 int set_bit(void * addr, unsigned int nr)
32 int mask, retval;
33 unsigned char *ADDR = (unsigned char *) addr;
35 ADDR += nr >> 3;
36 mask = 1 << (nr & 0x07);
37 retval = mask & *ADDR;
38 *ADDR |= mask;
39 return retval;
42 /*
43 * Clear the bit and return it's original value
45 int clear_bit(void * addr, unsigned int nr)
47 int mask, retval;
48 unsigned char *ADDR = (unsigned char *) addr;
50 ADDR += nr >> 3;
51 mask = 1 << (nr & 0x07);
52 retval = mask & *ADDR;
53 *ADDR &= ~mask;
54 return retval;
57 int test_bit(const void * addr, unsigned int nr)
59 int mask;
60 const unsigned char *ADDR = (const unsigned char *) addr;
62 ADDR += nr >> 3;
63 mask = 1 << (nr & 0x07);
64 return (mask & *ADDR);
67 uint32_t find_first_zero(void *buf, void *end)
69 uint32_t *p = (uint32_t *)buf;
70 uint32_t block = 0;
71 int i;
73 while (*p == 0xffffffff && (void *)p < end) {
74 p++;
75 block += 32;
77 if ((void *)p >= end)
78 return -1;
80 for (i = 0; i < 32; i++)
81 if (test_bit(p, i) == 0)
82 return block + i;
85 int read_sector(uint32_t sector, void *buf, int counts)
87 if (lseek(fd, sector << 9, SEEK_SET) < 0) {
88 printf("seek error...\n");
89 return;
92 return read(fd, buf, 512 * counts);
95 int write_sector(uint32_t sector, void *buf, int counts)
97 if (lseek(fd, sector << 9, SEEK_SET) < 0) {
98 printf("seek error...\n");
99 return;
102 return write(fd, buf, 512 * counts);
105 int tfs_bread(struct tfs_sb_info *sbi, uint32_t block, void *buf)
107 uint32_t sector = (block << (sbi->s_block_shift - 9)) + sbi->s_offset;
109 return read_sector(sector, buf, 1 << (sbi->s_block_shift - 9));
112 int tfs_bwrite(struct tfs_sb_info *sbi, uint32_t block, void *buf)
114 uint32_t sector = (block << (sbi->s_block_shift - 9)) + sbi->s_offset;
116 return write_sector(sector, buf, 1 << (sbi->s_block_shift - 9));