fixed lot of race conditions in kv.c