Two fixes
[tfsprogs.git] / balloc.c
blob9dbac757121af26da324b149043386b3641721a0
1 #include <stdio.h>
2 #include <malloc.h>
4 #include "tfs.h"
6 static void * tfs_read_block_bitmap(struct tfs_sb_info *sbi)
8 char *buf = malloc(sbi->s_block_size);
10 tfs_bread(sbi, sbi->s_block_bitmap, buf);
12 return buf;
16 * Free a block, return -1 if failed, or return 0
18 int tfs_free_block(struct tfs_sb_info *sbi, uint32_t block)
20 char *bitmap = tfs_read_block_bitmap(sbi);
22 if (clear_bit(bitmap, block) == 0) {
23 printf("ERROR: trying to free an free block!\n");
24 free(bitmap);
25 return -1;
28 tfs_bwrite(sbi, sbi->s_block_bitmap, bitmap);
29 free(bitmap);
30 return block;
33 int tfs_alloc_block(struct tfs_sb_info *sbi, uint32_t block)
35 char *bitmap = tfs_read_block_bitmap(sbi);
37 /* try the target first */
38 if (test_bit(bitmap, block) != 0)
39 block = find_first_zero(bitmap, bitmap + sbi->s_block_size);
40 if (block != -1) {
41 set_bit(bitmap, block);
42 tfs_bwrite(sbi, sbi->s_block_bitmap, bitmap);
45 free(bitmap);
46 return block;
49 #if 0 /* the deubg part */
50 #include <stdlib.h>
51 int main(int argc, char *argv[])
53 int i;
54 int block;
55 struct tfs_sb_info *sbi;
56 char *fs = argv[1];
57 char *command = argv[2];
58 char **blocks = argv + 3;
59 int count = argc - 3;
61 if (argc < 4) {
62 printf("Usage: balloc tfs.img command blocks...\n");
63 printf(" alloc, to alloc blocks\n");
64 printf(" feee, to free blocks\n");
65 return 1;
68 sbi = tfs_mount_by_fsname(fs);
69 if (!sbi) {
70 printf("tfs mount failed!\n");
71 return 1;
74 if (strcmp(command, "alloc") == 0) {
75 for (i = 0; i < count; i++) {
76 block = atoi(blocks[i]);
77 printf("trying to alloc block %u\n", block);
78 block = tfs_alloc_block(sbi, block);
79 printf("block number: %u allocated\n", block);
81 } else if (strcmp(command, "free") == 0) {
82 for (i = 0; i < count; i++) {
83 block = atoi(blocks[i]);
84 printf("trying to free block %u\n", block);
85 block = tfs_free_block(sbi, block);
86 printf("block number: %u freed\n", block);
88 } else {
89 printf("Unknown command!\n");
92 return 0;
94 #endif