xref: /haiku/src/tests/add-ons/kernel/file_systems/bfs/btree/cache.cpp (revision 4f00613311d0bd6b70fa82ce19931c41f071ea4e)
1 /* cache - emulation for the B+Tree torture test
2 **
3 ** Initial version by Axel Dörfler, axeld@pinc-software.de
4 ** This file may be used under the terms of the OpenBeOS License.
5 */
6 
7 
8 #include "cache.h"
9 
10 #include <File.h>
11 #include <List.h>
12 
13 #include <malloc.h>
14 #include <stdio.h>
15 
16 
17 /*	A note from the author: this cache implementation can only be used
18  *	with the test program, it really suites no other needs.
19  *	It's very simple and not that efficient, and simple holds the whole
20  *	file in memory, all the time.
21  */
22 
23 
24 BList gBlocks;
25 
26 
27 void
28 init_cache(BFile */*file*/,int32 /*blockSize*/)
29 {
30 }
31 
32 
33 void
34 shutdown_cache(BFile *file,int32 blockSize)
35 {
36 	for (int32 i = 0;i < gBlocks.CountItems();i++) {
37 		void *buffer = gBlocks.ItemAt(i);
38 		if (buffer == NULL) {
39 			printf("cache is corrupt!\n");
40 			exit(-1);
41 		}
42 		file->WriteAt(i * blockSize,buffer,blockSize);
43 		free(buffer);
44 	}
45 }
46 
47 
48 static status_t
49 readBlocks(BFile *file,uint32 num,uint32 size)
50 {
51 	for (uint32 i = gBlocks.CountItems(); i <= num; i++) {
52 		void *buffer = malloc(size);
53 		if (buffer == NULL)
54 			return B_NO_MEMORY;
55 
56 		gBlocks.AddItem(buffer);
57 		if (file->ReadAt(i * size,buffer,size) < B_OK)
58 			return B_IO_ERROR;
59 	}
60 	return B_OK;
61 }
62 
63 
64 int
65 cached_write(BFile *file, off_t num,const void *data,off_t numBlocks, int blockSize)
66 {
67 	//printf("cached_write(num = %Ld,data = %p,numBlocks = %Ld,blockSize = %ld)\n",num,data,numBlocks,blockSize);
68 	if (file == NULL)
69 		return B_BAD_VALUE;
70 
71 	if (num >= gBlocks.CountItems())
72 		puts("Oh no!");
73 
74 	void *buffer = gBlocks.ItemAt(num);
75 	if (buffer == NULL)
76 		return B_BAD_VALUE;
77 
78 	if (buffer != data && numBlocks == 1)
79 		memcpy(buffer,data,blockSize);
80 
81 	return B_OK;
82 }
83 
84 
85 void *
86 get_block(BFile *file, off_t num, int blockSize)
87 {
88 	//printf("get_block(num = %Ld,blockSize = %ld)\n",num,blockSize);
89 	if (file == NULL)
90 		return NULL;
91 
92 	if (num >= gBlocks.CountItems())
93 		readBlocks(file,num,blockSize);
94 
95 	return gBlocks.ItemAt(num);
96 }
97 
98 
99 int
100 release_block(BFile *file, off_t num)
101 {
102 	//printf("release_block(num = %Ld)\n",num);
103 	return 0;
104 }
105 
106 
107