+ ASSERT(b);
+
+ if (!kblock_buffered(b))
+ return 0;
+
+ if (kblock_cacheDirty(b))
+ {
+ LOG_INFO("flushing block %d\n", b->priv.curr_blk);
+ if (kblock_store(b, b->priv.curr_blk) == 0)
+ kblock_setDirty(b, false);
+ else
+ return EOF;
+ }
+ return 0;
+}
+
+
+static bool kblock_loadPage(struct KBlock *b, block_idx_t idx)
+{
+ ASSERT(b);
+
+ if (idx != b->priv.curr_blk)
+ {
+ LOG_INFO("loading block %d\n", idx);
+ if (kblock_flush(b) != 0 || kblock_load(b, idx) != 0)
+ return false;
+
+ b->priv.curr_blk = idx;
+ }
+ return true;
+}
+
+
+size_t kblock_write(struct KBlock *b, block_idx_t idx, const void *buf, size_t offset, size_t size)
+{
+ ASSERT(b);
+ ASSERT(buf);
+ ASSERT(idx < b->blk_cnt);
+ ASSERT(offset + size <= b->blk_size);
+
+ LOG_INFO("blk_idx %d, offset %d, size %d\n", idx, offset, size);
+
+ if (kblock_buffered(b))
+ {
+ if (!kblock_loadPage(b, idx))
+ return 0;
+
+ kblock_setDirty(b, true);
+ return kblock_writeBuf(b, buf, offset, size);
+ }
+ else
+ {
+ #ifdef _DEBUG
+ if (offset != 0 || size != b->blk_size)
+ ASSERT(kblock_partialWrite(b));
+ #endif
+ return kblock_writeDirect(b, idx, buf, offset, size);
+ }
+}
+
+int kblock_copy(struct KBlock *b, block_idx_t src, block_idx_t dest)
+{
+ ASSERT(b);
+ ASSERT(src < b->blk_cnt);
+ ASSERT(dest < b->blk_cnt);
+
+ if (kblock_buffered(b))
+ {
+ if (!kblock_loadPage(b, src))
+ return EOF;
+
+ b->priv.curr_blk = dest;
+ kblock_setDirty(b, true);
+ return 0;
+ }
+ else if (kblock_partialWrite(b))
+ {
+ uint8_t buf[16];
+ size_t blk_size = b->blk_size;
+ size_t offset = 0;
+
+ while (blk_size)
+ {
+ size_t size = MIN(sizeof(buf), blk_size);
+ if (kblock_readDirect(b, src, buf, offset, size) != size)
+ return EOF;
+ if (kblock_writeDirect(b, dest, buf, offset, size) != size)
+ return EOF;
+
+ blk_size -= size;
+ offset += size;
+ }
+ return 0;
+ }
+ else
+ {
+ ASSERT(0);
+ return EOF;
+ }
+}
+
+int kblock_swLoad(struct KBlock *b, block_idx_t index)
+{
+ return (kblock_readDirect(b, index, b->priv.buf, 0, b->blk_size) == b->blk_size) ? 0 : EOF;
+}
+
+int kblock_swStore(struct KBlock *b, block_idx_t index)
+{
+ return (kblock_writeDirect(b, index, b->priv.buf, 0, b->blk_size) == b->blk_size) ? 0 : EOF;
+}
+
+size_t kblock_swReadBuf(struct KBlock *b, void *buf, size_t offset, size_t size)
+{
+ ASSERT(buf);
+ ASSERT(offset + size <= b->blk_size);
+
+ memcpy(buf, (uint8_t *)b->priv.buf + offset, size);
+ return size;