/
FreeSpaceBitSet.java
322 lines (292 loc) · 9.89 KB
/
FreeSpaceBitSet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*
* Copyright 2004-2024 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (https://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.mvstore;
import java.util.BitSet;
import org.h2.util.MathUtils;
/**
* A free space bit set.
*/
public class FreeSpaceBitSet {
private static final boolean DETAILED_INFO = false;
/**
* The first usable block.
*/
private final int firstFreeBlock;
/**
* The block size in bytes.
*/
private final int blockSize;
/**
* The bit set.
*/
private final BitSet set = new BitSet();
/**
* Left-shifting register, which holds outcomes of recent allocations. Only
* allocations done in "reuseSpace" mode are recorded here. For example,
* rightmost bit set to 1 means that last allocation failed to find a hole
* big enough, and next bit set to 0 means that previous allocation request
* have found one.
*/
private int failureFlags;
/**
* Create a new free space map.
*
* @param firstFreeBlock the first free block
* @param blockSize the block size
*/
public FreeSpaceBitSet(int firstFreeBlock, int blockSize) {
this.firstFreeBlock = firstFreeBlock;
this.blockSize = blockSize;
clear();
}
/**
* Reset the list.
*/
public void clear() {
set.clear();
set.set(0, firstFreeBlock);
}
/**
* Check whether one of the blocks is in use.
*
* @param pos the position in bytes
* @param length the number of bytes
* @return true if a block is in use
*/
public boolean isUsed(long pos, int length) {
int start = getBlock(pos);
int blocks = getBlockCount(length);
for (int i = start; i < start + blocks; i++) {
if (!set.get(i)) {
return false;
}
}
return true;
}
/**
* Check whether one of the blocks is free.
*
* @param pos the position in bytes
* @param length the number of bytes
* @return true if a block is free
*/
public boolean isFree(long pos, int length) {
int start = getBlock(pos);
int blocks = getBlockCount(length);
for (int i = start; i < start + blocks; i++) {
if (set.get(i)) {
return false;
}
}
return true;
}
/**
* Allocate a number of blocks and mark them as used.
*
* @param length the number of bytes to allocate
* @return the start position in bytes
*/
public long allocate(int length) {
return allocate(length, 0, 0);
}
/**
* Allocate a number of blocks and mark them as used.
*
* @param length the number of bytes to allocate
* @param reservedLow start block index of the reserved area (inclusive)
* @param reservedHigh end block index of the reserved area (exclusive),
* special value -1 means beginning of the infinite free area
* @return the start position in bytes
*/
long allocate(int length, long reservedLow, long reservedHigh) {
return getPos(allocate(getBlockCount(length), (int)reservedLow, (int)reservedHigh, true));
}
/**
* Calculate starting position of the prospective allocation.
*
* @param blocks the number of blocks to allocate
* @param reservedLow start block index of the reserved area (inclusive)
* @param reservedHigh end block index of the reserved area (exclusive),
* special value -1 means beginning of the infinite free area
* @return the starting block index
*/
long predictAllocation(int blocks, long reservedLow, long reservedHigh) {
return allocate(blocks, (int)reservedLow, (int)reservedHigh, false);
}
boolean isFragmented() {
return Integer.bitCount(failureFlags & 0x0F) > 1;
}
private int allocate(int blocks, int reservedLow, int reservedHigh, boolean allocate) {
int freeBlocksTotal = 0;
for (int i = 0;;) {
int start = set.nextClearBit(i);
int end = set.nextSetBit(start + 1);
int freeBlocks = end - start;
if (end < 0 || freeBlocks >= blocks) {
if ((reservedHigh < 0 || start < reservedHigh) && start + blocks > reservedLow) { // overlap detected
if (reservedHigh >= 0) {
freeBlocksTotal += freeBlocks;
i = reservedHigh;
continue;
}
}
assert set.nextSetBit(start) == -1 || set.nextSetBit(start) >= start + blocks :
"Double alloc: " + Integer.toHexString(start) + "/" + Integer.toHexString(blocks) + " " + this;
if (allocate) {
set.set(start, start + blocks);
} else {
failureFlags <<= 1;
if (end < 0 && freeBlocksTotal > 4 * blocks) {
failureFlags |= 1;
}
}
return start;
}
freeBlocksTotal += freeBlocks;
i = end;
}
}
/**
* Mark the space as in use.
*
* @param pos the position in bytes
* @param length the number of bytes
*/
public void markUsed(long pos, int length) {
int start = getBlock(pos);
int blocks = getBlockCount(length);
// this is not an assert because we get called during file opening
if (set.nextSetBit(start) != -1 && set.nextSetBit(start) < start + blocks ) {
throw DataUtils.newMVStoreException(
DataUtils.ERROR_FILE_CORRUPT,
"Double mark: " + Integer.toHexString(start) +
"/" + Integer.toHexString(blocks) + " " + this);
}
set.set(start, start + blocks);
}
/**
* Mark the space as free.
*
* @param pos the position in bytes
* @param length the number of bytes
*/
public void free(long pos, int length) {
int start = getBlock(pos);
int blocks = getBlockCount(length);
assert set.nextClearBit(start) >= start + blocks :
"Double free: " + Integer.toHexString(start) + "/" + Integer.toHexString(blocks) + " " + this;
set.clear(start, start + blocks);
}
private long getPos(int block) {
return (long) block * (long) blockSize;
}
private int getBlock(long pos) {
return (int) (pos / blockSize);
}
private int getBlockCount(int length) {
return MathUtils.roundUpInt(length, blockSize) / blockSize;
}
/**
* Get the fill rate of the space in percent. The value 0 means the space is
* completely free, and 100 means it is completely full.
*
* @return the fill rate (0 - 100)
*/
int getFillRate() {
int usedBlocks = set.cardinality() - firstFreeBlock;
int totalBlocks = set.length() - firstFreeBlock;
return totalBlocks == 0 ? 0 : (int)((100L * usedBlocks + totalBlocks - 1) / totalBlocks);
}
/**
* Get the position of the first free space.
*
* @return the position.
*/
long getFirstFree() {
return getPos(set.nextClearBit(0));
}
/**
* Get the position of the last (infinite) free space.
*
* @return the position.
*/
long getLastFree() {
return getPos(getAfterLastBlock());
}
/**
* Get the index of the first block after last occupied one.
* It marks the beginning of the last (infinite) free space.
*
* @return block index
*/
int getAfterLastBlock() {
return set.previousSetBit(set.size() - 1) + 1;
}
/**
* Calculates relative "priority" for chunk to be moved.
*
* @param block where chunk starts
* @return priority, bigger number indicate that chunk need to be moved sooner
*/
int getMovePriority(int block) {
// The most desirable chunks to move are the ones sitting within
// a relatively short span of occupied blocks which is surrounded
// from both sides by relatively long free spans
int prevEnd = set.previousClearBit(block);
int freeSize;
if (prevEnd < 0) {
prevEnd = firstFreeBlock;
freeSize = 0;
} else {
freeSize = prevEnd - set.previousSetBit(prevEnd);
}
int nextStart = set.nextClearBit(block);
int nextEnd = set.nextSetBit(nextStart);
if (nextEnd >= 0) {
freeSize += nextEnd - nextStart;
}
return (nextStart - prevEnd - 1) * 1000 / (freeSize + 1);
}
@Override
public String toString() {
StringBuilder buff = new StringBuilder();
if (DETAILED_INFO) {
int onCount = 0, offCount = 0;
int on = 0;
for (int i = 0; i < set.length(); i++) {
if (set.get(i)) {
onCount++;
on++;
} else {
offCount++;
}
if ((i & 1023) == 1023) {
buff.append(String.format("%3x", on)).append(' ');
on = 0;
}
}
buff.append('\n')
.append(" on ").append(onCount).append(" off ").append(offCount)
.append(' ').append(100 * onCount / (onCount+offCount)).append("% used ");
}
buff.append('[');
for (int i = 0;;) {
if (i > 0) {
buff.append(", ");
}
int start = set.nextClearBit(i);
buff.append(Integer.toHexString(start)).append('-');
int end = set.nextSetBit(start + 1);
if (end < 0) {
break;
}
buff.append(Integer.toHexString(end - 1));
i = end + 1;
}
buff.append(']');
return buff.toString();
}
}