[kernel] Bug fixes and refactoring