Index: HelenOS.config
===================================================================
--- HelenOS.config	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ HelenOS.config	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -89,5 +89,5 @@
 @ "tmpfs" TMPFS image
 @ "fat" FAT16 image
-@ "ext2fs" EXT2 image
+@ "ext4fs" ext4 image
 ! RDFMT (choice)
 
@@ -589,5 +589,5 @@
 @ "ganged" Root hub ports are all powered or all off.
 @ "per_port" Powered status of every root hub port is independent.
-! [PLATFORM=ia32|PLATFORM=amd64] OHCI_POWER_SWITCH (choice)
+! [PLATFORM=ia32|PLATFORM=amd64|PLATFORM=ppc32] OHCI_POWER_SWITCH (choice)
 
 % GRUB boot loader architecture
Index: abi/include/ddi/irq.h
===================================================================
--- abi/include/ddi/irq.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ abi/include/ddi/irq.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -42,44 +42,74 @@
 
 typedef enum {
-	/** Read 1 byte from the I/O space. */
+	/** Read 1 byte from the I/O space.
+	 *
+	 * *addr(8) -> scratch[dstarg]
+	 */
 	CMD_PIO_READ_8 = 1,
-	/** Read 2 bytes from the I/O space. */
+	
+	/** Read 2 bytes from the I/O space.
+	 *
+	 * *addr(16) -> scratch[dstarg]
+	 */
 	CMD_PIO_READ_16,
-	/** Read 4 bytes from the I/O space. */
+	
+	/** Read 4 bytes from the I/O space.
+	 *
+	 * *addr(32) -> scratch[dstarg]
+	 */
 	CMD_PIO_READ_32,
 	
-	/** Write 1 byte to the I/O space. */
+	/** Write 1 byte to the I/O space.
+	 *
+	 * value(8) -> *addr
+	 */
 	CMD_PIO_WRITE_8,
-	/** Write 2 bytes to the I/O space. */
+	
+	/** Write 2 bytes to the I/O space.
+	 *
+	 * value(16) -> *addr
+	 */
 	CMD_PIO_WRITE_16,
-	/** Write 4 bytes to the I/O space. */
+	
+	/** Write 4 bytes to the I/O space.
+	 *
+	 * value(32) -> *addr
+	 */
 	CMD_PIO_WRITE_32,
 	
-	/**
-	 * Write 1 byte from the source argument
-	 * to the I/O space.
+	/** Write 1 byte to the I/O space.
+	 *
+	 * scratch[srcarg](8) -> *addr
 	 */
 	CMD_PIO_WRITE_A_8,
-	/**
-	 * Write 2 bytes from the source argument
-	 * to the I/O space.
+	
+	/** Write 2 bytes to the I/O space.
+	 *
+	 * scratch[srcarg](16) -> *addr
 	 */
 	CMD_PIO_WRITE_A_16,
-	/**
-	 * Write 4 bytes from the source argument
-	 * to the I/O space.
+	
+	/** Write 4 bytes to the I/O space.
+	 *
+	 * scratch[srcarg](32) -> *addr
 	 */
 	CMD_PIO_WRITE_A_32,
 	
-	/**
-	 * Perform a bit masking on the source argument
-	 * and store the result into the destination argument.
+	/** Load value.
+	 *
+	 * value -> scratch[dstarg]
 	 */
-	CMD_BTEST,
+	CMD_LOAD,
 	
-	/**
-	 * Predicate the execution of the following
-	 * N commands by the boolean value of the source
-	 * argument.
+	/** Perform bitwise conjunction.
+	 *
+	 * scratch[srcarg] & value -> scratch[dstarg]
+	 */
+	CMD_AND,
+	
+	/** Predicate the execution of the following commands.
+	 *
+	 * if (scratch[srcarg] == 0)
+	 *  (skip the following 'value' commands)
 	 */
 	CMD_PREDICATE,
Index: abi/include/syscall.h
===================================================================
--- abi/include/syscall.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ abi/include/syscall.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -63,6 +63,4 @@
 	SYS_PAGE_FIND_MAPPING,
 	
-	SYS_IPC_CALL_SYNC_FAST,
-	SYS_IPC_CALL_SYNC_SLOW,
 	SYS_IPC_CALL_ASYNC_FAST,
 	SYS_IPC_CALL_ASYNC_SLOW,
Index: boot/Makefile
===================================================================
--- boot/Makefile	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ boot/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -47,6 +47,6 @@
 	$(MKFAT) 1048576 $(DIST_PATH) $@
 endif
-ifeq ($(RDFMT),ext2fs)
-	$(MKEXT2) 1048576 $(DIST_PATH) $@
+ifeq ($(RDFMT),ext4fs)
+	$(MKEXT4) 1048576 $(DIST_PATH) $@
 endif
 
Index: boot/Makefile.common
===================================================================
--- boot/Makefile.common	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ boot/Makefile.common	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -55,5 +55,5 @@
 MKTMPFS = $(TOOLS_PATH)/mktmpfs.py
 MKFAT = $(TOOLS_PATH)/mkfat.py
-MKEXT2 = $(TOOLS_PATH)/mkext2.py
+MKEXT4 = $(TOOLS_PATH)/mkext4.py
 MKUIMAGE = $(TOOLS_PATH)/mkuimage.py
 
@@ -84,6 +84,6 @@
 endif
 
-ifeq ($(RDFMT),ext2fs)
-	INIT_TASKS += $(USPACE_PATH)/srv/fs/ext2fs/ext2fs
+ifeq ($(RDFMT),ext4fs)
+	INIT_TASKS += $(USPACE_PATH)/srv/fs/ext4fs/ext4fs
 endif
 
@@ -98,4 +98,5 @@
 	$(USPACE_PATH)/srv/bd/part/guid_part/g_part \
 	$(USPACE_PATH)/srv/bd/part/mbr_part/mbr_part \
+	$(USPACE_PATH)/srv/bd/sata_bd/sata_bd \
 	$(USPACE_PATH)/srv/clipboard/clipboard \
 	$(USPACE_PATH)/srv/fs/tmpfs/tmpfs \
@@ -105,4 +106,5 @@
 	$(USPACE_PATH)/srv/fs/exfat/exfat \
 	$(USPACE_PATH)/srv/fs/ext2fs/ext2fs \
+	$(USPACE_PATH)/srv/fs/ext4fs/ext4fs \
 	$(USPACE_PATH)/srv/hid/remcons/remcons \
 	$(USPACE_PATH)/srv/net/ethip/ethip \
@@ -122,5 +124,6 @@
 	nic/ne2k \
 	nic/e1k \
-	nic/rtl8139
+	nic/rtl8139 \
+	block/ahci
 
 RD_DRV_CFG =
@@ -171,4 +174,5 @@
 	$(USPACE_PATH)/app/tester/tester \
 	$(USPACE_PATH)/app/testread/testread \
+	$(USPACE_PATH)/app/testwrit/testwrit \
 	$(USPACE_PATH)/app/tetris/tetris \
 	$(USPACE_PATH)/app/trace/trace \
Index: boot/arch/ia64/Makefile.inc
===================================================================
--- boot/arch/ia64/Makefile.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ boot/arch/ia64/Makefile.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -31,7 +31,17 @@
 BFD_ARCH = ia64
 
+#
+# FIXME:
+#
+# The -fno-selective-scheduling and -fno-selective-scheduling2 options
+# should be removed as soon as a bug in GCC concerning unchecked
+# speculative loads is fixed.
+#
+# See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53975 for reference.
+#
+
 BITS = 64
 ENDIANESS = LE
-EXTRA_CFLAGS = -fno-unwind-tables -mfixed-range=f32-f127 -mno-pic -mno-sdata
+EXTRA_CFLAGS = -fno-unwind-tables -mfixed-range=f32-f127 -mno-pic -mno-sdata -fno-selective-scheduling -fno-selective-scheduling2
 
 RD_SRVS_NON_ESSENTIAL +=
Index: boot/arch/mips32/Makefile.inc
===================================================================
--- boot/arch/mips32/Makefile.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ boot/arch/mips32/Makefile.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -29,5 +29,5 @@
 BFD_ARCH = mips
 BITS = 32
-EXTRA_CFLAGS = -mno-abicalls -G 0 -fno-zero-initialized-in-bss -mips3 -mabi=32
+EXTRA_CFLAGS = -msoft-float -mno-abicalls -G 0 -fno-zero-initialized-in-bss -mips3 -mabi=32
 
 RD_SRVS_NON_ESSENTIAL += \
@@ -48,5 +48,4 @@
 	BFD_OUTPUT = binary
 	ENDIANESS = LE
-	EXTRA_GCC_CFLAGS = -mhard-float
 endif
 
Index: boot/arch/mips64/Makefile.inc
===================================================================
--- boot/arch/mips64/Makefile.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ boot/arch/mips64/Makefile.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -29,5 +29,5 @@
 BFD_ARCH = mips:4000
 BITS = 64
-EXTRA_CFLAGS = -mno-abicalls -G 0 -fno-zero-initialized-in-bss -mips3 -mabi=64
+EXTRA_CFLAGS = -msoft-float -mno-abicalls -G 0 -fno-zero-initialized-in-bss -mips3 -mabi=64
 
 ifeq ($(MACHINE),msim)
@@ -35,5 +35,4 @@
 	BFD_OUTPUT = binary
 	ENDIANESS = LE
-	EXTRA_GCC_CFLAGS = -mhard-float
 endif
 
Index: boot/arch/ppc32/Makefile.inc
===================================================================
--- boot/arch/ppc32/Makefile.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ boot/arch/ppc32/Makefile.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -43,5 +43,13 @@
 
 RD_DRVS += \
-	infrastructure/rootmac
+	infrastructure/rootmac \
+	bus/pci/pciintel \
+	bus/usb/ohci \
+	bus/usb/usbflbk \
+	bus/usb/usbhub \
+	bus/usb/usbhid \
+	bus/usb/usbmast \
+	bus/usb/usbmid \
+	bus/usb/vhc
 
 SOURCES = \
Index: boot/generic/src/str.c
===================================================================
--- boot/generic/src/str.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ boot/generic/src/str.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -354,12 +354,17 @@
  *
  * Do a char-by-char comparison of two NULL-terminated strings.
- * The strings are considered equal iff they consist of the same
- * characters on the minimum of their lengths.
+ * The strings are considered equal iff their length is equal
+ * and both strings consist of the same sequence of characters.
+ *
+ * A string S1 is less than another string S2 if it has a character with
+ * lower value at the first character position where the strings differ.
+ * If the strings differ in length, the shorter one is treated as if
+ * padded by characters with a value of zero.
  *
  * @param s1 First string to compare.
  * @param s2 Second string to compare.
  *
- * @return 0 if the strings are equal, -1 if first is smaller,
- *         1 if second smaller.
+ * @return 0 if the strings are equal, -1 if the first is less than the second,
+ *         1 if the second is less than the first.
  *
  */
Index: contrib/arch/HelenOS.adl
===================================================================
--- contrib/arch/HelenOS.adl	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ contrib/arch/HelenOS.adl	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -1,3 +1,3 @@
-system architecture HelenOS version 0.4.1 {
+system architecture HelenOS version 0.5.0 {
 	/* SPARTAN kernel */
 	inst kernel kernel;
Index: contrib/bazaar/bzreml/__init__.py
===================================================================
--- contrib/bazaar/bzreml/__init__.py	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ contrib/bazaar/bzreml/__init__.py	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -102,10 +102,18 @@
 	return ""
 
+def iter_reverse_revision_history(repository, revision_id):
+	"""Iterate backwards through revision ids in the lefthand history"""
+	
+	graph = repository.get_graph()
+	stop_revisions = (None, _mod_revision.NULL_REVISION)
+	return graph.iter_lefthand_ancestry(revision_id, stop_revisions)
+
 def revision_sequence(branch, revision_old_id, revision_new_id):
 	"""Calculate a sequence of revisions"""
 	
-	for revision_ac_id in branch.repository.iter_reverse_revision_history(revision_new_id):
+	for revision_ac_id in iter_reverse_revision_history(branch.repository, revision_new_id):
 		if (revision_ac_id == revision_old_id):
 			break
+		
 		yield revision_ac_id
 
@@ -117,7 +125,9 @@
 		branch.repository.lock_read()
 		try:
-			body = StringIO()
+			revision_prev_id = revision_old_id
 			
-			for revision_ac_id in revision_sequence(branch, revision_old_id, revision_new_id):
+			for revision_ac_id in reversed(list(revision_sequence(branch, revision_old_id, revision_new_id))):
+				body = StringIO()
+				
 				revision_ac = branch.repository.get_revision(revision_ac_id)
 				revision_ac_no = branch.revision_id_to_revno(revision_ac_id)
@@ -139,5 +149,5 @@
 				body.write("\n")
 				
-				commit_message = ""
+				commit_message = None
 				body.write("Log:\n")
 				if (not revision_ac.message):
@@ -147,59 +157,60 @@
 					for line in log.split("\n"):
 						body.write("%s\n" % line)
-						if (commit_message == ""):
+						if (commit_message == None):
 							commit_message = line
 				
-				if (commit_message == ""):
+				if (commit_message == None):
 					commit_message = "(empty)"
 				
 				body.write("\n")
+				
+				tree_prev = branch.repository.revision_tree(revision_prev_id)
+				tree_ac = branch.repository.revision_tree(revision_ac_id)
+				
+				delta = tree_ac.changes_from(tree_prev)
+				
+				if (len(delta.added) > 0):
+					body.write("Added:\n")
+					for item in delta.added:
+						body.write("    %s\n" % item[0])
+				
+				if (len(delta.removed) > 0):
+					body.write("Removed:\n")
+					for item in delta.removed:
+						body.write("    %s\n" % item[0])
+				
+				if (len(delta.renamed) > 0):
+					body.write("Renamed:\n")
+					for item in delta.renamed:
+						body.write("    %s -> %s\n" % (item[0], item[1]))
+				
+				if (len(delta.kind_changed) > 0):
+					body.write("Changed:\n")
+					for item in delta.kind_changed:
+						body.write("    %s\n" % item[0])
+				
+				if (len(delta.modified) > 0):
+					body.write("Modified:\n")
+					for item in delta.modified:
+						body.write("    %s\n" % item[0])
+				
+				body.write("\n")
+				
+				tree_prev.lock_read()
+				try:
+					tree_ac.lock_read()
+					try:
+						diff = DiffTree.from_trees_options(tree_prev, tree_ac, body, "utf8", None, "", "", None)
+						diff.show_diff(None, None)
+					finally:
+						tree_ac.unlock()
+				finally:
+					tree_prev.unlock()
+				
+				subject = "r%d - %s" % (revision_ac_no, commit_message)
+				send_smtp("localhost", config_sender(config), config_to(config), subject, body.getvalue())
+				
+				revision_prev_id = revision_ac_id
 			
-			tree_old = branch.repository.revision_tree(revision_old_id)
-			tree_new = branch.repository.revision_tree(revision_new_id)
-			
-			revision_new_no = branch.revision_id_to_revno(revision_new_id)
-			delta = tree_new.changes_from(tree_old)
-			
-			if (len(delta.added) > 0):
-				body.write("Added:\n")
-				for item in delta.added:
-					body.write("    %s\n" % item[0])
-			
-			if (len(delta.removed) > 0):
-				body.write("Removed:\n")
-				for item in delta.removed:
-					body.write("    %s\n" % item[0])
-			
-			if (len(delta.renamed) > 0):
-				body.write("Renamed:\n")
-				for item in delta.renamed:
-					body.write("    %s -> %s\n" % (item[0], item[1]))
-			
-			if (len(delta.kind_changed) > 0):
-				body.write("Changed:\n")
-				for item in delta.kind_changed:
-					body.write("    %s\n" % item[0])
-			
-			if (len(delta.modified) > 0):
-				body.write("Modified:\n")
-				for item in delta.modified:
-					body.write("    %s\n" % item[0])
-			
-			body.write("\n")
-			
-			tree_old.lock_read()
-			try:
-				tree_new.lock_read()
-				try:
-					diff = DiffTree.from_trees_options(tree_old, tree_new, body, "utf8", None, "", "", None)
-					diff.show_diff(None, None)
-				finally:
-					tree_new.unlock()
-			finally:
-				tree_old.unlock()
-			
-			subject = "r%d - %s" % (revision_new_no, commit_message)
-			
-			send_smtp("localhost", config_sender(config), config_to(config), subject, body.getvalue())
 		finally:
 			branch.repository.unlock()
Index: contrib/bazaar/bzreml/setup.py
===================================================================
--- contrib/bazaar/bzreml/setup.py	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ contrib/bazaar/bzreml/setup.py	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -7,5 +7,5 @@
 	description = 'Commit email plugin for Bazaar',
 	keywords = 'plugin bzr email',
-	version = '1.2',
+	version = '1.3',
 	url = 'http://www.decky.cz/',
 	license = 'BSD',
@@ -13,5 +13,5 @@
 	author_email = 'martin@decky.cz',
 	long_description = """Hooks into Bazaar and sends commit notification emails.""",
-	package_dir = {'bzrlib.plugins.eml':'.'}, 
+	package_dir = {'bzrlib.plugins.eml':'.'},
 	packages = ['bzrlib.plugins.eml']
 )
Index: contrib/bazaar/mbprotect/__init__.py
===================================================================
--- contrib/bazaar/mbprotect/__init__.py	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ contrib/bazaar/mbprotect/__init__.py	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -45,4 +45,11 @@
 from bzrlib.errors import TipChangeRejected
 
+def iter_reverse_revision_history(repository, revision_id):
+	"""Iterate backwards through revision ids in the lefthand history"""
+	
+	graph = repository.get_graph()
+	stop_revisions = (None, _mod_revision.NULL_REVISION)
+	return graph.iter_lefthand_ancestry(revision_id, stop_revisions)
+
 def pre_change_branch_tip(params):
 	repo = params.branch.repository
@@ -54,5 +61,5 @@
 	# First permitted case is appending changesets to main branch.Look for
 	# old tip in new main branch.
-	for revision_id in repo.iter_reverse_revision_history(params.new_revid):
+	for revision_id in iter_reverse_revision_history(repo, params.new_revid):
 		if revision_id == params.old_revid:
 			return	# Found old tip
@@ -60,5 +67,5 @@
 	# Another permitted case is backing out changesets. Look for new tip
 	# in old branch.
-	for revision_id in repo.iter_reverse_revision_history(params.old_revid):
+	for revision_id in iter_reverse_revision_history(repo, params.old_revid):
 		if revision_id == params.new_revid:
 			return	# Found new tip
Index: contrib/conf/mips32-gx.sh
===================================================================
--- contrib/conf/mips32-gx.sh	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ contrib/conf/mips32-gx.sh	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -8,3 +8,10 @@
 fi
 
-gxemul $@ -E oldtestmips -C R4000 -X image.boot -d d0:"$DISK_IMG"
+if [ "$1" == "-E" ] && [ -n "$2" ]; then
+	MACHINE="$2"
+	shift 2
+else
+	MACHINE="oldtestmips"
+fi
+
+gxemul $@ -E "$MACHINE" -C R4000 -X image.boot -d d0:"$DISK_IMG"
Index: defaults/mips32/Makefile.config
===================================================================
--- defaults/mips32/Makefile.config	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ defaults/mips32/Makefile.config	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -47,2 +47,4 @@
 CONFIG_MOUNT_DATA = n
 
+# Barebone build with essential binaries only 
+CONFIG_BAREBONE = y
Index: defaults/ppc32/Makefile.config
===================================================================
--- defaults/ppc32/Makefile.config	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ defaults/ppc32/Makefile.config	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -44,2 +44,5 @@
 CONFIG_MOUNT_DATA = n
 
+# OHCI root hub power switch, ganged is enough
+OHCI_POWER_SWITCH = ganged
+
Index: defaults/sparc64/ultra/Makefile.config
===================================================================
--- defaults/sparc64/ultra/Makefile.config	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ defaults/sparc64/ultra/Makefile.config	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -4,2 +4,5 @@
 # CPU type
 PROCESSOR = us
+
+# Barebone build with essential binaries only
+CONFIG_BAREBONE = y
Index: kernel/arch/amd64/src/asm.S
===================================================================
--- kernel/arch/amd64/src/asm.S	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/amd64/src/asm.S	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -362,5 +362,13 @@
 	 */
 	call syscall_handler
-	
+
+	/*
+	 * Test if the saved return address is canonical and not-kernel.
+	 * We do this by looking at the 16 most significant bits
+	 * of the saved return address (two bytes at offset 6).
+	 */
+	testw $0xffff, ISTATE_OFFSET_RIP+6(%rsp)
+	jnz bad_rip 
+
 	cli
 	
@@ -388,4 +396,14 @@
 	sysretq
 
+bad_rip:
+	movq %rsp, %rdi
+	movabs $bad_rip_msg, %rsi
+	xorb %al, %al
+	callq fault_from_uspace
+	/* not reached */
+	
+bad_rip_msg:
+	.asciz "Invalid instruction pointer."
+
 /** Print Unicode character to EGA display.
  *
Index: kernel/arch/amd64/src/boot/multiboot.S
===================================================================
--- kernel/arch/amd64/src/boot/multiboot.S	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/amd64/src/boot/multiboot.S	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -76,4 +76,5 @@
 
 multiboot_image_start:
+	cli
 	cld
 	
@@ -81,6 +82,10 @@
 	movl $START_STACK, %esp
 	
-	/* Initialize Global Descriptor Table register */
+	/*
+	 * Initialize Global Descriptor Table and
+	 * Interrupt Descriptor Table registers
+	 */
 	lgdtl bootstrap_gdtr
+	lidtl bootstrap_idtr
 	
 	/* Kernel data + stack */
@@ -645,4 +650,9 @@
 .section K_DATA_START, "aw", @progbits
 
+.global bootstrap_idtr
+bootstrap_idtr:
+	.word 0
+	.long 0
+
 .global bootstrap_gdtr
 bootstrap_gdtr:
Index: kernel/arch/amd64/src/boot/multiboot2.S
===================================================================
--- kernel/arch/amd64/src/boot/multiboot2.S	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/amd64/src/boot/multiboot2.S	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -116,4 +116,5 @@
 
 multiboot2_image_start:
+	cli
 	cld
 	
@@ -121,6 +122,10 @@
 	movl $START_STACK, %esp
 	
-	/* Initialize Global Descriptor Table register */
+	/*
+	 * Initialize Global Descriptor Table and
+	 * Interrupt Descriptor Table registers
+	 */
 	lgdtl bootstrap_gdtr
+	lidtl bootstrap_idtr
 	
 	/* Kernel data + stack */
Index: kernel/arch/amd64/src/boot/vesa_ret.inc
===================================================================
--- kernel/arch/amd64/src/boot/vesa_ret.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/amd64/src/boot/vesa_ret.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -1,4 +1,5 @@
 .code32
 vesa_init_protected:
+	cli
 	cld
 	
Index: kernel/arch/ia32/src/boot/multiboot.S
===================================================================
--- kernel/arch/ia32/src/boot/multiboot.S	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/ia32/src/boot/multiboot.S	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -73,4 +73,5 @@
 
 multiboot_image_start:
+	cli
 	cld
 	
@@ -78,6 +79,10 @@
 	movl $START_STACK, %esp
 	
-	/* Initialize Global Descriptor Table register */
+	/*
+	 * Initialize Global Descriptor Table and
+	 * Interrupt Descriptor Table registers
+	 */
 	lgdtl bootstrap_gdtr
+	lidtl bootstrap_idtr
 	
 	/* Kernel data + stack */
@@ -701,4 +706,9 @@
 page_directory:
 	.space 4096, 0
+
+.global bootstrap_idtr
+bootstrap_idtr:
+	.word 0
+	.long 0
 
 .global bootstrap_gdtr
Index: kernel/arch/ia32/src/boot/multiboot2.S
===================================================================
--- kernel/arch/ia32/src/boot/multiboot2.S	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/ia32/src/boot/multiboot2.S	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -114,4 +114,5 @@
 
 multiboot2_image_start:
+	cli
 	cld
 	
@@ -119,6 +120,10 @@
 	movl $START_STACK, %esp
 	
-	/* Initialize Global Descriptor Table register */
+	/*
+	 * Initialize Global Descriptor Table and
+	 * Interrupt Descriptor Table registers
+	 */
 	lgdtl bootstrap_gdtr
+	lidtl bootstrap_idtr
 	
 	/* Kernel data + stack */
Index: kernel/arch/ia32/src/boot/vesa_prot.inc
===================================================================
--- kernel/arch/ia32/src/boot/vesa_prot.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/ia32/src/boot/vesa_prot.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -88,4 +88,11 @@
 		/* Returned back to protected mode */
 		
+		/*
+		 * Initialize Global Descriptor Table and
+		 * Interrupt Descriptor Table registers
+		 */
+		lgdtl bootstrap_gdtr
+		lidtl bootstrap_idtr
+		
 		movzx %ax, %ecx
 		mov %ecx, KA2PA(bfb_scanline)
Index: kernel/arch/ia32/src/boot/vesa_real.inc
===================================================================
--- kernel/arch/ia32/src/boot/vesa_real.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/ia32/src/boot/vesa_real.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -30,5 +30,10 @@
 .code32
 vesa_init:
+	lidtl vesa_idtr
 	jmp $GDT_SELECTOR(VESA_INIT_DES), $vesa_init_real - vesa_init
+
+vesa_idtr:
+	.word 0x3ff
+	.long 0
 
 .code16
Index: kernel/arch/ia32/src/boot/vesa_ret.inc
===================================================================
--- kernel/arch/ia32/src/boot/vesa_ret.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/ia32/src/boot/vesa_ret.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -1,4 +1,5 @@
 .code32
 vesa_init_protected:
+	cli
 	cld
 	
Index: kernel/arch/ia64/Makefile.inc
===================================================================
--- kernel/arch/ia64/Makefile.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/ia64/Makefile.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -30,5 +30,15 @@
 BFD_ARCH = ia64-elf64
 
-CMN1 = -mconstant-gp -fno-unwind-tables -mfixed-range=f32-f127
+#
+# FIXME:
+#
+# The -fno-selective-scheduling and -fno-selective-scheduling2 options
+# should be removed as soon as a bug in GCC concerning unchecked
+# speculative loads is fixed.
+#
+# See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53975 for reference.
+#
+
+CMN1 = -mconstant-gp -fno-unwind-tables -mfixed-range=f32-f127 -fno-selective-scheduling -fno-selective-scheduling2
 GCC_CFLAGS += $(CMN1)
 ICC_CFLAGS += $(CMN1)
Index: kernel/arch/mips32/Makefile.inc
===================================================================
--- kernel/arch/mips32/Makefile.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/mips32/Makefile.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -29,5 +29,5 @@
 BFD_ARCH = mips
 BFD = binary
-GCC_CFLAGS += -mno-abicalls -G 0 -fno-zero-initialized-in-bss -mips3 -mabi=32
+GCC_CFLAGS += -msoft-float -mno-abicalls -G 0 -fno-zero-initialized-in-bss -mips3 -mabi=32
 
 BITS = 32
@@ -48,5 +48,4 @@
 	BFD_NAME = elf32-tradlittlemips
 	ENDIANESS = LE
-	GCC_CFLAGS += -mhard-float
 endif
 
Index: kernel/arch/mips64/Makefile.inc
===================================================================
--- kernel/arch/mips64/Makefile.inc	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/arch/mips64/Makefile.inc	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -29,5 +29,5 @@
 BFD_ARCH = mips:4000
 BFD = binary
-GCC_CFLAGS += -mno-abicalls -G 0 -fno-zero-initialized-in-bss -mips3 -mabi=64
+GCC_CFLAGS += -msoft-float -mno-abicalls -G 0 -fno-zero-initialized-in-bss -mips3 -mabi=64
 AFLAGS = -64
 
@@ -40,5 +40,4 @@
 	BFD_NAME = elf64-tradlittlemips
 	ENDIANESS = LE
-	GCC_CFLAGS += -mhard-float
 endif
 
Index: kernel/generic/include/interrupt.h
===================================================================
--- kernel/generic/include/interrupt.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/include/interrupt.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -38,4 +38,5 @@
 #include <arch/interrupt.h>
 #include <print.h>
+#include <stdarg.h>
 #include <typedefs.h>
 #include <proc/task.h>
@@ -58,4 +59,5 @@
 extern exc_table_t exc_table[];
 
+extern void fault_from_uspace(istate_t *, const char *, ...);
 extern void fault_if_from_uspace(istate_t *, const char *, ...)
     PRINTF_ATTRIBUTE(2, 3);
Index: kernel/generic/include/ipc/ipc.h
===================================================================
--- kernel/generic/include/ipc/ipc.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/include/ipc/ipc.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -77,7 +77,4 @@
 	waitq_t wq;
 	
-	/** Linkage for the list of task's synchronous answerboxes. */
-	link_t sync_box_link;
-	
 	/** Phones connected to this answerbox. */
 	list_t connected_phones;
@@ -116,10 +113,4 @@
 	struct task *sender;
 	
-	/*
-	 * The caller box is different from sender->answerbox
-	 * for synchronous calls.
-	 */
-	answerbox_t *callerbox;
-	
 	/** Private data to internal IPC. */
 	sysarg_t priv;
@@ -147,5 +138,4 @@
 
 extern int ipc_call(phone_t *, call_t *);
-extern int ipc_call_sync(phone_t *, call_t *);
 extern call_t *ipc_wait_for_call(answerbox_t *, uint32_t, unsigned int);
 extern int ipc_forward(call_t *, phone_t *, answerbox_t *, unsigned int);
Index: kernel/generic/include/ipc/irq.h
===================================================================
--- kernel/generic/include/ipc/irq.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/include/ipc/irq.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -37,8 +37,8 @@
 
 /** Maximum number of IPC IRQ programmed I/O ranges. */
-#define IRQ_MAX_RANGE_COUNT	8
+#define IRQ_MAX_RANGE_COUNT  8
 
 /** Maximum length of IPC IRQ program. */
-#define IRQ_MAX_PROG_SIZE  20
+#define IRQ_MAX_PROG_SIZE  256
 
 #include <ipc/ipc.h>
Index: kernel/generic/include/ipc/sysipc.h
===================================================================
--- kernel/generic/include/ipc/sysipc.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/include/ipc/sysipc.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -40,7 +40,4 @@
 #include <typedefs.h>
 
-extern sysarg_t sys_ipc_call_sync_fast(sysarg_t, sysarg_t, sysarg_t,
-    sysarg_t, sysarg_t, ipc_data_t *);
-extern sysarg_t sys_ipc_call_sync_slow(sysarg_t, ipc_data_t *, ipc_data_t *);
 extern sysarg_t sys_ipc_call_async_fast(sysarg_t, sysarg_t, sysarg_t,
     sysarg_t, sysarg_t, sysarg_t);
Index: kernel/generic/include/proc/task.h
===================================================================
--- kernel/generic/include/proc/task.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/include/proc/task.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -94,5 +94,4 @@
 	phone_t phones[IPC_MAX_PHONES];
 	stats_ipc_t ipc_info;   /**< IPC statistics */
-	list_t sync_boxes;      /**< List of synchronous answerboxes. */
 	event_t events[EVENT_TASK_END - EVENT_END];
 	
Index: kernel/generic/src/console/kconsole.c
===================================================================
--- kernel/generic/src/console/kconsole.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/src/console/kconsole.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -202,11 +202,14 @@
  *
  */
-NO_TRACE static int cmdtab_compl(char *input, size_t size, indev_t * indev)
+NO_TRACE static int cmdtab_compl(char *input, size_t size, indev_t *indev)
 {
 	const char *name = input;
 	
 	size_t found = 0;
-	/* Maximum Match Length : Length of longest matching common substring in
-	   case more than one match is found */
+	
+	/*
+	 * Maximum Match Length: Length of longest matching common
+	 * substring in case more than one match is found.
+	 */
 	size_t max_match_len = size;
 	size_t max_match_len_tmp = size;
@@ -229,8 +232,12 @@
 	}
 	
-	/* If possible completions are more than MAX_TAB_HINTS, ask user whether to display them or not. */
+	/*
+	 * If the number of possible completions is more than MAX_TAB_HINTS,
+	 * ask the user whether to display them or not.
+	 */
 	if (found > MAX_TAB_HINTS) {
 		printf("\n");
-		continue_showing_hints = console_prompt_display_all_hints(indev, found);
+		continue_showing_hints =
+		    console_prompt_display_all_hints(indev, found);
 	}
 	
@@ -240,21 +247,28 @@
 		while (cmdtab_search_one(name, &pos)) {
 			cmd_info_t *hlp = list_get_instance(pos, cmd_info_t, link);
-
+			
 			if (continue_showing_hints) {
 				printf("%s (%s)\n", hlp->name, hlp->description);
 				--hints_to_show;
 				++total_hints_shown;
-
-				if (hints_to_show == 0 && total_hints_shown != found) { /* Time to ask user to continue */
-					continue_showing_hints = console_prompt_more_hints(indev, &hints_to_show);
+				
+				if ((hints_to_show == 0) && (total_hints_shown != found)) {
+					/* Ask user to continue */
+					continue_showing_hints =
+					    console_prompt_more_hints(indev, &hints_to_show);
 				}
 			}
-
+			
 			pos = pos->next;
-			for(max_match_len_tmp = 0; output[max_match_len_tmp] == hlp->name[input_len + max_match_len_tmp]
-					&& max_match_len_tmp < max_match_len; ++max_match_len_tmp);
+			
+			for (max_match_len_tmp = 0;
+			    (output[max_match_len_tmp] ==
+			    hlp->name[input_len + max_match_len_tmp]) &&
+			    (max_match_len_tmp < max_match_len); ++max_match_len_tmp);
+			
 			max_match_len = max_match_len_tmp;
 		}
-		/* keep only the characters common in all completions */
+		
+		/* Keep only the characters common in all completions */
 		output[max_match_len] = 0;
 	}
@@ -310,6 +324,8 @@
 				continue;
 			
-			/* Find the beginning of the word
-			   and copy it to tmp */
+			/*
+			 * Find the beginning of the word
+			 * and copy it to tmp
+			 */
 			size_t beg;
 			for (beg = position - 1; (beg > 0) && (!isspace(current[beg]));
@@ -333,6 +349,8 @@
 				continue;
 
-			/* We have hints, may be many. In case of more than one hint,
-			   tmp will contain the common prefix. */
+			/*
+			 * We have hints, possibly many. In case of more than one hint,
+			 * tmp will contain the common prefix.
+			 */
 			size_t off = 0;
 			size_t i = 0;
@@ -340,4 +358,5 @@
 				if (!wstr_linsert(current, ch, position + i, MAX_CMDLINE))
 					break;
+				
 				i++;
 			}
Index: kernel/generic/src/console/prompt.c
===================================================================
--- kernel/generic/src/console/prompt.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/src/console/prompt.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -43,5 +43,7 @@
  * @param indev Where to read characters from.
  * @param hints Number of hints that would be displayed.
+ *
  * @return Whether to print all hints.
+ *
  */
 bool console_prompt_display_all_hints(indev_t *indev, size_t hints)
@@ -49,17 +51,17 @@
 	ASSERT(indev);
 	ASSERT(hints > 0);
-
-	printf("Display all %zu possibilities? (y or n)", hints);
-
+	
+	printf("Display all %zu possibilities? (y or n) ", hints);
+	
 	while (true) {
 		wchar_t answer = indev_pop_character(indev);
-
-		if (answer == 'y' || answer == 'Y') {
-			printf(" y");
+		
+		if ((answer == 'y') || (answer == 'Y')) {
+			printf("y");
 			return true;
 		}
-
-		if (answer == 'n' || answer == 'N') {
-			printf(" n");
+		
+		if ((answer == 'n') || (answer == 'N')) {
+			printf("n");
 			return false;
 		}
@@ -71,7 +73,9 @@
  * When the function returns false, @p display_hints is set to zero.
  *
- * @param[in] indev Where to read characters from.
+ * @param[in]  indev         Where to read characters from.
  * @param[out] display_hints How many hints to display.
+ *
  * @return Whether to display more hints.
+ *
  */
 bool console_prompt_more_hints(indev_t *indev, size_t *display_hints)
@@ -79,25 +83,25 @@
 	ASSERT(indev);
 	ASSERT(display_hints != NULL);
-
+	
 	printf("--More--");
 	while (true) {
 		wchar_t continue_showing_hints = indev_pop_character(indev);
 		/* Display a full page again? */
-		if (continue_showing_hints == 'y'
-		    || continue_showing_hints == 'Y'
-		    || continue_showing_hints == ' ') {
+		if ((continue_showing_hints == 'y') ||
+		    (continue_showing_hints == 'Y') ||
+		    (continue_showing_hints == ' ')) {
 			*display_hints = MAX_TAB_HINTS - 1;
 			break;
 		}
-
+		
 		/* Stop displaying hints? */
-		if (continue_showing_hints == 'n'
-		    || continue_showing_hints == 'N'
-		    || continue_showing_hints == 'q'
-		    || continue_showing_hints == 'Q') {
+		if ((continue_showing_hints == 'n') ||
+		    (continue_showing_hints == 'N') ||
+		    (continue_showing_hints == 'q') ||
+		    (continue_showing_hints == 'Q')) {
 			*display_hints = 0;
 			break;
 		}
-
+		
 		/* Show one more hint? */
 		if (continue_showing_hints == '\n') {
@@ -106,8 +110,8 @@
 		}
 	}
-
+	
 	/* Delete the --More-- option */
 	printf("\r         \r");
-
+	
 	return *display_hints > 0;
 }
Index: kernel/generic/src/debug/symtab.c
===================================================================
--- kernel/generic/src/debug/symtab.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/src/debug/symtab.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -210,5 +210,5 @@
  *
  */
-int symtab_compl(char *input, size_t size, indev_t * indev)
+int symtab_compl(char *input, size_t size, indev_t *indev)
 {
 #ifdef CONFIG_SYMTAB
@@ -227,6 +227,9 @@
 	const char *hint;
 	char output[MAX_SYMBOL_NAME];
-	/* Maximum Match Length : Length of longest matching common substring in
-	   case more than one match is found */
+	
+	/*
+	 * Maximum Match Length: Length of longest matching common substring in
+	 * case more than one match is found.
+	 */
 	size_t max_match_len = size;
 	size_t max_match_len_tmp = size;
@@ -238,9 +241,8 @@
 	
 	output[0] = 0;
-
-	while ((hint = symtab_search_one(name, &pos))) {
-		++pos;
-	}
-
+	
+	while ((hint = symtab_search_one(name, &pos)))
+		pos++;
+	
 	pos = 0;
 	
@@ -253,8 +255,12 @@
 	}
 	
-	/* If possible completions are more than MAX_TAB_HINTS, ask user whether to display them or not. */
+	/*
+	 * If the number of possible completions is more than MAX_TAB_HINTS,
+	 * ask the user whether to display them or not.
+	 */
 	if (found > MAX_TAB_HINTS) {
 		printf("\n");
-		continue_showing_hints = console_prompt_display_all_hints(indev, found);
+		continue_showing_hints =
+		    console_prompt_display_all_hints(indev, found);
 	}
 	
@@ -265,20 +271,27 @@
 			sym_name = symbol_table[pos].symbol_name;
 			pos++;
-
-			if (continue_showing_hints) { /* We are still showing hints */
+			
+			if (continue_showing_hints) {
+				/* We are still showing hints */
 				printf("%s\n", sym_name);
 				--hints_to_show;
 				++total_hints_shown;
-
-				if (hints_to_show == 0 && total_hints_shown != found) { /* Time to ask user to continue */
-					continue_showing_hints = console_prompt_more_hints(indev, &hints_to_show);
+				
+				if ((hints_to_show == 0) && (total_hints_shown != found)) {
+					/* Ask the user to continue */
+					continue_showing_hints =
+					    console_prompt_more_hints(indev, &hints_to_show);
 				}
 			}
-
-			for(max_match_len_tmp = 0; output[max_match_len_tmp] == sym_name[input_len + max_match_len_tmp]
-					&& max_match_len_tmp < max_match_len; ++max_match_len_tmp);
+			
+			for (max_match_len_tmp = 0;
+			    (output[max_match_len_tmp] ==
+			    sym_name[input_len + max_match_len_tmp]) &&
+			    (max_match_len_tmp < max_match_len); ++max_match_len_tmp);
+			
 			max_match_len = max_match_len_tmp;
 		}
-		/* keep only the characters common in all completions */
+		
+		/* Keep only the characters common in all completions */
 		output[max_match_len] = 0;
 	}
Index: kernel/generic/src/interrupt/interrupt.c
===================================================================
--- kernel/generic/src/interrupt/interrupt.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/src/interrupt/interrupt.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -50,4 +50,5 @@
 #include <panic.h>
 #include <print.h>
+#include <stdarg.h>
 #include <symtab.h>
 #include <proc/thread.h>
@@ -165,12 +166,6 @@
 }
 
-/** Terminate thread and task if exception came from userspace.
- *
- */
-NO_TRACE void fault_if_from_uspace(istate_t *istate, const char *fmt, ...)
-{
-	if (!istate_from_uspace(istate))
-		return;
-	
+static NO_TRACE void fault_from_uspace_core(istate_t *istate, const char *fmt, va_list args)
+{
 	printf("Task %s (%" PRIu64 ") killed due to an exception at "
 	    "program counter %p.\n", TASK->name, TASK->taskid,
@@ -181,12 +176,34 @@
 	
 	printf("Kill message: ");
+	vprintf(fmt, args);
+	printf("\n");
+	
+	task_kill_self(true);
+}
+
+/** Terminate thread and task after the exception came from userspace.
+ *
+ */
+NO_TRACE void fault_from_uspace(istate_t *istate, const char *fmt, ...)
+{
+	va_list args;
+
+	va_start(args, fmt);
+	fault_from_uspace_core(istate, fmt, args);
+	va_end(args);
+}
+
+/** Terminate thread and task if exception came from userspace.
+ *
+ */
+NO_TRACE void fault_if_from_uspace(istate_t *istate, const char *fmt, ...)
+{
+	if (!istate_from_uspace(istate))
+		return;
 	
 	va_list args;
 	va_start(args, fmt);
-	vprintf(fmt, args);
+	fault_from_uspace_core(istate, fmt, args);
 	va_end(args);
-	printf("\n");
-	
-	task_kill_self(true);
 }
 
Index: kernel/generic/src/ipc/ipc.c
===================================================================
--- kernel/generic/src/ipc/ipc.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/src/ipc/ipc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -71,5 +71,4 @@
 {
 	memsetb(call, sizeof(*call), 0);
-	call->callerbox = &TASK->answerbox;
 	call->sender = TASK;
 	call->buffer = NULL;
@@ -120,5 +119,4 @@
 	irq_spinlock_initialize(&box->irq_lock, "ipc.box.irqlock");
 	waitq_initialize(&box->wq);
-	link_initialize(&box->sync_box_link);
 	list_initialize(&box->connected_phones);
 	list_initialize(&box->calls);
@@ -163,47 +161,4 @@
 }
 
-/** Helper function to facilitate synchronous calls.
- *
- * @param phone   Destination kernel phone structure.
- * @param request Call structure with request.
- *
- * @return EOK on success or EINTR if the sleep was interrupted.
- *
- */
-int ipc_call_sync(phone_t *phone, call_t *request)
-{
-	answerbox_t *sync_box = slab_alloc(ipc_answerbox_slab, 0);
-	ipc_answerbox_init(sync_box, TASK);
-	
-	/*
-	 * Put the answerbox on the TASK's list of synchronous answerboxes so
-	 * that it can be cleaned up if the call is interrupted.
-	 */
-	irq_spinlock_lock(&TASK->lock, true);
-	list_append(&sync_box->sync_box_link, &TASK->sync_boxes);
-	irq_spinlock_unlock(&TASK->lock, true);
-	
-	/* We will receive data in a special box. */
-	request->callerbox = sync_box;
-	
-	ipc_call(phone, request);
-	if (!ipc_wait_for_call(sync_box, SYNCH_NO_TIMEOUT,
-	    SYNCH_FLAGS_INTERRUPTIBLE)) {
-		/* The answerbox and the call will be freed by ipc_cleanup(). */
-		return EINTR;
-	}
-	
-	/*
-	 * The answer arrived without interruption so we can remove the
-	 * answerbox from the TASK's list of synchronous answerboxes.
-	 */
-	irq_spinlock_lock(&TASK->lock, true);
-	list_remove(&sync_box->sync_box_link);
-	irq_spinlock_unlock(&TASK->lock, true);
-	
-	slab_free(ipc_answerbox_slab, sync_box);
-	return EOK;
-}
-
 /** Answer a message which was not dispatched and is not listed in any queue.
  *
@@ -214,5 +169,5 @@
 static void _ipc_answer_free_call(call_t *call, bool selflocked)
 {
-	answerbox_t *callerbox = call->callerbox;
+	answerbox_t *callerbox = &call->sender->answerbox;
 	bool do_lock = ((!selflocked) || callerbox != (&TASK->answerbox));
 	
@@ -606,18 +561,4 @@
 	ipc_cleanup_call_list(&TASK->answerbox.calls);
 	irq_spinlock_unlock(&TASK->answerbox.lock, true);
-	
-	/* Wait for all answers to interrupted synchronous calls to arrive */
-	ipl_t ipl = interrupts_disable();
-	while (!list_empty(&TASK->sync_boxes)) {
-		answerbox_t *box = list_get_instance(
-		    list_first(&TASK->sync_boxes), answerbox_t, sync_box_link);
-		
-		list_remove(&box->sync_box_link);
-		call_t *call = ipc_wait_for_call(box, SYNCH_NO_TIMEOUT,
-		    SYNCH_FLAGS_NONE);
-		ipc_call_free(call);
-		slab_free(ipc_answerbox_slab, box);
-	}
-	interrupts_restore(ipl);
 	
 	/* Wait for all answers to asynchronous calls to arrive */
Index: kernel/generic/src/ipc/irq.c
===================================================================
--- kernel/generic/src/ipc/irq.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/src/ipc/irq.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -39,14 +39,14 @@
  * when interrupt is detected. The application may provide a simple 'top-half'
  * handler as part of its registration, which can perform simple operations
- * (read/write port/memory, add information to notification ipc message).
+ * (read/write port/memory, add information to notification IPC message).
  *
  * The structure of a notification message is as follows:
  * - IMETHOD: interface and method as registered by
  *            the SYS_IRQ_REGISTER syscall
- * - ARG1: payload modified by a 'top-half' handler
- * - ARG2: payload modified by a 'top-half' handler
- * - ARG3: payload modified by a 'top-half' handler
- * - ARG4: payload modified by a 'top-half' handler
- * - ARG5: payload modified by a 'top-half' handler
+ * - ARG1: payload modified by a 'top-half' handler (scratch[1])
+ * - ARG2: payload modified by a 'top-half' handler (scratch[2])
+ * - ARG3: payload modified by a 'top-half' handler (scratch[3])
+ * - ARG4: payload modified by a 'top-half' handler (scratch[4])
+ * - ARG5: payload modified by a 'top-half' handler (scratch[5])
  * - in_phone_hash: interrupt counter (may be needed to assure correct order
  *                  in multithreaded drivers)
@@ -87,7 +87,5 @@
 static void ranges_unmap(irq_pio_range_t *ranges, size_t rangecount)
 {
-	size_t i;
-
-	for (i = 0; i < rangecount; i++) {
+	for (size_t i = 0; i < rangecount; i++) {
 #ifdef IO_SPACE_BOUNDARY
 		if ((void *) ranges[i].base >= IO_SPACE_BOUNDARY)
@@ -100,14 +98,11 @@
     irq_cmd_t *cmds, size_t cmdcount)
 {
-	uintptr_t *pbase;
-	size_t i, j;
-
 	/* Copy the physical base addresses aside. */
-	pbase = malloc(rangecount * sizeof(uintptr_t), 0);
-	for (i = 0; i < rangecount; i++)
+	uintptr_t *pbase = malloc(rangecount * sizeof(uintptr_t), 0);
+	for (size_t i = 0; i < rangecount; i++)
 		pbase[i] = ranges[i].base;
-
+	
 	/* Map the PIO ranges into the kernel virtual address space. */
-	for (i = 0; i < rangecount; i++) {
+	for (size_t i = 0; i < rangecount; i++) {
 #ifdef IO_SPACE_BOUNDARY
 		if ((void *) ranges[i].base < IO_SPACE_BOUNDARY)
@@ -122,25 +117,25 @@
 		}
 	}
-
+	
 	/* Rewrite the pseudocode addresses from physical to kernel virtual. */
-	for (i = 0; i < cmdcount; i++) {
+	for (size_t i = 0; i < cmdcount; i++) {
 		uintptr_t addr;
 		size_t size;
-
+		
 		/* Process only commands that use an address. */
 		switch (cmds[i].cmd) {
 		case CMD_PIO_READ_8:
-        	case CMD_PIO_WRITE_8:
-        	case CMD_PIO_WRITE_A_8:
+		case CMD_PIO_WRITE_8:
+		case CMD_PIO_WRITE_A_8:
 			size = 1;
 			break;
-        	case CMD_PIO_READ_16:
-        	case CMD_PIO_WRITE_16:
-        	case CMD_PIO_WRITE_A_16:
+		case CMD_PIO_READ_16:
+		case CMD_PIO_WRITE_16:
+		case CMD_PIO_WRITE_A_16:
 			size = 2;
 			break;
-        	case CMD_PIO_READ_32:
-        	case CMD_PIO_WRITE_32:
-        	case CMD_PIO_WRITE_A_32:
+		case CMD_PIO_READ_32:
+		case CMD_PIO_WRITE_32:
+		case CMD_PIO_WRITE_A_32:
 			size = 4;
 			break;
@@ -149,21 +144,21 @@
 			continue;
 		}
-
+		
 		addr = (uintptr_t) cmds[i].addr;
 		
+		size_t j;
 		for (j = 0; j < rangecount; j++) {
-
 			/* Find the matching range. */
 			if (!iswithin(pbase[j], ranges[j].size, addr, size))
 				continue;
-
+			
 			/* Switch the command to a kernel virtual address. */
 			addr -= pbase[j];
 			addr += ranges[j].base;
-
+			
 			cmds[i].addr = (void *) addr;
 			break;
 		}
-
+		
 		if (j == rangecount) {
 			/*
@@ -176,6 +171,46 @@
 		}
 	}
-
+	
 	free(pbase);
+	return EOK;
+}
+
+/** Statically check the top-half pseudocode
+ *
+ * Check the top-half pseudocode for invalid or unsafe
+ * constructs.
+ *
+ */
+static int code_check(irq_cmd_t *cmds, size_t cmdcount)
+{
+	for (size_t i = 0; i < cmdcount; i++) {
+		/*
+		 * Check for accepted ranges.
+		 */
+		if (cmds[i].cmd >= CMD_LAST)
+			return EINVAL;
+		
+		if (cmds[i].srcarg >= IPC_CALL_LEN)
+			return EINVAL;
+		
+		if (cmds[i].dstarg >= IPC_CALL_LEN)
+			return EINVAL;
+		
+		switch (cmds[i].cmd) {
+		case CMD_PREDICATE:
+			/*
+			 * Check for control flow overflow.
+			 * Note that jumping just beyond the last
+			 * command is a correct behaviour.
+			 */
+			if (i + cmds[i].value > cmdcount)
+				return EINVAL;
+			
+			break;
+		default:
+			break;
+		}
+	}
+	
 	return EOK;
 }
@@ -207,5 +242,5 @@
 	irq_pio_range_t *ranges = NULL;
 	irq_cmd_t *cmds = NULL;
-
+	
 	irq_code_t *code = malloc(sizeof(*code), 0);
 	int rc = copy_from_uspace(code, ucode, sizeof(*code));
@@ -222,5 +257,5 @@
 	if (rc != EOK)
 		goto error;
-
+	
 	cmds = malloc(sizeof(code->cmds[0]) * code->cmdcount, 0);
 	rc = copy_from_uspace(cmds, code->cmds,
@@ -228,20 +263,26 @@
 	if (rc != EOK)
 		goto error;
-
+	
+	rc = code_check(cmds, code->cmdcount);
+	if (rc != EOK)
+		goto error;
+	
 	rc = ranges_map_and_apply(ranges, code->rangecount, cmds,
 	    code->cmdcount);
 	if (rc != EOK)
 		goto error;
-
+	
 	code->ranges = ranges;
 	code->cmds = cmds;
-
+	
 	return code;
-
+	
 error:
 	if (cmds)
 		free(cmds);
+	
 	if (ranges)
 		free(ranges);
+	
 	free(code);
 	return NULL;
@@ -250,11 +291,12 @@
 /** Register an answerbox as a receiving end for IRQ notifications.
  *
- * @param box		Receiving answerbox.
- * @param inr		IRQ number.
- * @param devno		Device number.
- * @param imethod	Interface and method to be associated with the
- *			notification.
- * @param ucode		Uspace pointer to top-half pseudocode.
- * @return		EOK on success or a negative error code.
+ * @param box     Receiving answerbox.
+ * @param inr     IRQ number.
+ * @param devno   Device number.
+ * @param imethod Interface and method to be associated with the
+ *                notification.
+ * @param ucode   Uspace pointer to top-half pseudocode.
+ *
+ * @return EOK on success or a negative error code.
  *
  */
@@ -266,5 +308,5 @@
 		(sysarg_t) devno
 	};
-
+	
 	if ((inr < 0) || (inr > last_inr))
 		return ELIMIT;
@@ -329,8 +371,10 @@
 /** Unregister task from IRQ notification.
  *
- * @param box		Answerbox associated with the notification.
- * @param inr		IRQ number.
- * @param devno		Device number.
- * @return		EOK on success or a negative error code.
+ * @param box   Answerbox associated with the notification.
+ * @param inr   IRQ number.
+ * @param devno Device number.
+ *
+ * @return EOK on success or a negative error code.
+ *
  */
 int ipc_irq_unregister(answerbox_t *box, inr_t inr, devno_t devno)
@@ -340,5 +384,5 @@
 		(sysarg_t) devno
 	};
-
+	
 	if ((inr < 0) || (inr > last_inr))
 		return ELIMIT;
@@ -436,5 +480,5 @@
 		/* Remove from the hash table. */
 		hash_table_remove(&irq_uspace_hash_table, key, 2);
-
+		
 		/*
 		 * Release both locks so that we can free the pseudo code.
@@ -442,5 +486,5 @@
 		irq_spinlock_unlock(&box->irq_lock, false);
 		irq_spinlock_unlock(&irq_uspace_hash_table_lock, true);
-
+		
 		code_free(irq->notif_cfg.code);
 		free(irq);
@@ -492,30 +536,19 @@
 	
 	for (size_t i = 0; i < code->cmdcount; i++) {
-		uint32_t dstval;
-		
 		uintptr_t srcarg = code->cmds[i].srcarg;
 		uintptr_t dstarg = code->cmds[i].dstarg;
 		
-		if (srcarg >= IPC_CALL_LEN)
-			break;
-		
-		if (dstarg >= IPC_CALL_LEN)
-			break;
-	
 		switch (code->cmds[i].cmd) {
 		case CMD_PIO_READ_8:
-			dstval = pio_read_8((ioport8_t *) code->cmds[i].addr);
-			if (dstarg)
-				scratch[dstarg] = dstval;
+			scratch[dstarg] =
+			    pio_read_8((ioport8_t *) code->cmds[i].addr);
 			break;
 		case CMD_PIO_READ_16:
-			dstval = pio_read_16((ioport16_t *) code->cmds[i].addr);
-			if (dstarg)
-				scratch[dstarg] = dstval;
+			scratch[dstarg] =
+			    pio_read_16((ioport16_t *) code->cmds[i].addr);
 			break;
 		case CMD_PIO_READ_32:
-			dstval = pio_read_32((ioport32_t *) code->cmds[i].addr);
-			if (dstarg)
-				scratch[dstarg] = dstval;
+			scratch[dstarg] =
+			    pio_read_32((ioport32_t *) code->cmds[i].addr);
 			break;
 		case CMD_PIO_WRITE_8:
@@ -532,32 +565,26 @@
 			break;
 		case CMD_PIO_WRITE_A_8:
-			if (srcarg) {
-				pio_write_8((ioport8_t *) code->cmds[i].addr,
-				    (uint8_t) scratch[srcarg]);
-			}
+			pio_write_8((ioport8_t *) code->cmds[i].addr,
+			    (uint8_t) scratch[srcarg]);
 			break;
 		case CMD_PIO_WRITE_A_16:
-			if (srcarg) {
-				pio_write_16((ioport16_t *) code->cmds[i].addr,
-				    (uint16_t) scratch[srcarg]);
-			}
+			pio_write_16((ioport16_t *) code->cmds[i].addr,
+			    (uint16_t) scratch[srcarg]);
 			break;
 		case CMD_PIO_WRITE_A_32:
-			if (srcarg) {
-				pio_write_32((ioport32_t *) code->cmds[i].addr,
-				    (uint32_t) scratch[srcarg]);
-			}
-			break;
-		case CMD_BTEST:
-			if ((srcarg) && (dstarg)) {
-				dstval = scratch[srcarg] & code->cmds[i].value;
-				scratch[dstarg] = dstval;
-			}
+			pio_write_32((ioport32_t *) code->cmds[i].addr,
+			    (uint32_t) scratch[srcarg]);
+			break;
+		case CMD_LOAD:
+			scratch[dstarg] = code->cmds[i].value;
+			break;
+		case CMD_AND:
+			scratch[dstarg] = scratch[srcarg] &
+			    code->cmds[i].value;
 			break;
 		case CMD_PREDICATE:
-			if ((srcarg) && (!scratch[srcarg])) {
+			if (scratch[srcarg] == 0)
 				i += code->cmds[i].value;
-				continue;
-			}
+			
 			break;
 		case CMD_ACCEPT:
@@ -582,5 +609,5 @@
 {
 	ASSERT(irq);
-
+	
 	ASSERT(interrupts_disabled());
 	ASSERT(irq_spinlock_locked(&irq->lock));
Index: kernel/generic/src/ipc/sysipc.c
===================================================================
--- kernel/generic/src/ipc/sysipc.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/src/ipc/sysipc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -612,123 +612,4 @@
 		break;
 	}
-	
-	return 0;
-}
-
-/** Make a fast call over IPC, wait for reply and return to user.
- *
- * This function can handle only three arguments of payload, but is faster than
- * the generic function (i.e. sys_ipc_call_sync_slow()).
- *
- * @param phoneid Phone handle for the call.
- * @param imethod Interface and method of the call.
- * @param arg1    Service-defined payload argument.
- * @param arg2    Service-defined payload argument.
- * @param arg3    Service-defined payload argument.
- * @param data    Address of user-space structure where the reply call will
- *                be stored.
- *
- * @return 0 on success.
- * @return ENOENT if there is no such phone handle.
- *
- */
-sysarg_t sys_ipc_call_sync_fast(sysarg_t phoneid, sysarg_t imethod,
-    sysarg_t arg1, sysarg_t arg2, sysarg_t arg3, ipc_data_t *data)
-{
-	phone_t *phone;
-	if (phone_get(phoneid, &phone) != EOK)
-		return ENOENT;
-	
-	call_t *call = ipc_call_alloc(0);
-	IPC_SET_IMETHOD(call->data, imethod);
-	IPC_SET_ARG1(call->data, arg1);
-	IPC_SET_ARG2(call->data, arg2);
-	IPC_SET_ARG3(call->data, arg3);
-	
-	/*
-	 * To achieve deterministic behavior, zero out arguments that are beyond
-	 * the limits of the fast version.
-	 */
-	IPC_SET_ARG4(call->data, 0);
-	IPC_SET_ARG5(call->data, 0);
-	
-	int res = request_preprocess(call, phone);
-	int rc;
-	
-	if (!res) {
-#ifdef CONFIG_UDEBUG
-		udebug_stoppable_begin();
-#endif
-		rc = ipc_call_sync(phone, call);
-#ifdef CONFIG_UDEBUG
-		udebug_stoppable_end();
-#endif
-		
-		if (rc != EOK) {
-			/* The call will be freed by ipc_cleanup(). */
-			return rc;
-		}
-		
-		process_answer(call);
-	} else
-		IPC_SET_RETVAL(call->data, res);
-	
-	rc = STRUCT_TO_USPACE(&data->args, &call->data.args);
-	ipc_call_free(call);
-	if (rc != 0)
-		return rc;
-	
-	return 0;
-}
-
-/** Make a synchronous IPC call allowing to transmit the entire payload.
- *
- * @param phoneid Phone handle for the call.
- * @param request User-space address of call data with the request.
- * @param reply   User-space address of call data where to store the
- *                answer.
- *
- * @return Zero on success or an error code.
- *
- */
-sysarg_t sys_ipc_call_sync_slow(sysarg_t phoneid, ipc_data_t *request,
-    ipc_data_t *reply)
-{
-	phone_t *phone;
-	if (phone_get(phoneid, &phone) != EOK)
-		return ENOENT;
-	
-	call_t *call = ipc_call_alloc(0);
-	int rc = copy_from_uspace(&call->data.args, &request->args,
-	    sizeof(call->data.args));
-	if (rc != 0) {
-		ipc_call_free(call);
-		return (sysarg_t) rc;
-	}
-	
-	int res = request_preprocess(call, phone);
-	
-	if (!res) {
-#ifdef CONFIG_UDEBUG
-		udebug_stoppable_begin();
-#endif
-		rc = ipc_call_sync(phone, call);
-#ifdef CONFIG_UDEBUG
-		udebug_stoppable_end();
-#endif
-		
-		if (rc != EOK) {
-			/* The call will be freed by ipc_cleanup(). */
-			return rc;
-		}
-		
-		process_answer(call);
-	} else
-		IPC_SET_RETVAL(call->data, res);
-	
-	rc = STRUCT_TO_USPACE(&reply->args, &call->data.args);
-	ipc_call_free(call);
-	if (rc != 0)
-		return rc;
 	
 	return 0;
Index: kernel/generic/src/lib/str.c
===================================================================
--- kernel/generic/src/lib/str.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/src/lib/str.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -456,12 +456,17 @@
  *
  * Do a char-by-char comparison of two NULL-terminated strings.
- * The strings are considered equal iff they consist of the same
- * characters on the minimum of their lengths.
+ * The strings are considered equal iff their length is equal
+ * and both strings consist of the same sequence of characters.
+ *
+ * A string S1 is less than another string S2 if it has a character with
+ * lower value at the first character position where the strings differ.
+ * If the strings differ in length, the shorter one is treated as if
+ * padded by characters with a value of zero.
  *
  * @param s1 First string to compare.
  * @param s2 Second string to compare.
  *
- * @return 0 if the strings are equal, -1 if first is smaller,
- *         1 if second smaller.
+ * @return 0 if the strings are equal, -1 if the first is less than the second,
+ *         1 if the second is less than the first.
  *
  */
@@ -494,6 +499,14 @@
  *
  * Do a char-by-char comparison of two NULL-terminated strings.
- * The strings are considered equal iff they consist of the same
- * characters on the minimum of their lengths and the length limit.
+ * The strings are considered equal iff
+ * min(str_length(s1), max_len) == min(str_length(s2), max_len)
+ * and both strings consist of the same sequence of characters,
+ * up to max_len characters.
+ *
+ * A string S1 is less than another string S2 if it has a character with
+ * lower value at the first character position where the strings differ.
+ * If the strings differ in length, the shorter one is treated as if
+ * padded by characters with a value of zero. Only the first max_len
+ * characters are considered.
  *
  * @param s1      First string to compare.
@@ -501,6 +514,6 @@
  * @param max_len Maximum number of characters to consider.
  *
- * @return 0 if the strings are equal, -1 if first is smaller,
- *         1 if second smaller.
+ * @return 0 if the strings are equal, -1 if the first is less than the second,
+ *         1 if the second is less than the first.
  *
  */
Index: kernel/generic/src/proc/task.c
===================================================================
--- kernel/generic/src/proc/task.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/src/proc/task.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -156,5 +156,4 @@
 	
 	list_initialize(&task->threads);
-	list_initialize(&task->sync_boxes);
 	
 	ipc_answerbox_init(&task->answerbox, task);
Index: kernel/generic/src/syscall/syscall.c
===================================================================
--- kernel/generic/src/syscall/syscall.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ kernel/generic/src/syscall/syscall.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -151,6 +151,4 @@
 	
 	/* IPC related syscalls. */
-	(syshandler_t) sys_ipc_call_sync_fast,
-	(syshandler_t) sys_ipc_call_sync_slow,
 	(syshandler_t) sys_ipc_call_async_fast,
 	(syshandler_t) sys_ipc_call_async_slow,
Index: release/Makefile
===================================================================
--- release/Makefile	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ release/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -33,5 +33,5 @@
 
 PROFILES = amd64 arm32/GXemul arm32/integratorcp arm32/gta02 ia32 \
-    ia64/i460GX ia64/ski mips32/GXemul mips32/msim sparc64/niagara \
+    ia64/i460GX ia64/ski mips32/GXemul mips32/msim ppc32 \
     sparc64/ultra
 
@@ -71,5 +71,5 @@
 release: src_rel
 	for profile in $(PROFILES); do \
-		$(MAKE) -C $(EXPORT_DIR) clean ; \
+		$(MAKE) -C $(EXPORT_DIR) distclean ; \
 		$(MAKE) -C $(EXPORT_DIR) PROFILE=$$profile ; \
 		$(MAKE) PROFILE=$$profile releasefile ; \
@@ -79,5 +79,5 @@
 	rm -rf $(EXPORT_DIR)
 	mkdir -p $(EXPORT_DIR)
-	$(BZR) export $(EXPORT_DIR)
+	$(BZR) export $(EXPORT_DIR) ../
 
 src_rel $(SRC_ARCHIVE): export
Index: tools/mkext4.py
===================================================================
--- tools/mkext4.py	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ tools/mkext4.py	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,1 @@
+mkext2.py
Index: uspace/Makefile
===================================================================
--- uspace/Makefile	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -47,5 +47,4 @@
 	app/klog \
 	app/loc \
-	app/lsusb \
 	app/mkfat \
 	app/mkexfat \
@@ -59,4 +58,5 @@
 	app/tester \
 	app/testread \
+	app/testwrit \
 	app/tetris \
 	app/trace \
@@ -85,4 +85,5 @@
 	srv/vfs \
 	srv/bd/ata_bd \
+	srv/bd/sata_bd \
 	srv/bd/file_bd \
 	srv/bd/gxe_bd \
@@ -97,4 +98,5 @@
 	srv/fs/locfs \
 	srv/fs/ext2fs \
+	srv/fs/ext4fs \
 	srv/hid/console \
 	srv/hid/s3c24xx_ts \
@@ -105,4 +107,5 @@
 	drv/infrastructure/root \
 	drv/infrastructure/rootvirt \
+	drv/block/ahci \
 	drv/char/i8042 \
 	drv/char/ps2mouse \
@@ -169,4 +172,5 @@
 	DIRS += \
 		drv/infrastructure/rootmac \
+		drv/bus/pci/pciintel \
 		srv/hw/bus/cuda_adb
 endif
@@ -194,4 +198,5 @@
 	lib/nic \
 	lib/ext2 \
+	lib/ext4 \
 	lib/usb \
 	lib/usbhost \
Index: uspace/Makefile.common
===================================================================
--- uspace/Makefile.common	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/Makefile.common	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -115,4 +115,5 @@
 
 LIBEXT2_PREFIX = $(LIB_PREFIX)/ext2
+LIBEXT4_PREFIX = $(LIB_PREFIX)/ext4
 
 LIBUSB_PREFIX = $(LIB_PREFIX)/usb
Index: uspace/app/bdsh/cmds/modules/cat/cat.c
===================================================================
--- uspace/app/bdsh/cmds/modules/cat/cat.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/app/bdsh/cmds/modules/cat/cat.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -176,12 +176,12 @@
 
 	bool reading_stdin = dash_represents_stdin && (str_cmp(fname, "-") == 0);
-
+	
 	if (reading_stdin) {
 		fd = fileno(stdin);
 		/* Allow storing the whole UTF-8 character. */
 		blen = STR_BOUNDS(1);
-	} else {
+	} else
 		fd = open(fname, O_RDONLY);
-	}
+	
 	if (fd < 0) {
 		printf("Unable to open %s\n", fname);
@@ -222,6 +222,6 @@
 			bytes_to_read = 1;
 		} else {
-			if ((length != CAT_FULL_FILE)
-			    && (length - (off64_t)count <= (off64_t)(blen - copied_bytes))) {
+			if ((length != CAT_FULL_FILE) &&
+			    (length - (off64_t)count <= (off64_t)(blen - copied_bytes))) {
 				bytes_to_read = (size_t) (length - count);
 			} else {
@@ -229,4 +229,5 @@
 			}
 		}
+		
 		bytes = read(fd, buff + copied_bytes, bytes_to_read);
 		bytes += copied_bytes;
@@ -261,8 +262,7 @@
 			reads++;
 		}
-
-		if (reading_stdin) {
+		
+		if (reading_stdin)
 			fflush(stdout);
-		}
 	} while (bytes > 0 && !should_quit && (count < length || length == CAT_FULL_FILE));
 
Index: pace/app/lsusb/Makefile
===================================================================
--- uspace/app/lsusb/Makefile	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ 	(revision )
@@ -1,44 +1,0 @@
-#
-# Copyright (c) 2011 Vojtech Horky
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-#
-# - Redistributions of source code must retain the above copyright
-#   notice, this list of conditions and the following disclaimer.
-# - Redistributions in binary form must reproduce the above copyright
-#   notice, this list of conditions and the following disclaimer in the
-#   documentation and/or other materials provided with the distribution.
-# - The name of the author may not be used to endorse or promote products
-#   derived from this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
-# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
-# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
-# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
-# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-
-USPACE_PREFIX = ../..
-BINARY = lsusb
-
-LIBS = \
-	$(LIBUSBDEV_PREFIX)/libusbdev.a \
-	$(LIBUSB_PREFIX)/libusb.a \
-	$(LIBDRV_PREFIX)/libdrv.a
-EXTRA_CFLAGS = \
-	-I$(LIBUSB_PREFIX)/include \
-	-I$(LIBUSBDEV_PREFIX)/include \
-	-I$(LIBDRV_PREFIX)/include
-
-SOURCES = \
-	main.c
-
-include $(USPACE_PREFIX)/Makefile.common
Index: pace/app/lsusb/main.c
===================================================================
--- uspace/app/lsusb/main.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ 	(revision )
@@ -1,139 +1,0 @@
-/*
- * Copyright (c) 2010-2011 Vojtech Horky
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * - Redistributions of source code must retain the above copyright
- *   notice, this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - The name of the author may not be used to endorse or promote products
- *   derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/** @addtogroup lsusb
- * @{
- */
-/**
- * @file
- * Listing of USB host controllers.
- */
-
-#include <inttypes.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <str_error.h>
-#include <bool.h>
-#include <getopt.h>
-#include <devman.h>
-#include <loc.h>
-#include <usb/dev/hub.h>
-#include <usb/hc.h>
-
-#define NAME "lsusb"
-
-#define MAX_USB_ADDRESS USB11_ADDRESS_MAX
-#define MAX_PATH_LENGTH 1024
-
-static void print_found_hc(service_id_t sid, const char *path)
-{
-	printf("Bus %" PRIun ": %s\n", sid, path);
-}
-static void print_found_dev(usb_address_t addr, const char *path)
-{
-	printf("  Device %02d: %s\n", addr, path);
-}
-
-static void print_hc_devices(devman_handle_t hc_handle)
-{
-	int rc;
-	usb_hc_connection_t conn;
-
-	usb_hc_connection_initialize(&conn, hc_handle);
-	rc = usb_hc_connection_open(&conn);
-	if (rc != EOK) {
-		printf(NAME ": failed to connect to HC: %s.\n",
-		    str_error(rc));
-		return;
-	}
-	usb_address_t addr;
-	for (addr = 1; addr < MAX_USB_ADDRESS; addr++) {
-		devman_handle_t dev_handle;
-		rc = usb_hc_get_handle_by_address(&conn, addr, &dev_handle);
-		if (rc != EOK) {
-			continue;
-		}
-		char path[MAX_PATH_LENGTH];
-		rc = devman_fun_get_path(dev_handle, path, MAX_PATH_LENGTH);
-		if (rc != EOK) {
-			continue;
-		}
-		print_found_dev(addr, path);
-	}
-	usb_hc_connection_close(&conn);
-}
-
-int main(int argc, char *argv[])
-{
-	category_id_t usbhc_cat;
-	service_id_t *svcs;
-	size_t count;
-	size_t i;
-	int rc;
-
-	rc = loc_category_get_id(USB_HC_CATEGORY, &usbhc_cat, 0);
-	if (rc != EOK) {
-		printf(NAME ": Error resolving category '%s'",
-		    USB_HC_CATEGORY);
-		return 1;
-	}
-
-	rc = loc_category_get_svcs(usbhc_cat, &svcs, &count);
-	if (rc != EOK) {
-		printf(NAME ": Error getting list of host controllers.\n");
-		return 1;
-	}
-
-	for (i = 0; i < count; i++) {
-		devman_handle_t hc_handle = 0;
-		int rc = usb_ddf_get_hc_handle_by_sid(svcs[i], &hc_handle);
-		if (rc != EOK) {
-			printf(NAME ": Error resolving handle of HC with SID %"
-			    PRIun ", skipping.\n", svcs[i]);
-			continue;
-		}
-		char path[MAX_PATH_LENGTH];
-		rc = devman_fun_get_path(hc_handle, path, MAX_PATH_LENGTH);
-		if (rc != EOK) {
-			printf(NAME ": Error resolving path of HC with SID %"
-			    PRIun ", skipping.\n", svcs[i]);
-			continue;
-		}
-		print_found_hc(svcs[i], path);
-		print_hc_devices(hc_handle);
-	}
-
-	free(svcs);
-
-	return 0;
-}
-
-
-/** @}
- */
Index: uspace/app/sportdmp/sportdmp.c
===================================================================
--- uspace/app/sportdmp/sportdmp.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/app/sportdmp/sportdmp.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -37,15 +37,25 @@
 static void syntax_print(void)
 {
-	fprintf(stderr, "Usage: sportdmp <baud> <device_service>\n");
+	fprintf(stderr, "Usage: sportdmp [--baud=<baud>] [device_service]\n");
 }
 
 int main(int argc, char **argv)
 {
-	const char* svc_path = "devices/\\hw\\pci0\\00:01.0\\com1\\a";
 	sysarg_t baud = 9600;
+	service_id_t svc_id;
 	
-	if (argc > 1) {
+	int arg = 1;
+	int rc;
+		
+	if (argc > arg && str_test_prefix(argv[arg], "--baud=")) {
+		size_t arg_offset = str_lsize(argv[arg], 7);
+		char* arg_str = argv[arg] + arg_offset;
+		if (str_length(arg_str) == 0) {
+			fprintf(stderr, "--baud requires an argument\n");
+			syntax_print();
+			return 1;
+		}
 		char *endptr;
-		baud = strtol(argv[1], &endptr, 10);
+		baud = strtol(arg_str, &endptr, 10);
 		if (*endptr != '\0') {
 			fprintf(stderr, "Invalid value for baud\n");
@@ -53,26 +63,55 @@
 			return 1;
 		}
+		arg++;
 	}
 	
-	if (argc > 2) {
-		svc_path = argv[2];
+	if (argc > arg) {
+		rc = loc_service_get_id(argv[arg], &svc_id, 0);
+		if (rc != EOK) {
+			fprintf(stderr, "Cannot find device service %s\n",
+			    argv[arg]);
+			return 1;
+		}
+		arg++;
+	}
+	else {
+		category_id_t serial_cat_id;
+		
+		rc = loc_category_get_id("serial", &serial_cat_id, 0);
+		if (rc != EOK) {
+			fprintf(stderr, "Failed getting id of category "
+			    "'serial'\n");
+			return 1;
+		}
+		
+		service_id_t *svc_ids;
+		size_t svc_count;
+		
+		rc = loc_category_get_svcs(serial_cat_id, &svc_ids, &svc_count);		if (rc != EOK) {
+			fprintf(stderr, "Failed getting list of services\n");
+			return 1;
+		}
+		
+		if (svc_count == 0) {
+			fprintf(stderr, "No service in category 'serial'\n");
+			free(svc_ids);
+			return 1;
+		}
+		
+		svc_id = svc_ids[0];
+		free(svc_ids);
 	}
 	
-	if (argc > 3) {
+	if (argc > arg) {
+		fprintf(stderr, "Too many arguments\n");
 		syntax_print();
 		return 1;
 	}
 	
-	service_id_t svc_id;
-	int rc = loc_service_get_id(svc_path, &svc_id, IPC_FLAG_BLOCKING);
-	if (rc != EOK) {
-		fprintf(stderr, "Cannot find device service %s\n", svc_path);
-		return 1;
-	}
 	
 	async_sess_t *sess = loc_service_connect(EXCHANGE_SERIALIZE, svc_id,
 	    IPC_FLAG_BLOCKING);
 	if (!sess) {
-		fprintf(stderr, "Failed connecting to service %s\n", svc_path);
+		fprintf(stderr, "Failed connecting to service\n");
 	}
 	
Index: uspace/app/testwrit/Makefile
===================================================================
--- uspace/app/testwrit/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/app/testwrit/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,35 @@
+#
+# Copyright (c) 2011 Frantisek Princ
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+#   notice, this list of conditions and the following disclaimer.
+# - Redistributions in binary form must reproduce the above copyright
+#   notice, this list of conditions and the following disclaimer in the
+#   documentation and/or other materials provided with the distribution.
+# - The name of the author may not be used to endorse or promote products
+#   derived from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+USPACE_PREFIX = ../..
+BINARY = testwrit
+
+SOURCES = \
+	testwrit.c
+
+include $(USPACE_PREFIX)/Makefile.common
Index: uspace/app/testwrit/testwrit.c
===================================================================
--- uspace/app/testwrit/testwrit.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/app/testwrit/testwrit.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2011 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup test
+ * @{
+ */
+
+#include <stdio.h>
+#include <unistd.h>
+
+#define BUF_SIZE  1024
+
+int main(int argc, char *argv[])
+{
+	char buffer[BUF_SIZE];
+	uint64_t iterations, i;
+	FILE *file;
+	char *file_name;
+	
+	/* Prepare some example data */
+	memset(buffer, 0xcafebabe, BUF_SIZE);
+	
+	if (argc != 3) {
+		printf("syntax: testwrit <iterations> <target file>\n");
+		return 1;
+	}
+	
+	char *end;
+	iterations = strtoul(argv[1], &end, 10);
+	file_name = argv[2];
+	
+	/* Open target file */
+	file = fopen(file_name, "a");
+	if (file == NULL) {
+		printf("Failed opening file\n");
+		return 1;
+	}
+	
+	/* Writing loop */
+	for (i = 0; i < iterations; ++i) {
+		fwrite(buffer, 1, BUF_SIZE, file);
+	}
+	
+	fclose(file);
+	
+	return 0;
+}
+
+/**
+ * @}
+ */
Index: uspace/app/trace/syscalls.c
===================================================================
--- uspace/app/trace/syscalls.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/app/trace/syscalls.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -53,6 +53,4 @@
     [SYS_AS_AREA_DESTROY] = { "as_area_destroy",	1,	V_ERRNO },
 
-    [SYS_IPC_CALL_SYNC_FAST] = { "ipc_call_sync_fast",	6,	V_ERRNO },
-    [SYS_IPC_CALL_SYNC_SLOW] = { "ipc_call_sync_slow",	3,	V_ERRNO },
     [SYS_IPC_CALL_ASYNC_FAST] = { "ipc_call_async_fast", 6,	V_HASH },
     [SYS_IPC_CALL_ASYNC_SLOW] = { "ipc_call_async_slow", 2,	V_HASH },
Index: uspace/app/trace/trace.c
===================================================================
--- uspace/app/trace/trace.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/app/trace/trace.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -318,61 +318,4 @@
 }
 
-static void sc_ipc_call_sync_fast(sysarg_t *sc_args)
-{
-	ipc_call_t question, reply;
-	int rc;
-	int phoneid;
-
-	phoneid = sc_args[0];
-
-	IPC_SET_IMETHOD(question, sc_args[1]);
-	IPC_SET_ARG1(question, sc_args[2]);
-	IPC_SET_ARG2(question, sc_args[3]);
-	IPC_SET_ARG3(question, sc_args[4]);
-	IPC_SET_ARG4(question, 0);
-	IPC_SET_ARG5(question, 0);
-
-	memset(&reply, 0, sizeof(reply));
-	rc = udebug_mem_read(sess, &reply.args, sc_args[5], sizeof(reply.args));
-	if (rc < 0)
-		return;
-	
-	ipcp_call_sync(phoneid, &question, &reply);
-}
-
-static void sc_ipc_call_sync_slow_b(unsigned thread_id, sysarg_t *sc_args)
-{
-	ipc_call_t question;
-	int rc;
-
-	memset(&question, 0, sizeof(question));
-	rc = udebug_mem_read(sess, &question.args, sc_args[1],
-	    sizeof(question.args));
-
-	if (rc < 0) {
-		printf("Error: mem_read->%d\n", rc);
-		return;
-	}
-
-	thread_ipc_req[thread_id] = question;
-}
-
-static void sc_ipc_call_sync_slow_e(unsigned thread_id, sysarg_t *sc_args)
-{
-	ipc_call_t reply;
-	int rc;
-
-	memset(&reply, 0, sizeof(reply));
-	rc = udebug_mem_read(sess, &reply.args, sc_args[2],
-	    sizeof(reply.args));
-
-	if (rc < 0) {
-		printf("Error: mem_read->%d\n", rc);
-		return;
-	}
-
-	ipcp_call_sync(sc_args[0], &thread_ipc_req[thread_id], &reply);
-}
-
 static void sc_ipc_wait(sysarg_t *sc_args, int sc_rc)
 {
@@ -408,12 +351,4 @@
 		print_sc_args(sc_args, syscall_desc[sc_id].n_args);
 	}
-
-	switch (sc_id) {
-	case SYS_IPC_CALL_SYNC_SLOW:
-		sc_ipc_call_sync_slow_b(thread_id, sc_args);
-		break;
-	default:
-		break;
-	}
 }
 
@@ -447,10 +382,4 @@
 	case SYS_IPC_CALL_ASYNC_SLOW:
 		sc_ipc_call_async_slow(sc_args, sc_rc);
-		break;
-	case SYS_IPC_CALL_SYNC_FAST:
-		sc_ipc_call_sync_fast(sc_args);
-		break;
-	case SYS_IPC_CALL_SYNC_SLOW:
-		sc_ipc_call_sync_slow_e(thread_id, sc_args);
 		break;
 	case SYS_IPC_WAIT:
Index: uspace/app/usbinfo/Makefile
===================================================================
--- uspace/app/usbinfo/Makefile	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/app/usbinfo/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -47,4 +47,5 @@
 	hid.c \
 	info.c \
+	list.c \
 	main.c
 
Index: uspace/app/usbinfo/list.c
===================================================================
--- uspace/app/usbinfo/list.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/app/usbinfo/list.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2010-2011 Vojtech Horky
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup lsusb
+ * @{
+ */
+/**
+ * @file
+ * Listing of USB host controllers.
+ */
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <str_error.h>
+#include <bool.h>
+#include <getopt.h>
+#include <devman.h>
+#include <loc.h>
+#include <usb/dev/hub.h>
+#include <usb/hc.h>
+
+#include "usbinfo.h"
+
+#define MAX_USB_ADDRESS USB11_ADDRESS_MAX
+#define MAX_PATH_LENGTH 1024
+
+static void print_found_hc(service_id_t sid, const char *path)
+{
+	printf("Bus %" PRIun ": %s\n", sid, path);
+}
+static void print_found_dev(usb_address_t addr, const char *path)
+{
+	printf("  Device %02d: %s\n", addr, path);
+}
+
+static void print_hc_devices(devman_handle_t hc_handle)
+{
+	int rc;
+	usb_hc_connection_t conn;
+
+	usb_hc_connection_initialize(&conn, hc_handle);
+	rc = usb_hc_connection_open(&conn);
+	if (rc != EOK) {
+		printf(NAME ": failed to connect to HC: %s.\n",
+		    str_error(rc));
+		return;
+	}
+	usb_address_t addr;
+	for (addr = 1; addr < MAX_USB_ADDRESS; addr++) {
+		devman_handle_t dev_handle;
+		rc = usb_hc_get_handle_by_address(&conn, addr, &dev_handle);
+		if (rc != EOK) {
+			continue;
+		}
+		char path[MAX_PATH_LENGTH];
+		rc = devman_fun_get_path(dev_handle, path, MAX_PATH_LENGTH);
+		if (rc != EOK) {
+			continue;
+		}
+		print_found_dev(addr, path);
+	}
+	usb_hc_connection_close(&conn);
+}
+
+void list(void)
+{
+	category_id_t usbhc_cat;
+	service_id_t *svcs;
+	size_t count;
+	size_t i;
+	int rc;
+
+	rc = loc_category_get_id(USB_HC_CATEGORY, &usbhc_cat, 0);
+	if (rc != EOK) {
+		printf(NAME ": Error resolving category '%s'",
+		    USB_HC_CATEGORY);
+		return;
+	}
+
+	rc = loc_category_get_svcs(usbhc_cat, &svcs, &count);
+	if (rc != EOK) {
+		printf(NAME ": Error getting list of host controllers.\n");
+		return;
+	}
+
+	for (i = 0; i < count; i++) {
+		devman_handle_t hc_handle = 0;
+		int rc = usb_ddf_get_hc_handle_by_sid(svcs[i], &hc_handle);
+		if (rc != EOK) {
+			printf(NAME ": Error resolving handle of HC with SID %"
+			    PRIun ", skipping.\n", svcs[i]);
+			continue;
+		}
+		char path[MAX_PATH_LENGTH];
+		rc = devman_fun_get_path(hc_handle, path, MAX_PATH_LENGTH);
+		if (rc != EOK) {
+			printf(NAME ": Error resolving path of HC with SID %"
+			    PRIun ", skipping.\n", svcs[i]);
+			continue;
+		}
+		print_found_hc(svcs[i], path);
+		print_hc_devices(hc_handle);
+	}
+
+	free(svcs);
+}
+
+
+/** @}
+ */
Index: uspace/app/usbinfo/main.c
===================================================================
--- uspace/app/usbinfo/main.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/app/usbinfo/main.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -62,4 +62,5 @@
 
 	_OPTION("-h --help", "Print this help and exit.");
+	_OPTION("-l --list", "Print a list of host controllers and devices.");
 	_OPTION("-i --identification", "Brief device identification.");
 	_OPTION("-m --match-ids", "Print match ids generated for the device.");
@@ -82,4 +83,5 @@
 	{"help", no_argument, NULL, 'h'},
 	{"identification", no_argument, NULL, 'i'},
+	{"list", no_argument, NULL, 'l'},
 	{"match-ids", no_argument, NULL, 'm'},
 	{"descriptor-tree", no_argument, NULL, 't'},
@@ -91,5 +93,5 @@
 	{0, 0, NULL, 0}
 };
-static const char *short_options = "himtTsSrR";
+static const char *short_options = "hilmtTsSrR";
 
 static usbinfo_action_t actions[] = {
@@ -146,4 +148,5 @@
 	}
 
+	bool something_active = false;
 	/*
 	 * Process command-line options. They determine what shall be
@@ -156,4 +159,7 @@
 		switch (opt) {
 			case -1:
+				break;
+			case 'l':
+				list();
 				break;
 			case '?':
@@ -168,4 +174,5 @@
 					if (actions[idx].opt == opt) {
 						actions[idx].active = true;
+						something_active = true;
 						break;
 					}
@@ -178,13 +185,4 @@
 
 	/* Set the default action. */
-	int idx = 0;
-	bool something_active = false;
-	while (actions[idx].opt != 0) {
-		if (actions[idx].active) {
-			something_active = true;
-			break;
-		}
-		idx++;
-	}
 	if (!something_active) {
 		actions[0].active = true;
Index: uspace/app/usbinfo/usbinfo.h
===================================================================
--- uspace/app/usbinfo/usbinfo.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/app/usbinfo/usbinfo.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -79,4 +79,5 @@
     dump_descriptor_in_tree_t, size_t, void *);
 
+void list(void);
 
 void dump_short_device_identification(usbinfo_device_t *);
Index: uspace/drv/block/ahci/Makefile
===================================================================
--- uspace/drv/block/ahci/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/drv/block/ahci/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,37 @@
+#
+# Copyright (c) 2012 Petr Jerman
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+#   notice, this list of conditions and the following disclaimer.
+# - Redistributions in binary form must reproduce the above copyright
+#   notice, this list of conditions and the following disclaimer in the
+#   documentation and/or other materials provided with the distribution.
+# - The name of the author may not be used to endorse or promote products
+#   derived from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+USPACE_PREFIX = ../../..
+LIBS = $(LIBDRV_PREFIX)/libdrv.a
+EXTRA_CFLAGS += -I$(LIBDRV_PREFIX)/include
+BINARY = ahci
+
+SOURCES = \
+	ahci.c
+
+include $(USPACE_PREFIX)/Makefile.common
Index: uspace/drv/block/ahci/ahci.c
===================================================================
--- uspace/drv/block/ahci/ahci.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/drv/block/ahci/ahci.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,1336 @@
+/*
+ * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @file
+ * AHCI SATA driver implementation.
+ */
+
+#include <as.h>
+#include <errno.h>
+#include <stdio.h>
+#include <devman.h>
+#include <ddf/interrupt.h>
+#include <ddf/log.h>
+#include <device/hw_res_parsed.h>
+#include <device/pci.h>
+#include <sysinfo.h>
+#include <ipc/irc.h>
+#include <ns.h>
+#include <ahci_iface.h>
+#include "ahci.h"
+#include "ahci_hw.h"
+#include "ahci_sata.h"
+
+#define NAME  "ahci"
+
+#define LO(ptr) \
+	((uint32_t) (((uint64_t) ((uintptr_t) (ptr))) & 0xffffffff))
+
+#define HI(ptr) \
+	((uint32_t) (((uint64_t) ((uintptr_t) (ptr))) >> 32))
+
+/** Interrupt pseudocode for a single port
+ *
+ * The interrupt handling works as follows:
+ *
+ * 1. Port interrupt status register is read
+ *    (stored as arg2).
+ * 2. If port interrupt is indicated, then:
+ *    3. Port interrupt status register is cleared.
+ *    4. Global interrupt status register is read
+ *       and cleared (any potential interrupts from
+ *       other ports are reasserted automatically).
+ *    5. Port number is stored as arg1.
+ *    6. The interrupt is accepted.
+ *
+ */
+#define AHCI_PORT_CMDS(port) \
+	{ \
+		/* Read port interrupt status register */ \
+		.cmd = CMD_PIO_READ_32, \
+		.addr = NULL, \
+		.dstarg = 2 \
+	}, \
+	{ \
+		/* Check if port asserted interrupt */ \
+		.cmd = CMD_PREDICATE, \
+		.value = 5, \
+		.srcarg = 2, \
+	}, \
+	{ \
+		/* Clear port interrupt status register */ \
+		.cmd = CMD_PIO_WRITE_A_32, \
+		.addr = NULL, \
+		.srcarg = 2 \
+	}, \
+	{ \
+		/* Read global interrupt status register */ \
+		.cmd = CMD_PIO_READ_32, \
+		.addr = NULL, \
+		.dstarg = 0 \
+	}, \
+	{ \
+		/* Clear global interrupt status register */ \
+		.cmd = CMD_PIO_WRITE_A_32, \
+		.addr = NULL, \
+		.srcarg = 0 \
+	}, \
+	{ \
+		/* Indicate port interrupt assertion */ \
+		.cmd = CMD_LOAD, \
+		.value = (port), \
+		.dstarg = 1 \
+	}, \
+	{ \
+		/* Accept the interrupt */ \
+		.cmd = CMD_ACCEPT \
+	}
+
+static int ahci_get_sata_device_name(ddf_fun_t *, size_t, char *);
+static int ahci_get_num_blocks(ddf_fun_t *, uint64_t *);
+static int ahci_get_block_size(ddf_fun_t *, size_t *);
+static int ahci_read_blocks(ddf_fun_t *, uint64_t, size_t, void *);
+static int ahci_write_blocks(ddf_fun_t *, uint64_t, size_t, void *);
+
+static int ahci_identify_device(sata_dev_t *);
+static int ahci_set_highest_ultra_dma_mode(sata_dev_t *);
+static int ahci_rb_fpdma(sata_dev_t *, void *, uint64_t);
+static int ahci_wb_fpdma(sata_dev_t *, void *, uint64_t);
+
+static void ahci_sata_devices_create(ahci_dev_t *, ddf_dev_t *);
+static ahci_dev_t *ahci_ahci_create(ddf_dev_t *);
+static void ahci_ahci_hw_start(ahci_dev_t *);
+
+static int ahci_dev_add(ddf_dev_t *);
+
+static void ahci_get_model_name(uint16_t *, char *);
+static int ahci_enable_interrupt(int);
+
+static fibril_mutex_t sata_devices_count_lock;
+static int sata_devices_count = 0;
+
+/*----------------------------------------------------------------------------*/
+/*-- AHCI Interface ----------------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+static ahci_iface_t ahci_interface = {
+	.get_sata_device_name = &ahci_get_sata_device_name,
+	.get_num_blocks = &ahci_get_num_blocks,
+	.get_block_size = &ahci_get_block_size,
+	.read_blocks = &ahci_read_blocks,
+	.write_blocks = &ahci_write_blocks
+};
+
+static ddf_dev_ops_t ahci_ops = {
+	.interfaces[AHCI_DEV_IFACE] = &ahci_interface
+};
+
+static driver_ops_t driver_ops = {
+	.dev_add = &ahci_dev_add
+};
+
+static driver_t ahci_driver = {
+	.name = NAME,
+	.driver_ops = &driver_ops
+};
+
+/** Get SATA device name.
+ *
+ * @param fun                  Device function handling the call.
+ * @param sata_dev_name_length Length of the sata_dev_name buffer.
+ * @param sata_dev_name        Buffer for SATA device name.
+ *
+ * @return EOK.
+ *
+ */
+static int ahci_get_sata_device_name(ddf_fun_t *fun,
+    size_t sata_dev_name_length, char *sata_dev_name)
+{
+	sata_dev_t *sata = (sata_dev_t *) fun->driver_data;
+	str_cpy(sata_dev_name, sata_dev_name_length, sata->model);
+	return EOK;
+}
+
+/** Get Number of blocks in SATA device.
+ *
+ * @param fun    Device function handling the call.
+ * @param blocks Return number of blocks in SATA device.
+ *
+ * @return EOK.
+ *
+ */
+static int ahci_get_num_blocks(ddf_fun_t *fun, uint64_t *num_blocks)
+{
+	sata_dev_t *sata = (sata_dev_t *) fun->driver_data;
+	*num_blocks = sata->blocks;
+	return EOK;
+}
+
+/** Get SATA device block size.
+ *
+ * @param fun        Device function handling the call.
+ * @param block_size Return block size.
+ *
+ * @return EOK.
+ *
+ */
+static int ahci_get_block_size(ddf_fun_t *fun, size_t *block_size)
+{
+	sata_dev_t *sata = (sata_dev_t *) fun->driver_data;
+	*block_size = sata->block_size;
+	return EOK;
+}
+
+/** Read data blocks into SATA device.
+ *
+ * @param fun      Device function handling the call.
+ * @param blocknum Number of first block.
+ * @param count    Number of blocks to read.
+ * @param buf      Buffer for data.
+ *
+ * @return EOK if succeed, error code otherwise
+ *
+ */
+static int ahci_read_blocks(ddf_fun_t *fun, uint64_t blocknum,
+    size_t count, void *buf)
+{
+	sata_dev_t *sata = (sata_dev_t *) fun->driver_data;
+	
+	void *phys;
+	void *ibuf;
+	int rc = dmamem_map_anonymous(sata->block_size, AS_AREA_READ | AS_AREA_WRITE,
+	    0, &phys, (void **) &ibuf);
+	if (rc != EOK) {
+		ddf_msg(LVL_ERROR, "Cannot allocate read buffer.");
+		return rc;
+	}
+	
+	bzero(buf, sata->block_size);
+	
+	fibril_mutex_lock(&sata->lock);
+	
+	for (size_t cur = 0; cur < count; cur++) {
+		rc = ahci_rb_fpdma(sata, phys, blocknum + cur);
+		if (rc != EOK)
+			break;
+		
+		memcpy((void *) (((uint8_t *) buf) + (sata->block_size * cur)),
+		    ibuf, sata->block_size);
+	}
+	
+	fibril_mutex_unlock(&sata->lock);
+	dmamem_unmap_anonymous(ibuf);
+	
+	return rc;
+}
+
+/** Write data blocks into SATA device.
+ *
+ * @param fun      Device function handling the call.
+ * @param blocknum Number of first block.
+ * @param count    Number of blocks to write.
+ * @param buf      Buffer with data.
+ *
+ * @return EOK if succeed, error code otherwise
+ *
+ */
+static int ahci_write_blocks(ddf_fun_t *fun, uint64_t blocknum,
+    size_t count, void *buf)
+{
+	sata_dev_t *sata = (sata_dev_t *) fun->driver_data;
+	
+	void *phys;
+	void *ibuf;
+	int rc = dmamem_map_anonymous(sata->block_size, AS_AREA_READ | AS_AREA_WRITE,
+	    0, &phys, (void **) &ibuf);
+	if (rc != EOK) {
+		ddf_msg(LVL_ERROR, "Cannot allocate write buffer.");
+		return rc;
+	}
+	
+	fibril_mutex_lock(&sata->lock);
+	
+	for (size_t cur = 0; cur < count; cur++) {
+		memcpy(ibuf, (void *) (((uint8_t *) buf) + (sata->block_size * cur)),
+		    sata->block_size);
+		rc = ahci_wb_fpdma(sata, phys, blocknum + cur);
+		if (rc != EOK)
+			break;
+	}
+	
+	fibril_mutex_unlock(&sata->lock);
+	dmamem_unmap_anonymous(ibuf);
+	
+	return rc;
+}
+
+/*----------------------------------------------------------------------------*/
+/*-- AHCI Commands -----------------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+/** Wait for interrupt event.
+ *
+ * @param sata SATA device structure.
+ *
+ * @return Value of interrupt state register.
+ *
+ */
+static ahci_port_is_t ahci_wait_event(sata_dev_t *sata)
+{
+	fibril_mutex_lock(&sata->event_lock);
+	
+	sata->event_pxis = 0;
+	while (sata->event_pxis == 0)
+		fibril_condvar_wait(&sata->event_condvar, &sata->event_lock);
+	
+	ahci_port_is_t pxis = sata->event_pxis;
+	
+	if (ahci_port_is_permanent_error(pxis))
+		sata->is_invalid_device = true;
+	
+	fibril_mutex_unlock(&sata->event_lock);
+	
+	return pxis;
+}
+
+/** Set AHCI registers for identifying SATA device.
+ *
+ * @param sata SATA device structure.
+ * @param phys Physical address of working buffer.
+ *
+ */
+static void ahci_identify_device_cmd(sata_dev_t *sata, void *phys)
+{
+	volatile sata_std_command_frame_t *cmd =
+	    (sata_std_command_frame_t *) sata->cmd_table;
+	
+	cmd->fis_type = SATA_CMD_FIS_TYPE;
+	cmd->c = SATA_CMD_FIS_COMMAND_INDICATOR;
+	cmd->command = 0xec;
+	cmd->features = 0;
+	cmd->lba_lower = 0;
+	cmd->device = 0;
+	cmd->lba_upper = 0;
+	cmd->features_upper = 0;
+	cmd->count = 0;
+	cmd->reserved1 = 0;
+	cmd->control = 0;
+	cmd->reserved2 = 0;
+	
+	volatile ahci_cmd_prdt_t *prdt =
+	    (ahci_cmd_prdt_t *) (&sata->cmd_table[0x20]);
+	
+	prdt->data_address_low = LO(phys);
+	prdt->data_address_upper = HI(phys);
+	prdt->reserved1 = 0;
+	prdt->dbc = SATA_IDENTIFY_DEVICE_BUFFER_LENGTH - 1;
+	prdt->reserved2 = 0;
+	prdt->ioc = 0;
+	
+	sata->cmd_header->prdtl = 1;
+	sata->cmd_header->flags =
+	    AHCI_CMDHDR_FLAGS_CLEAR_BUSY_UPON_OK |
+	    AHCI_CMDHDR_FLAGS_2DWCMD;
+	sata->cmd_header->bytesprocessed = 0;
+	
+	/* Run command. */
+	sata->port->pxsact |= 1;
+	sata->port->pxci |= 1;
+}
+
+/** Set AHCI registers for identifying packet SATA device.
+ *
+ * @param sata SATA device structure.
+ * @param phys Physical address of working buffer.
+ *
+ */
+static void ahci_identify_packet_device_cmd(sata_dev_t *sata, void *phys)
+{
+	volatile sata_std_command_frame_t *cmd =
+	    (sata_std_command_frame_t *) sata->cmd_table;
+	
+	cmd->fis_type = SATA_CMD_FIS_TYPE;
+	cmd->c = SATA_CMD_FIS_COMMAND_INDICATOR;
+	cmd->command = 0xa1;
+	cmd->features = 0;
+	cmd->lba_lower = 0;
+	cmd->device = 0;
+	cmd->lba_upper = 0;
+	cmd->features_upper = 0;
+	cmd->count = 0;
+	cmd->reserved1 = 0;
+	cmd->control = 0;
+	cmd->reserved2 = 0;
+	
+	volatile ahci_cmd_prdt_t *prdt =
+	    (ahci_cmd_prdt_t *) (&sata->cmd_table[0x20]);
+	
+	prdt->data_address_low = LO(phys);
+	prdt->data_address_upper = HI(phys);
+	prdt->reserved1 = 0;
+	prdt->dbc = SATA_IDENTIFY_DEVICE_BUFFER_LENGTH - 1;
+	prdt->reserved2 = 0;
+	prdt->ioc = 0;
+	
+	sata->cmd_header->prdtl = 1;
+	sata->cmd_header->flags =
+	    AHCI_CMDHDR_FLAGS_CLEAR_BUSY_UPON_OK |
+	    AHCI_CMDHDR_FLAGS_2DWCMD;
+	sata->cmd_header->bytesprocessed = 0;
+	
+	/* Run command. */
+	sata->port->pxsact |= 1;
+	sata->port->pxci |= 1;
+}
+
+/** Fill device identification in SATA device structure.
+ *
+ * @param sata SATA device structure.
+ *
+ * @return EOK if succeed, error code otherwise.
+ *
+ */
+static int ahci_identify_device(sata_dev_t *sata)
+{
+	if (sata->is_invalid_device) {
+		ddf_msg(LVL_ERROR,
+		    "Identify command device on invalid device");
+		return EINTR;
+	}
+	
+	void *phys;
+	sata_identify_data_t *idata;
+	int rc = dmamem_map_anonymous(SATA_IDENTIFY_DEVICE_BUFFER_LENGTH,
+	    AS_AREA_READ | AS_AREA_WRITE, 0, &phys, (void **) &idata);
+	if (rc != EOK) {
+		ddf_msg(LVL_ERROR, "Cannot allocate buffer to identify device.");
+		return rc;
+	}
+	
+	bzero(idata, SATA_IDENTIFY_DEVICE_BUFFER_LENGTH);
+	
+	fibril_mutex_lock(&sata->lock);
+	
+	ahci_identify_device_cmd(sata, phys);
+	ahci_port_is_t pxis = ahci_wait_event(sata);
+	
+	if (sata->is_invalid_device) {
+		ddf_msg(LVL_ERROR,
+		    "Unrecoverable error during ata identify device");
+		goto error;
+	}
+	
+	if (ahci_port_is_tfes(pxis)) {
+		ahci_identify_packet_device_cmd(sata, phys);
+		pxis = ahci_wait_event(sata);
+		
+		if ((sata->is_invalid_device) || (ahci_port_is_error(pxis))) {
+			ddf_msg(LVL_ERROR,
+			    "Unrecoverable error during ata identify packet device");
+			goto error;
+		}
+		
+		sata->is_packet_device = true;
+	}
+	
+	ahci_get_model_name(idata->model_name, sata->model);
+	
+	/*
+	 * Due to QEMU limitation (as of 2012-06-22),
+	 * only NCQ FPDMA mode is supported.
+	 */
+	if ((idata->sata_cap & sata_np_cap_ncq) == 0) {
+		ddf_msg(LVL_ERROR, "%s: NCQ must be supported", sata->model);
+		goto error;
+	}
+	
+	uint16_t logsec = idata->physical_logic_sector_size;
+	if ((logsec & 0xc000) == 0x4000) {
+		/* Length of sector may be larger than 512 B */
+		if (logsec & 0x0100) {
+			/* Size of sector is larger than 512 B */
+			ddf_msg(LVL_ERROR,
+			    "%s: Sector length other than 512 B not supported",
+			    sata->model);
+			goto error;
+		}
+		
+		if ((logsec & 0x0200) && ((logsec & 0x000f) != 0)) {
+			/* Physical sectors per logical sector is greather than 1 */
+			ddf_msg(LVL_ERROR,
+			    "%s: Sector length other than 512 B not supported",
+			    sata->model);
+			goto error;
+		}
+	}
+	
+	if (sata->is_packet_device) {
+		/*
+		 * Due to QEMU limitation (as of 2012-06-22),
+		 * only NCQ FPDMA mode supported - block size is
+		 * 512 B, not 2048 B!
+		 */
+		sata->block_size = SATA_DEFAULT_SECTOR_SIZE;
+		sata->blocks = 0;
+	} else {
+		sata->block_size = SATA_DEFAULT_SECTOR_SIZE;
+		
+		if ((idata->caps & sata_rd_cap_lba) == 0) {
+			ddf_msg(LVL_ERROR, "%s: LBA for NCQ must be supported",
+			    sata->model);
+			goto error;
+		} else if ((idata->cmd_set1 & sata_cs1_addr48) == 0) {
+			sata->blocks = (uint32_t) idata->total_lba28_0 |
+			    ((uint32_t) idata->total_lba28_1 << 16);
+		} else {
+			/* Device supports LBA-48 addressing. */
+			sata->blocks = (uint64_t) idata->total_lba48_0 |
+			    ((uint64_t) idata->total_lba48_1 << 16) |
+			    ((uint64_t) idata->total_lba48_2 << 32) |
+			    ((uint64_t) idata->total_lba48_3 << 48);
+		}
+	}
+	
+	uint8_t udma_mask = idata->udma & 0x007f;
+	sata->highest_udma_mode = (uint8_t) -1;
+	if (udma_mask == 0) {
+		ddf_msg(LVL_ERROR,
+		    "%s: UDMA mode for NCQ FPDMA mode must be supported",
+		    sata->model);
+		goto error;
+	} else {
+		for (uint8_t i = 0; i < 7; i++) {
+			if (udma_mask & (1 << i))
+				sata->highest_udma_mode = i;
+		}
+	}
+	
+	fibril_mutex_unlock(&sata->lock);
+	dmamem_unmap_anonymous(idata);
+	
+	return EOK;
+	
+error:
+	fibril_mutex_unlock(&sata->lock);
+	dmamem_unmap_anonymous(idata);
+	
+	return EINTR;
+}
+
+/** Set AHCI registers for setting SATA device transfer mode.
+ *
+ * @param sata SATA device structure.
+ * @param phys Physical address of working buffer.
+ * @param mode Required mode.
+ *
+ */
+static void ahci_set_mode_cmd(sata_dev_t *sata, void* phys, uint8_t mode)
+{
+	volatile sata_std_command_frame_t *cmd =
+	    (sata_std_command_frame_t *) sata->cmd_table;
+	
+	cmd->fis_type = SATA_CMD_FIS_TYPE;
+	cmd->c = SATA_CMD_FIS_COMMAND_INDICATOR; 
+	cmd->command = 0xef;
+	cmd->features = 0x03;
+	cmd->lba_lower = 0;
+	cmd->device = 0;
+	cmd->lba_upper = 0;
+	cmd->features_upper = 0;
+	cmd->count = mode;
+	cmd->reserved1 = 0;
+	cmd->control = 0;
+	cmd->reserved2 = 0;
+	
+	volatile ahci_cmd_prdt_t *prdt =
+	    (ahci_cmd_prdt_t *) (&sata->cmd_table[0x20]);
+	
+	prdt->data_address_low = LO(phys);
+	prdt->data_address_upper = HI(phys);
+	prdt->reserved1 = 0;
+	prdt->dbc = SATA_SET_FEATURE_BUFFER_LENGTH - 1;
+	prdt->reserved2 = 0;
+	prdt->ioc = 0;
+	
+	sata->cmd_header->prdtl = 1;
+	sata->cmd_header->flags =
+	    AHCI_CMDHDR_FLAGS_CLEAR_BUSY_UPON_OK |
+	    AHCI_CMDHDR_FLAGS_2DWCMD;
+	sata->cmd_header->bytesprocessed = 0;
+	
+	/* Run command. */
+	sata->port->pxsact |= 1;
+	sata->port->pxci |= 1;
+}
+
+/** Set highest ultra DMA mode supported by SATA device.
+ *
+ * @param sata SATA device structure.
+ *
+ * @return EOK if succeed, error code otherwise
+ *
+ */
+static int ahci_set_highest_ultra_dma_mode(sata_dev_t *sata)
+{
+	if (sata->is_invalid_device) {
+		ddf_msg(LVL_ERROR,
+		    "%s: Setting highest UDMA mode on invalid device",
+		    sata->model);
+		return EINTR;
+	}
+	
+	if (sata->highest_udma_mode == (uint8_t) -1) {
+		ddf_msg(LVL_ERROR,
+		    "%s: No AHCI UDMA support.", sata->model);
+		return EINTR;
+	}
+	
+	if (sata->highest_udma_mode > 6) {
+		ddf_msg(LVL_ERROR,
+		    "%s: Unknown AHCI UDMA mode.", sata->model);
+		return EINTR;
+	}
+	
+	void *phys;
+	sata_identify_data_t *idata;
+	int rc = dmamem_map_anonymous(SATA_SET_FEATURE_BUFFER_LENGTH,
+	    AS_AREA_READ | AS_AREA_WRITE, 0, &phys, (void **) &idata);
+	if (rc != EOK) {
+		ddf_msg(LVL_ERROR, "Cannot allocate buffer for device set mode.");
+		return rc;
+	}
+	
+	bzero(idata, SATA_SET_FEATURE_BUFFER_LENGTH);
+	
+	fibril_mutex_lock(&sata->lock);
+	
+	uint8_t mode = 0x40 | (sata->highest_udma_mode & 0x07);
+	ahci_set_mode_cmd(sata, phys, mode);
+	ahci_port_is_t pxis = ahci_wait_event(sata);
+	
+	if (sata->is_invalid_device) {
+		ddf_msg(LVL_ERROR,
+		    "%s: Unrecoverable error during set highest UDMA mode",
+		    sata->model);
+		goto error;
+	}
+	
+	if (ahci_port_is_error(pxis)) {
+		ddf_msg(LVL_ERROR,
+		    "%s: Error during set highest UDMA mode", sata->model);
+		goto error;
+	}
+	
+	fibril_mutex_unlock(&sata->lock);
+	dmamem_unmap_anonymous(idata);
+	
+	return EOK;
+	
+error:
+	fibril_mutex_unlock(&sata->lock);
+	dmamem_unmap_anonymous(idata);
+	
+	return EINTR;
+}
+
+/** Set AHCI registers for reading one sector from the SATA device using FPDMA.
+ *
+ * @param sata     SATA device structure.
+ * @param phys     Physical address of buffer for sector data.
+ * @param blocknum Block number to read.
+ *
+ */
+static void ahci_rb_fpdma_cmd(sata_dev_t *sata, void *phys, uint64_t blocknum)
+{
+	volatile sata_ncq_command_frame_t *cmd =
+	    (sata_ncq_command_frame_t *) sata->cmd_table;
+	
+	cmd->fis_type = SATA_CMD_FIS_TYPE;
+	cmd->c = SATA_CMD_FIS_COMMAND_INDICATOR;
+	cmd->command = 0x60;
+	cmd->tag = 0;
+	cmd->control = 0;
+	
+	cmd->reserved1 = 0;
+	cmd->reserved2 = 0;
+	cmd->reserved3 = 0;
+	cmd->reserved4 = 0;
+	cmd->reserved5 = 0;
+	cmd->reserved6 = 0;
+	
+	cmd->sector_count_low = 1;
+	cmd->sector_count_high = 0;
+	
+	cmd->lba0 = blocknum & 0xff;
+	cmd->lba1 = (blocknum >> 8) & 0xff;
+	cmd->lba2 = (blocknum >> 16) & 0xff;
+	cmd->lba3 = (blocknum >> 24) & 0xff;
+	cmd->lba4 = (blocknum >> 32) & 0xff;
+	cmd->lba5 = (blocknum >> 40) & 0xff;
+	
+	volatile ahci_cmd_prdt_t *prdt =
+	    (ahci_cmd_prdt_t *) (&sata->cmd_table[0x20]);
+	
+	prdt->data_address_low = LO(phys);
+	prdt->data_address_upper = HI(phys);
+	prdt->reserved1 = 0;
+	prdt->dbc = sata->block_size - 1;
+	prdt->reserved2 = 0;
+	prdt->ioc = 0;
+	
+	sata->cmd_header->prdtl = 1;
+	sata->cmd_header->flags =
+	    AHCI_CMDHDR_FLAGS_CLEAR_BUSY_UPON_OK |
+	    AHCI_CMDHDR_FLAGS_5DWCMD;
+	sata->cmd_header->bytesprocessed = 0;
+	
+	sata->port->pxsact |= 1;
+	sata->port->pxci |= 1;
+}
+
+/** Read one sector from the SATA device using FPDMA.
+ *
+ * @param sata     SATA device structure.
+ * @param phys     Physical address of buffer for sector data.
+ * @param blocknum Block number to read.
+ *
+ * @return EOK if succeed, error code otherwise
+ *
+ */
+static int ahci_rb_fpdma(sata_dev_t *sata, void *phys, uint64_t blocknum)
+{
+	if (sata->is_invalid_device) {
+		ddf_msg(LVL_ERROR,
+		    "%s: FPDMA read from invalid device", sata->model);
+		return EINTR;
+	}
+	
+	ahci_rb_fpdma_cmd(sata, phys, blocknum);
+	ahci_port_is_t pxis = ahci_wait_event(sata);
+	
+	if ((sata->is_invalid_device) || (ahci_port_is_error(pxis))) {
+		ddf_msg(LVL_ERROR,
+		    "%s: Unrecoverable error during FPDMA read", sata->model);
+		return EINTR;
+	}
+	
+	return EOK;
+}
+
+/** Set AHCI registers for writing one sector to the SATA device, use FPDMA.
+ *
+ * @param sata     SATA device structure.
+ * @param phys     Physical address of buffer with sector data.
+ * @param blocknum Block number to write.
+ *
+ * @return EOK if succeed, error code otherwise
+ *
+ */
+static void ahci_wb_fpdma_cmd(sata_dev_t *sata, void *phys, uint64_t blocknum)
+{
+	volatile sata_ncq_command_frame_t *cmd =
+	    (sata_ncq_command_frame_t *) sata->cmd_table;
+	
+	cmd->fis_type = SATA_CMD_FIS_TYPE;
+	cmd->c = SATA_CMD_FIS_COMMAND_INDICATOR;
+	cmd->command = 0x61;
+	cmd->tag = 0;
+	cmd->control = 0;
+	
+	cmd->reserved1 = 0;
+	cmd->reserved2 = 0;
+	cmd->reserved3 = 0;
+	cmd->reserved4 = 0;
+	cmd->reserved5 = 0;
+	cmd->reserved6 = 0;
+	
+	cmd->sector_count_low = 1;
+	cmd->sector_count_high = 0;
+	
+	cmd->lba0 = blocknum & 0xff;
+	cmd->lba1 = (blocknum >> 8) & 0xff;
+	cmd->lba2 = (blocknum >> 16) & 0xff;
+	cmd->lba3 = (blocknum >> 24) & 0xff;
+	cmd->lba4 = (blocknum >> 32) & 0xff;
+	cmd->lba5 = (blocknum >> 40) & 0xff;
+	
+	volatile ahci_cmd_prdt_t *prdt =
+	    (ahci_cmd_prdt_t *) (&sata->cmd_table[0x20]);
+	
+	prdt->data_address_low = LO(phys);
+	prdt->data_address_upper = HI(phys);
+	prdt->reserved1 = 0;
+	prdt->dbc = sata->block_size - 1;
+	prdt->reserved2 = 0;
+	prdt->ioc = 0;
+	
+	sata->cmd_header->prdtl = 1;
+	sata->cmd_header->flags =
+	    AHCI_CMDHDR_FLAGS_CLEAR_BUSY_UPON_OK |
+	    AHCI_CMDHDR_FLAGS_WRITE |
+	    AHCI_CMDHDR_FLAGS_5DWCMD;
+	sata->cmd_header->bytesprocessed = 0;
+	
+	sata->port->pxsact |= 1;
+	sata->port->pxci |= 1;
+}
+
+/** Write one sector into the SATA device, use FPDMA.
+ *
+ * @param sata     SATA device structure.
+ * @param phys     Physical addres of buffer with sector data.
+ * @param blocknum Block number to write.
+ *
+ * @return EOK if succeed, error code otherwise
+ *
+ */
+static int ahci_wb_fpdma(sata_dev_t *sata, void *phys, uint64_t blocknum)
+{
+	if (sata->is_invalid_device) {
+		ddf_msg(LVL_ERROR,
+		    "%s: FPDMA write to invalid device", sata->model);
+		return EINTR;
+	}
+	
+	ahci_wb_fpdma_cmd(sata, phys, blocknum);
+	ahci_port_is_t pxis = ahci_wait_event(sata);
+	
+	if ((sata->is_invalid_device) || (ahci_port_is_error(pxis))) {
+		ddf_msg(LVL_ERROR,
+		    "%s: Unrecoverable error during FPDMA write", sata->model);
+		return EINTR;
+	}
+	
+	return EOK;
+}
+
+/*----------------------------------------------------------------------------*/
+/*-- Interrupts handling -----------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+static irq_pio_range_t ahci_ranges[] = {
+	{
+		.base = 0,
+		.size = 0,
+	}
+};
+
+static irq_cmd_t ahci_cmds[] = {
+	AHCI_PORT_CMDS(0),
+	AHCI_PORT_CMDS(1),
+	AHCI_PORT_CMDS(2),
+	AHCI_PORT_CMDS(3),
+	AHCI_PORT_CMDS(4),
+	AHCI_PORT_CMDS(5),
+	AHCI_PORT_CMDS(6),
+	AHCI_PORT_CMDS(7),
+	AHCI_PORT_CMDS(8),
+	AHCI_PORT_CMDS(9),
+	AHCI_PORT_CMDS(10),
+	AHCI_PORT_CMDS(11),
+	AHCI_PORT_CMDS(12),
+	AHCI_PORT_CMDS(13),
+	AHCI_PORT_CMDS(14),
+	AHCI_PORT_CMDS(15),
+	AHCI_PORT_CMDS(16),
+	AHCI_PORT_CMDS(17),
+	AHCI_PORT_CMDS(18),
+	AHCI_PORT_CMDS(19),
+	AHCI_PORT_CMDS(20),
+	AHCI_PORT_CMDS(21),
+	AHCI_PORT_CMDS(22),
+	AHCI_PORT_CMDS(23),
+	AHCI_PORT_CMDS(24),
+	AHCI_PORT_CMDS(25),
+	AHCI_PORT_CMDS(26),
+	AHCI_PORT_CMDS(27),
+	AHCI_PORT_CMDS(28),
+	AHCI_PORT_CMDS(29),
+	AHCI_PORT_CMDS(30),
+	AHCI_PORT_CMDS(31)
+};
+
+/** AHCI interrupt handler.
+ *
+ * @param dev   DDF device structure.
+ * @param iid   The IPC call id.
+ * @param icall The IPC call structure.
+ *
+ */
+static void ahci_interrupt(ddf_dev_t *dev, ipc_callid_t iid, ipc_call_t *icall)
+{
+	ahci_dev_t *ahci = (ahci_dev_t *) dev->driver_data;
+	unsigned int port = IPC_GET_ARG1(*icall);
+	ahci_port_is_t pxis = IPC_GET_ARG2(*icall);
+	
+	if (port >= AHCI_MAX_PORTS)
+		return;
+	
+	sata_dev_t *sata = (sata_dev_t *) ahci->sata_devs[port];
+	if (sata == NULL)
+		return;
+	
+	/* Evaluate port event */
+	if ((ahci_port_is_end_of_operation(pxis)) ||
+	    (ahci_port_is_error(pxis))) {
+		fibril_mutex_lock(&sata->event_lock);
+		
+		sata->event_pxis = pxis;
+		fibril_condvar_signal(&sata->event_condvar);
+		
+		fibril_mutex_unlock(&sata->event_lock);
+	}
+}
+
+/*----------------------------------------------------------------------------*/
+/*-- AHCI and SATA device creating and initializing routines -----------------*/
+/*----------------------------------------------------------------------------*/
+
+/** Allocate SATA device structure with buffers for hardware.
+ *
+ * @param port AHCI port structure
+ *
+ * @return SATA device structure if succeed, NULL otherwise.
+ *
+ */
+static sata_dev_t *ahci_sata_allocate(volatile ahci_port_t *port)
+{
+	size_t size = 4096;
+	void *phys = NULL;
+	void *virt_fb = NULL;
+	void *virt_cmd = NULL;
+	void *virt_table = NULL;
+	
+	sata_dev_t *sata = malloc(sizeof(sata_dev_t));
+	if (sata == NULL)
+		return NULL;
+	
+	bzero(sata, sizeof(sata_dev_t));
+	
+	sata->port = port;
+	
+	/* Allocate and init retfis structure. */
+	int rc = dmamem_map_anonymous(size, AS_AREA_READ | AS_AREA_WRITE, 0,
+	    &phys, &virt_fb);
+	if (rc != EOK)
+		goto error_retfis;
+	
+	bzero(virt_fb, size);
+	sata->port->pxfbu = HI(phys);
+	sata->port->pxfb = LO(phys);
+	
+	/* Allocate and init command header structure. */
+	rc = dmamem_map_anonymous(size, AS_AREA_READ | AS_AREA_WRITE, 0,
+	    &phys, &virt_cmd);
+	if (rc != EOK)
+		goto error_cmd;
+	
+	bzero(virt_cmd, size);
+	sata->port->pxclbu = HI(phys);
+	sata->port->pxclb = LO(phys);
+	sata->cmd_header = (ahci_cmdhdr_t *) virt_cmd;
+	
+	/* Allocate and init command table structure. */
+	rc = dmamem_map_anonymous(size, AS_AREA_READ | AS_AREA_WRITE, 0,
+	    &phys, &virt_table);
+	if (rc != EOK)
+		goto error_table;
+	
+	bzero(virt_table, size);
+	sata->cmd_header->cmdtableu = HI(phys);
+	sata->cmd_header->cmdtable = LO(phys);
+	sata->cmd_table = (uint32_t*) virt_table;
+	
+	return sata;
+	
+error_table:
+	dmamem_unmap(virt_cmd, size);
+error_cmd:
+	dmamem_unmap(virt_fb, size);
+error_retfis:
+	free(sata);
+	return NULL;
+}
+
+/** Initialize and start SATA hardware device.
+ *
+ * @param sata SATA device structure.
+ *
+ */
+static void ahci_sata_hw_start(sata_dev_t *sata)
+{
+	ahci_port_cmd_t pxcmd;
+	
+	pxcmd.u32 = sata->port->pxcmd;
+	
+	/* Frame receiver disabled. */
+	pxcmd.fre = 0;
+	
+	/* Disable process the command list. */
+	pxcmd.st = 0;
+	
+	sata->port->pxcmd = pxcmd.u32;
+	
+	/* Clear interrupt status. */
+	sata->port->pxis = 0xffffffff;
+	
+	/* Clear error status. */
+	sata->port->pxserr = 0xffffffff;
+	
+	/* Enable all interrupts. */
+	sata->port->pxie = 0xffffffff;
+	
+	/* Frame receiver enabled. */
+	pxcmd.fre = 1;
+	
+	/* Enable process the command list. */
+	pxcmd.st = 1;
+	
+	sata->port->pxcmd = pxcmd.u32;
+}
+
+/** Create and initialize connected SATA structure device
+ *
+ * @param ahci     AHCI device structure.
+ * @param dev      DDF device structure.
+ * @param port     AHCI port structure.
+ * @param port_num Number of AHCI port with existing SATA device.
+ *
+ * @return EOK if succeed, error code otherwise.
+ *
+ */
+static int ahci_sata_create(ahci_dev_t *ahci, ddf_dev_t *dev,
+    volatile ahci_port_t *port, unsigned int port_num)
+{
+	ddf_fun_t *fun = NULL;
+	sata_dev_t *sata = ahci_sata_allocate(port);
+	if (sata == NULL)
+		return EINTR;
+	
+	/* Set pointers between SATA and AHCI structures. */
+	sata->ahci = ahci;
+	sata->port_num = port_num;
+	ahci->sata_devs[port_num] = sata;
+	
+	/* Initialize synchronization structures */
+	fibril_mutex_initialize(&sata->lock);
+	fibril_mutex_initialize(&sata->event_lock);
+	fibril_condvar_initialize(&sata->event_condvar);
+	
+	ahci_sata_hw_start(sata);
+	
+	/* Identify device. */
+	if (ahci_identify_device(sata) != EOK)
+		goto error;
+	
+	/* Set required UDMA mode */
+	if (ahci_set_highest_ultra_dma_mode(sata) != EOK)
+		goto error;
+	
+	/* Add device to the system */
+	char sata_dev_name[16];
+	snprintf(sata_dev_name, 16, "ahci_%u", sata_devices_count);
+	
+	fibril_mutex_lock(&sata_devices_count_lock);
+	sata_devices_count++;
+	fibril_mutex_unlock(&sata_devices_count_lock);
+	
+	fun = ddf_fun_create(dev, fun_exposed, sata_dev_name);
+	if (fun == NULL) {
+		ddf_msg(LVL_ERROR, "Failed creating function.");
+		goto error;
+	}
+	
+	fun->ops = &ahci_ops;
+	fun->driver_data = sata;
+	int rc = ddf_fun_bind(fun);
+	if (rc != EOK) {
+		ddf_msg(LVL_ERROR, "Failed binding function.");
+		goto error;
+	}
+	
+	return EOK;
+	
+error:
+	sata->is_invalid_device = true;
+	if (fun != NULL)
+		ddf_fun_destroy(fun);
+	
+	return EINTR;
+}
+
+/** Create and initialize all SATA structure devices for connected SATA drives.
+ *
+ * @param ahci AHCI device structure.
+ * @param dev  DDF device structure.
+ *
+ */
+static void ahci_sata_devices_create(ahci_dev_t *ahci, ddf_dev_t *dev)
+{
+	for (unsigned int port_num = 0; port_num < AHCI_MAX_PORTS; port_num++) {
+		/* Active ports only */
+		if (!(ahci->memregs->ghc.pi & (1 << port_num)))
+			continue;
+		
+		volatile ahci_port_t *port = ahci->memregs->ports + port_num;
+		
+		/* Active devices only */
+		ahci_port_ssts_t pxssts;
+		pxssts.u32 = port->pxssts;
+		if (pxssts.det != AHCI_PORT_SSTS_DET_ACTIVE)
+			continue;
+		
+		ahci_sata_create(ahci, dev, port, port_num);
+	}
+}
+
+/** Create AHCI device structure, intialize it and register interrupt routine.
+ *
+ * @param dev DDF device structure.
+ *
+ * @return AHCI device structure if succeed, NULL otherwise.
+ *
+ */
+static ahci_dev_t *ahci_ahci_create(ddf_dev_t *dev)
+{
+	ahci_dev_t *ahci = malloc(sizeof(ahci_dev_t));
+	if (!ahci)
+		return NULL;
+	
+	bzero(ahci, sizeof(ahci_dev_t));
+	
+	ahci->dev = dev;
+	
+	hw_res_list_parsed_t hw_res_parsed;
+	hw_res_list_parsed_init(&hw_res_parsed);
+	if (hw_res_get_list_parsed(dev->parent_sess, &hw_res_parsed, 0) != EOK)
+		goto error_get_res_parsed;
+	
+	/* Map AHCI registers. */
+	ahci->memregs = NULL;
+	
+	physmem_map((void *) (size_t) (hw_res_parsed.mem_ranges.ranges[0].address),
+	    AHCI_MEMREGS_PAGES_COUNT, AS_AREA_READ | AS_AREA_WRITE,
+	    (void **) &ahci->memregs);
+	if (ahci->memregs == NULL)
+		goto error_map_registers;
+	
+	/* Register interrupt handler */
+	ahci_ranges[0].base = (size_t) hw_res_parsed.mem_ranges.ranges[0].address;
+	ahci_ranges[0].size = sizeof(ahci_memregs_t);
+	
+	for (unsigned int port = 0; port < AHCI_MAX_PORTS; port++) {
+		size_t base = port * 7;
+		
+		ahci_cmds[base].addr =
+		    ((uint32_t *) (size_t) hw_res_parsed.mem_ranges.ranges[0].address) +
+		    AHCI_PORTS_REGISTERS_OFFSET + port * AHCI_PORT_REGISTERS_SIZE +
+		    AHCI_PORT_IS_REGISTER_OFFSET;
+		ahci_cmds[base + 2].addr = ahci_cmds[base].addr;
+		
+		ahci_cmds[base + 3].addr =
+		    ((uint32_t *) (size_t) hw_res_parsed.mem_ranges.ranges[0].address) +
+		    AHCI_GHC_IS_REGISTER_OFFSET;
+		ahci_cmds[base + 4].addr = ahci_cmds[base + 3].addr;
+	}
+	
+	irq_code_t ct;
+	ct.cmdcount = sizeof(ahci_cmds) / sizeof(irq_cmd_t);
+	ct.cmds = ahci_cmds;
+	ct.rangecount = sizeof(ahci_ranges) / sizeof(irq_pio_range_t);
+	ct.ranges = ahci_ranges;
+	
+	int rc = register_interrupt_handler(dev, hw_res_parsed.irqs.irqs[0],
+	    ahci_interrupt, &ct);
+	if (rc != EOK) {
+		ddf_msg(LVL_ERROR, "Failed registering interrupt handler.");
+		goto error_register_interrupt_handler;
+	}
+	
+	rc = ahci_enable_interrupt(hw_res_parsed.irqs.irqs[0]);
+	if (rc != EOK) {
+		ddf_msg(LVL_ERROR, "Failed enable interupt.");
+		goto error_enable_interrupt;
+	}
+	
+	hw_res_list_parsed_clean(&hw_res_parsed);
+	return ahci;
+	
+error_enable_interrupt:
+	unregister_interrupt_handler(dev, hw_res_parsed.irqs.irqs[0]);
+	
+error_register_interrupt_handler:
+	// FIXME: unmap physical memory
+	
+error_map_registers:
+	hw_res_list_parsed_clean(&hw_res_parsed);
+	
+error_get_res_parsed:
+	free(ahci);
+	return NULL;
+}
+
+/** Initialize and start AHCI hardware device.
+ *
+ * @param ahci AHCI device.
+ *
+ */
+static void ahci_ahci_hw_start(ahci_dev_t *ahci)
+{
+	/* Disable command completion coalescing feature */
+	ahci_ghc_ccc_ctl_t ccc;
+	
+	ccc.u32 = ahci->memregs->ghc.ccc_ctl;
+	ccc.en = 0;
+	ahci->memregs->ghc.ccc_ctl = ccc.u32;
+	
+	/* Set master latency timer. */
+	pci_config_space_write_8(ahci->dev->parent_sess, AHCI_PCI_MLT, 32);
+	
+	/* Enable PCI interrupt and bus mastering */
+	ahci_pcireg_cmd_t cmd;
+	
+	pci_config_space_read_16(ahci->dev->parent_sess, AHCI_PCI_CMD, &cmd.u16);
+	cmd.id = 0;
+	cmd.bme = 1;
+	pci_config_space_write_16(ahci->dev->parent_sess, AHCI_PCI_CMD, cmd.u16);
+	
+	/* Enable AHCI and interrupt. */
+	ahci->memregs->ghc.ghc = AHCI_GHC_GHC_AE | AHCI_GHC_GHC_IE;
+}
+
+/** AHCI device driver initialization
+ *
+ * Create and initialize all SATA structure devices for connected
+ * SATA drives.
+ *
+ * @param dev DDF device structure.
+ *
+ * @return EOK if succeed, error code otherwise.
+ *
+ */
+static int ahci_dev_add(ddf_dev_t *dev)	
+{
+	/* Connect to parent device */
+	dev->parent_sess = devman_parent_device_connect(EXCHANGE_SERIALIZE,
+	    dev->handle, IPC_FLAG_BLOCKING);
+	if (dev->parent_sess == NULL)
+		return EINTR;
+	
+	ahci_dev_t *ahci = ahci_ahci_create(dev);
+	if (ahci == NULL)
+		goto error;
+	
+	dev->driver_data = ahci;
+	
+	/* Start AHCI hardware. */
+	ahci_ahci_hw_start(ahci);
+	
+	/* Create device structures for sata devices attached to AHCI. */
+	ahci_sata_devices_create(ahci, dev);
+	
+	return EOK;
+	
+error:
+	async_hangup(dev->parent_sess);
+	return EINTR;
+}
+
+/*----------------------------------------------------------------------------*/
+/*-- Helpers and utilities ---------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+/** Convert SATA model name
+ *
+ * Convert SATA model name from machine format returned by
+ * identify device command to human readable form.
+ *
+ * @param src Source buffer with device name in machine format.
+ * @param dst Buffer for human readable string, minimum size is 41 chars.
+ *
+ */
+static void ahci_get_model_name(uint16_t *src, char *dst)
+{
+	uint8_t model[40];
+	bzero(model, 40);
+	
+	for (unsigned int i = 0; i < 20; i++) {
+		uint16_t w = src[i];
+		model[2 * i] = w >> 8;
+		model[2 * i + 1] = w & 0x00ff;
+	}
+	
+	uint32_t len = 40;
+	while ((len > 0) && (model[len - 1] == 0x20))
+		len--;
+	
+	size_t pos = 0;
+	for (unsigned int i = 0; i < len; i++) {
+		uint8_t c = model[i];
+		if (c >= 0x80)
+			c = '?';
+		
+		chr_encode(c, dst, &pos, 40);
+	}
+	
+	dst[pos] = '\0';
+}
+
+/** Enable interrupt using SERVICE_IRC.
+ *
+ * @param irq Requested irq number.
+ *
+ * @return EOK if succeed, error code otherwise.
+ *
+ */
+static int ahci_enable_interrupt(int irq)
+{
+	async_sess_t *irc_sess = NULL;
+	irc_sess = service_connect_blocking(EXCHANGE_SERIALIZE, SERVICE_IRC, 0, 0);
+	if (!irc_sess)
+		return EINTR;
+	
+	async_exch_t *exch = async_exchange_begin(irc_sess);
+	const int rc = async_req_1_0(exch, IRC_ENABLE_INTERRUPT, irq);
+	async_exchange_end(exch);
+	
+	async_hangup(irc_sess);
+	return rc;
+}
+
+/*----------------------------------------------------------------------------*/
+/*-- AHCI Main routine -------------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+int main(int argc, char *argv[])
+{
+	printf("%s: HelenOS AHCI device driver\n", NAME);
+	ddf_log_init(NAME, LVL_ERROR);
+	fibril_mutex_initialize(&sata_devices_count_lock);
+	return ddf_driver_main(&ahci_driver);
+}
Index: uspace/drv/block/ahci/ahci.h
===================================================================
--- uspace/drv/block/ahci/ahci.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/drv/block/ahci/ahci.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @file
+ * Header for AHCI driver.
+ */
+
+#ifndef __AHCI_H__
+#define __AHCI_H__
+
+#include <sys/types.h>
+#include <devman.h>
+#include <ddf/interrupt.h>
+#include <stdio.h>
+#include "ahci_hw.h"
+
+/** AHCI Device. */
+typedef struct {
+	/** Pointer to ddf device. */
+	ddf_dev_t *dev;
+	
+	/** Pointer to AHCI memory registers. */
+	volatile ahci_memregs_t *memregs;
+	
+	/** Pointers to sata devices. */
+	void *sata_devs[AHCI_MAX_PORTS];
+} ahci_dev_t;
+
+/** SATA Device. */
+typedef struct {
+	/** Pointer to AHCI device. */
+	ahci_dev_t *ahci;
+	
+	/** SATA port number (0-31). */
+	uint8_t port_num;
+	
+	/** Device in invalid state (disconnected and so on). */
+	bool is_invalid_device;
+	
+	/** Pointer to SATA port. */
+	volatile ahci_port_t *port;
+	
+	/** Pointer to command header. */
+	volatile ahci_cmdhdr_t *cmd_header;
+	
+	/** Pointer to command table. */
+	volatile uint32_t *cmd_table;
+	
+	/** Mutex for single operation on device. */
+	fibril_mutex_t lock;
+	
+	/** Mutex for event signaling condition variable. */
+	fibril_mutex_t event_lock;
+	
+	/** Event signaling condition variable. */
+	fibril_condvar_t event_condvar;
+	
+	/** Event interrupt state. */
+	ahci_port_is_t event_pxis;
+	
+	/** Block device service id. */
+	service_id_t service_id;
+	
+	/** Number of device data blocks. */
+	uint64_t blocks;
+	
+	/** Size of device data blocks. */
+	size_t block_size;
+	
+	/** Name of SATA device. */
+	char model[STR_BOUNDS(40) + 1];
+	
+	/** Device in invalid state (disconnected and so on). */
+	bool is_packet_device;
+	
+	/** Highest UDMA mode supported. */
+	uint8_t highest_udma_mode;
+} sata_dev_t;
+
+#endif
Index: uspace/drv/block/ahci/ahci.ma
===================================================================
--- uspace/drv/block/ahci/ahci.ma	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/drv/block/ahci/ahci.ma	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,3 @@
+10 pci/ven=8086&dev=2922
+10 pci/ven=8086&dev=2829
+10 pci/ven=1002&dev=4391
Index: uspace/drv/block/ahci/ahci_hw.h
===================================================================
--- uspace/drv/block/ahci/ahci_hw.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/drv/block/ahci/ahci_hw.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,1050 @@
+/*
+ * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @file
+ * Header for AHCI driver (AHCI 1.3 specification).
+ */
+
+#ifndef __AHCI_HW_H__
+#define __AHCI_HW_H__
+
+#include <sys/types.h>
+
+/*----------------------------------------------------------------------------*/
+/*-- AHCI standard constants -------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+/** AHCI standard 1.3 - maximum ports. */
+#define AHCI_MAX_PORTS  32
+
+/*----------------------------------------------------------------------------*/
+/*-- AHCI PCI Registers ------------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+/** AHCI PCI register Identifiers offset. */
+#define AHCI_PCI_ID     0x00
+/** AHCI PCI register Command offset. */
+#define AHCI_PCI_CMD    0x04
+/** AHCI PCI register Device Status offset. */
+#define AHCI_PCI_STS    0x06
+/** AHCI PCI register Revision ID offset. */
+#define AHCI_PCI_RID    0x08
+/** AHCI PCI register Class Codes offset. */
+#define AHCI_PCI_CC     0x09
+/** AHCI PCI register Cache Line Size offset. */
+#define AHCI_PCI_CLS    0x0C
+/** AHCI PCI register Master Latency Timer offset. */
+#define AHCI_PCI_MLT    0x0D
+/** AHCI PCI register Header Type offset. */
+#define AHCI_PCI_HTYPE  0x0E
+/** AHCI PCI register Built In Self Test (Optional) offset. */
+#define AHCI_PCI_BIST   0x0F
+/** AHCI PCI register Other Base Address Registres (Optional). */
+#define AHCI_PCI_BAR0   0x10
+/** AHCI PCI register Other Base Address Registres (Optional). */
+#define AHCI_PCI_BAR1   0x14
+/** AHCI PCI register Other Base Address Registres (Optional). */
+#define AHCI_PCI_BAR2   0x18
+/** AHCI PCI register Other Base Address Registres (Optional). */
+#define AHCI_PCI_BAR3   0x1C
+/** AHCI PCI register Other Base Address Registres (Optional). */
+#define AHCI_PCI_BAR4   0x20
+/** AHCI PCI register AHCI Base Address offset. */
+#define AHCI_PCI_ABAR   0x24
+/** AHCI PCI register Subsystem Identifiers offset. */
+#define AHCI_PCI_SS     0x2C
+/** AHCI PCI register Expansion ROM Base Address (Optional) offset. */
+#define AHCI_PCI_EROM   0x30
+/** AHCI PCI register Capabilities Pointer offset. */
+#define AHCI_PCI_CAP    0x34
+/** AHCI PCI register Interrupt Information offset. */
+#define AHCI_PCI_INTR   0x3C
+/** AHCI PCI register Min Grant (Optional) offset. */
+#define AHCI_PCI_MGNT   0x3E
+/** AHCI PCI register Max Latency (Optional) offset. */
+#define AHCI_PCI_MLAT   0x3F
+
+/** AHCI PCI register Identifiers. */
+typedef struct {
+	/** Indicates the company vendor assigned by the PCI SIG. */
+	uint16_t vendorid;
+	/** Indicates what device number assigned by the vendor */
+	uint16_t deviceid;
+} ahci_pcireg_id_t;
+
+/** AHCI PCI register Command. */
+typedef union {
+	struct {
+		/** I/O Space Enable. */
+		unsigned int iose : 1;
+		/** Memory Space Enable. */
+		unsigned int mse : 1;
+		/** Bus Master Enable. */
+		unsigned int bme : 1;
+		/** Special Cycle Enable. */
+		unsigned int sce : 1;
+		/** Memory Write and Invalidate Enable. */
+		unsigned int mwie : 1;
+		/** VGA Palette Snooping Enable. */
+		unsigned int vga : 1;
+		/** Parity Error Response Enable. */
+		unsigned int pee : 1;
+		/** Wait Cycle Enable. */
+		unsigned int wcc : 1;
+		/** SERR# Enable. */
+		unsigned int see : 1;
+		/** Fast Back-to-Back Enable. */
+		unsigned int fbe : 1;
+		/** Interrupt Disable - disables the HBA from generating interrupts.
+		 * This bit does not have any effect on MSI operation.
+		 */
+		unsigned int id : 1;
+		/** Reserved. */
+		unsigned int reserved : 5;
+	};
+	uint16_t u16;
+} ahci_pcireg_cmd_t;
+
+/** AHCI PCI register Command - Interrupt Disable bit. */
+#define AHCI_PCIREG_CMD_ID  0x0400
+
+/** AHCI PCI register Command - Bus Master Enable bit. */
+#define AHCI_PCIREG_CMD_BME  0x0004
+
+/** AHCI PCI register Device status. */
+typedef union {
+	struct {
+		/** Reserved. */
+		unsigned int reserved1 : 3;
+		/** Indicate the interrupt status of the device (1 = asserted). */
+		unsigned int is : 1;
+		/** Indicates presence of capatibility list. */
+		unsigned int cl : 1;
+		/** 66 Mhz capable. */
+		unsigned int c66 : 1;
+		/** Reserved. */
+		unsigned int reserved2 : 1;
+		/** Fast back to back capable. */
+		unsigned int fbc : 1;
+		/** Master data parity error detected. */
+		unsigned int dpd : 1;
+		/** Device select timing. */
+		unsigned int devt : 2;
+		/** Signaled target abort. */
+		unsigned int sta : 1;
+		/** Received target abort. */
+		unsigned int rta : 1;
+		/** Received master abort. */
+		unsigned int rma : 1;
+		/** Signaled system error. */
+		unsigned int sse : 1;
+		/** Detected parity error. */
+		unsigned int dpe : 1;
+	};
+	uint16_t u16;
+} ahci_pcireg_sts_t;
+
+/** AHCI PCI register Revision ID. */
+typedef struct {
+	/** Indicates stepping of the HBA hardware. */
+	uint8_t u8;
+} ahci_pcireg_rid_t;
+
+/** AHCI PCI register Class Codes. */
+typedef struct {
+	/** Programing interface, when set to 01h and the scc is set to 06h,
+	 * indicates that this an AHCI HBA major revision 1.
+	 */
+	uint8_t pi;
+	/** When set to 06h, indicates that is a SATA device. */
+	uint8_t scc;
+	/** Value 01 indicates that is a mass storage device. */
+	uint8_t bcc;
+} ahci_pcireg_cc_t_t;
+
+/** AHCI PCI register Cache Line Size. */
+typedef struct {
+	/** Cache line size for use with the memory write and invalidate command. */
+	uint8_t u8;
+} ahci_pcireg_cls_t;
+
+/** AHCI PCI register Master Latency Timer. */
+typedef struct {
+	/** Master latency timer,indicates the number of clocks the HBA is allowed
+	 * to acts as master on PCI.
+	 */
+	uint8_t u8;
+} ahci_pcireg_mlt_t;
+
+/** AHCI PCI register Header Type. */
+typedef union {
+	struct {
+		/** Header layout. */
+		unsigned int hl : 7;
+		/** Multi function device flag. */
+		unsigned int mfd : 1;
+	};
+	uint8_t u8;
+} ahci_pciregs_htype_t;
+
+/** AHCI PCI register Built in self test. */
+typedef union {
+	struct {
+	/** Indicates the completion status of BIST
+	 * non-zero value indicates a failure.
+	 */
+	unsigned int cc : 4;
+	/** Reserved. */
+	unsigned int reserved : 2;
+	/** Software sets this bit to 1 to invoke BIST,
+	 * the HBA clears this bit to 0 when BIST is complete.
+	 */
+	unsigned int sb : 1;
+	/** BIST capable. */
+	unsigned int bc : 1;
+	};
+	uint8_t u8;
+} ahci_pciregs_bist_t;
+
+/** AHCI PCI register AHCI Base Address <BAR 5>. */
+typedef union {
+	struct {
+		/** Indicates a request for register memory space. */
+		unsigned int rte : 1;
+		/** Indicates the this range can be mapped anywhere in 32-bit address
+		 * space.
+		 */
+		unsigned int tp : 2;
+		/** Indicate that this range is not prefetchable. */
+		unsigned int pf : 1;
+		/** Reserved. */
+		unsigned int reserved : 9;
+		/** Base address of registry memory space. */
+		unsigned int ba : 19;
+	};
+	uint32_t u32;
+} ahci_pciregs_abar_t;
+
+/** AHCI PCI register Subsystem Identifiers. */
+typedef struct
+{
+	/** Sub system vendor identifier. */
+	uint8_t ssvid;
+	/** Sub system identifier. */
+	uint8_t ssid;
+} ahci_pcireg_ss_t;
+
+/** AHCI PCI registers Expansion ROM Base Address. */
+typedef struct
+{
+	/** Indicates the base address of the HBA expansion ROM. */
+	uint32_t u32;
+} ahci_pcireg_erom_t;
+
+/** AHCI PCI register Capabilities Pointer. */
+typedef struct
+{
+	/** Indicates the first capability pointer offset. */
+	uint8_t u8;
+} ahci_pcireg_cap_t;
+
+/** AHCI PCI register Interrupt Information. */
+typedef struct
+{
+	/* Software written value to indicate which interrupt vector
+	 * the interrupt is connected to.
+	 */
+	uint8_t iline;
+	/** This indicates the interrupt pin the HBA uses. */
+	uint8_t ipin;
+} ahci_pcireg_intr;
+
+/** AHCI PCI register Min Grant (Optional). */
+typedef struct
+{
+	/** Indicates the minimum grant time that the device
+	 * wishes grant asserted.
+	 */
+	uint8_t u8;
+} ahci_pcireg_mgnt_t;
+
+/** AHCI PCI register Max Latency (Optional). */
+typedef struct
+{
+	/** Indicates the maximum latency that the device can withstand. */
+	uint8_t u8;
+} ahci_pcireg_mlat_t;
+
+/*----------------------------------------------------------------------------*/
+/*-- AHCI Memory Registers ---------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+/** Number of pages for ahci memory registers. */
+#define AHCI_MEMREGS_PAGES_COUNT  8
+
+/** AHCI Memory register Generic Host Control - HBA Capabilities. */
+typedef union {
+	struct {
+		/** Number of Ports. */
+		unsigned int np : 5;
+		/** Supports External SATA. */
+		unsigned int sxs : 1;
+		/** Enclosure Management Supported. */
+		unsigned int ems : 1;
+		/** Command Completion Coalescing Supported. */
+		unsigned int cccs : 1;
+		/** Number of Command Slots. */
+		unsigned int ncs : 5;
+		/** Partial State Capable. */
+		unsigned int psc : 1;
+		/** Slumber State Capable. */
+		unsigned int ssc : 1;
+		/** PIO Multiple DRQ Block. */
+		unsigned int pmd : 1;
+		/** FIS-based Switching Supported. */
+		unsigned int fbss : 1;
+		/** Supports Port Multiplier. */
+		unsigned int spm : 1;
+		/** Supports AHCI mode only. */
+		unsigned int sam : 1;
+		/** Reserved. */
+		unsigned int reserved : 1;
+		/** Interface Speed Support. */
+		unsigned int iss : 4;
+		/** Supports Command List Override. */
+		unsigned int sclo : 1;
+		/** Supports Activity LED. */
+		unsigned int sal : 1;
+		/** Supports Aggressive Link Power Management. */
+		unsigned int salp : 1;
+		/** Supports Staggered Spin-up. */
+		unsigned int sss : 1;
+		/** Supports Mechanical Presence Switch. */
+		unsigned int smps : 1;
+		/** Supports SNotification Register. */
+		unsigned int ssntf : 1;
+		/** Supports Native Command Queuing. */
+		unsigned int sncq : 1;
+		/** Supports 64-bit Addressing. */
+		unsigned int s64a : 1;
+	};
+	uint32_t u32;
+} ahci_ghc_cap_t;
+
+/** AHCI Memory register Generic Host Control Global Host Control. */
+typedef union {
+	struct {
+		/** HBA Reset. */
+		unsigned int hr : 1;
+		/** Interrupt Enable. */
+		unsigned int ie : 1;
+		/** MSI Revert to Single Message. */
+		unsigned int mrsm : 1;
+		/** Reserved. */
+		unsigned int reserved : 28;
+		/** AHCI Enable. */
+		unsigned int ae : 1;
+	};
+	uint32_t u32;
+} ahci_ghc_ghc_t;
+
+/** AHCI Enable mask bit. */
+#define AHCI_GHC_GHC_AE  0x80000000
+
+/** AHCI Interrupt Enable mask bit. */
+#define AHCI_GHC_GHC_IE  0x00000002
+
+/** AHCI Memory register Interrupt pending register. */
+typedef uint32_t ahci_ghc_is_t;
+
+/** AHCI GHC register offset. */
+#define AHCI_GHC_IS_REGISTER_OFFSET  2
+
+/** AHCI ports registers offset. */
+#define AHCI_PORTS_REGISTERS_OFFSET  64
+
+/** AHCI port registers size. */
+#define AHCI_PORT_REGISTERS_SIZE  32
+
+/** AHCI port IS register offset. */
+#define AHCI_PORT_IS_REGISTER_OFFSET  4
+
+/** AHCI Memory register Ports implemented. */
+typedef struct {
+	/** If a bit is set to 1, the corresponding port
+	 * is available for software use.
+	 */
+	uint32_t u32;
+} ahci_ghc_pi_t;
+
+/** AHCI Memory register AHCI version. */
+typedef struct {
+	/** Indicates the minor version */
+	uint16_t mnr;
+	/** Indicates the major version */
+	uint16_t mjr;
+} ahci_ghc_vs_t;
+
+/** AHCI Memory register Command completion coalesce control. */
+typedef union {
+	struct {
+		/** Enable CCC features. */
+		unsigned int en : 1;
+		/** Reserved. */
+		unsigned int reserved : 2;
+		/** Interrupt number for CCC. */
+		unsigned int intr : 5;
+		/** Number of command completions that are necessary to cause
+		 * a CCC interrupt.
+		 */
+		uint8_t cc;
+		/** Timeout value in  ms. */
+		uint16_t tv;
+	};
+	uint32_t u32;
+} ahci_ghc_ccc_ctl_t;
+
+/** AHCI Memory register Command completion coalescing ports. */
+typedef struct
+{
+	/** If a bit is set to 1, the corresponding port is
+	 * part of the command completion coalescing feature.
+	 */
+	uint32_t u32;
+} ahci_ghc_ccc_ports_t;
+
+/** AHCI Memory register Enclosure management location. */
+typedef struct
+{
+	/** Size of the transmit message buffer area in dwords. */
+	uint16_t sz;
+	/*
+	 * Offset of the transmit message buffer area in dwords
+	 * from the beginning of ABAR
+	 */
+	uint16_t ofst;
+} ahci_ghc_em_loc;
+
+/** AHCI Memory register Enclosure management control. */
+typedef union {
+	struct {
+		/** Message received. */
+		unsigned int mr : 1;
+		/** Reserved. */
+		unsigned int reserved : 7;
+		/** Transmit message. */
+		unsigned int tm : 1;
+		/** Reset. */
+		unsigned int rst : 1;
+		/** Reserved. */
+		unsigned int reserved2 : 6;
+		/** LED message types. */
+		unsigned int led : 1;
+		/** Support SAFT-TE message type. */
+		unsigned int safte : 1;
+		/** Support SES-2 message type. */
+		unsigned int ses2 : 1;
+		/** Support SGPIO register. */
+		unsigned int sgpio : 1;
+		/** Reserved. */
+		unsigned int reserved3 : 4;
+		/** Single message buffer. */
+		unsigned int smb : 1;
+		/**  Support transmitting only. */
+		unsigned int xmt : 1;
+		/** Activity LED hardware driven. */
+		unsigned int alhd : 1;
+		/** Port multiplier support. */
+		unsigned int pm : 1;
+		/** Reserved. */
+		unsigned int reserved4 : 4;
+	};
+	uint32_t u32;
+} ahci_ghc_em_ctl_t;
+
+/** AHCI Memory register HBA capatibilities extended. */
+typedef union {
+	struct {
+		/** HBA support BIOS/OS handoff mechanism,
+		 * implemented BOHC register.
+		 */
+		unsigned int boh : 1;
+		/** Support for NVMHCI register. */
+		unsigned int nvmp : 1;
+		/** Automatic partial to slumber transition support. */
+		unsigned int apst : 1;
+		/** Reserved. */
+		unsigned int reserved : 29;
+	};
+	uint32_t u32;
+} ahci_ghc_cap2_t;
+
+/** AHCI Memory register BIOS/OS Handoff control and status. */
+typedef union {
+	struct {
+		/** BIOS Owned semaphore. */
+		unsigned int bos : 1;
+		/** OS Owned semaphore. */
+		unsigned int oos : 1;
+		/** SMI on OS ownership change enable. */
+		unsigned int sooe : 1;
+		/** OS ownership change. */
+		unsigned int ooc : 1;
+		/** BIOS Busy. */
+		unsigned int bb : 1;
+		/** Reserved. */
+		unsigned int reserved : 27;
+	};
+	uint32_t u32;
+} ahci_ghc_bohc_t;
+
+/** AHCI Memory register Generic Host Control. */
+typedef struct
+{
+	/** Host Capabilities */
+	uint32_t cap;
+	/** Global Host Control */
+	uint32_t ghc;
+	/** Interrupt Status */
+	ahci_ghc_is_t is;
+	/** Ports Implemented */
+	uint32_t pi;
+	/** Version */
+	uint32_t vs;
+	/** Command Completion Coalescing Control */
+	uint32_t ccc_ctl;
+	/** Command Completion Coalescing Ports */
+	uint32_t ccc_ports;
+	/** Enclosure Management Location */
+	uint32_t em_loc;
+	/** Enclosure Management Control */
+	uint32_t em_ctl;
+	/** Host Capabilities Extended */
+	uint32_t cap2;
+	/** BIOS/OS Handoff Control and Status */
+	uint32_t bohc;
+} ahci_ghc_t;
+
+/** AHCI Memory register Port x Command List Base Address. */
+typedef union {
+	struct {
+		/** Reserved. */
+		unsigned int reserved : 10;
+		/** Command List Base Address (CLB) - Indicates the 32-bit base physical
+		 * address for the command list for this port. This base is used when
+		 * fetching commands to execute. The structure pointed to by this
+		 * address range is 1K-bytes in length. This address must be 1K-byte
+		 * aligned as indicated by bits 09:00 being read only.
+		 */
+		unsigned int clb : 22;
+	};
+	uint32_t u32;
+} ahci_port_clb_t;
+
+/** AHCI Memory register Port x Command List Base Address Upper 32-Bits. */
+typedef struct {
+	/** Command List Base Address Upper (CLBU): Indicates the upper 32-bits
+	 * for the command list base physical address for this port. This base
+	 * is used when fetching commands to execute. This register shall
+	 * be read only for HBAs that do not support 64-bit addressing.
+	 */
+	uint32_t u32;
+} ahci_port_clbu_t;
+
+/** AHCI Memory register Port x FIS Base Address. */
+typedef union {
+	struct {
+		/** Reserved. */
+		unsigned int reserved : 8;
+		/** FIS Base Address (FB) - Indicates the 32-bit base physical address
+		 * for received FISes. The structure pointed to by this address range
+		 * is 256 bytes in length. This address must be 256-byte aligned as
+		 * indicated by bits 07:00 being read only. When FIS-based switching
+		 * is in use, this structure is 4KB in length and the address shall be
+		 * 4KB aligned.
+		 */
+		unsigned int fb : 24;
+	};
+	uint32_t u32;
+} ahci_port_fb_t;
+
+/** AHCI Memory register Port x FIS Base Address Upper 32-Bits. */
+typedef struct {
+	/** FIS Base Address Upper (FBU) - Indicates the upper 32-bits
+	 * for the received FIS base physical address for this port. This register
+	 * shall be read only for HBAs that do not support 64-bit addressing.
+	 */
+	uint32_t u32;
+} ahci_port_fbu_t;
+
+/** AHCI Memory register Port x Interrupt Status. */
+typedef uint32_t ahci_port_is_t;
+
+#define AHCI_PORT_IS_DHRS  (1 << 0)
+#define AHCI_PORT_IS_PSS   (1 << 1)
+#define AHCI_PORT_IS_DSS   (1 << 2)
+#define AHCI_PORT_IS_SDBS  (1 << 3)
+#define AHCI_PORT_IS_UFS   (1 << 4)
+#define AHCI_PORT_IS_DPS   (1 << 5)
+#define AHCI_PORT_IS_PCS   (1 << 6)
+#define AHCI_PORT_IS_DMPS  (1 << 7)
+
+#define AHCI_PORT_IS_PRCS  (1 << 22)
+#define AHCI_PORT_IS_IPMS  (1 << 23)
+#define AHCI_PORT_IS_OFS   (1 << 24)
+#define AHCI_PORT_IS_INFS  (1 << 26)
+#define AHCI_PORT_IS_IFS   (1 << 27)
+#define AHCI_PORT_IS_HDBS  (1 << 28)
+#define AHCI_PORT_IS_HBFS  (1 << 29)
+#define AHCI_PORT_IS_TFES  (1 << 30)
+#define AHCI_PORT_IS_CPDS  (1 << 31)
+
+#define AHCI_PORT_END_OF_OPERATION \
+	(AHCI_PORT_IS_DHRS | \
+	AHCI_PORT_IS_SDBS )
+
+#define AHCI_PORT_IS_ERROR \
+	(AHCI_PORT_IS_UFS | \
+	AHCI_PORT_IS_PCS | \
+	AHCI_PORT_IS_DMPS | \
+	AHCI_PORT_IS_PRCS | \
+	AHCI_PORT_IS_IPMS | \
+	AHCI_PORT_IS_OFS | \
+	AHCI_PORT_IS_INFS | \
+	AHCI_PORT_IS_IFS | \
+	AHCI_PORT_IS_HDBS | \
+	AHCI_PORT_IS_HBFS | \
+	AHCI_PORT_IS_TFES | \
+	AHCI_PORT_IS_CPDS)
+
+#define AHCI_PORT_IS_PERMANENT_ERROR \
+	(AHCI_PORT_IS_PCS | \
+	AHCI_PORT_IS_DMPS | \
+	AHCI_PORT_IS_PRCS | \
+	AHCI_PORT_IS_IPMS | \
+	AHCI_PORT_IS_CPDS )
+
+/** Evaluate end of operation status from port interrupt status.
+ *
+ * @param port_is Value of port interrupt status.
+ *
+ * @return Indicate end of operation status.
+ *
+ */
+static inline int ahci_port_is_end_of_operation(ahci_port_is_t port_is)
+{
+	return port_is & AHCI_PORT_END_OF_OPERATION;
+}
+
+/** Evaluate error status from port interrupt status.
+ *
+ * @param port_is Value of port interrupt status.
+ *
+ * @return Indicate error status.
+ *
+ */
+static inline int ahci_port_is_error(ahci_port_is_t port_is)
+{
+	return port_is & AHCI_PORT_IS_ERROR;
+}
+
+/** Evaluate permanent error status from port interrupt status.
+ *
+ * @param port_is Value of port interrupt status.
+ *
+ * @return Indicate permanent error status.
+ *
+ */
+static inline int ahci_port_is_permanent_error(ahci_port_is_t port_is)
+{
+	return port_is & AHCI_PORT_IS_PERMANENT_ERROR;
+}
+
+/** Evaluate task file error status from port interrupt status.
+ *
+ * @param port_is Value of port interrupt status.
+ *
+ * @return Indicate error status.
+ *
+ */
+static inline int ahci_port_is_tfes(ahci_port_is_t port_is)
+{
+	return port_is & AHCI_PORT_IS_TFES;
+}
+
+/** AHCI Memory register Port x Interrupt Enable. */
+typedef union {
+	struct {
+		/** Device to Host Register FIS Interrupt Enable. */
+		unsigned int dhre : 1;
+		/** PIO Setup FIS Interrupt Enable. */
+		unsigned int pse : 1;
+		/** DMA Setup FIS Interrupt Enable. */
+		unsigned int dse : 1;
+		/** Set Device Bits Interrupt Eenable. */
+		unsigned int sdbe : 1;
+		/** Unknown FIS Interrupt Enable. */
+		unsigned int ufe : 1;
+		/** Descriptor Processed Interrupt Enable. */
+		unsigned int dpe : 1;
+		/** Port Change Interrupt Enable. */
+		unsigned int pce : 1;
+		/** Device Mechanical Presence Enable. */
+		unsigned int dmpe : 1;
+		/** Reserved. */
+		unsigned int reserved1 : 14;
+		/** PhyRdy Change Interrupt Enable. */
+		unsigned int prce : 1;
+		/** Incorrect Port Multiplier Enable. */
+		unsigned int ipme : 1;
+		/** Overflow Status Enable. */
+		unsigned int ofe : 1;
+		/** Reserved. */
+		unsigned int reserved2 : 1;
+		/** Interface Non-fatal Error Enable. */
+		unsigned int infe : 1;
+		/** Interface Fatal Error Enable. */
+		unsigned int ife : 1;
+		/** Host Bus Data Error Enable. */
+		unsigned int hbde : 1;
+		/** Host Bus Fatal Error Enable. */
+		unsigned int hbfe : 1;
+		/** Task File Error Enable. */
+		unsigned int tfee : 1;
+		/** Cold Port Detect Enable. */
+		unsigned int cpde : 1;
+	};
+	uint32_t u32;
+} ahci_port_ie_t;
+
+/** AHCI Memory register Port x Command and Status. */
+typedef union {
+	struct {
+		/** Start - when set, the HBA may process the command list. */
+		unsigned int st : 1;
+		/** Spin-Up Device. */
+		unsigned int sud : 1;
+		/** Power On Device. */
+		unsigned int pod : 1;
+		/** Command List Override. */
+		unsigned int clo : 1;
+		/** FIS Receive Enable. */
+		unsigned int fre : 1;
+		/** Reserved. */
+		unsigned int reserved : 3;
+		/** Current Command Slot. */
+		unsigned int ccs : 5;
+		/** Mechanical Presence Switch State. */
+		unsigned int mpss : 1;
+		/** FIS Receive Running. */
+		unsigned int fr : 1;
+		/** Command List Running. */
+		unsigned int cr : 1;
+		/** Cold Presence State. */
+		unsigned int cps : 1;
+		/** Port Multiplier Attached. */
+		unsigned int pma : 1;
+		/** Hot Plug Capable Port. */
+		unsigned int hpcp : 1;
+		/** Mechanical Presence Switch Attached to Port. */
+		unsigned int mpsp : 1;
+		/** Cold Presence Detection. */
+		unsigned int cpd : 1;
+		/** External SATA Port. */
+		unsigned int esp : 1;
+		/** FIS-based Switching Capable Port. */
+		unsigned int fbscp : 1;
+		/** Automatic Partial to Slumber Transitions Enabled. */
+		unsigned int apste : 1;
+		/** Device is ATAPI. */
+		unsigned int atapi : 1;
+		/** Drive LED on ATAPI Enable. */
+		unsigned int dlae : 1;
+		/** Aggressive Link Power Management Enable. */
+		unsigned int alpe : 1;
+		/** Aggressive Slumber / Partial. */
+		unsigned int asp : 1;
+		/** Interface Communication Control.
+		 * Values:
+		 * 7h - fh Reserved,
+		 * 6h Slumber - This shall cause the HBA to request a transition
+		 * of the interface to the Slumber state,
+		 * 3h - 5h Reserved,
+		 * 2h Partial - This shall cause the HBA to request a transition
+		 * of the interface to the Partial state,
+		 * 1h Active,
+		 * 0h No-Op / Idle.
+		 */
+		unsigned int icc : 4;
+	};
+	uint32_t u32;
+} ahci_port_cmd_t;
+
+/** AHCI Memory register Port x Task File Data. */
+typedef union {
+	struct {
+		/** Status (STS): Contains the latest copy of the task file
+		 * status register.
+		 */
+		uint8_t sts;
+		/** Error (ERR) - Contains the latest copy of the task file
+		 * error register.
+		 */
+		uint8_t err;
+		/** Reserved. */
+		uint16_t reserved;
+	};
+	uint32_t u32;
+} ahci_port_tfd_t;
+
+/** AHCI Memory register Port x Signature. */
+typedef union {
+	struct {
+		/** Sector Count Register */
+		uint8_t sector_count;
+		/** LBA Low Register */
+		uint8_t lba_lr;
+		/** LBA Mid Register */
+		uint8_t lba_mr;
+		/** LBA High Register */
+		uint8_t lba_hr;
+	};
+	uint32_t u32;
+} ahci_port_sig_t;
+
+/** AHCI Memory register Port x Serial ATA Status (SCR0: SStatus). */
+typedef union {
+	struct {
+		/** Device Detection */
+		unsigned int det : 4;
+		/** Current Interface Speed */
+		unsigned int spd : 4;
+		/** Interface Power Management */
+		unsigned int ipm : 4;
+		/** Reserved. */
+		unsigned int reserved : 20;
+	};
+	uint32_t u32;
+} ahci_port_ssts_t;
+
+/** Device detection active status. */
+#define AHCI_PORT_SSTS_DET_ACTIVE  3
+
+/** AHCI Memory register Port x Serial ATA Control (SCR2: SControl). */
+typedef union {
+	struct {
+		/** Device Detection Initialization */
+		unsigned int det : 4;
+		/** Speed Allowed */
+		unsigned int spd : 4;
+		/** Interface Power Management Transitions Allowed */
+		unsigned int ipm : 4;
+		/** Reserved. */
+		unsigned int reserved : 20;
+	};
+	uint32_t u32;
+} ahci_port_sctl_t;
+
+/** AHCI Memory register Port x Port x Serial ATA Error (SCR1: SError). */
+typedef struct {
+	/** Error (ERR) - The ERR field contains error information for use
+	 * by host software in determining the appropriate response to the
+	 * error condition.
+	 */
+	uint16_t err;
+	/** Diagnostics (DIAG) - Contains diagnostic error information for use
+	 * by diagnostic software in validating correct operation or isolating
+	 * failure modes.
+	 */
+	uint16_t diag;
+} ahci_port_serr_t;
+
+/** AHCI Memory register Port x Serial ATA Active (SCR3: SActive). */
+typedef struct {
+	/** Device Status - Each bit corresponds to the TAG and
+	 * command slot of a native queued command, where bit 0 corresponds
+	 * to TAG 0 and command slot 0.
+	 */
+	uint32_t u32;
+} ahci_port_sact_t;
+
+/** AHCI Memory register Port x Command Issue. */
+typedef struct {
+	/** Commands Issued - Each bit corresponds to a command slot,
+	 *  where bit 0 corresponds to command slot 0.
+	 */
+	uint32_t u32;
+} ahci_port_ci_t;
+
+/** AHCI Memory register Port x Serial ATA Notification
+ * (SCR4: SNotification).
+ */
+typedef struct {
+	/** PM Notify (PMN): This field indicates whether a particular device with
+	 * the corresponding PM Port number issued a Set Device Bits FIS
+	 * to the host with the Notification bit set.
+	 */
+	uint16_t pmn;
+	/** Reserved. */
+	uint16_t reserved;
+} ahci_port_sntf_t;
+
+/** AHCI Memory register Port x FIS-based Switching Control.
+ * This register is used to control and obtain status
+ * for Port Multiplier FIS-based switching.
+ */
+typedef union {
+	struct {
+		/** Enable */
+		unsigned int en : 1;
+		/** Device Error Clear */
+		unsigned int dec : 1;
+		/** Single Device Error */
+		unsigned int sde : 1;
+		/** Reserved. */
+		unsigned int reserved1 : 5;
+		/** Device To Issue */
+		unsigned int dev : 1;
+		/** Active Device Optimization */
+		unsigned int ado : 1;
+		/** Device With Error */
+		unsigned int dwe : 1;
+		/** Reserved. */
+		unsigned int reserved2 : 1;
+	};
+	uint32_t u32;
+} ahci_port_fbs_t;
+
+/** AHCI Memory register Port. */
+typedef volatile struct
+{
+	/** Port x Command List Base Address. */
+	uint32_t pxclb;
+	/** Port x Command List Base Address Upper 32-Bits. */
+	uint32_t pxclbu;
+	/** Port x FIS Base Address. */
+	uint32_t pxfb;
+	/** Port x FIS Base Address Upper 32-Bits. */
+	uint32_t pxfbu;
+	/** Port x Interrupt Status. */
+	ahci_port_is_t pxis;
+	/** Port x Interrupt Enable. */
+	uint32_t pxie;
+	/** Port x Command and Status. */
+	uint32_t pxcmd;
+	/** Reserved. */
+	uint32_t reserved1;
+	/** Port x Task File Data. */
+	uint32_t pxtfd;
+	/**  Port x Signature. */
+	uint32_t pxsig;
+	/** Port x Serial ATA Status (SCR0: SStatus). */
+	uint32_t pxssts;
+	/** Port x Serial ATA Control (SCR2: SControl). */
+	uint32_t pxsctl;
+	/** Port x Serial ATA Error (SCR1: SError). */
+	uint32_t pxserr;
+	/** Port x Serial ATA Active (SCR3: SActive). */
+	uint32_t pxsact;
+	/** Port x Command Issue. */
+	uint32_t pxci;
+	/** Port x Serial ATA Notification (SCR4: SNotification). */
+	uint32_t pxsntf;
+	/** Port x FIS-based Switching Control. */
+	uint32_t pxfbs;
+	/** Reserved. */
+	uint32_t reserved2[11];
+	/** Port x Vendor Specific. */
+	uint32_t pxvs[4];
+} ahci_port_t;
+
+/** AHCI Memory Registers. */
+typedef volatile struct {
+	/** Generic Host Control. */
+	ahci_ghc_t ghc;
+	/** Reserved. */
+	uint32_t reserved[13];
+	/** Reserved for NVMHCI. */
+	uint32_t reservedfornvmhci[16];
+	/** Vendor Specific registers. */
+	uint32_t vendorspecificsregs[24];
+	/** Ports. */
+	ahci_port_t ports[AHCI_MAX_PORTS];
+} ahci_memregs_t;
+
+/** AHCI Command header entry.
+ *
+ * This structure is not an AHCI register.
+ *
+ */
+typedef volatile struct {
+	/** Flags. */
+	uint16_t flags;
+	/** Physical Region Descriptor Table Length. */
+	uint16_t prdtl;
+	/** Physical Region Descriptor Byte Count. */
+	uint32_t bytesprocessed;
+	 /** Command Table Descriptor Base Address. */
+	uint32_t cmdtable;
+	/** Command Table Descriptor Base Address Upper 32-bits. */
+	uint32_t cmdtableu;
+} ahci_cmdhdr_t;
+
+/** Clear Busy upon R_OK (C) flag. */
+#define AHCI_CMDHDR_FLAGS_CLEAR_BUSY_UPON_OK  0x0400
+
+/** Write operation flag. */
+#define AHCI_CMDHDR_FLAGS_WRITE  0x0040
+
+/** 2 DW length command flag. */
+#define AHCI_CMDHDR_FLAGS_2DWCMD  0x0002
+
+/** 5 DW length command flag. */
+#define AHCI_CMDHDR_FLAGS_5DWCMD  0x0005
+
+/** AHCI Command Physical Region Descriptor entry.
+ *
+ * This structure is not an AHCI register.
+ *
+ */
+typedef volatile struct {
+	/** Word aligned 32-bit data base address. */
+	uint32_t data_address_low;
+	/** Upper data base address, valid only for 64-bit HBA addressing. */
+	uint32_t data_address_upper;
+	/** Reserved. */
+	uint32_t reserved1;
+	/** Data byte count */
+	unsigned int dbc : 22;
+	/** Reserved */
+	unsigned int reserved2 : 9;
+	/** Set Interrupt on each operation completion */
+	unsigned int ioc : 1;
+} ahci_cmd_prdt_t;
+
+#endif
Index: uspace/drv/block/ahci/ahci_sata.h
===================================================================
--- uspace/drv/block/ahci/ahci_sata.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/drv/block/ahci/ahci_sata.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,283 @@
+/*
+ * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @file
+ * Header for AHCI driver (SATA/ATA and related things).
+ */
+
+#ifndef __AHCI_SATA_H__
+#define __AHCI_SATA_H__
+
+#include <sys/types.h>
+
+/*----------------------------------------------------------------------------*/
+/*-- SATA Buffer Lengths -----------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+/** Default sector size in bytes. */
+#define SATA_DEFAULT_SECTOR_SIZE  512
+
+/** Size for set feature command buffer in bytes. */
+#define SATA_SET_FEATURE_BUFFER_LENGTH  512
+
+/** Size for indentify (packet) device buffer in bytes. */
+#define SATA_IDENTIFY_DEVICE_BUFFER_LENGTH  512
+
+/*----------------------------------------------------------------------------*/
+/*-- SATA Fis Frames ---------------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+/** Sata FIS Type number. */
+#define SATA_CMD_FIS_TYPE  0x27
+
+/** Sata FIS Type command indicator. */
+#define SATA_CMD_FIS_COMMAND_INDICATOR  0x80
+
+/** Standard Command frame. */
+typedef struct {
+	/** FIS type - always SATA_CMD_FIS_TYPE. */
+	unsigned int fis_type : 8;
+	/** Indicate that FIS is a Command - always SATA_CMD_FIS_COMMAND_INDICATOR. */
+	unsigned int c : 8;
+	/** Command - Identity device - 0xec, Set fetures - 0xef. */
+	unsigned int command : 8;
+	/** Features - subcommand for set features - set tranfer mode - 0x03. */
+	unsigned int features : 8;
+	/** 0:23 bits of LBA. */
+	unsigned int lba_lower : 24;
+	/** Device. */
+	unsigned int device : 8;
+	/** 24:47 bits of LBA. */
+	unsigned int lba_upper : 24;
+	/** Features - subcommand for set features - set tranfer mode - 0x03. */
+	unsigned int features_upper : 8;
+	/** Sector count - transfer mode for set transfer mode operation. */
+	unsigned int count : 16;
+	/** Reserved. */
+	unsigned int reserved1 : 8;
+	/** Control. */
+	unsigned int control : 8;
+	/** Reserved. */
+	unsigned int reserved2 : 32;
+} sata_std_command_frame_t;
+
+/** Command frame for NCQ data operation. */
+typedef struct {
+	/** FIS type - always 0x27. */
+	uint8_t fis_type;
+	/** Indicate that FIS is a Command - always SATA_CMD_FIS_COMMAND_INDICATOR. */
+	uint8_t c;
+	/** Command - FPDMA Read - 0x60, FPDMA Write - 0x61. */
+	uint8_t command;
+	/** bits 7:0 of sector count. */
+	uint8_t sector_count_low;
+	/** bits 7:0 of lba. */
+	uint8_t lba0;
+	/** bits 15:8 of lba. */
+	uint8_t lba1;
+	/** bits 23:16 of lba. */
+	uint8_t lba2;
+	uint8_t fua;
+	/** bits 31:24 of lba. */
+	uint8_t lba3;
+	/** bits 39:32 of lba. */
+	uint8_t lba4;
+	/** bits 47:40 of lba. */
+	uint8_t lba5;
+	/** bits 15:8 of sector count. */
+	uint8_t sector_count_high;
+	/** Tag number of NCQ operation. */
+	uint8_t tag;
+	/** Reserved. */
+	uint8_t reserved1;
+	/** Reserved. */
+	uint8_t reserved2;
+	/** Control. */
+	uint8_t control;
+	/** Reserved. */
+	uint8_t reserved3;
+	/** Reserved. */
+	uint8_t reserved4;
+	/** Reserved. */
+	uint8_t reserved5;
+	/** Reserved. */
+	uint8_t reserved6;
+} sata_ncq_command_frame_t;
+
+/*----------------------------------------------------------------------------*/
+/*-- SATA Identify device ----------------------------------------------------*/
+/*----------------------------------------------------------------------------*/
+
+/** Data returned from identify device and identify packet device command. */
+typedef struct {
+	uint16_t gen_conf;
+	uint16_t cylinders;
+	uint16_t reserved2;
+	uint16_t heads;
+	uint16_t _vs4;
+	uint16_t _vs5;
+	uint16_t sectors;
+	uint16_t _vs7;
+	uint16_t _vs8;
+	uint16_t _vs9;
+	
+	uint16_t serial_number[10];
+	uint16_t _vs20;
+	uint16_t _vs21;
+	uint16_t vs_bytes;
+	uint16_t firmware_rev[4];
+	uint16_t model_name[20];
+	
+	uint16_t max_rw_multiple;
+	uint16_t reserved48;
+	/* Different meaning for packet device. */
+	uint16_t caps;
+	uint16_t reserved50;
+	uint16_t pio_timing;
+	uint16_t dma_timing;
+	
+	uint16_t validity;
+	uint16_t cur_cyl;
+	uint16_t cur_heads;
+	uint16_t cur_sectors;
+	uint16_t cur_capacity0;
+	uint16_t cur_capacity1;
+	uint16_t mss;
+	uint16_t total_lba28_0;
+	uint16_t total_lba28_1;
+	uint16_t sw_dma;
+	uint16_t mw_dma;
+	uint16_t pio_modes;
+	uint16_t min_mw_dma_cycle;
+	uint16_t rec_mw_dma_cycle;
+	uint16_t min_raw_pio_cycle;
+	uint16_t min_iordy_pio_cycle;
+	
+	uint16_t reserved69;
+	uint16_t reserved70;
+	uint16_t reserved71;
+	uint16_t reserved72;
+	uint16_t reserved73;
+	uint16_t reserved74;
+	
+	uint16_t queue_depth;
+	/** SATA capatibilities - different meaning for packet device. */
+	uint16_t sata_cap;
+	/** SATA additional capatibilities - different meaning for packet device. */
+	uint16_t sata_cap2;
+	uint16_t reserved78[1 + 79 - 78];
+	uint16_t version_maj;
+	uint16_t version_min;
+	uint16_t cmd_set0;
+	uint16_t cmd_set1;
+	uint16_t csf_sup_ext;
+	uint16_t csf_enabled0;
+	uint16_t csf_enabled1;
+	uint16_t csf_default;
+	uint16_t udma;
+	
+	uint16_t reserved89[1 + 99 - 89];
+	
+	/* Total number of blocks in LBA-48 addressing. */
+	uint16_t total_lba48_0;
+	uint16_t total_lba48_1;
+	uint16_t total_lba48_2;
+	uint16_t total_lba48_3;
+	
+	uint16_t reserved104[1 + 105 - 104];
+	uint16_t physical_logic_sector_size;
+	/* Note: more fields are defined in ATA/ATAPI-7. */
+	uint16_t reserved107[1 + 127 - 107];
+	uint16_t reserved128[1 + 159 - 128];
+	uint16_t reserved160[1 + 255 - 160];
+} sata_identify_data_t;
+
+/** Capability bits for register device. */
+enum sata_rd_caps {
+	sata_rd_cap_iordy = 0x0800,
+	sata_rd_cap_iordy_cbd = 0x0400,
+	sata_rd_cap_lba = 0x0200,
+	sata_rd_cap_dma = 0x0100
+};
+
+/** Bits of @c identify_data_t.cmd_set1. */
+enum sata_cs1 {
+	/** 48-bit address feature set. */
+	sata_cs1_addr48 = 0x0400
+};
+
+/** SATA capatibilities for not packet device - Serial ATA revision 3_1. */
+enum sata_np_caps {
+	/** Supports READ LOG DMA EXT. */
+	sata_np_cap_log_ext = 0x8000,
+	/** Supports Device Automatic Partial to Slumber transitions. */
+	sata_np_cap_dev_slm = 0x4000,
+	/** Supports Host Automatic Partial to Slumber transitions. */
+	sata_np_cap_host_slm = 0x2000,
+	/** Supports NCQ priority information. */
+	sata_np_cap_ncq_prio = 0x1000,
+	/** Supports Unload while NCQ command outstanding. */
+	sata_np_cap_unload_ncq = 0x0800,
+	/** Supports Phy event counters. */
+	sata_np_cap_phy_ctx = 0x0400,
+	/** Supports recepits of host-initiated interface power management. */
+	sata_np_cap_host_pmngmnt = 0x0200,
+	
+	/** Supports NCQ. */
+	sata_np_cap_ncq = 0x0100,
+	
+	/** Supports SATA 3. */
+	sata_np_cap_sata_3 = 0x0008,
+	/** Supports SATA 2. */
+	sata_np_cap_sata_2 = 0x0004,
+	/** Supports SATA 1. */
+	sata_np_cap_sata_1 = 0x0002
+};
+
+/** SATA capatibilities for packet device - Serial ATA revision 3_1. */
+enum sata_pt_caps {
+	/** Supports READ LOG DMA EXT. */
+	sata_pt_cap_log_ext = 0x8000,
+	/** Supports Device Automatic Partial to Slumber transitions. */
+	sata_pt_cap_dev_slm = 0x4000,
+	/** Supports Host Automatic Partial to Slumber transitions. */
+	sata_pt_cap_host_slm = 0x2000,
+	/** Supports Phy event counters. */
+	sata_pt_cap_phy_ctx = 0x0400,
+	/** Supports recepits of host-initiated interface power management. */
+	sata_pt_cap_host_pmngmnt = 0x0200,
+	
+	/** Supports SATA 3. */
+	sata_pt_cap_sat_3 = 0x0008,
+	/** Supports SATA 2. */
+	sata_pt_cap_sat_2 = 0x0004,
+	/** Supports SATA 1. */
+	sata_pt_cap_sat_1 = 0x0002
+};
+
+#endif
Index: uspace/drv/bus/pci/pciintel/pci.c
===================================================================
--- uspace/drv/bus/pci/pciintel/pci.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/pci/pciintel/pci.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -38,4 +38,5 @@
 
 #include <assert.h>
+#include <byteorder.h>
 #include <stdio.h>
 #include <errno.h>
@@ -231,15 +232,16 @@
 	void *addr = bus->conf_data_port + (reg & 3);
 	
-	pio_write_32(bus->conf_addr_port, conf_addr);
+	pio_write_32(bus->conf_addr_port, host2uint32_t_le(conf_addr));
 	
 	switch (len) {
 	case 1:
+		/* No endianness change for 1 byte */
 		buf[0] = pio_read_8(addr);
 		break;
 	case 2:
-		((uint16_t *) buf)[0] = pio_read_16(addr);
+		((uint16_t *) buf)[0] = uint16_t_le2host(pio_read_16(addr));
 		break;
 	case 4:
-		((uint32_t *) buf)[0] = pio_read_32(addr);
+		((uint32_t *) buf)[0] = uint32_t_le2host(pio_read_32(addr));
 		break;
 	}
@@ -254,19 +256,19 @@
 	fibril_mutex_lock(&bus->conf_mutex);
 	
-	uint32_t conf_addr;
-	conf_addr = CONF_ADDR(fun->bus, fun->dev, fun->fn, reg);
+	const uint32_t conf_addr = CONF_ADDR(fun->bus, fun->dev, fun->fn, reg);
 	void *addr = bus->conf_data_port + (reg & 3);
 	
-	pio_write_32(bus->conf_addr_port, conf_addr);
+	pio_write_32(bus->conf_addr_port, host2uint32_t_le(conf_addr));
 	
 	switch (len) {
 	case 1:
+		/* No endianness change for 1 byte */
 		pio_write_8(addr, buf[0]);
 		break;
 	case 2:
-		pio_write_16(addr, ((uint16_t *) buf)[0]);
+		pio_write_16(addr, host2uint16_t_le(((uint16_t *) buf)[0]));
 		break;
 	case 4:
-		pio_write_32(addr, ((uint32_t *) buf)[0]);
+		pio_write_32(addr, host2uint32_t_le(((uint32_t *) buf)[0]));
 		break;
 	}
@@ -650,15 +652,23 @@
 	got_res = true;
 	
+	
+	assert(hw_resources.count > 1);
+	assert(hw_resources.resources[0].type == IO_RANGE);
+	assert(hw_resources.resources[0].res.io_range.size >= 4);
+	
+	assert(hw_resources.resources[1].type == IO_RANGE);
+	assert(hw_resources.resources[1].res.io_range.size >= 4);
+	
 	ddf_msg(LVL_DEBUG, "conf_addr = %" PRIx64 ".",
 	    hw_resources.resources[0].res.io_range.address);
-	
-	assert(hw_resources.count > 0);
-	assert(hw_resources.resources[0].type == IO_RANGE);
-	assert(hw_resources.resources[0].res.io_range.size == 8);
+	ddf_msg(LVL_DEBUG, "data_addr = %" PRIx64 ".",
+	    hw_resources.resources[1].res.io_range.address);
 	
 	bus->conf_io_addr =
 	    (uint32_t) hw_resources.resources[0].res.io_range.address;
-	
-	if (pio_enable((void *)(uintptr_t)bus->conf_io_addr, 8,
+	bus->conf_io_data =
+	    (uint32_t) hw_resources.resources[1].res.io_range.address;
+	
+	if (pio_enable((void *)(uintptr_t)bus->conf_io_addr, 4,
 	    &bus->conf_addr_port)) {
 		ddf_msg(LVL_ERROR, "Failed to enable configuration ports.");
@@ -666,5 +676,10 @@
 		goto fail;
 	}
-	bus->conf_data_port = (char *) bus->conf_addr_port + 4;
+	if (pio_enable((void *)(uintptr_t)bus->conf_io_data, 4,
+	    &bus->conf_data_port)) {
+		ddf_msg(LVL_ERROR, "Failed to enable configuration ports.");
+		rc = EADDRNOTAVAIL;
+		goto fail;
+	}
 	
 	/* Make the bus device more visible. It has no use yet. */
Index: uspace/drv/bus/pci/pciintel/pci.h
===================================================================
--- uspace/drv/bus/pci/pciintel/pci.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/pci/pciintel/pci.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -46,4 +46,5 @@
 	ddf_dev_t *dnode;
 	uint32_t conf_io_addr;
+	uint32_t conf_io_data;
 	void *conf_data_port;
 	void *conf_addr_port;
Index: uspace/drv/bus/usb/ehci/main.c
===================================================================
--- uspace/drv/bus/usb/ehci/main.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ehci/main.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -49,9 +49,9 @@
 
 static int ehci_dev_add(ddf_dev_t *device);
-/*----------------------------------------------------------------------------*/
+
 static driver_ops_t ehci_driver_ops = {
 	.dev_add = ehci_dev_add,
 };
-/*----------------------------------------------------------------------------*/
+
 static driver_t ehci_driver = {
 	.name = NAME,
@@ -62,5 +62,5 @@
 };
 
-/*----------------------------------------------------------------------------*/
+
 /** Initializes a new ddf driver instance of EHCI hcd.
  *
@@ -121,5 +121,5 @@
 #undef CHECK_RET_RETURN
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initializes global driver structures (NONE).
  *
Index: uspace/drv/bus/usb/ohci/endpoint_list.c
===================================================================
--- uspace/drv/bus/usb/ohci/endpoint_list.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/endpoint_list.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -65,5 +65,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Set the next list in transfer list chain.
  *
@@ -80,5 +80,5 @@
 	ed_append_ed(instance->list_head, next->list_head);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Add endpoint to the list and queue.
  *
@@ -132,5 +132,5 @@
 	fibril_mutex_unlock(&instance->guard);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Remove endpoint from the list and queue.
  *
@@ -162,5 +162,5 @@
 		qpos = "NOT FIRST";
 	}
-	assert((prev_ed->next & ED_NEXT_PTR_MASK) == addr_to_phys(ep->ed));
+	assert(ed_next(prev_ed) == addr_to_phys(ep->ed));
 	prev_ed->next = ep->ed->next;
 	/* Make sure ED is updated */
Index: uspace/drv/bus/usb/ohci/hc.c
===================================================================
--- uspace/drv/bus/usb/ohci/hc.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/hc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -26,4 +26,5 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /** @addtogroup drvusbohcihc
  * @{
@@ -32,4 +33,5 @@
  * @brief OHCI Host controller driver routines
  */
+
 #include <errno.h>
 #include <str_error.h>
@@ -49,5 +51,5 @@
 static const irq_pio_range_t ohci_pio_ranges[] = {
 	{
-		.base = 0,	/* filled later */
+		.base = 0,
 		.size = sizeof(ohci_regs_t)
 	}
@@ -55,9 +57,28 @@
 
 static const irq_cmd_t ohci_irq_commands[] = {
-	{ .cmd = CMD_PIO_READ_32, .dstarg = 1, .addr = NULL /* filled later */ },
-	{ .cmd = CMD_BTEST, .srcarg = 1, .dstarg = 2, .value = OHCI_USED_INTERRUPTS },
-	{ .cmd = CMD_PREDICATE, .srcarg = 2, .value = 2 },
-	{ .cmd = CMD_PIO_WRITE_A_32, .srcarg = 1, .addr = NULL /* filled later */ },
-	{ .cmd = CMD_ACCEPT },
+	{
+		.cmd = CMD_PIO_READ_32,
+		.dstarg = 1,
+		.addr = NULL
+	},
+	{
+		.cmd = CMD_AND,
+		.srcarg = 1,
+		.dstarg = 2,
+		.value = 0
+	},
+	{
+		.cmd = CMD_PREDICATE,
+		.srcarg = 2,
+		.value = 2
+	},
+	{
+		.cmd = CMD_PIO_WRITE_A_32,
+		.srcarg = 1,
+		.addr = NULL
+	},
+	{
+		.cmd = CMD_ACCEPT
+	}
 };
 
@@ -68,5 +89,5 @@
 static int interrupt_emulator(hc_t *instance);
 static int hc_schedule(hcd_t *hcd, usb_transfer_batch_t *batch);
-/*----------------------------------------------------------------------------*/
+
 /** Get number of PIO ranges used in IRQ code.
  * @return Number of ranges.
@@ -76,6 +97,5 @@
 	return sizeof(ohci_pio_ranges) / sizeof(irq_pio_range_t);
 }
-/*----------------------------------------------------------------------------*/
-/*----------------------------------------------------------------------------*/
+
 /** Get number of commands used in IRQ code.
  * @return Number of commands.
@@ -85,5 +105,5 @@
 	return sizeof(ohci_irq_commands) / sizeof(irq_cmd_t);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Generate IRQ code.
  * @param[out] ranges PIO ranges buffer.
@@ -112,8 +132,9 @@
 	cmds[0].addr = (void *) &registers->interrupt_status;
 	cmds[3].addr = (void *) &registers->interrupt_status;
+	OHCI_WR(cmds[1].value, OHCI_USED_INTERRUPTS);
 
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Announce OHCI root hub to the DDF
  *
@@ -174,5 +195,5 @@
 #undef CHECK_RET_RELEASE
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize OHCI hc driver structure
  *
@@ -227,5 +248,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 void hc_enqueue_endpoint(hc_t *instance, const endpoint_t *ep)
 {
@@ -241,23 +262,24 @@
 	switch (ep->transfer_type) {
 	case USB_TRANSFER_CONTROL:
-		instance->registers->control &= ~C_CLE;
+		OHCI_CLR(instance->registers->control, C_CLE);
 		endpoint_list_add_ep(list, ohci_ep);
-		instance->registers->control_current = 0;
-		instance->registers->control |= C_CLE;
+		OHCI_WR(instance->registers->control_current, 0);
+		OHCI_SET(instance->registers->control, C_CLE);
 		break;
 	case USB_TRANSFER_BULK:
-		instance->registers->control &= ~C_BLE;
+		OHCI_CLR(instance->registers->control, C_BLE);
 		endpoint_list_add_ep(list, ohci_ep);
-		instance->registers->control |= C_BLE;
+		OHCI_WR(instance->registers->bulk_current, 0);
+		OHCI_SET(instance->registers->control, C_BLE);
 		break;
 	case USB_TRANSFER_ISOCHRONOUS:
 	case USB_TRANSFER_INTERRUPT:
-		instance->registers->control &= (~C_PLE & ~C_IE);
+		OHCI_CLR(instance->registers->control, C_PLE | C_IE);
 		endpoint_list_add_ep(list, ohci_ep);
-		instance->registers->control |= C_PLE | C_IE;
-		break;
-	}
-}
-/*----------------------------------------------------------------------------*/
+		OHCI_SET(instance->registers->control, C_PLE | C_IE);
+		break;
+	}
+}
+
 void hc_dequeue_endpoint(hc_t *instance, const endpoint_t *ep)
 {
@@ -273,19 +295,20 @@
 	switch (ep->transfer_type) {
 	case USB_TRANSFER_CONTROL:
-		instance->registers->control &= ~C_CLE;
+		OHCI_CLR(instance->registers->control, C_CLE);
 		endpoint_list_remove_ep(list, ohci_ep);
-		instance->registers->control_current = 0;
-		instance->registers->control |= C_CLE;
+		OHCI_WR(instance->registers->control_current, 0);
+		OHCI_SET(instance->registers->control, C_CLE);
 		break;
 	case USB_TRANSFER_BULK:
-		instance->registers->control &= ~C_BLE;
+		OHCI_CLR(instance->registers->control, C_BLE);
 		endpoint_list_remove_ep(list, ohci_ep);
-		instance->registers->control |= C_BLE;
+		OHCI_WR(instance->registers->bulk_current, 0);
+		OHCI_SET(instance->registers->control, C_BLE);
 		break;
 	case USB_TRANSFER_ISOCHRONOUS:
 	case USB_TRANSFER_INTERRUPT:
-		instance->registers->control &= (~C_PLE & ~C_IE);
+		OHCI_CLR(instance->registers->control, C_PLE | C_IE);
 		endpoint_list_remove_ep(list, ohci_ep);
-		instance->registers->control |= C_PLE | C_IE;
+		OHCI_SET(instance->registers->control, C_PLE | C_IE);
 		break;
 	default:
@@ -293,5 +316,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /** Add USB transfer to the schedule.
  *
@@ -308,4 +331,5 @@
 	/* Check for root hub communication */
 	if (batch->ep->address == instance->rh.address) {
+		usb_log_debug("OHCI root hub request.\n");
 		rh_request(&instance->rh, batch);
 		return EOK;
@@ -323,8 +347,8 @@
 	{
 	case USB_TRANSFER_CONTROL:
-		instance->registers->command_status |= CS_CLF;
+		OHCI_SET(instance->registers->command_status, CS_CLF);
 		break;
 	case USB_TRANSFER_BULK:
-		instance->registers->command_status |= CS_BLF;
+		OHCI_SET(instance->registers->command_status, CS_BLF);
 		break;
 	default:
@@ -334,5 +358,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Interrupt handling routine
  *
@@ -342,4 +366,5 @@
 void hc_interrupt(hc_t *instance, uint32_t status)
 {
+	status = OHCI_RD(status);
 	assert(instance);
 	if ((status & ~I_SF) == 0) /* ignore sof status */
@@ -352,8 +377,8 @@
 		fibril_mutex_lock(&instance->guard);
 		usb_log_debug2("HCCA: %p-%#" PRIx32 " (%p).\n", instance->hcca,
-		    instance->registers->hcca,
+		    OHCI_RD(instance->registers->hcca),
 		    (void *) addr_to_phys(instance->hcca));
 		usb_log_debug2("Periodic current: %#" PRIx32 ".\n",
-		    instance->registers->periodic_current);
+		    OHCI_RD(instance->registers->periodic_current));
 
 		link_t *current = list_first(&instance->pending_batches);
@@ -379,5 +404,5 @@
 
 }
-/*----------------------------------------------------------------------------*/
+
 /** Check status register regularly
  *
@@ -397,5 +422,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Turn off any (BIOS)driver that might be in control of the device.
  *
@@ -410,5 +435,5 @@
 
 	usb_log_debug("Requesting OHCI control.\n");
-	if (instance->registers->revision & R_LEGACY_FLAG) {
+	if (OHCI_RD(instance->registers->revision) & R_LEGACY_FLAG) {
 		/* Turn off legacy emulation, it should be enough to zero
 		 * the lowest bit, but it caused problems. Thus clear all
@@ -419,18 +444,18 @@
 		(uint32_t*)((char*)instance->registers + LEGACY_REGS_OFFSET);
 		usb_log_debug("OHCI legacy register %p: %x.\n",
-		    ohci_emulation_reg, *ohci_emulation_reg);
+		    ohci_emulation_reg, OHCI_RD(*ohci_emulation_reg));
 		/* Zero everything but A20State */
-		*ohci_emulation_reg &= 0x100;
+		OHCI_CLR(*ohci_emulation_reg, ~0x100);
 		usb_log_debug(
 		    "OHCI legacy register (should be 0 or 0x100) %p: %x.\n",
-		    ohci_emulation_reg, *ohci_emulation_reg);
+		    ohci_emulation_reg, OHCI_RD(*ohci_emulation_reg));
 	}
 
 	/* Interrupt routing enabled => smm driver is active */
-	if (instance->registers->control & C_IR) {
+	if (OHCI_RD(instance->registers->control) & C_IR) {
 		usb_log_debug("SMM driver: request ownership change.\n");
-		instance->registers->command_status |= CS_OCR;
+		OHCI_SET(instance->registers->command_status, CS_OCR);
 		/* Hope that SMM actually knows its stuff or we can hang here */
-		while (instance->registers->control & C_IR) {
+		while (OHCI_RD(instance->registers->control & C_IR)) {
 			async_usleep(1000);
 		}
@@ -449,5 +474,5 @@
 			return;
 		}
-		/* HC is suspended assert resume for 20ms, */
+		/* HC is suspended assert resume for 20ms */
 		C_HCFS_SET(instance->registers->control, C_HCFS_RESUME);
 		async_usleep(20000);
@@ -461,5 +486,5 @@
 	async_usleep(50000);
 }
-/*----------------------------------------------------------------------------*/
+
 /** OHCI hw initialization routine.
  *
@@ -473,5 +498,5 @@
 
 	/* Save contents of fm_interval register */
-	const uint32_t fm_interval = instance->registers->fm_interval;
+	const uint32_t fm_interval = OHCI_RD(instance->registers->fm_interval);
 	usb_log_debug2("Old value of HcFmInterval: %x.\n", fm_interval);
 
@@ -479,6 +504,6 @@
 	usb_log_debug2("HC reset.\n");
 	size_t time = 0;
-	instance->registers->command_status = CS_HCR;
-	while (instance->registers->command_status & CS_HCR) {
+	OHCI_WR(instance->registers->command_status, CS_HCR);
+	while (OHCI_RD(instance->registers->command_status) & CS_HCR) {
 		async_usleep(10);
 		time += 10;
@@ -487,23 +512,23 @@
 
 	/* Restore fm_interval */
-	instance->registers->fm_interval = fm_interval;
-	assert((instance->registers->command_status & CS_HCR) == 0);
+	OHCI_WR(instance->registers->fm_interval, fm_interval);
+	assert((OHCI_RD(instance->registers->command_status) & CS_HCR) == 0);
 
 	/* hc is now in suspend state */
 	usb_log_debug2("HC should be in suspend state(%x).\n",
-	    instance->registers->control);
+	    OHCI_RD(instance->registers->control));
 
 	/* Use HCCA */
-	instance->registers->hcca = addr_to_phys(instance->hcca);
+	OHCI_WR(instance->registers->hcca, addr_to_phys(instance->hcca));
 
 	/* Use queues */
-	instance->registers->bulk_head =
-	    instance->lists[USB_TRANSFER_BULK].list_head_pa;
+	OHCI_WR(instance->registers->bulk_head,
+	    instance->lists[USB_TRANSFER_BULK].list_head_pa);
 	usb_log_debug2("Bulk HEAD set to: %p (%#" PRIx32 ").\n",
 	    instance->lists[USB_TRANSFER_BULK].list_head,
 	    instance->lists[USB_TRANSFER_BULK].list_head_pa);
 
-	instance->registers->control_head =
-	    instance->lists[USB_TRANSFER_CONTROL].list_head_pa;
+	OHCI_WR(instance->registers->control_head,
+	    instance->lists[USB_TRANSFER_CONTROL].list_head_pa);
 	usb_log_debug2("Control HEAD set to: %p (%#" PRIx32 ").\n",
 	    instance->lists[USB_TRANSFER_CONTROL].list_head,
@@ -511,26 +536,27 @@
 
 	/* Enable queues */
-	instance->registers->control |= (C_PLE | C_IE | C_CLE | C_BLE);
-	usb_log_debug2("All queues enabled(%x).\n",
-	    instance->registers->control);
+	OHCI_SET(instance->registers->control, (C_PLE | C_IE | C_CLE | C_BLE));
+	usb_log_debug("Queues enabled(%x).\n",
+	    OHCI_RD(instance->registers->control));
 
 	/* Enable interrupts */
-	instance->registers->interrupt_enable = OHCI_USED_INTERRUPTS;
-	usb_log_debug2("Enabled interrupts: %x.\n",
-	    instance->registers->interrupt_enable);
-	instance->registers->interrupt_enable = I_MI;
+	OHCI_WR(instance->registers->interrupt_enable, OHCI_USED_INTERRUPTS);
+	usb_log_debug("Enabled interrupts: %x.\n",
+	    OHCI_RD(instance->registers->interrupt_enable));
+	OHCI_WR(instance->registers->interrupt_enable, I_MI);
 
 	/* Set periodic start to 90% */
-	uint32_t frame_length = ((fm_interval >> FMI_FI_SHIFT) & FMI_FI_MASK);
-	instance->registers->periodic_start = (frame_length / 10) * 9;
+	const uint32_t frame_length =
+	    (fm_interval >> FMI_FI_SHIFT) & FMI_FI_MASK;
+	OHCI_WR(instance->registers->periodic_start,
+	    ((frame_length / 10) * 9) & PS_MASK << PS_SHIFT);
 	usb_log_debug2("All periodic start set to: %x(%u - 90%% of %d).\n",
-	    instance->registers->periodic_start,
-	    instance->registers->periodic_start, frame_length);
-
+	    OHCI_RD(instance->registers->periodic_start),
+	    OHCI_RD(instance->registers->periodic_start), frame_length);
 	C_HCFS_SET(instance->registers->control, C_HCFS_OPERATIONAL);
 	usb_log_debug("OHCI HC up and running (ctl_reg=0x%x).\n",
-	    instance->registers->control);
-}
-/*----------------------------------------------------------------------------*/
+	    OHCI_RD(instance->registers->control));
+}
+
 /** Initialize schedule queues
  *
@@ -566,5 +592,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize memory structures used by the OHCI hcd.
  *
@@ -587,10 +613,9 @@
 	if (instance->hcca == NULL)
 		return ENOMEM;
-	bzero(instance->hcca, sizeof(hcca_t));
 	usb_log_debug2("OHCI HCCA initialized at %p.\n", instance->hcca);
 
-	for (unsigned i = 0; i < 32; ++i) {
-		instance->hcca->int_ep[i] =
-		    instance->lists[USB_TRANSFER_INTERRUPT].list_head_pa;
+	for (unsigned i = 0; i < HCCA_INT_EP_COUNT; ++i) {
+		hcca_set_int_ep(instance->hcca, i,
+		    instance->lists[USB_TRANSFER_INTERRUPT].list_head_pa);
 	}
 	usb_log_debug2("Interrupt HEADs set to: %p (%#" PRIx32 ").\n",
Index: uspace/drv/bus/usb/ohci/hw_struct/endpoint_descriptor.c
===================================================================
--- uspace/drv/bus/usb/ohci/hw_struct/endpoint_descriptor.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/hw_struct/endpoint_descriptor.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -58,5 +58,5 @@
 		/* Mark as dead, used for dummy EDs at the beginning of
 		 * endpoint lists. */
-		instance->status = ED_STATUS_K_FLAG;
+		OHCI_MEM32_WR(instance->status, ED_STATUS_K_FLAG);
 		return;
 	}
@@ -65,27 +65,27 @@
 
 	/* Status: address, endpoint nr, direction mask and max packet size. */
-	instance->status = 0
-	    | ((ep->address & ED_STATUS_FA_MASK) << ED_STATUS_FA_SHIFT)
+	OHCI_MEM32_WR(instance->status,
+	    ((ep->address & ED_STATUS_FA_MASK) << ED_STATUS_FA_SHIFT)
 	    | ((ep->endpoint & ED_STATUS_EN_MASK) << ED_STATUS_EN_SHIFT)
 	    | ((dir[ep->direction] & ED_STATUS_D_MASK) << ED_STATUS_D_SHIFT)
 	    | ((ep->max_packet_size & ED_STATUS_MPS_MASK)
-	        << ED_STATUS_MPS_SHIFT);
+	        << ED_STATUS_MPS_SHIFT));
 
 	/* Low speed flag */
 	if (ep->speed == USB_SPEED_LOW)
-		instance->status |= ED_STATUS_S_FLAG;
+		OHCI_MEM32_SET(instance->status, ED_STATUS_S_FLAG);
 
 	/* Isochronous format flag */
 	if (ep->transfer_type == USB_TRANSFER_ISOCHRONOUS)
-		instance->status |= ED_STATUS_F_FLAG;
+		OHCI_MEM32_SET(instance->status, ED_STATUS_F_FLAG);
 
 	/* Set TD to the list */
 	const uintptr_t pa = addr_to_phys(td);
-	instance->td_head = pa & ED_TDHEAD_PTR_MASK;
-	instance->td_tail = pa & ED_TDTAIL_PTR_MASK;
+	OHCI_MEM32_WR(instance->td_head, pa & ED_TDHEAD_PTR_MASK);
+	OHCI_MEM32_WR(instance->td_tail, pa & ED_TDTAIL_PTR_MASK);
 
 	/* Set toggle bit */
 	if (ep->toggle)
-		instance->td_head |= ED_TDHEAD_TOGGLE_CARRY;
+		OHCI_MEM32_SET(instance->td_head, ED_TDHEAD_TOGGLE_CARRY);
 
 }
Index: uspace/drv/bus/usb/ohci/hw_struct/endpoint_descriptor.h
===================================================================
--- uspace/drv/bus/usb/ohci/hw_struct/endpoint_descriptor.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/hw_struct/endpoint_descriptor.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -44,4 +44,5 @@
 
 #include "completion_codes.h"
+#include "mem_access.h"
 
 /**
@@ -116,6 +117,12 @@
 {
 	assert(instance);
-	return (instance->td_head & ED_TDHEAD_HALTED_FLAG)
-	    || (instance->status & ED_STATUS_K_FLAG);
+	return (OHCI_MEM32_RD(instance->td_head) & ED_TDHEAD_HALTED_FLAG)
+	    || (OHCI_MEM32_RD(instance->status) & ED_STATUS_K_FLAG);
+}
+
+static inline void ed_clear_halt(ed_t *instance)
+{
+	assert(instance);
+	OHCI_MEM32_CLR(instance->td_head, ED_TDHEAD_HALTED_FLAG);
 }
 
@@ -128,6 +135,6 @@
 {
 	assert(instance);
-	return (instance->td_head & ED_TDHEAD_PTR_MASK)
-	    != (instance->td_tail & ED_TDTAIL_PTR_MASK);
+	return (OHCI_MEM32_RD(instance->td_head) & ED_TDHEAD_PTR_MASK)
+	    != (OHCI_MEM32_RD(instance->td_tail) & ED_TDTAIL_PTR_MASK);
 }
 
@@ -141,5 +148,17 @@
 	assert(instance);
 	const uintptr_t pa = addr_to_phys(td);
-	instance->td_tail = pa & ED_TDTAIL_PTR_MASK;
+	OHCI_MEM32_WR(instance->td_tail, pa & ED_TDTAIL_PTR_MASK);
+}
+
+static inline uint32_t ed_tail_td(const ed_t *instance)
+{
+	assert(instance);
+	return OHCI_MEM32_RD(instance->td_tail) & ED_TDTAIL_PTR_MASK;
+}
+
+static inline uint32_t ed_head_td(const ed_t *instance)
+{
+	assert(instance);
+	return OHCI_MEM32_RD(instance->td_head) & ED_TDHEAD_PTR_MASK;
 }
 
@@ -155,5 +174,11 @@
 	const uint32_t pa = addr_to_phys(next);
 	assert((pa & ED_NEXT_PTR_MASK) << ED_NEXT_PTR_SHIFT == pa);
-	instance->next = pa;
+	OHCI_MEM32_WR(instance->next, pa);
+}
+
+static inline uint32_t ed_next(const ed_t *instance)
+{
+	assert(instance);
+	return OHCI_MEM32_RD(instance->next) & ED_NEXT_PTR_MASK;
 }
 
@@ -166,5 +191,5 @@
 {
 	assert(instance);
-	return (instance->td_head & ED_TDHEAD_TOGGLE_CARRY) ? 1 : 0;
+	return (OHCI_MEM32_RD(instance->td_head) & ED_TDHEAD_TOGGLE_CARRY) ? 1 : 0;
 }
 
@@ -178,9 +203,9 @@
 	assert(instance);
 	if (toggle) {
-		instance->td_head |= ED_TDHEAD_TOGGLE_CARRY;
+		OHCI_MEM32_SET(instance->td_head, ED_TDHEAD_TOGGLE_CARRY);
 	} else {
 		/* Clear halted flag when reseting toggle TODO: Why? */
-		instance->td_head &= ~ED_TDHEAD_TOGGLE_CARRY;
-		instance->td_head &= ~ED_TDHEAD_HALTED_FLAG;
+		OHCI_MEM32_CLR(instance->td_head, ED_TDHEAD_TOGGLE_CARRY);
+		OHCI_MEM32_CLR(instance->td_head, ED_TDHEAD_HALTED_FLAG);
 	}
 }
Index: uspace/drv/bus/usb/ohci/hw_struct/hcca.h
===================================================================
--- uspace/drv/bus/usb/ohci/hw_struct/hcca.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/hw_struct/hcca.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -38,19 +38,49 @@
 #include <malloc.h>
 
+#include "mem_access.h"
+
+#define HCCA_INT_EP_COUNT  32
+
 /** Host controller communication area.
  * Shared memory used for communication between the controller and the driver.
  */
 typedef struct hcca {
-	uint32_t int_ep[32];
+	/** Interrupt endpoints */
+	uint32_t int_ep[HCCA_INT_EP_COUNT];
+	/** Frame number. */
 	uint16_t frame_number;
 	uint16_t pad1;
+	/** Pointer to the last completed TD. (useless) */
 	uint32_t done_head;
+	/** Padding to make the size 256B */
 	uint32_t reserved[30];
 } hcca_t;
 
-static inline void * hcca_get(void)
+/** Allocate properly aligned structure.
+ *
+ * The returned structure is zeroed upon allocation.
+ *
+ * @return Usable HCCA memory structure.
+ */
+static inline hcca_t * hcca_get(void)
 {
 	assert(sizeof(hcca_t) == 256);
-	return memalign(256, sizeof(hcca_t));
+	hcca_t *hcca = memalign(256, sizeof(hcca_t));
+	if (hcca)
+		bzero(hcca, sizeof(hcca_t));
+	return hcca;
+}
+
+/** Set HCCA interrupt endpoint pointer table entry.
+ * @param hcca HCCA memory structure.
+ * @param index table index.
+ * @param pa Physical address.
+ */
+static inline void hcca_set_int_ep(hcca_t *hcca, unsigned index, uintptr_t pa)
+{
+	assert(hcca);
+	assert(index < HCCA_INT_EP_COUNT);
+	OHCI_MEM32_WR(hcca->int_ep[index], pa);
+
 }
 #endif
Index: uspace/drv/bus/usb/ohci/hw_struct/mem_access.h
===================================================================
--- uspace/drv/bus/usb/ohci/hw_struct/mem_access.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/drv/bus/usb/ohci/hw_struct/mem_access.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2012 Jan Vesely
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/** @addtogroup drvusbohci
+ * @{
+ */
+/** @file
+ * @brief OHCI driver
+ */
+#ifndef DRV_OHCI_HW_MEM_ACCESS_H
+#define DRV_OHCI_HW_MEM_ACCESS_H
+
+#include <byteorder.h>
+
+#define OHCI_MEM32_WR(reg, val) reg = host2uint32_t_le(val)
+#define OHCI_MEM32_RD(reg) uint32_t_le2host(reg)
+#define OHCI_MEM32_SET(reg, val) reg |= host2uint32_t_le(val)
+#define OHCI_MEM32_CLR(reg, val) reg &= host2uint32_t_le(~val)
+
+#endif
+
+/*
+ * @}
+ */
+
Index: uspace/drv/bus/usb/ohci/hw_struct/transfer_descriptor.c
===================================================================
--- uspace/drv/bus/usb/ohci/hw_struct/transfer_descriptor.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/hw_struct/transfer_descriptor.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -33,4 +33,6 @@
  */
 #include <usb/usb.h>
+#include <mem.h>
+#include "../utils/malloc32.h"
 #include "transfer_descriptor.h"
 
@@ -58,26 +60,26 @@
 	bzero(instance, sizeof(td_t));
 	/* Set PID and Error code */
-	instance->status = 0
-	    | ((dir[direction] & TD_STATUS_DP_MASK) << TD_STATUS_DP_SHIFT)
-	    | ((CC_NOACCESS2 & TD_STATUS_CC_MASK) << TD_STATUS_CC_SHIFT);
+	OHCI_MEM32_WR(instance->status,
+	    ((dir[direction] & TD_STATUS_DP_MASK) << TD_STATUS_DP_SHIFT)
+	    | ((CC_NOACCESS2 & TD_STATUS_CC_MASK) << TD_STATUS_CC_SHIFT));
 
 	if (toggle == 0 || toggle == 1) {
 		/* Set explicit toggle bit */
-		instance->status |= TD_STATUS_T_USE_TD_FLAG;
-		instance->status |= toggle ? TD_STATUS_T_FLAG : 0;
+		OHCI_MEM32_SET(instance->status, TD_STATUS_T_USE_TD_FLAG);
+		OHCI_MEM32_SET(instance->status, toggle ? TD_STATUS_T_FLAG : 0);
 	}
 
 	/* Alow less data on input. */
 	if (dir == USB_DIRECTION_IN) {
-		instance->status |= TD_STATUS_ROUND_FLAG;
+		OHCI_MEM32_SET(instance->status, TD_STATUS_ROUND_FLAG);
 	}
 
 	if (buffer != NULL) {
 		assert(size != 0);
-		instance->cbp = addr_to_phys(buffer);
-		instance->be = addr_to_phys(buffer + size - 1);
+		OHCI_MEM32_WR(instance->cbp, addr_to_phys(buffer));
+		OHCI_MEM32_WR(instance->be, addr_to_phys(buffer + size - 1));
 	}
 
-	instance->next = addr_to_phys(next) & TD_NEXT_PTR_MASK;
+	OHCI_MEM32_WR(instance->next, addr_to_phys(next) & TD_NEXT_PTR_MASK);
 
 }
Index: uspace/drv/bus/usb/ohci/hw_struct/transfer_descriptor.h
===================================================================
--- uspace/drv/bus/usb/ohci/hw_struct/transfer_descriptor.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/hw_struct/transfer_descriptor.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -38,5 +38,5 @@
 #include <stdint.h>
 
-#include "../utils/malloc32.h"
+#include "mem_access.h"
 #include "completion_codes.h"
 
@@ -100,6 +100,6 @@
 {
 	assert(instance);
-	const int cc =
-	    (instance->status >> TD_STATUS_CC_SHIFT) & TD_STATUS_CC_MASK;
+	const int cc =(OHCI_MEM32_RD(instance->status)
+	    >> TD_STATUS_CC_SHIFT) & TD_STATUS_CC_MASK;
 	/* This value is changed on transfer completion,
 	 * either to CC_NOERROR or and error code.
@@ -119,6 +119,6 @@
 {
 	assert(instance);
-	const int cc =
-	    (instance->status >> TD_STATUS_CC_SHIFT) & TD_STATUS_CC_MASK;
+	const int cc = (OHCI_MEM32_RD(instance->status)
+	    >> TD_STATUS_CC_SHIFT) & TD_STATUS_CC_MASK;
 	return cc_to_rc(cc);
 }
@@ -136,5 +136,5 @@
 		return 0;
 	/* Buffer end points to the last byte of transfer buffer, so add 1 */
-	return instance->be - instance->cbp + 1;
+	return OHCI_MEM32_RD(instance->be) - OHCI_MEM32_RD(instance->cbp) + 1;
 }
 #endif
Index: uspace/drv/bus/usb/ohci/main.c
===================================================================
--- uspace/drv/bus/usb/ohci/main.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/main.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -63,14 +63,14 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 static driver_ops_t ohci_driver_ops = {
 	.dev_add = ohci_dev_add,
 };
-/*----------------------------------------------------------------------------*/
+
 static driver_t ohci_driver = {
 	.name = NAME,
 	.driver_ops = &ohci_driver_ops
 };
-/*----------------------------------------------------------------------------*/
+
 /** Initializes global driver structures (NONE).
  *
Index: uspace/drv/bus/usb/ohci/ohci.c
===================================================================
--- uspace/drv/bus/usb/ohci/ohci.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/ohci.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -75,5 +75,5 @@
 	hc_interrupt(&ohci->hc, status);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Get USB address assigned to root hub.
  *
@@ -92,5 +92,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Gets handle of the respective hc (this device, hc function).
  *
@@ -110,5 +110,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Root hub USB interface */
 static usb_iface_t usb_iface = {
@@ -116,15 +116,15 @@
 	.get_my_address = rh_get_my_address,
 };
-/*----------------------------------------------------------------------------*/
+
 /** Standard USB HC options (HC interface) */
 static ddf_dev_ops_t hc_ops = {
 	.interfaces[USBHC_DEV_IFACE] = &hcd_iface,
 };
-/*----------------------------------------------------------------------------*/
+
 /** Standard USB RH options (RH interface) */
 static ddf_dev_ops_t rh_ops = {
 	.interfaces[USB_DEV_IFACE] = &usb_iface,
 };
-/*----------------------------------------------------------------------------*/
+
 /** Initialize hc and rh ddf structures and their respective drivers.
  *
Index: uspace/drv/bus/usb/ohci/ohci_batch.c
===================================================================
--- uspace/drv/bus/usb/ohci/ohci_batch.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/ohci_batch.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -44,5 +44,5 @@
 
 static void (*const batch_setup[])(ohci_transfer_batch_t*, usb_direction_t);
-/*----------------------------------------------------------------------------*/
+
 /** Safely destructs ohci_transfer_batch_t structure
  *
@@ -67,5 +67,5 @@
 	free(ohci_batch);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Finishes usb_transfer_batch and destroys the structure.
  *
@@ -80,5 +80,5 @@
 	ohci_transfer_batch_dispose(ohci_batch);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Allocate memory and initialize internal data structure.
  *
@@ -158,5 +158,5 @@
 #undef CHECK_NULL_DISPOSE_RET
 }
-/*----------------------------------------------------------------------------*/
+
 /** Check batch TDs' status.
  *
@@ -199,20 +199,21 @@
 		    ohci_batch->tds[i]->next, ohci_batch->tds[i]->be);
 
-		/* If the TD got all its data through, it will report 0 bytes
-		 * remain, the sole exception is INPUT with data rounding flag
-		 * (short), i.e. every INPUT. Nice thing is that short packets
-		 * will correctly report remaining data, thus making
-		 * this computation correct (short packets need to be produced
-		 * by the last TD)
-		 * NOTE: This also works for CONTROL transfer as
-		 * the first TD will return 0 remain.
-		 * NOTE: Short packets don't break the assumption that
-		 * we leave the very last(unused) TD behind.
-		 */
-		ohci_batch->usb_batch->transfered_size
-		    -= td_remain_size(ohci_batch->tds[i]);
-
 		ohci_batch->usb_batch->error = td_error(ohci_batch->tds[i]);
-		if (ohci_batch->usb_batch->error != EOK) {
+		if (ohci_batch->usb_batch->error == EOK) {
+			/* If the TD got all its data through, it will report
+			 * 0 bytes remain, the sole exception is INPUT with
+			 * data rounding flag (short), i.e. every INPUT.
+			 * Nice thing is that short packets will correctly
+			 * report remaining data, thus making this computation
+			 * correct (short packets need to be produced by the
+			 * last TD)
+			 * NOTE: This also works for CONTROL transfer as
+			 * the first TD will return 0 remain.
+			 * NOTE: Short packets don't break the assumption that
+			 * we leave the very last(unused) TD behind.
+			 */
+			ohci_batch->usb_batch->transfered_size
+			    -= td_remain_size(ohci_batch->tds[i]);
+		} else {
 			usb_log_debug("Batch %p found error TD(%zu):%08x.\n",
 			    ohci_batch->usb_batch, i,
@@ -231,14 +232,13 @@
 
 			/* Check TD assumption */
-			const uint32_t pa =
-			    addr_to_phys(ohci_batch->tds[leave_td]);
-			assert((ohci_batch->ed->td_head & ED_TDHEAD_PTR_MASK)
-			    == pa);
-
+			assert(ed_head_td(ohci_batch->ed) ==
+			    addr_to_phys(ohci_batch->tds[leave_td]));
+
+			/* Set tail to the same TD */
 			ed_set_tail_td(ohci_batch->ed,
 			    ohci_batch->tds[leave_td]);
 
 			/* Clear possible ED HALT */
-			ohci_batch->ed->td_head &= ~ED_TDHEAD_HALTED_FLAG;
+			ed_clear_halt(ohci_batch->ed);
 			break;
 		}
@@ -253,11 +253,10 @@
 
 	/* Make sure that we are leaving the right TD behind */
-	const uint32_t pa = addr_to_phys(ohci_ep->td);
-	assert(pa == (ohci_batch->ed->td_head & ED_TDHEAD_PTR_MASK));
-	assert(pa == (ohci_batch->ed->td_tail & ED_TDTAIL_PTR_MASK));
+	assert(addr_to_phys(ohci_ep->td) == ed_head_td(ohci_batch->ed));
+	assert(addr_to_phys(ohci_ep->td) == ed_tail_td(ohci_batch->ed));
 
 	return true;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Starts execution of the TD list
  *
@@ -269,5 +268,5 @@
 	ed_set_tail_td(ohci_batch->ed, ohci_batch->tds[ohci_batch->td_count]);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Prepare generic control transfer
  *
@@ -345,5 +344,5 @@
 	    USB_TRANSFER_BATCH_ARGS(*ohci_batch->usb_batch));
 }
-/*----------------------------------------------------------------------------*/
+
 /** Prepare generic data transfer
  *
@@ -392,5 +391,5 @@
 	    USB_TRANSFER_BATCH_ARGS(*ohci_batch->usb_batch));
 }
-/*----------------------------------------------------------------------------*/
+
 /** Transfer setup table. */
 static void (*const batch_setup[])(ohci_transfer_batch_t*, usb_direction_t) =
Index: uspace/drv/bus/usb/ohci/ohci_batch.h
===================================================================
--- uspace/drv/bus/usb/ohci/ohci_batch.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/ohci_batch.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -63,5 +63,5 @@
 void ohci_transfer_batch_commit(const ohci_transfer_batch_t *batch);
 void ohci_transfer_batch_finish_dispose(ohci_transfer_batch_t *batch);
-/*----------------------------------------------------------------------------*/
+
 static inline ohci_transfer_batch_t *ohci_transfer_batch_from_link(link_t *l)
 {
Index: uspace/drv/bus/usb/ohci/ohci_endpoint.c
===================================================================
--- uspace/drv/bus/usb/ohci/ohci_endpoint.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/ohci_endpoint.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -48,5 +48,5 @@
 	ed_toggle_set(instance->ed, toggle);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Callback to get value of toggle bit.
  *
@@ -61,5 +61,5 @@
 	return ed_toggle_get(instance->ed);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Creates new hcd endpoint representation.
  *
@@ -93,5 +93,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Disposes hcd endpoint structure
  *
Index: uspace/drv/bus/usb/ohci/ohci_regs.h
===================================================================
--- uspace/drv/bus/usb/ohci/ohci_regs.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/ohci_regs.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -35,4 +35,11 @@
 #define DRV_OHCI_OHCI_REGS_H
 #include <sys/types.h>
+#include <byteorder.h>
+
+#define OHCI_WR(reg, val) reg = host2uint32_t_le(val)
+#define OHCI_RD(reg) uint32_t_le2host(reg)
+#define OHCI_SET(reg, val) reg |= host2uint32_t_le(val)
+#define OHCI_CLR(reg, val) reg &= host2uint32_t_le(~val)
+
 
 #define LEGACY_REGS_OFFSET 0x100
@@ -42,14 +49,14 @@
 	const ioport32_t revision;
 #define R_REVISION_MASK (0x3f)
-#define R_REVISION_SHIFT (0)
 #define R_LEGACY_FLAG   (0x80)
 
 	ioport32_t control;
-#define C_CBSR_MASK (0x3) /* Control-bulk service ratio */
+/* Control-bulk service ratio */
 #define C_CBSR_1_1  (0x0)
 #define C_CBSR_1_2  (0x1)
 #define C_CBSR_1_3  (0x2)
 #define C_CBSR_1_4  (0x3)
-#define C_CBSR_SHIFT (0)
+#define C_CBSR_MASK (0x3)
+#define C_CBSR_SHIFT 0
 
 #define C_PLE (1 << 2)   /* Periodic list enable */
@@ -58,22 +65,20 @@
 #define C_BLE (1 << 5)   /* Bulk list enable */
 
-#define C_HCFS_MASK        (0x3) /* Host controller functional state */
+/* Host controller functional state */
 #define C_HCFS_RESET       (0x0)
 #define C_HCFS_RESUME      (0x1)
 #define C_HCFS_OPERATIONAL (0x2)
 #define C_HCFS_SUSPEND     (0x3)
-#define C_HCFS_SHIFT       (6)
-
-#define C_HCFS_GET(reg) \
-	((reg >> C_HCFS_SHIFT) & C_HCFS_MASK)
-#define C_HCFS_SET(reg, hcfs_state) \
+#define C_HCFS_GET(reg) ((OHCI_RD(reg) >> 6) & 0x3)
+#define C_HCFS_SET(reg, value) \
 do { \
-	reg = (reg & ~(C_HCFS_MASK << C_HCFS_SHIFT)) \
-	    | ((hcfs_state & C_HCFS_MASK) << C_HCFS_SHIFT); \
+	uint32_t r = OHCI_RD(reg); \
+	r &= ~(0x3 << 6); \
+	r |= (value & 0x3) << 6; \
+	OHCI_WR(reg, r); \
 } while (0)
 
-
-#define C_IR  (1 << 8)   /* Interrupt routing, make sure it's 0 */
-#define C_RWC (1 << 9)   /* Remote wakeup connected, host specific */
+#define C_IR  (1 << 8)  /* Interrupt routing, make sure it's 0 */
+#define C_RWC (1 << 9)  /* Remote wakeup connected, host specific */
 #define C_RWE (1 << 10)  /* Remote wakeup enable */
 
@@ -83,6 +88,8 @@
 #define CS_BLF (1 << 2)   /* Bulk list filled */
 #define CS_OCR (1 << 3)   /* Ownership change request */
+#if 0
 #define CS_SOC_MASK (0x3) /* Scheduling overrun count */
 #define CS_SOC_SHIFT (16)
+#endif
 
 	/** Interupt enable/disable/status,
@@ -101,5 +108,5 @@
 #define I_RHSC (1 << 6)   /* Root hub status change */
 #define I_OC   (1 << 30)  /* Ownership change */
-#define I_MI   (1 << 31)  /* Master interrupt (all/any interrupts) */
+#define I_MI   (1 << 31)  /* Master interrupt (any/all) */
 
 	/** HCCA pointer (see hw_struct hcca.h) */
@@ -145,5 +152,6 @@
 	/** Remaining bit time in frame to start periodic transfers */
 	ioport32_t periodic_start;
-#define PS_PS_MASK (0x3fff) /* bit time when periodic get priority (0x3e67) */
+#define PS_MASK 0x3fff
+#define PS_SHIFT 0
 
 	/** Threshold for starting LS transaction */
@@ -153,46 +161,54 @@
 	/** The first root hub control register */
 	ioport32_t rh_desc_a;
-#define RHDA_NDS_MASK (0xff) /* Number of downstream ports, max 15 */
-#define RHDA_NDS_SHIFT (0)
-#define RHDA_PSM_FLAG  (1 << 8)  /* Power switching mode: 0-global, 1-per port*/
-#define RHDA_NPS_FLAG  (1 << 9)  /* No power switch: 1-power on, 0-use PSM*/
-#define RHDA_DT_FLAG   (1 << 10) /* 1-Compound device, must be 0 */
-#define RHDA_OCPM_FLAG (1 << 11) /* Over-current mode: 0-global, 1-per port */
-#define RHDA_NOCP_FLAG (1 << 12) /* OC control: 0-use OCPM, 1-OC off */
-#define RHDA_POTPGT_MASK (0xff)  /* Power on to power good time */
-#define RHDA_POTPGT_SHIFT (24)
+/** Number of downstream ports, max 15 */
+#define RHDA_NDS_MASK  (0xff)
+/** Power switching mode: 0-global, 1-per port*/
+#define RHDA_PSM_FLAG  (1 << 8)
+/** No power switch: 1-power on, 0-use PSM*/
+#define RHDA_NPS_FLAG  (1 << 9)
+/** 1-Compound device, must be 0 */
+#define RHDA_DT_FLAG   (1 << 10)
+/** Over-current mode: 0-global, 1-per port */
+#define RHDA_OCPM_FLAG (1 << 11)
+/** OC control: 0-use OCPM, 1-OC off */
+#define RHDA_NOCP_FLAG (1 << 12)
+/** Power on to power good time */
+#define RHDA_POTPGT_SHIFT   24
 
 	/** The other root hub control register */
 	ioport32_t rh_desc_b;
-#define RHDB_DR_MASK (0xffff) /* Device removable mask */
-#define RHDB_DR_SHIFT (0)
-#define RHDB_PCC_MASK (0xffff) /* Power control mask */
-#define RHDB_PCC_SHIFT (16)
-
-/* Port device removable status */
-#define RHDB_DR_FLAG(port) (((1 << port) & RHDB_DR_MASK) << RHDB_DR_SHIFT)
-/* Port power control status: 1-per port power control, 0-global power switch */
-#define RHDB_PPC_FLAG(port) (((1 << port) & RHDB_DR_MASK) << RHDB_DR_SHIFT)
+/** Device removable mask */
+#define RHDB_DR_SHIFT   0
+#define RHDB_DR_MASK    0xffff
+/** Power control mask */
+#define RHDB_PCC_MASK (0xffff)
+#define RHDB_PCC_SHIFT 16
 
 	/** Root hub status register */
 	ioport32_t rh_status;
-#define RHS_LPS_FLAG  (1 <<  0)/* read: 0,
-                                * write: 0-no effect,
-                                *        1-turn off port power for ports
-                                *        specified in PPCM(RHDB), or all ports,
-                                *        if power is set globally */
+/* read: 0,
+ * write: 0-no effect,
+ *        1-turn off port power for ports
+ *        specified in PPCM(RHDB), or all ports,
+ *        if power is set globally */
+#define RHS_LPS_FLAG  (1 <<  0)
 #define RHS_CLEAR_GLOBAL_POWER RHS_LPS_FLAG /* synonym for the above */
-#define RHS_OCI_FLAG  (1 <<  1)/* Over-current indicator, if per-port: 0 */
-#define RHS_DRWE_FLAG (1 << 15)/* read: 0-connect status change does not wake HC
-                                *       1-connect status change wakes HC
-                                * write: 1-set DRWE, 0-no effect */
+/** Over-current indicator, if per-port: 0 */
+#define RHS_OCI_FLAG  (1 <<  1)
+
+/* read: 0-connect status change does not wake HC
+ *       1-connect status change wakes HC
+ * write: 1-set DRWE, 0-no effect */
+#define RHS_DRWE_FLAG (1 << 15)
 #define RHS_SET_DRWE RHS_DRWE_FLAG
-#define RHS_LPSC_FLAG (1 << 16)/* read: 0,
-                                * write: 0-no effect
-                                *        1-turn on port power for ports
-                                *        specified in PPCM(RHDB), or all ports,
-                                *        if power is set globally */
+/* read: 0,
+ * write: 0-no effect
+ *        1-turn on port power for ports
+ *        specified in PPCM(RHDB), or all ports,
+ *        if power is set globally */
+#define RHS_LPSC_FLAG (1 << 16)
 #define RHS_SET_GLOBAL_POWER RHS_LPSC_FLAG /* synonym for the above */
-#define RHS_OCIC_FLAG (1 << 17)/* Over-current indicator change   */
+/** Over-current change indicator*/
+#define RHS_OCIC_FLAG (1 << 17)
 #define RHS_CLEAR_DRWE (1 << 31)
 
@@ -200,32 +216,33 @@
 	ioport32_t rh_port_status[];
 #define RHPS_CCS_FLAG (1 << 0) /* r: current connect status,
-                                * w: 1-clear port enable, 0-nothing */
+                                               * w: 1-clear port enable, 0-N/S*/
 #define RHPS_CLEAR_PORT_ENABLE RHPS_CCS_FLAG
 #define RHPS_PES_FLAG (1 << 1) /* r: port enable status
-                                * w: 1-set port enable, 0-nothing */
+                                              * w: 1-set port enable, 0-N/S */
 #define RHPS_SET_PORT_ENABLE RHPS_PES_FLAG
 #define RHPS_PSS_FLAG (1 << 2) /* r: port suspend status
-                                * w: 1-set port suspend, 0-nothing */
+                                               * w: 1-set port suspend, 0-N/S */
 #define RHPS_SET_PORT_SUSPEND RHPS_PSS_FLAG
-#define RHPS_POCI_FLAG (1 << 3) /* r: port over-current (if reports are per-port
-                                 * w: 1-clear port suspend (start resume
-                                 *      if suspened)
-                                 *    0-nothing */
+#define RHPS_POCI_FLAG (1 << 3) /* r: port over-current
+                                                * (if reports are per-port
+                                                * w: 1-clear port suspend
+						*  (start resume if suspened)
+                                                *    0-nothing */
 #define RHPS_CLEAR_PORT_SUSPEND RHPS_POCI_FLAG
 #define RHPS_PRS_FLAG (1 << 4) /* r: port reset status
-                                * w: 1-set port reset, 0-nothing */
+                                               * w: 1-set port reset, 0-N/S */
 #define RHPS_SET_PORT_RESET RHPS_PRS_FLAG
 #define RHPS_PPS_FLAG (1 << 8) /* r: port power status
-                                * w: 1-set port power, 0-nothing */
+                                              * w: 1-set port power, 0-N/S */
 #define RHPS_SET_PORT_POWER RHPS_PPS_FLAG
 #define RHPS_LSDA_FLAG (1 << 9) /* r: low speed device attached
-                                 * w: 1-clear port power, 0-nothing */
+                                                * w: 1-clear port power, 0-N/S*/
 #define RHPS_CLEAR_PORT_POWER RHPS_LSDA_FLAG
-#define RHPS_CSC_FLAG  (1 << 16) /* connect status change Write-Clean */
+#define RHPS_CSC_FLAG  (1 << 16) /* connect status change WC */
 #define RHPS_PESC_FLAG (1 << 17) /* port enable status change WC */
 #define RHPS_PSSC_FLAG (1 << 18) /* port suspend status change WC */
 #define RHPS_OCIC_FLAG (1 << 19) /* port over-current change WC */
 #define RHPS_PRSC_FLAG (1 << 20) /* port reset status change WC */
-#define RHPS_CHANGE_WC_MASK 0x1f0000
+#define RHPS_CHANGE_WC_MASK (0x1f0000)
 } __attribute__((packed)) ohci_regs_t;
 #endif
Index: uspace/drv/bus/usb/ohci/root_hub.c
===================================================================
--- uspace/drv/bus/usb/ohci/root_hub.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/root_hub.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -33,17 +33,19 @@
  */
 #include <assert.h>
+#include <byteorder.h>
 #include <errno.h>
 #include <str_error.h>
 #include <fibril_synch.h>
 
+#include <usb/usb.h>
 #include <usb/debug.h>
 #include <usb/dev/request.h>
 #include <usb/classes/hub.h>
 
-#include "root_hub.h"
 #include <usb/classes/classes.h>
 #include <usb/classes/hub.h>
 #include <usb/dev/driver.h>
 #include "ohci_regs.h"
+#include "root_hub.h"
 
 /**
@@ -122,4 +124,6 @@
 {
 	assert(request);
+	usb_log_debug("Sending interrupt vector(%zu) %hhx:%hhx.\n",
+	    size, ((uint8_t*)&mask)[0], ((uint8_t*)&mask)[1]);
 	usb_transfer_batch_finish_error(request, &mask, size, EOK);
 	usb_transfer_batch_destroy(request);
@@ -150,6 +154,6 @@
 
 	instance->registers = regs;
-	instance->port_count =
-	    (instance->registers->rh_desc_a >> RHDA_NDS_SHIFT) & RHDA_NDS_MASK;
+	instance->port_count = OHCI_RD(regs->rh_desc_a) & RHDA_NDS_MASK;
+	usb_log_debug2("rh_desc_a: %x.\n", OHCI_RD(regs->rh_desc_a));
 	if (instance->port_count > 15) {
 		usb_log_warning("OHCI specification does not allow more than 15"
@@ -163,35 +167,39 @@
 
 #if defined OHCI_POWER_SWITCH_no
+	usb_log_debug("OHCI rh: Set power mode to no power switching.\n");
 	/* Set port power mode to no power-switching. (always on) */
-	instance->registers->rh_desc_a |= RHDA_NPS_FLAG;
+	OHCI_SET(regs->rh_desc_a, RHDA_NPS_FLAG);
 
 	/* Set to no over-current reporting */
-	instance->registers->rh_desc_a |= RHDA_NOCP_FLAG;
+	OHCI_SET(regs->rh_desc_a, RHDA_NOCP_FLAG);
 
 #elif defined OHCI_POWER_SWITCH_ganged
-	/* Set port power mode to no ganged power-switching. */
-	instance->registers->rh_desc_a &= ~RHDA_NPS_FLAG;
-	instance->registers->rh_desc_a &= ~RHDA_PSM_FLAG;
-	instance->registers->rh_status = RHS_CLEAR_GLOBAL_POWER;
+	usb_log_debug("OHCI rh: Set power mode to ganged power switching.\n");
+	/* Set port power mode to ganged power-switching. */
+	OHCI_CLR(regs->rh_desc_a, RHDA_NPS_FLAG);
+	OHCI_CLR(regs->rh_desc_a, RHDA_PSM_FLAG);
+
+	/* Turn off power (hub driver will turn this back on)*/
+	OHCI_WR(regs->rh_status, RHS_CLEAR_GLOBAL_POWER);
 
 	/* Set to global over-current */
-	instance->registers->rh_desc_a &= ~RHDA_NOCP_FLAG;
-	instance->registers->rh_desc_a &= ~RHDA_OCPM_FLAG;
+	OHCI_CLR(regs->rh_desc_a, RHDA_NOCP_FLAG);
+	OHCI_CLR(regs->rh_desc_a, RHDA_OCPM_FLAG);
 #else
-	/* Set port power mode to no per port power-switching. */
-	instance->registers->rh_desc_a &= ~RHDA_NPS_FLAG;
-	instance->registers->rh_desc_a |= RHDA_PSM_FLAG;
+	usb_log_debug("OHCI rh: Set power mode to per-port power switching.\n");
+	/* Set port power mode to per port power-switching. */
+	OHCI_CLR(regs->rh_desc_a, RHDA_NPS_FLAG);
+	OHCI_SET(regs->rh_desc_a, RHDA_PSM_FLAG);
 
 	/* Control all ports by global switch and turn them off */
-	instance->registers->rh_desc_b &= (RHDB_PCC_MASK << RHDB_PCC_SHIFT);
-	instance->registers->rh_status = RHS_CLEAR_GLOBAL_POWER;
+	OHCI_CLR(regs->rh_desc_b, RHDB_PCC_MASK << RHDB_PCC_SHIFT);
+	OHCI_WR(regs->rh_status, RHS_CLEAR_GLOBAL_POWER);
 
 	/* Return control to per port state */
-	instance->registers->rh_desc_b |=
-		((1 << (instance->port_count + 1)) - 1) << RHDB_PCC_SHIFT;
+	OHCI_SET(regs->rh_desc_b, RHDB_PCC_MASK << RHDB_PCC_SHIFT);
 
 	/* Set per port over-current */
-	instance->registers->rh_desc_a &= ~RHDA_NOCP_FLAG;
-	instance->registers->rh_desc_a |= RHDA_OCPM_FLAG;
+	OHCI_CLR(regs->rh_desc_a, RHDA_NOCP_FLAG);
+	OHCI_SET(regs->rh_desc_a, RHDA_OCPM_FLAG);
 #endif
 
@@ -202,5 +210,5 @@
 	    instance->port_count);
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Process root hub request.
@@ -226,7 +234,7 @@
 		fibril_mutex_lock(&instance->guard);
 		assert(instance->unfinished_interrupt_transfer == NULL);
-		uint16_t mask = create_interrupt_mask(instance);
+		const uint16_t mask = create_interrupt_mask(instance);
 		if (mask == 0) {
-			usb_log_debug("No changes...\n");
+			usb_log_debug("No changes(%hx)...\n", mask);
 			instance->unfinished_interrupt_transfer = request;
 		} else {
@@ -243,5 +251,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Process interrupt on a hub device.
@@ -257,5 +265,5 @@
 	if (instance->unfinished_interrupt_transfer) {
 		usb_log_debug("Finalizing interrupt transfer\n");
-		uint16_t mask = create_interrupt_mask(instance);
+		const uint16_t mask = create_interrupt_mask(instance);
 		interrupt_request(instance->unfinished_interrupt_transfer,
 		    mask, instance->interrupt_mask_size);
@@ -264,5 +272,5 @@
 	fibril_mutex_unlock(&instance->guard);
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Create hub descriptor.
@@ -282,6 +290,6 @@
 	instance->hub_descriptor_size = size;
 
-	uint32_t hub_desc = instance->registers->rh_desc_a;
-	uint32_t port_desc = instance->registers->rh_desc_b;
+	const uint32_t hub_desc = OHCI_RD(instance->registers->rh_desc_a);
+	const uint32_t port_desc = OHCI_RD(instance->registers->rh_desc_b);
 
 	/* bDescLength */
@@ -305,21 +313,19 @@
 	instance->descriptors.hub[4] = 0;
 	/* bPwrOn2PwrGood */
-	instance->descriptors.hub[5] =
-	    (hub_desc >> RHDA_POTPGT_SHIFT) & RHDA_POTPGT_MASK;
+	instance->descriptors.hub[5] = hub_desc >> RHDA_POTPGT_SHIFT;
 	/* bHubContrCurrent, root hubs don't need no power. */
 	instance->descriptors.hub[6] = 0;
 
 	/* Device Removable and some legacy 1.0 stuff*/
-	instance->descriptors.hub[7] =
-	    (port_desc >> RHDB_DR_SHIFT) & RHDB_DR_MASK & 0xff;
+	instance->descriptors.hub[7] = (port_desc >> RHDB_DR_SHIFT) & 0xff;
 	instance->descriptors.hub[8] = 0xff;
 	if (instance->interrupt_mask_size == 2) {
 		instance->descriptors.hub[8] =
-		    (port_desc >> RHDB_DR_SHIFT) & RHDB_DR_MASK >> 8;
+		    (port_desc >> RHDB_DR_SHIFT) >> 8;
 		instance->descriptors.hub[9]  = 0xff;
 		instance->descriptors.hub[10] = 0xff;
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize hub descriptors.
  *
@@ -341,11 +347,11 @@
 	    instance->interrupt_mask_size;
 
-	instance->descriptors.configuration.total_length =
+	instance->descriptors.configuration.total_length = uint16_host2usb(
 	    sizeof(usb_standard_configuration_descriptor_t) +
 	    sizeof(usb_standard_endpoint_descriptor_t) +
 	    sizeof(usb_standard_interface_descriptor_t) +
-	    instance->hub_descriptor_size;
-}
-/*----------------------------------------------------------------------------*/
+	    instance->hub_descriptor_size);
+}
+
 /**
  * Create bitmap of changes to answer status interrupt.
@@ -364,19 +370,19 @@
 
 	/* Only local power source change and over-current change can happen */
-	if (instance->registers->rh_status & (RHS_LPSC_FLAG | RHS_OCIC_FLAG)) {
+	if (OHCI_RD(instance->registers->rh_status)
+	    & (RHS_LPSC_FLAG | RHS_OCIC_FLAG)) {
 		mask |= 1;
 	}
 	for (size_t port = 1; port <= instance->port_count; ++port) {
 		/* Write-clean bits are those that indicate change */
-		if (RHPS_CHANGE_WC_MASK
-		    & instance->registers->rh_port_status[port - 1]) {
-
+		if (OHCI_RD(instance->registers->rh_port_status[port - 1])
+		    & RHPS_CHANGE_WC_MASK) {
 			mask |= (1 << port);
 		}
 	}
-	/* USB is little endian */
-	return host2uint32_t_le(mask);
-}
-/*----------------------------------------------------------------------------*/
+	usb_log_debug2("OHCI root hub interrupt mask: %hx.\n", mask);
+	return uint16_host2usb(mask);
+}
+
 /**
  * Create answer to status request.
@@ -396,4 +402,6 @@
 	usb_device_request_setup_packet_t *request_packet =
 	    (usb_device_request_setup_packet_t*)request->setup_buffer;
+
+	const uint16_t index = uint16_usb2host(request_packet->index);
 
 	switch (request_packet->request_type)
@@ -406,7 +414,8 @@
 			TRANSFER_END(request, EOVERFLOW);
 		} else {
-			uint32_t data = instance->registers->rh_status &
-			    (RHS_LPS_FLAG | RHS_LPSC_FLAG
-			        | RHS_OCI_FLAG | RHS_OCIC_FLAG);
+			const uint32_t data =
+			    OHCI_RD(instance->registers->rh_status) &
+			        (RHS_LPS_FLAG | RHS_LPSC_FLAG
+			            | RHS_OCI_FLAG | RHS_OCIC_FLAG);
 			TRANSFER_END_DATA(request, &data, sizeof(data));
 		}
@@ -420,10 +429,11 @@
 			TRANSFER_END(request, EOVERFLOW);
 		} else {
-			unsigned port = request_packet->index;
+			const unsigned port = index;
 			if (port < 1 || port > instance->port_count)
 				TRANSFER_END(request, EINVAL);
-
-			uint32_t data =
-			    instance->registers->rh_port_status[port - 1];
+			/* Register format matches the format of port status
+			 * field */
+			const uint32_t data = uint32_host2usb(OHCI_RD(
+			    instance->registers->rh_port_status[port - 1]));
 			TRANSFER_END_DATA(request, &data, sizeof(data));
 		}
@@ -434,5 +444,5 @@
 			TRANSFER_END(request, EOVERFLOW);
 		} else {
-			uint16_t data =
+			const uint16_t data =
 			    uint16_host2usb(USB_DEVICE_STATUS_SELF_POWERED);
 			TRANSFER_END_DATA(request, &data, sizeof(data));
@@ -441,10 +451,10 @@
 	case SETUP_REQUEST_TO_HOST(USB_REQUEST_TYPE_STANDARD, USB_REQUEST_RECIPIENT_INTERFACE):
 		/* Hubs are allowed to have only one interface */
-		if (request_packet->index != 0)
+		if (index != 0)
 			TRANSFER_END(request, EINVAL);
 		/* Fall through, as the answer will be the same: 0x0000 */
 	case SETUP_REQUEST_TO_HOST(USB_REQUEST_TYPE_STANDARD, USB_REQUEST_RECIPIENT_ENDPOINT):
 		/* Endpoint 0 (default control) and 1 (interrupt) */
-		if (request_packet->index >= 2)
+		if (index >= 2)
 			TRANSFER_END(request, EINVAL);
 
@@ -455,5 +465,5 @@
 		} else {
 			/* Endpoints are OK. (We don't halt) */
-			uint16_t data = 0;
+			const uint16_t data = 0;
 			TRANSFER_END_DATA(request, &data, sizeof(data));
 		}
@@ -465,5 +475,5 @@
 
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Create answer to a descriptor request.
@@ -482,6 +492,8 @@
 	usb_device_request_setup_packet_t *setup_request =
 	    (usb_device_request_setup_packet_t *) request->setup_buffer;
-	uint16_t setup_request_value = setup_request->value_high;
-	switch (setup_request_value)
+	/* "The wValue field specifies the descriptor type in the high byte
+	 * and the descriptor index in the low byte (refer to Table 9-5)." */
+	const int desc_type = uint16_usb2host(setup_request->value) >> 8;
+	switch (desc_type)
 	{
 	case USB_DESCTYPE_HUB:
@@ -530,5 +542,5 @@
 		    setup_request->value,
 		    setup_request->request_type, setup_request->request,
-		    setup_request_value, setup_request->index,
+		    desc_type, setup_request->index,
 		    setup_request->length);
 		TRANSFER_END(request, EINVAL);
@@ -537,5 +549,5 @@
 	TRANSFER_END(request, ENOTSUP);
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * process feature-enabling request on hub
@@ -554,21 +566,27 @@
 		return EINVAL;
 
-	switch (feature)
-	{
-	case USB_HUB_FEATURE_PORT_POWER:   //8
-		/* No power switching */
-		if (instance->registers->rh_desc_a & RHDA_NPS_FLAG)
-			return EOK;
-		/* Ganged power switching */
-		if (!(instance->registers->rh_desc_a & RHDA_PSM_FLAG)) {
-			instance->registers->rh_status = RHS_SET_GLOBAL_POWER;
-			return EOK;
+	switch (feature) {
+	case USB_HUB_FEATURE_PORT_POWER:   /*8*/
+		{
+			const uint32_t rhda =
+			    OHCI_RD(instance->registers->rh_desc_a);
+			/* No power switching */
+			if (rhda & RHDA_NPS_FLAG)
+				return EOK;
+			/* Ganged power switching, one port powers all */
+			if (!(rhda & RHDA_PSM_FLAG)) {
+				OHCI_WR(instance->registers->rh_status,
+				    RHS_SET_GLOBAL_POWER);
+				return EOK;
+			}
 		}
-	case USB_HUB_FEATURE_PORT_ENABLE:  //1
-	case USB_HUB_FEATURE_PORT_SUSPEND: //2
-	case USB_HUB_FEATURE_PORT_RESET:   //4
-		/* Nice thing is that these shifts correspond to the position
-		 * of control bits in register */
-		instance->registers->rh_port_status[port - 1] = (1 << feature);
+			/* Fall through */
+	case USB_HUB_FEATURE_PORT_ENABLE:  /*1*/
+	case USB_HUB_FEATURE_PORT_SUSPEND: /*2*/
+	case USB_HUB_FEATURE_PORT_RESET:   /*4*/
+		usb_log_debug2("Setting port POWER, ENABLE, SUSPEND or RESET "
+		    "on port %"PRIu16".\n", port);
+		OHCI_WR(instance->registers->rh_port_status[port - 1],
+		    1 << feature);
 		return EOK;
 	default:
@@ -576,5 +594,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Process feature clear request.
@@ -596,35 +614,42 @@
 	switch (feature)
 	{
-	case USB_HUB_FEATURE_PORT_POWER:          //8
-		/* No power switching */
-		if (instance->registers->rh_desc_a & RHDA_NPS_FLAG)
-			return ENOTSUP;
-		/* Ganged power switching */
-		if (!(instance->registers->rh_desc_a & RHDA_PSM_FLAG)) {
-			instance->registers->rh_status = RHS_CLEAR_GLOBAL_POWER;
+	case USB_HUB_FEATURE_PORT_POWER:          /*8*/
+		{
+			const uint32_t rhda =
+			    OHCI_RD(instance->registers->rh_desc_a);
+			/* No power switching */
+			if (rhda & RHDA_NPS_FLAG)
+				return ENOTSUP;
+			/* Ganged power switching, one port powers all */
+			if (!(rhda & RHDA_PSM_FLAG)) {
+				OHCI_WR(instance->registers->rh_status,
+				    RHS_CLEAR_GLOBAL_POWER);
+				return EOK;
+			}
+			OHCI_WR(instance->registers->rh_port_status[port - 1],
+			    RHPS_CLEAR_PORT_POWER);
 			return EOK;
 		}
-		instance->registers->rh_port_status[port - 1] =
-			RHPS_CLEAR_PORT_POWER;
+
+	case USB_HUB_FEATURE_PORT_ENABLE:         /*1*/
+		OHCI_WR(instance->registers->rh_port_status[port - 1],
+		    RHPS_CLEAR_PORT_ENABLE);
 		return EOK;
 
-	case USB_HUB_FEATURE_PORT_ENABLE:         //1
-		instance->registers->rh_port_status[port - 1] =
-			RHPS_CLEAR_PORT_ENABLE;
+	case USB_HUB_FEATURE_PORT_SUSPEND:        /*2*/
+		OHCI_WR(instance->registers->rh_port_status[port - 1],
+		    RHPS_CLEAR_PORT_SUSPEND);
 		return EOK;
 
-	case USB_HUB_FEATURE_PORT_SUSPEND:        //2
-		instance->registers->rh_port_status[port - 1] =
-			RHPS_CLEAR_PORT_SUSPEND;
-		return EOK;
-
-	case USB_HUB_FEATURE_C_PORT_CONNECTION:   //16
-	case USB_HUB_FEATURE_C_PORT_ENABLE:       //17
-	case USB_HUB_FEATURE_C_PORT_SUSPEND:      //18
-	case USB_HUB_FEATURE_C_PORT_OVER_CURRENT: //19
-	case USB_HUB_FEATURE_C_PORT_RESET:        //20
-		/* Nice thing is that these shifts correspond to the position
-		 * of control bits in register */
-		instance->registers->rh_port_status[port - 1] = (1 << feature);
+	case USB_HUB_FEATURE_C_PORT_CONNECTION:   /*16*/
+	case USB_HUB_FEATURE_C_PORT_ENABLE:       /*17*/
+	case USB_HUB_FEATURE_C_PORT_SUSPEND:      /*18*/
+	case USB_HUB_FEATURE_C_PORT_OVER_CURRENT: /*19*/
+	case USB_HUB_FEATURE_C_PORT_RESET:        /*20*/
+		usb_log_debug2("Clearing port C_CONNECTION, C_ENABLE, "
+		    "C_SUSPEND, C_OC or C_RESET on port %"PRIu16".\n", port);
+		/* Bit offsets correspond to the feature number */
+		OHCI_WR(instance->registers->rh_port_status[port - 1],
+		    1 << feature);
 		return EOK;
 
@@ -633,5 +658,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * process one of requests that do not request nor carry additional data
@@ -654,5 +679,5 @@
 	case USB_HUB_REQ_TYPE_SET_PORT_FEATURE:
 		usb_log_debug("USB_HUB_REQ_TYPE_SET_PORT_FEATURE\n");
-		int ret = set_feature_port(instance,
+		const int ret = set_feature_port(instance,
 		    setup_request->value, setup_request->index);
 		TRANSFER_END(request, ret);
@@ -671,5 +696,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * process one of requests that do not request nor carry additional data
@@ -693,5 +718,5 @@
 	case USB_HUB_REQ_TYPE_CLEAR_PORT_FEATURE:
 		usb_log_debug("USB_HUB_REQ_TYPE_CLEAR_PORT_FEATURE\n");
-		int ret = clear_feature_port(instance,
+		const int ret = clear_feature_port(instance,
 		    setup_request->value, setup_request->index);
 		TRANSFER_END(request, ret);
@@ -706,6 +731,7 @@
 		 * as root hubs do not support local power status feature.
 		 * (OHCI pg. 127) */
-		if (setup_request->value == USB_HUB_FEATURE_C_HUB_OVER_CURRENT) {
-			instance->registers->rh_status = RHS_OCIC_FLAG;
+		if (uint16_usb2host(setup_request->value)
+		    == USB_HUB_FEATURE_C_HUB_OVER_CURRENT) {
+			OHCI_WR(instance->registers->rh_status, RHS_OCIC_FLAG);
 			TRANSFER_END(request, EOK);
 		}
@@ -717,5 +743,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Process hub control request.
@@ -771,5 +797,5 @@
 		if (request->buffer_size == 0)
 			TRANSFER_END(request, EOVERFLOW);
-		uint8_t config = 1;
+		const uint8_t config = 1;
 		TRANSFER_END_DATA(request, &config, sizeof(config));
 
@@ -790,10 +816,10 @@
 			TRANSFER_END(request, EINVAL);
 
-		instance->address = setup_request->value;
+		instance->address = uint16_usb2host(setup_request->value);
 		TRANSFER_END(request, EOK);
 
 	case USB_DEVREQ_SET_CONFIGURATION:
 		usb_log_debug("USB_DEVREQ_SET_CONFIGURATION: %u\n",
-		    setup_request->value);
+		    uint16_usb2host(setup_request->value));
 		/* We have only one configuration, it's number is 1 */
 		if (uint16_usb2host(setup_request->value) != 1)
Index: uspace/drv/bus/usb/ohci/utils/malloc32.h
===================================================================
--- uspace/drv/bus/usb/ohci/utils/malloc32.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/ohci/utils/malloc32.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -63,5 +63,5 @@
 	return result;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Physical mallocator simulator
  *
@@ -71,5 +71,5 @@
 static inline void * malloc32(size_t size)
 	{ return memalign(OHCI_ALIGN, size); }
-/*----------------------------------------------------------------------------*/
+
 /** Physical mallocator simulator
  *
Index: uspace/drv/bus/usb/uhci/hc.c
===================================================================
--- uspace/drv/bus/usb/uhci/hc.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhci/hc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -50,5 +50,5 @@
 static const irq_pio_range_t uhci_irq_pio_ranges[] = {
 	{
-		.base = 0,	/* filled later */
+		.base = 0,
 		.size = sizeof(uhci_regs_t)
 	}
@@ -56,10 +56,28 @@
 
 static const irq_cmd_t uhci_irq_commands[] = {
-	{ .cmd = CMD_PIO_READ_16, .dstarg = 1, .addr = NULL/*filled later*/},
-	{ .cmd = CMD_BTEST, .srcarg = 1, .dstarg = 2,
-	  .value = UHCI_STATUS_USED_INTERRUPTS | UHCI_STATUS_NM_INTERRUPTS },
-	{ .cmd = CMD_PREDICATE, .srcarg = 2, .value = 2 },
-	{ .cmd = CMD_PIO_WRITE_A_16, .srcarg = 1, .addr = NULL/*filled later*/},
-	{ .cmd = CMD_ACCEPT },
+	{
+		.cmd = CMD_PIO_READ_16,
+		.dstarg = 1,
+		.addr = NULL
+	},
+	{
+		.cmd = CMD_AND,
+		.srcarg = 1,
+		.dstarg = 2,
+		.value = UHCI_STATUS_USED_INTERRUPTS | UHCI_STATUS_NM_INTERRUPTS
+	},
+	{
+		.cmd = CMD_PREDICATE,
+		.srcarg = 2,
+		.value = 2
+	},
+	{
+		.cmd = CMD_PIO_WRITE_A_16,
+		.srcarg = 1,
+		.addr = NULL
+	},
+	{
+		.cmd = CMD_ACCEPT
+	}
 };
 
@@ -72,5 +90,5 @@
 static int hc_debug_checker(void *arg);
 
-/*----------------------------------------------------------------------------*/
+
 /** Get number of PIO ranges used in IRQ code.
  * @return Number of ranges.
@@ -80,5 +98,5 @@
 	return sizeof(uhci_irq_pio_ranges) / sizeof(irq_pio_range_t);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Get number of commands used in IRQ code.
  * @return Number of commands.
@@ -88,5 +106,5 @@
 	return sizeof(uhci_irq_commands) / sizeof(irq_cmd_t);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Generate IRQ code.
  * @param[out] ranges PIO ranges buffer.
@@ -118,5 +136,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Take action based on the interrupt cause.
  *
@@ -175,5 +193,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize UHCI hc driver structure
  *
@@ -235,5 +253,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize UHCI hc hw resources.
  *
@@ -277,5 +295,5 @@
 	    UHCI_CMD_RUN_STOP | UHCI_CMD_MAX_PACKET | UHCI_CMD_CONFIGURE);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize UHCI hc memory structures.
  *
@@ -319,5 +337,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize UHCI hc transfer lists.
  *
@@ -381,5 +399,5 @@
 #undef CHECK_RET_CLEAR_RETURN
 }
-/*----------------------------------------------------------------------------*/
+
 /** Schedule batch for execution.
  *
@@ -409,5 +427,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Polling function, emulates interrupts.
  *
@@ -432,5 +450,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Debug function, checks consistency of memory structures.
  *
Index: uspace/drv/bus/usb/uhci/hw_struct/queue_head.h
===================================================================
--- uspace/drv/bus/usb/uhci/hw_struct/queue_head.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhci/hw_struct/queue_head.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -47,5 +47,5 @@
 	volatile link_pointer_t element;
 } __attribute__((packed)) qh_t;
-/*----------------------------------------------------------------------------*/
+
 /** Initialize queue head structure
  *
@@ -61,5 +61,5 @@
 	instance->next = LINK_POINTER_TERM;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Set queue head next pointer
  *
@@ -81,5 +81,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /** Set queue head element pointer
  *
Index: uspace/drv/bus/usb/uhci/hw_struct/transfer_descriptor.c
===================================================================
--- uspace/drv/bus/usb/uhci/hw_struct/transfer_descriptor.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhci/hw_struct/transfer_descriptor.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -107,5 +107,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /** Convert TD status into standard error code
  *
@@ -145,5 +145,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Print values in status field (dw1) in a human readable way.
  *
Index: uspace/drv/bus/usb/uhci/hw_struct/transfer_descriptor.h
===================================================================
--- uspace/drv/bus/usb/uhci/hw_struct/transfer_descriptor.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhci/hw_struct/transfer_descriptor.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -100,5 +100,5 @@
 
 void td_print_status(const td_t *instance);
-/*----------------------------------------------------------------------------*/
+
 /** Helper function for parsing actual size out of TD.
  *
@@ -113,5 +113,5 @@
 	return ((s >> TD_STATUS_ACTLEN_POS) + 1) & TD_STATUS_ACTLEN_MASK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Check whether less than max data were received on SPD marked transfer.
  *
@@ -129,5 +129,5 @@
 	    (instance->status | TD_STATUS_SPD_FLAG) && act_size < max_size;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Helper function for parsing value of toggle bit.
  *
@@ -140,5 +140,5 @@
 	return (instance->device & TD_DEVICE_DATA_TOGGLE_ONE_FLAG) ? 1 : 0;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Helper function for parsing value of active bit
  *
@@ -151,5 +151,5 @@
 	return (instance->status & TD_STATUS_ERROR_ACTIVE) != 0;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Helper function for setting IOC bit.
  *
@@ -161,5 +161,5 @@
 	instance->status |= TD_STATUS_IOC_FLAG;
 }
-/*----------------------------------------------------------------------------*/
+
 #endif
 /**
Index: uspace/drv/bus/usb/uhci/main.c
===================================================================
--- uspace/drv/bus/usb/uhci/main.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhci/main.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -44,14 +44,14 @@
 
 static int uhci_dev_add(ddf_dev_t *device);
-/*----------------------------------------------------------------------------*/
+
 static driver_ops_t uhci_driver_ops = {
 	.dev_add = uhci_dev_add,
 };
-/*----------------------------------------------------------------------------*/
+
 static driver_t uhci_driver = {
 	.name = NAME,
 	.driver_ops = &uhci_driver_ops
 };
-/*----------------------------------------------------------------------------*/
+
 /** Initialize a new ddf driver instance for uhci hc and hub.
  *
@@ -75,5 +75,5 @@
 	return ret;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize global driver structures (NONE).
  *
Index: uspace/drv/bus/usb/uhci/transfer_list.c
===================================================================
--- uspace/drv/bus/usb/uhci/transfer_list.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhci/transfer_list.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -42,5 +42,5 @@
 static void transfer_list_remove_batch(
     transfer_list_t *instance, uhci_transfer_batch_t *uhci_batch);
-/*----------------------------------------------------------------------------*/
+
 /** Initialize transfer list structures.
  *
@@ -69,5 +69,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Dispose transfer list structures.
  *
@@ -97,5 +97,5 @@
 	qh_set_next_qh(instance->queue_head, next->queue_head);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Add transfer batch to the list and queue.
  *
@@ -144,5 +144,5 @@
 	fibril_mutex_unlock(&instance->guard);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Add completed batches to the provided list.
  *
@@ -171,5 +171,5 @@
 	fibril_mutex_unlock(&instance->guard);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Walk the list and finish all batches with EINTR.
  *
@@ -188,5 +188,5 @@
 	fibril_mutex_unlock(&instance->guard);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Remove a transfer batch from the list and queue.
  *
Index: uspace/drv/bus/usb/uhci/uhci.c
===================================================================
--- uspace/drv/bus/usb/uhci/uhci.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhci/uhci.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -65,5 +65,5 @@
 	return dev->driver_data;
 }
-/*----------------------------------------------------------------------------*/
+
 /** IRQ handling callback, forward status from call to diver structure.
  *
@@ -83,10 +83,10 @@
 	hc_interrupt(&uhci->hc, status);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Operations supported by the HC driver */
 static ddf_dev_ops_t hc_ops = {
 	.interfaces[USBHC_DEV_IFACE] = &hcd_iface, /* see iface.h/c */
 };
-/*----------------------------------------------------------------------------*/
+
 /** Gets handle of the respective hc.
  *
@@ -105,10 +105,10 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** USB interface implementation used by RH */
 static usb_iface_t usb_iface = {
 	.get_hc_handle = usb_iface_get_hc_handle,
 };
-/*----------------------------------------------------------------------------*/
+
 /** Get root hub hw resources (I/O registers).
  *
@@ -123,5 +123,5 @@
 	return &rh->resource_list;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Interface to provide the root hub driver with hw info */
 static hw_res_ops_t hw_res_iface = {
@@ -129,5 +129,5 @@
 	.enable_interrupt = NULL,
 };
-/*----------------------------------------------------------------------------*/
+
 /** RH function support for uhci_rhd */
 static ddf_dev_ops_t rh_ops = {
@@ -135,5 +135,5 @@
 	.interfaces[HW_RES_DEV_IFACE] = &hw_res_iface
 };
-/*----------------------------------------------------------------------------*/
+
 /** Initialize hc and rh DDF structures and their respective drivers.
  *
Index: uspace/drv/bus/usb/uhci/uhci_batch.c
===================================================================
--- uspace/drv/bus/usb/uhci/uhci_batch.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhci/uhci_batch.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -58,5 +58,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /** Finishes usb_transfer_batch and destroys the structure.
  *
@@ -71,8 +71,8 @@
 	uhci_transfer_batch_dispose(uhci_batch);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Transfer batch setup table. */
 static void (*const batch_setup[])(uhci_transfer_batch_t*, usb_direction_t);
-/*----------------------------------------------------------------------------*/
+
 /** Allocate memory and initialize internal data structure.
  *
@@ -143,5 +143,5 @@
 	return uhci_batch;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Check batch TDs for activity.
  *
@@ -196,5 +196,5 @@
 	return true;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Direction to pid conversion table */
 static const usb_packet_id direction_pids[] = {
@@ -202,5 +202,5 @@
 	[USB_DIRECTION_OUT] = USB_PID_OUT,
 };
-/*----------------------------------------------------------------------------*/
+
 /** Prepare generic data transfer
  *
@@ -259,5 +259,5 @@
 	    USB_TRANSFER_BATCH_ARGS(*uhci_batch->usb_batch));
 }
-/*----------------------------------------------------------------------------*/
+
 /** Prepare generic control transfer
  *
@@ -331,5 +331,5 @@
 	    uhci_batch->tds[td].status);
 }
-/*----------------------------------------------------------------------------*/
+
 static void (*const batch_setup[])(uhci_transfer_batch_t*, usb_direction_t) =
 {
Index: uspace/drv/bus/usb/uhci/uhci_batch.h
===================================================================
--- uspace/drv/bus/usb/uhci/uhci_batch.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhci/uhci_batch.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -76,5 +76,5 @@
 	    uhci_batch->td_count * sizeof(td_t);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Get offset to data buffer accessible to the HC hw.
  * @param uhci_batch UHCI batch structure.
@@ -89,5 +89,5 @@
 	    uhci_batch->usb_batch->setup_size;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Aborts the batch.
  * Sets error to EINTR and size off transferd data to 0, before finishing the
@@ -103,5 +103,5 @@
 	uhci_transfer_batch_finish_dispose(uhci_batch);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Linked list conversion wrapper.
  * @param l Linked list link.
Index: uspace/drv/bus/usb/uhci/utils/malloc32.h
===================================================================
--- uspace/drv/bus/usb/uhci/utils/malloc32.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhci/utils/malloc32.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -35,10 +35,11 @@
 #define DRV_UHCI_UTILS_MALLOC32_H
 
+#include <as.h>
 #include <assert.h>
-#include <unistd.h>
+#include <ddi.h>
 #include <errno.h>
 #include <malloc.h>
 #include <mem.h>
-#include <as.h>
+#include <unistd.h>
 
 #define UHCI_STRCUTURES_ALIGNMENT 16
@@ -63,5 +64,5 @@
 	return result;
 }
-/*----------------------------------------------------------------------------*/
+
 /** DMA malloc simulator
  *
@@ -85,5 +86,5 @@
 	return memalign(alignment, size);
 }
-/*----------------------------------------------------------------------------*/
+
 /** DMA malloc simulator
  *
@@ -92,5 +93,5 @@
 static inline void free32(void *addr)
 	{ free(addr); }
-/*----------------------------------------------------------------------------*/
+
 /** Create 4KB page mapping
  *
@@ -99,16 +100,13 @@
 static inline void * get_page(void)
 {
-	void *address = as_area_create(AS_AREA_ANY, UHCI_REQUIRED_PAGE_SIZE,
-	    AS_AREA_READ | AS_AREA_WRITE);
-	if (address == AS_MAP_FAILED)
-		return NULL;
-	
-	return address;
+	void *address, *phys;
+	const int ret = dmamem_map_anonymous(UHCI_REQUIRED_PAGE_SIZE,
+	    AS_AREA_READ | AS_AREA_WRITE, 0, &phys, &address);
+	return ret == EOK ? address : NULL;
 }
-/*----------------------------------------------------------------------------*/
+
 static inline void return_page(void *page)
 {
-	if (page)
-		as_area_destroy(page);
+	dmamem_unmap_anonymous(page);
 }
 
Index: uspace/drv/bus/usb/uhcirh/port.c
===================================================================
--- uspace/drv/bus/usb/uhcirh/port.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhcirh/port.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -63,5 +63,5 @@
 	return pio_read_16(port->address);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Register writing helper function.
  *
@@ -75,5 +75,5 @@
 	pio_write_16(port->address, val);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize UHCI root hub port instance.
  *
@@ -127,5 +127,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Cleanup UHCI root hub port instance.
  *
@@ -141,5 +141,5 @@
 	return;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Periodically checks port status and reports new devices.
  *
@@ -210,5 +210,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Callback for enabling port during adding a new device.
  *
@@ -247,5 +247,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize and report connected device.
  *
@@ -282,5 +282,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Remove device.
  *
@@ -324,5 +324,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Enable or disable root hub port.
  *
@@ -358,5 +358,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Print the port status value in a human friendly way
  *
Index: uspace/drv/bus/usb/uhcirh/root_hub.c
===================================================================
--- uspace/drv/bus/usb/uhcirh/root_hub.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/uhcirh/root_hub.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -79,5 +79,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Cleanup UHCI root hub instance.
  *
@@ -92,5 +92,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * @}
Index: uspace/drv/bus/usb/usbhid/generic/hiddev.c
===================================================================
--- uspace/drv/bus/usb/usbhid/generic/hiddev.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/generic/hiddev.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -46,5 +46,5 @@
 #include "usbhid.h"
 
-/*----------------------------------------------------------------------------*/
+
 
 const usb_endpoint_description_t usb_hid_generic_poll_endpoint_description = {
@@ -60,5 +60,5 @@
 const char *HID_GENERIC_CLASS_NAME = "hid";
 
-/*----------------------------------------------------------------------------*/
+
 static size_t usb_generic_hid_get_event_length(ddf_fun_t *fun);
 static int usb_generic_hid_get_event(ddf_fun_t *fun, uint8_t *buffer,
@@ -68,5 +68,5 @@
 static int usb_generic_get_report_descriptor(ddf_fun_t *fun, uint8_t *desc,
     size_t size, size_t *actual_size);
-/*----------------------------------------------------------------------------*/
+
 static usbhid_iface_t usb_generic_iface = {
 	.get_event = usb_generic_hid_get_event,
@@ -75,10 +75,10 @@
 	.get_report_descriptor = usb_generic_get_report_descriptor
 };
-/*----------------------------------------------------------------------------*/
+
 static ddf_dev_ops_t usb_generic_hid_ops = {
 	.interfaces[USBHID_DEV_IFACE] = &usb_generic_iface,
 	.open = usb_generic_hid_client_connected
 };
-/*----------------------------------------------------------------------------*/
+
 static size_t usb_generic_hid_get_event_length(ddf_fun_t *fun)
 {
@@ -97,5 +97,5 @@
 	return hid_dev->max_input_report_size;
 }
-/*----------------------------------------------------------------------------*/
+
 static int usb_generic_hid_get_event(ddf_fun_t *fun, uint8_t *buffer,
     size_t size, size_t *act_size, int *event_nr, unsigned int flags)
@@ -127,5 +127,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 static size_t usb_generic_get_report_descriptor_length(ddf_fun_t *fun)
 {
@@ -144,5 +144,5 @@
 	return hid_dev->report_desc_size;
 }
-/*----------------------------------------------------------------------------*/
+
 static int usb_generic_get_report_descriptor(ddf_fun_t *fun, uint8_t *desc,
     size_t size, size_t *actual_size)
@@ -166,5 +166,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 static int usb_generic_hid_client_connected(ddf_fun_t *fun)
 {
@@ -172,5 +172,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 void usb_generic_hid_deinit(usb_hid_dev_t *hid_dev, void *data)
 {
@@ -189,5 +189,5 @@
 	ddf_fun_destroy(fun);
 }
-/*----------------------------------------------------------------------------*/
+
 int usb_generic_hid_init(usb_hid_dev_t *hid_dev, void **data)
 {
@@ -224,5 +224,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 bool usb_generic_hid_polling_callback(usb_hid_dev_t *hid_dev, void *data)
 {
Index: uspace/drv/bus/usb/usbhid/generic/hiddev.h
===================================================================
--- uspace/drv/bus/usb/usbhid/generic/hiddev.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/generic/hiddev.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -47,5 +47,5 @@
 const char *HID_GENERIC_CLASS_NAME;
 
-/*----------------------------------------------------------------------------*/
+
 
 int usb_generic_hid_init(struct usb_hid_dev *hid_dev, void **data);
Index: uspace/drv/bus/usb/usbhid/kbd/kbddev.c
===================================================================
--- uspace/drv/bus/usb/usbhid/kbd/kbddev.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/kbd/kbddev.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -71,5 +71,7 @@
 #include "../usbhid.h"
 
-/*----------------------------------------------------------------------------*/
+static void default_connection_handler(ddf_fun_t *, ipc_callid_t, ipc_call_t *);
+static ddf_dev_ops_t kbdops = { .default_handler = default_connection_handler };
+
 
 static const unsigned DEFAULT_ACTIVE_MODS = KM_NUM_LOCK;
@@ -86,5 +88,5 @@
 static const unsigned int DEFAULT_REPEAT_DELAY = 50 * 1000;
 
-/*----------------------------------------------------------------------------*/
+
 /** Keyboard polling endpoint description for boot protocol class. */
 const usb_endpoint_description_t usb_hid_kbd_poll_endpoint_description = {
@@ -101,5 +103,5 @@
 
 static void usb_kbd_set_led(usb_hid_dev_t *hid_dev, usb_kbd_t *kbd_dev);
-/*----------------------------------------------------------------------------*/
+
 static const uint8_t USB_KBD_BOOT_REPORT_DESCRIPTOR[] = {
 	0x05, 0x01,  /* Usage Page (Generic Desktop), */
@@ -136,5 +138,5 @@
 	0xC0         /* End Collection */
 };
-/*----------------------------------------------------------------------------*/
+
 typedef enum usb_kbd_flags {
 	USB_KBD_STATUS_UNINITIALIZED = 0,
@@ -142,7 +144,7 @@
 	USB_KBD_STATUS_TO_DESTROY = -1
 } usb_kbd_flags;
-/*----------------------------------------------------------------------------*/
+
 /* IPC method handler                                                         */
-/*----------------------------------------------------------------------------*/
+
 /**
  * Default handler for IPC methods not handled by DDF.
@@ -187,6 +189,6 @@
 			break;
 		}
-		if (kbd_dev->console_sess == NULL) {
-			kbd_dev->console_sess = sess;
+		if (kbd_dev->client_sess == NULL) {
+			kbd_dev->client_sess = sess;
 			usb_log_debug("%s: OK\n", __FUNCTION__);
 			async_answer_0(icallid, EOK);
@@ -206,7 +208,7 @@
 
 }
-/*----------------------------------------------------------------------------*/
+
 /* Key processing functions                                                   */
-/*----------------------------------------------------------------------------*/
+
 /**
  * Handles turning of LED lights on and off.
@@ -281,5 +283,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /** Send key event.
  *
@@ -292,5 +294,5 @@
 {
 	usb_log_debug2("Sending kbdev event %d/%d to the console\n", type, key);
-	if (kbd_dev->console_sess == NULL) {
+	if (kbd_dev->client_sess == NULL) {
 		usb_log_warning(
 		    "Connection to console not ready, key discarded.\n");
@@ -298,5 +300,5 @@
 	}
 
-	async_exch_t *exch = async_exchange_begin(kbd_dev->console_sess);
+	async_exch_t *exch = async_exchange_begin(kbd_dev->client_sess);
 	if (exch != NULL) {
 		async_msg_2(exch, KBDEV_EVENT, type, key);
@@ -306,5 +308,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 static inline int usb_kbd_is_lock(unsigned int key_code)
 {
@@ -313,5 +315,5 @@
 	    || key_code == KC_CAPS_LOCK);
 }
-/*----------------------------------------------------------------------------*/
+
 static size_t find_in_array_int32(int32_t val, int32_t *arr, size_t arr_size)
 {
@@ -324,5 +326,5 @@
 	return (size_t) -1;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Checks if some keys were pressed or released and generates key events.
@@ -407,7 +409,7 @@
 	usb_log_debug2("Stored keys %s.\n", key_buffer);
 }
-/*----------------------------------------------------------------------------*/
+
 /* General kbd functions                                                      */
-/*----------------------------------------------------------------------------*/
+
 /**
  * Processes data received from the device in form of report.
@@ -479,7 +481,7 @@
 	usb_kbd_check_key_changes(hid_dev, kbd_dev);
 }
-/*----------------------------------------------------------------------------*/
+
 /* HID/KBD structure manipulation                                             */
-/*----------------------------------------------------------------------------*/
+
 static int usb_kbd_create_function(usb_kbd_t *kbd_dev)
 {
@@ -499,5 +501,5 @@
 	/* Store the initialized HID device and HID ops
 	 * to the DDF function. */
-	fun->ops = &kbd_dev->ops;
+	fun->ops = &kbdops;
 	fun->driver_data = kbd_dev;
 
@@ -535,7 +537,7 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /* API functions                                                              */
-/*----------------------------------------------------------------------------*/
+
 /**
  * Initialization of the USB/HID keyboard structure.
@@ -576,5 +578,4 @@
 	fibril_mutex_initialize(&kbd_dev->repeat_mtx);
 	kbd_dev->initialized = USB_KBD_STATUS_UNINITIALIZED;
-	kbd_dev->ops.default_handler = default_connection_handler;
 
 	/* Store link to HID device */
@@ -700,5 +701,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 bool usb_kbd_polling_callback(usb_hid_dev_t *hid_dev, void *data)
 {
@@ -714,15 +715,15 @@
 	return true;
 }
-/*----------------------------------------------------------------------------*/
+
 int usb_kbd_is_initialized(const usb_kbd_t *kbd_dev)
 {
 	return (kbd_dev->initialized == USB_KBD_STATUS_INITIALIZED);
 }
-/*----------------------------------------------------------------------------*/
+
 int usb_kbd_is_ready_to_destroy(const usb_kbd_t *kbd_dev)
 {
 	return (kbd_dev->initialized == USB_KBD_STATUS_TO_DESTROY);
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Properly destroys the USB/HID keyboard structure.
@@ -737,6 +738,6 @@
 
 	/* Hangup session to the console. */
-	if (kbd_dev->console_sess)
-		async_hangup(kbd_dev->console_sess);
+	if (kbd_dev->client_sess)
+		async_hangup(kbd_dev->client_sess);
 
 	//assert(!fibril_mutex_is_locked((*kbd_dev)->repeat_mtx));
@@ -765,5 +766,5 @@
 	free(kbd_dev);
 }
-/*----------------------------------------------------------------------------*/
+
 void usb_kbd_deinit(usb_hid_dev_t *hid_dev, void *data)
 {
@@ -778,5 +779,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 int usb_kbd_set_boot_protocol(usb_hid_dev_t *hid_dev)
 {
Index: uspace/drv/bus/usb/usbhid/kbd/kbddev.h
===================================================================
--- uspace/drv/bus/usb/usbhid/kbd/kbddev.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/kbd/kbddev.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -50,5 +50,5 @@
 struct usb_hid_dev;
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * USB/HID keyboard device type.
@@ -82,9 +82,6 @@
 	unsigned lock_keys;
 
-	/** IPC session to the console device (for sending key events). */
-	async_sess_t *console_sess;
-
-	/** @todo What is this actually? */
-	ddf_dev_ops_t ops;
+	/** IPC session to client (for sending key events). */
+	async_sess_t *client_sess;
 
 	/** Information for auto-repeat of keys. */
@@ -116,5 +113,5 @@
 } usb_kbd_t;
 
-/*----------------------------------------------------------------------------*/
+
 
 extern const usb_endpoint_description_t usb_hid_kbd_poll_endpoint_description;
@@ -123,5 +120,5 @@
 const char *HID_KBD_CLASS_NAME;
 
-/*----------------------------------------------------------------------------*/
+
 
 int usb_kbd_init(struct usb_hid_dev *hid_dev, void **data);
Index: uspace/drv/bus/usb/usbhid/kbd/kbdrepeat.c
===================================================================
--- uspace/drv/bus/usb/usbhid/kbd/kbdrepeat.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/kbd/kbdrepeat.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -105,5 +105,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Main routine to be executed by a fibril for handling auto-repeat.
@@ -132,5 +132,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Start repeating particular key.
@@ -149,5 +149,5 @@
 	fibril_mutex_unlock(&kbd->repeat_mtx);
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Stop repeating particular key.
Index: uspace/drv/bus/usb/usbhid/kbd/kbdrepeat.h
===================================================================
--- uspace/drv/bus/usb/usbhid/kbd/kbdrepeat.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/kbd/kbdrepeat.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -42,5 +42,5 @@
 struct usb_kbd_t;
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * Structure for keeping information needed for auto-repeat of keys.
@@ -57,5 +57,5 @@
 } usb_kbd_repeat_t;
 
-/*----------------------------------------------------------------------------*/
+
 
 int usb_kbd_repeat_fibril(void *arg);
Index: uspace/drv/bus/usb/usbhid/main.c
===================================================================
--- uspace/drv/bus/usb/usbhid/main.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/main.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -113,5 +113,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Callback for a device about to be removed from the driver.
@@ -126,5 +126,5 @@
 	return ENOTSUP;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Callback for removing a device from the driver.
@@ -152,5 +152,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** USB generic driver callbacks */
 static const usb_driver_ops_t usb_hid_driver_ops = {
@@ -159,5 +159,5 @@
 	.device_gone = usb_hid_device_gone,
 };
-/*----------------------------------------------------------------------------*/
+
 /** The driver itself. */
 static const usb_driver_t usb_hid_driver = {
@@ -166,5 +166,5 @@
         .endpoints = usb_hid_endpoints
 };
-/*----------------------------------------------------------------------------*/
+
 int main(int argc, char *argv[])
 {
Index: uspace/drv/bus/usb/usbhid/mouse/mousedev.c
===================================================================
--- uspace/drv/bus/usb/usbhid/mouse/mousedev.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/mouse/mousedev.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -54,5 +54,8 @@
 #define NAME "mouse"
 
-/*----------------------------------------------------------------------------*/
+static void default_connection_handler(ddf_fun_t *, ipc_callid_t, ipc_call_t *);
+
+static ddf_dev_ops_t ops = { .default_handler = default_connection_handler };
+
 
 const usb_endpoint_description_t usb_hid_mouse_poll_endpoint_description = {
@@ -71,5 +74,5 @@
 static const uint8_t IDLE_RATE = 0;
 
-/*----------------------------------------------------------------------------*/
+
 static const uint8_t USB_MOUSE_BOOT_REPORT_DESCRIPTOR[] = {
 	0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
@@ -101,5 +104,5 @@
 };
 
-/*----------------------------------------------------------------------------*/
+
 
 /** Default handler for IPC methods not handled by DDF.
@@ -143,5 +146,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 static int get_mouse_axis_move_value(uint8_t rid, usb_hid_report_t *report,
     int32_t usage)
@@ -221,20 +224,10 @@
 		assert(index < mouse_dev->buttons_count);
 
-		if (mouse_dev->buttons[index] == 0 && field->value != 0) {
+		if (mouse_dev->buttons[index] != field->value) {
 			async_exch_t *exch =
 			    async_exchange_begin(mouse_dev->mouse_sess);
 			if (exch != NULL) {
 				async_req_2_0(exch, MOUSEEV_BUTTON_EVENT,
-				    field->usage, 1);
-				async_exchange_end(exch);
-				mouse_dev->buttons[index] = field->value;
-			}
-
-		} else if (mouse_dev->buttons[index] != 0 && field->value == 0) {
-			async_exch_t *exch =
-			    async_exchange_begin(mouse_dev->mouse_sess);
-			if (exch != NULL) {
-				async_req_2_0(exch, MOUSEEV_BUTTON_EVENT,
-				    field->usage, 0);
+				    field->usage, (field->value != 0) ? 1 : 0);
 				async_exchange_end(exch);
 				mouse_dev->buttons[index] = field->value;
@@ -252,5 +245,5 @@
 	return true;
 }
-/*----------------------------------------------------------------------------*/
+
 #define FUN_UNBIND_DESTROY(fun) \
 if (fun) { \
@@ -263,5 +256,5 @@
 	} \
 } else (void)0
-/*----------------------------------------------------------------------------*/
+
 static int usb_mouse_create_function(usb_hid_dev_t *hid_dev, usb_mouse_t *mouse)
 {
@@ -279,5 +272,5 @@
 	}
 
-	fun->ops = &mouse->ops;
+	fun->ops = &ops;
 	fun->driver_data = mouse;
 
@@ -302,5 +295,4 @@
 	}
 	mouse->mouse_fun = fun;
-
 	return EOK;
 }
@@ -345,5 +337,5 @@
 	return highest_button;
 }
-/*----------------------------------------------------------------------------*/
+
 int usb_mouse_init(usb_hid_dev_t *hid_dev, void **data)
 {
@@ -379,7 +371,4 @@
 	}
 
-	// set handler for incoming calls
-	mouse_dev->ops.default_handler = default_connection_handler;
-
 	// TODO: how to know if the device supports the request???
 	usbhid_req_set_idle(&hid_dev->usb_dev->ctrl_pipe,
@@ -398,5 +387,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 bool usb_mouse_polling_callback(usb_hid_dev_t *hid_dev, void *data)
 {
@@ -411,5 +400,5 @@
 	return usb_mouse_process_report(hid_dev, mouse_dev);
 }
-/*----------------------------------------------------------------------------*/
+
 void usb_mouse_deinit(usb_hid_dev_t *hid_dev, void *data)
 {
@@ -432,5 +421,5 @@
 	free(mouse_dev);
 }
-/*----------------------------------------------------------------------------*/
+
 int usb_mouse_set_boot_protocol(usb_hid_dev_t *hid_dev)
 {
Index: uspace/drv/bus/usb/usbhid/mouse/mousedev.h
===================================================================
--- uspace/drv/bus/usb/usbhid/mouse/mousedev.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/mouse/mousedev.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -42,9 +42,9 @@
 struct usb_hid_dev;
 
-/*----------------------------------------------------------------------------*/
+
 
 /** Container for USB mouse device. */
 typedef struct {
-	/** IPC session to console (consumer). */
+	/** IPC session to consumer. */
 	async_sess_t *mouse_sess;
 
@@ -53,10 +53,9 @@
 	size_t buttons_count;
 
-	ddf_dev_ops_t ops;
 	/* DDF mouse function */
 	ddf_fun_t *mouse_fun;
 } usb_mouse_t;
 
-/*----------------------------------------------------------------------------*/
+
 
 extern const usb_endpoint_description_t usb_hid_mouse_poll_endpoint_description;
@@ -65,5 +64,5 @@
 const char *HID_MOUSE_CATEGORY;
 
-/*----------------------------------------------------------------------------*/
+
 
 int usb_mouse_init(struct usb_hid_dev *hid_dev, void **data);
@@ -75,5 +74,5 @@
 int usb_mouse_set_boot_protocol(struct usb_hid_dev *hid_dev);
 
-/*----------------------------------------------------------------------------*/
+
 
 #endif // USB_HID_MOUSEDEV_H_
Index: uspace/drv/bus/usb/usbhid/multimedia/multimedia.c
===================================================================
--- uspace/drv/bus/usb/usbhid/multimedia/multimedia.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/multimedia/multimedia.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -54,5 +54,5 @@
 #define NAME  "multimedia-keys"
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * Logitech UltraX device type.
@@ -70,5 +70,5 @@
 
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * Default handler for IPC methods not handled by DDF.
@@ -106,9 +106,9 @@
 		async_answer_0(icallid, EINVAL);
 }
-/*----------------------------------------------------------------------------*/
+
 static ddf_dev_ops_t multimedia_ops = {
 	.default_handler = default_connection_handler
 };
-/*----------------------------------------------------------------------------*/
+
 /**
  * Processes key events.
@@ -155,5 +155,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 int usb_multimedia_init(struct usb_hid_dev *hid_dev, void **data)
 {
@@ -216,5 +216,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 void usb_multimedia_deinit(struct usb_hid_dev *hid_dev, void *data)
 {
@@ -239,5 +239,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 bool usb_multimedia_polling_callback(struct usb_hid_dev *hid_dev, void *data)
 {
Index: uspace/drv/bus/usb/usbhid/multimedia/multimedia.h
===================================================================
--- uspace/drv/bus/usb/usbhid/multimedia/multimedia.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/multimedia/multimedia.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -41,5 +41,5 @@
 struct usb_hid_dev;
 
-/*----------------------------------------------------------------------------*/
+
 
 int usb_multimedia_init(struct usb_hid_dev *hid_dev, void **data);
@@ -49,5 +49,5 @@
 bool usb_multimedia_polling_callback(struct usb_hid_dev *hid_dev, void *data);
 
-/*----------------------------------------------------------------------------*/
+
 
 #endif // USB_HID_MULTIMEDIA_H_
Index: uspace/drv/bus/usb/usbhid/subdrivers.h
===================================================================
--- uspace/drv/bus/usb/usbhid/subdrivers.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/subdrivers.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -40,5 +40,5 @@
 #include "kbd/kbddev.h"
 
-/*----------------------------------------------------------------------------*/
+
 
 typedef struct usb_hid_subdriver_usage {
@@ -47,5 +47,5 @@
 } usb_hid_subdriver_usage_t;
 
-/*----------------------------------------------------------------------------*/
+
 
 /** Structure representing the mapping between device requirements and the 
@@ -81,10 +81,10 @@
 } usb_hid_subdriver_mapping_t;
 
-/*----------------------------------------------------------------------------*/
+
 
 extern const usb_hid_subdriver_mapping_t usb_hid_subdrivers[];
 extern const size_t USB_HID_MAX_SUBDRIVERS;
 
-/*----------------------------------------------------------------------------*/
+
 
 #endif /* USB_HID_SUBDRIVERS_H_ */
Index: uspace/drv/bus/usb/usbhid/usbhid.c
===================================================================
--- uspace/drv/bus/usb/usbhid/usbhid.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/usbhid.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -58,5 +58,5 @@
 	NULL
 };
-/*----------------------------------------------------------------------------*/
+
 static int usb_hid_set_boot_kbd_subdriver(usb_hid_dev_t *hid_dev)
 {
@@ -74,5 +74,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 static int usb_hid_set_boot_mouse_subdriver(usb_hid_dev_t *hid_dev)
 {
@@ -90,5 +90,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 static int usb_hid_set_generic_hid_subdriver(usb_hid_dev_t *hid_dev)
 {
@@ -110,5 +110,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 static bool usb_hid_ids_match(const usb_hid_dev_t *hid_dev,
     const usb_hid_subdriver_mapping_t *mapping)
@@ -122,5 +122,5 @@
 	    == mapping->product_id);
 }
-/*----------------------------------------------------------------------------*/
+
 static bool usb_hid_path_matches(usb_hid_dev_t *hid_dev,
     const usb_hid_subdriver_mapping_t *mapping)
@@ -178,5 +178,5 @@
 	return matches;
 }
-/*----------------------------------------------------------------------------*/
+
 static int usb_hid_save_subdrivers(usb_hid_dev_t *hid_dev,
     const usb_hid_subdriver_t **subdrivers, unsigned count)
@@ -211,5 +211,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 static int usb_hid_find_subdrivers(usb_hid_dev_t *hid_dev)
 {
@@ -263,5 +263,5 @@
 	return usb_hid_save_subdrivers(hid_dev, subdrivers, count);
 }
-/*----------------------------------------------------------------------------*/
+
 static int usb_hid_check_pipes(usb_hid_dev_t *hid_dev, const usb_device_t *dev)
 {
@@ -290,5 +290,5 @@
 	return ENOTSUP;
 }
-/*----------------------------------------------------------------------------*/
+
 static int usb_hid_init_report(usb_hid_dev_t *hid_dev)
 {
@@ -322,5 +322,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /*
  * This functions initializes required structures from the device's descriptors
@@ -458,5 +458,5 @@
 	return rc;
 }
-/*----------------------------------------------------------------------------*/
+
 bool usb_hid_polling_callback(usb_device_t *dev, uint8_t *buffer,
     size_t buffer_size, void *arg)
@@ -500,5 +500,5 @@
 	return cont;
 }
-/*----------------------------------------------------------------------------*/
+
 void usb_hid_polling_ended_callback(usb_device_t *dev, bool reason, void *arg)
 {
@@ -517,15 +517,15 @@
 	hid_dev->running = false;
 }
-/*----------------------------------------------------------------------------*/
+
 void usb_hid_new_report(usb_hid_dev_t *hid_dev)
 {
 	++hid_dev->report_nr;
 }
-/*----------------------------------------------------------------------------*/
+
 int usb_hid_report_number(const usb_hid_dev_t *hid_dev)
 {
 	return hid_dev->report_nr;
 }
-/*----------------------------------------------------------------------------*/
+
 void usb_hid_deinit(usb_hid_dev_t *hid_dev)
 {
Index: uspace/drv/bus/usb/usbhid/usbhid.h
===================================================================
--- uspace/drv/bus/usb/usbhid/usbhid.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhid/usbhid.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -95,5 +95,5 @@
 };
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * Structure for holding general HID device data.
@@ -132,5 +132,5 @@
 };
 
-/*----------------------------------------------------------------------------*/
+
 
 enum {
@@ -143,5 +143,5 @@
 extern const usb_endpoint_description_t *usb_hid_endpoints[];
 
-/*----------------------------------------------------------------------------*/
+
 
 int usb_hid_init(usb_hid_dev_t *hid_dev, usb_device_t *dev);
Index: uspace/drv/bus/usb/usbhub/port.c
===================================================================
--- uspace/drv/bus/usb/usbhub/port.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhub/port.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -70,5 +70,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Clear feature on hub port.
@@ -92,5 +92,5 @@
 	    sizeof(clear_request), NULL, 0);
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Set feature on hub port.
@@ -114,5 +114,5 @@
 	    sizeof(clear_request), NULL, 0);
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Mark reset process as failed due to external reasons
@@ -129,5 +129,5 @@
 	fibril_mutex_unlock(&port->mutex);
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Process interrupts on given port
@@ -245,5 +245,5 @@
 	    port->port_number, status);
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * routine called when a device on port has been removed
@@ -299,5 +299,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Process port reset change
@@ -335,5 +335,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /** Retrieve port status.
  *
@@ -352,5 +352,5 @@
 		.request = USB_HUB_REQUEST_GET_STATUS,
 		.value = 0,
-		.index = port->port_number,
+		.index = uint16_host2usb(port->port_number),
 		.length = sizeof(usb_port_status_t),
 	};
@@ -375,5 +375,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Callback for enabling a specific port.
  *
@@ -407,5 +407,5 @@
 	return port->reset_okay ? EOK : ESTALL;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Fibril for adding a new device.
  *
@@ -454,5 +454,5 @@
 	return rc;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Start device adding when connection change is detected.
  *
Index: uspace/drv/bus/usb/usbhub/status.h
===================================================================
--- uspace/drv/bus/usb/usbhub/status.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhub/status.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -42,6 +42,7 @@
  * should not be accessed directly, use supplied getter/setter methods.
  *
- * For more information refer to table 11-15 in
- * "Universal Serial Bus Specification Revision 1.1"
+ * For more information refer to tables 11-15 and 11-16 in
+ * "Universal Serial Bus Specification Revision 1.1" pages 274 and 277
+ * (290 and 293 in pdf)
  *
  */
Index: uspace/drv/bus/usb/usbhub/usbhub.c
===================================================================
--- uspace/drv/bus/usb/usbhub/usbhub.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbhub/usbhub.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -165,5 +165,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Turn off power to all ports.
@@ -176,5 +176,5 @@
 	return ENOTSUP;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Remove all attached devices
@@ -219,5 +219,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Callback for polling hub for changes.
  *
@@ -256,5 +256,5 @@
 	return true;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Load hub-specific information into hub_dev structure and process if needed
@@ -331,5 +331,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Set configuration of and USB device
@@ -378,5 +378,5 @@
 	return opResult;
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Process hub over current change
@@ -416,5 +416,5 @@
 
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * Process hub interrupts.
@@ -485,5 +485,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /**
  * callback called from hub polling fibril when the fibril terminates
Index: uspace/drv/bus/usb/usbmid/main.c
===================================================================
--- uspace/drv/bus/usb/usbmid/main.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/bus/usb/usbmid/main.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -61,5 +61,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Callback when a MID device is about to be removed from the host.
  *
@@ -115,5 +115,5 @@
 	return ret;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Callback when a MID device was removed from the host.
  *
Index: uspace/drv/char/i8042/i8042.c
===================================================================
--- uspace/drv/char/i8042/i8042.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/char/i8042/i8042.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -120,5 +120,5 @@
 	},
 	{
-		.cmd = CMD_BTEST,
+		.cmd = CMD_AND,
 		.value = i8042_OUTPUT_FULL,
 		.srcarg = 1,
Index: uspace/drv/infrastructure/rootmac/rootmac.c
===================================================================
--- uspace/drv/infrastructure/rootmac/rootmac.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/infrastructure/rootmac/rootmac.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -52,10 +52,20 @@
 } rootmac_fun_t;
 
-static hw_resource_t pci_conf_regs = {
-	.type = IO_RANGE,
-	.res.io_range = {
-		.address = 0xCF8,
-		.size = 8,
-		.endianness = LITTLE_ENDIAN
+static hw_resource_t pci_conf_regs[] = {
+	{
+		.type = IO_RANGE,
+		.res.io_range = {
+			.address = 0xfec00000,
+			.size = 4,
+			.endianness = LITTLE_ENDIAN
+		}
+	},
+	{
+		.type = IO_RANGE,
+		.res.io_range = {
+			.address = 0xfee00000,
+			.size = 4,
+			.endianness = LITTLE_ENDIAN
+		}
 	}
 };
@@ -63,6 +73,6 @@
 static rootmac_fun_t pci_data = {
 	.hw_resources = {
-		1,
-		&pci_conf_regs
+		2,
+		pci_conf_regs
 	}
 };
@@ -127,7 +137,12 @@
 static int rootmac_dev_add(ddf_dev_t *dev)
 {
+#if 0
 	/* Register functions */
-	if (!rootmac_add_fun(dev, "pci0", "pangea_pci", &pci_data))
+	if (!rootmac_add_fun(dev, "pci0", "intel_pci", &pci_data))
 		ddf_msg(LVL_ERROR, "Failed to add functions for Mac platform.");
+#else
+	(void)pci_data;
+	(void)rootmac_add_fun;
+#endif
 	
 	return EOK;
Index: uspace/drv/infrastructure/rootpc/rootpc.c
===================================================================
--- uspace/drv/infrastructure/rootpc/rootpc.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/infrastructure/rootpc/rootpc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -75,10 +75,20 @@
 };
 
-static hw_resource_t pci_conf_regs = {
-	.type = IO_RANGE,
-	.res.io_range = {
-		.address = 0xCF8,
-		.size = 8,
-		.endianness = LITTLE_ENDIAN
+static hw_resource_t pci_conf_regs[] = {
+	{
+		.type = IO_RANGE,
+		.res.io_range = {
+			.address = 0xCF8,
+			.size = 4,
+			.endianness = LITTLE_ENDIAN
+		}
+	},
+	{
+		.type = IO_RANGE,
+		.res.io_range = {
+			.address = 0xCFC,
+			.size = 4,
+			.endianness = LITTLE_ENDIAN
+		}
 	}
 };
@@ -86,6 +96,6 @@
 static rootpc_fun_t pci_data = {
 	.hw_resources = {
-		1,
-		&pci_conf_regs
+		sizeof(pci_conf_regs)/sizeof(pci_conf_regs[0]),
+		pci_conf_regs
 	}
 };
Index: uspace/drv/nic/ne2k/dp8390.c
===================================================================
--- uspace/drv/nic/ne2k/dp8390.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/nic/ne2k/dp8390.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -201,5 +201,5 @@
 	/* Check if the DP8390 is really there */
 	uint8_t val = pio_read_8(ne2k->port + DP_CR);
-	if ((val & (CR_STP | CR_DM_ABORT)) != (CR_STP | CR_DM_ABORT))
+	if ((val & (CR_STP | CR_TXP | CR_DM_ABORT)) != (CR_STP | CR_DM_ABORT))
 		return EXDEV;
 	
Index: uspace/drv/nic/ne2k/ne2k.c
===================================================================
--- uspace/drv/nic/ne2k/ne2k.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/drv/nic/ne2k/ne2k.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -83,5 +83,5 @@
 	{
 		/* Mask supported interrupt causes */
-		.cmd = CMD_BTEST,
+		.cmd = CMD_AND,
 		.value = (ISR_PRX | ISR_PTX | ISR_RXE | ISR_TXE | ISR_OVW |
 		    ISR_CNT | ISR_RDC),
Index: uspace/lib/c/Makefile
===================================================================
--- uspace/lib/c/Makefile	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -71,4 +71,5 @@
 	generic/device/nic.c \
 	generic/device/pci.c \
+	generic/device/ahci.c \
 	generic/elf/elf_load.c \
 	generic/event.c \
Index: uspace/lib/c/arch/abs32le/_link.ld.in
===================================================================
--- uspace/lib/c/arch/abs32le/_link.ld.in	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/abs32le/_link.ld.in	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -14,12 +14,16 @@
 SECTIONS {
 #ifdef LOADER
+	. = 0x70001000 + SIZEOF_HEADERS;
+	
 	.interp : {
 		*(.interp);
-	} :interp
-	
-	. = 0x70001000 + SIZEOF_HEADERS;
+	} :interp :text
 #else
 	. = 0x1000 + SIZEOF_HEADERS;
 #endif
+	
+	/* Make sure the code is aligned reasonably */
+	. = ALIGN(., 16);
+	
 	.text : {
 		*(.text .text.*);
Index: uspace/lib/c/arch/amd64/_link.ld.in
===================================================================
--- uspace/lib/c/arch/amd64/_link.ld.in	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/amd64/_link.ld.in	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -15,12 +15,16 @@
 SECTIONS {
 #ifdef LOADER
+	. = 0x70001000 + SIZEOF_HEADERS;
+	
 	.interp : {
 		*(.interp);
-	} :interp
-	
-	. = 0x70001000 + SIZEOF_HEADERS;
+	} :interp :text
 #else
 	. = 0x1000 + SIZEOF_HEADERS;
 #endif
+	
+	/* Make sure the code is aligned reasonably */
+	. = ALIGN(., 16);
+	
 	.init : {
 		*(.init);
Index: uspace/lib/c/arch/amd64/include/elf_linux.h
===================================================================
--- uspace/lib/c/arch/amd64/include/elf_linux.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/amd64/include/elf_linux.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -66,4 +66,16 @@
 	uint64_t rsp;
 	uint64_t ss;
+
+	/*
+	 * The following registers need to be part of elf_regs_t.
+	 * Unfortunately, we don't have any information about them in our
+	 * istate_t.
+	 */
+	uint64_t unused_fs_base;
+	uint64_t unused_gs_base;
+	uint64_t unused_ds;
+	uint64_t unused_es;
+	uint64_t unused_fs;
+	uint64_t unused_gs;
 } elf_regs_t;
 
@@ -91,4 +103,14 @@
 	elf_regs->rsp = istate->rsp;
 	elf_regs->ss = istate->ss;
+
+	/*
+	 * Reset the registers for which there is not enough info in istate_t.
+	 */
+	elf_regs->unused_fs_base = 0;
+	elf_regs->unused_gs_base = 0;
+	elf_regs->unused_ds = 0;
+	elf_regs->unused_es = 0;
+	elf_regs->unused_fs = 0;
+	elf_regs->unused_gs = 0;
 }
 
Index: uspace/lib/c/arch/arm32/_link.ld.in
===================================================================
--- uspace/lib/c/arch/arm32/_link.ld.in	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/arm32/_link.ld.in	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -14,12 +14,16 @@
 SECTIONS {
 #ifdef LOADER
+	. = 0x70001000 + SIZEOF_HEADERS;
+	
 	.interp : {
 		*(.interp);
-	} :interp
-	
-	. = 0x70001000 + SIZEOF_HEADERS;
+	} :interp :text
 #else
 	. = 0x1000 + SIZEOF_HEADERS;
 #endif
+	
+	/* Make sure the code is aligned reasonably */
+	. = ALIGN(., 8);
+	
 	.init : {
 		*(.init);
Index: uspace/lib/c/arch/arm32/src/fibril.S
===================================================================
--- uspace/lib/c/arch/arm32/src/fibril.S	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/arm32/src/fibril.S	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -35,5 +35,5 @@
 	stmia r0!, {sp, lr}
 	stmia r0!, {r4-r11}
-
+	
 	# return 1
 	mov r0, #1
@@ -43,6 +43,6 @@
 	ldmia r0!, {sp, lr}
 	ldmia r0!, {r4-r11}
-
-	#return 0
+	
+	# return 0
 	mov r0, #0
 	mov pc, lr
Index: uspace/lib/c/arch/arm32/src/stacktrace_asm.S
===================================================================
--- uspace/lib/c/arch/arm32/src/stacktrace_asm.S	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/arm32/src/stacktrace_asm.S	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -41,4 +41,4 @@
 
 stacktrace_pc_get:
-	mov r0, lr 
+	mov r0, lr
 	mov pc, lr
Index: uspace/lib/c/arch/arm32/src/thread_entry.s
===================================================================
--- uspace/lib/c/arch/arm32/src/thread_entry.s	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/arm32/src/thread_entry.s	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -42,4 +42,4 @@
 	push {fp, ip, lr, pc}
 	sub fp, ip, #4
-
-        b __thread_main
+	
+	b __thread_main
Index: uspace/lib/c/arch/ia32/_link.ld.in
===================================================================
--- uspace/lib/c/arch/ia32/_link.ld.in	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/ia32/_link.ld.in	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -19,9 +19,4 @@
 
 SECTIONS {
-#if defined(LOADER) || defined(DLEXE)
-	.interp : {
-		*(.interp);
-	} :interp
-#endif
 #ifdef LOADER
 	. = 0x70001000 + SIZEOF_HEADERS;
@@ -29,4 +24,14 @@
 	. = 0x1000 + SIZEOF_HEADERS;
 #endif
+	
+#if defined(LOADER) || defined(DLEXE)
+	.interp : {
+		*(.interp);
+	} :interp :text
+#endif
+	
+	/* Make sure the code is aligned reasonably */
+	. = ALIGN(., 16);
+	
 	.init : {
 		*(.init);
@@ -37,5 +42,5 @@
 		*(.rodata .rodata.*);
 	} :text
-
+	
 #if defined(SHLIB) || defined(DLEXE)
 	.rel.plt : {
@@ -80,12 +85,13 @@
 #if defined(SHLIB) || defined(DLEXE)
 	.data.rel : {
-                *(.data.rel .data.rel.*);
+		*(.data.rel .data.rel.*);
 	} :data
-
+	
 	.got : {
-                *(.got);
+		*(.got);
 	} :data
+	
 	.got.plt : {
-                *(.got.plt);
+		*(.got.plt);
 	} :data
 #endif
Index: uspace/lib/c/arch/ia64/Makefile.common
===================================================================
--- uspace/lib/c/arch/ia64/Makefile.common	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/ia64/Makefile.common	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -27,5 +27,15 @@
 #
 
-GCC_CFLAGS += -fno-unwind-tables
+#
+# FIXME:
+#
+# The -fno-selective-scheduling and -fno-selective-scheduling2 options
+# should be removed as soon as a bug in GCC concerning unchecked
+# speculative loads is fixed.
+#
+# See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53975 for reference.
+#
+
+GCC_CFLAGS += -fno-unwind-tables -fno-selective-scheduling -fno-selective-scheduling2
 
 ENDIANESS = LE
Index: uspace/lib/c/arch/ia64/_link.ld.in
===================================================================
--- uspace/lib/c/arch/ia64/_link.ld.in	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/ia64/_link.ld.in	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -14,18 +14,16 @@
 SECTIONS {
 #ifdef LOADER
+	. = 0x800000000 + SIZEOF_HEADERS;
+	
 	.interp : {
 		*(.interp);
-	} :interp
-	
-	. = 0x800000000 + SIZEOF_HEADERS;
+	} :interp :text
 #else
 	. = 0x4000 + SIZEOF_HEADERS;
 #endif
-	/*
-	 * XXX This is just a work around. Problem: .init section does not
-	 * have the proper alignment.
-	 */
+	
+	/* Make sure the code is aligned reasonably */
 	. = ALIGN(., 16);
-
+	
 	.init : {
 		*(.init);
Index: uspace/lib/c/arch/mips32/Makefile.common
===================================================================
--- uspace/lib/c/arch/mips32/Makefile.common	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/mips32/Makefile.common	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -27,5 +27,5 @@
 #
 
-GCC_CFLAGS += -mips3 -mabi=32
+GCC_CFLAGS += -msoft-float -mips3 -mabi=32
 
 ENDIANESS = LE
Index: uspace/lib/c/arch/mips32/_link.ld.in
===================================================================
--- uspace/lib/c/arch/mips32/_link.ld.in	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/mips32/_link.ld.in	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -14,12 +14,16 @@
 SECTIONS {
 #ifdef LOADER
+	. = 0x70004000 + SIZEOF_HEADERS;
+	
 	.interp : {
 		*(.interp);
-	} :interp
-	
-	. = 0x70004000 + SIZEOF_HEADERS;
+	} :interp :text
 #else
 	. = 0x4000 + SIZEOF_HEADERS;
 #endif
+	
+	/* Make sure the code is aligned reasonably */
+	. = ALIGN(., 16);
+	
 	.init : {
 		*(.init);
Index: uspace/lib/c/arch/mips32eb/Makefile.common
===================================================================
--- uspace/lib/c/arch/mips32eb/Makefile.common	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/mips32eb/Makefile.common	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -27,5 +27,5 @@
 #
 
-GCC_CFLAGS += -mips3 -mabi=32
+GCC_CFLAGS += -msoft-float -mips3 -mabi=32
 
 ENDIANESS = BE
Index: uspace/lib/c/arch/mips64/Makefile.common
===================================================================
--- uspace/lib/c/arch/mips64/Makefile.common	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/mips64/Makefile.common	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -27,5 +27,5 @@
 #
 
-GCC_CFLAGS += -mips3 -mabi=64
+GCC_CFLAGS += -msoft-float -mips3 -mabi=64
 AFLAGS = -64
 
Index: uspace/lib/c/arch/mips64/_link.ld.in
===================================================================
--- uspace/lib/c/arch/mips64/_link.ld.in	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/mips64/_link.ld.in	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -15,12 +15,16 @@
 SECTIONS {
 #ifdef LOADER
+	. = 0x70004000 + SIZEOF_HEADERS;
+	
 	.interp : {
 		*(.interp);
-	} :interp
-	
-	. = 0x70004000 + SIZEOF_HEADERS;
+	} :interp :text
 #else
 	. = 0x4000 + SIZEOF_HEADERS;
 #endif
+	
+	/* Make sure the code is aligned reasonably */
+	. = ALIGN(., 16);
+	
 	.init : {
 		*(.init);
Index: uspace/lib/c/arch/ppc32/_link.ld.in
===================================================================
--- uspace/lib/c/arch/ppc32/_link.ld.in	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/ppc32/_link.ld.in	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -15,12 +15,16 @@
 SECTIONS {
 #ifdef LOADER
+	. = 0x70001000 + SIZEOF_HEADERS;
+	
 	.interp : {
 		*(.interp);
-	} :interp
-	
-	. = 0x70001000 + SIZEOF_HEADERS;
+	} :interp :text
 #else
 	. = 0x1000 + SIZEOF_HEADERS;
 #endif
+	
+	/* Make sure the code is aligned reasonably */
+	. = ALIGN(., 4);
+	
 	.init : {
 		*(.init);
Index: uspace/lib/c/arch/sparc64/_link.ld.in
===================================================================
--- uspace/lib/c/arch/sparc64/_link.ld.in	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/arch/sparc64/_link.ld.in	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -14,12 +14,16 @@
 SECTIONS {
 #ifdef LOADER
+	. = 0x70004000 + SIZEOF_HEADERS;
+	
 	.interp : {
 		*(.interp);
-	} :interp
-	
-	. = 0x70004000 + SIZEOF_HEADERS;
+	} :interp :text
 #else
 	. = 0x4000 + SIZEOF_HEADERS;
 #endif
+	
+	/* Make sure the code is aligned reasonably */
+	. = ALIGN(., 16);
+	
 	.init : {
 		*(.init);
Index: uspace/lib/c/generic/async.c
===================================================================
--- uspace/lib/c/generic/async.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/generic/async.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -114,4 +114,5 @@
 #include <stdlib.h>
 #include <macros.h>
+#include "private/libc.h"
 
 #define CLIENT_HASH_TABLE_BUCKETS  32
@@ -2166,5 +2167,6 @@
 int async_share_in_finalize(ipc_callid_t callid, void *src, unsigned int flags)
 {
-	return ipc_share_in_finalize(callid, src, flags);
+	return ipc_answer_3(callid, EOK, (sysarg_t) src, (sysarg_t) flags,
+	    (sysarg_t) __entry);
 }
 
@@ -2233,5 +2235,5 @@
 int async_share_out_finalize(ipc_callid_t callid, void **dst)
 {
-	return ipc_share_out_finalize(callid, dst);
+	return ipc_answer_2(callid, EOK, (sysarg_t) __entry, (sysarg_t) dst);
 }
 
@@ -2317,5 +2319,5 @@
 int async_data_read_finalize(ipc_callid_t callid, const void *src, size_t size)
 {
-	return ipc_data_read_finalize(callid, src, size);
+	return ipc_answer_2(callid, EOK, (sysarg_t) src, (sysarg_t) size);
 }
 
@@ -2420,5 +2422,5 @@
 int async_data_write_finalize(ipc_callid_t callid, void *dst, size_t size)
 {
-	return ipc_data_write_finalize(callid, dst, size);
+	return ipc_answer_2(callid, EOK, (sysarg_t) dst, (sysarg_t) size);
 }
 
Index: uspace/lib/c/generic/device/ahci.c
===================================================================
--- uspace/lib/c/generic/device/ahci.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/c/generic/device/ahci.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,185 @@
+/*
+ * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libc
+ * @{
+ */
+/** @file
+ */
+
+#include <ipc/dev_iface.h>
+#include <assert.h>
+#include <device/ahci.h>
+#include <errno.h>
+#include <async.h>
+#include <ipc/services.h>
+#include <stdio.h>
+#include <as.h>
+
+typedef enum {
+	IPC_M_AHCI_GET_SATA_DEVICE_NAME,
+	IPC_M_AHCI_GET_NUM_BLOCKS,
+	IPC_M_AHCI_GET_BLOCK_SIZE,
+	IPC_M_AHCI_READ_BLOCKS,
+	IPC_M_AHCI_WRITE_BLOCKS,
+} ahci_iface_funcs_t;
+
+#define MAX_NAME_LENGTH  1024
+
+#define LO(ptr) \
+	((uint32_t) (((uint64_t) ((uintptr_t) (ptr))) & 0xffffffff))
+
+#define HI(ptr) \
+	((uint32_t) (((uint64_t) ((uintptr_t) (ptr))) >> 32))
+
+async_sess_t* ahci_get_sess(devman_handle_t funh, char **name)
+{
+	// FIXME: Use a better way than substring match
+	
+	*name = NULL;
+	
+	char devn[MAX_NAME_LENGTH];
+	int rc = devman_fun_get_name(funh, devn, MAX_NAME_LENGTH);
+	if (rc != EOK)
+		return NULL;
+	
+	size_t devn_size = str_size(devn);
+	
+	if ((devn_size > 5) && (str_lcmp(devn, "ahci_", 5) == 0)) {
+		async_sess_t *sess = devman_device_connect(EXCHANGE_PARALLEL,
+		    funh, IPC_FLAG_BLOCKING);
+		
+		if (sess) {
+			*name = str_dup(devn);
+			return sess;
+		}
+	}
+	
+	return NULL;
+}
+
+int ahci_get_sata_device_name(async_sess_t *sess, size_t sata_dev_name_length,
+    char *sata_dev_name)
+{
+	async_exch_t *exch = async_exchange_begin(sess);
+	if (!exch)
+		return EINVAL;
+	
+	aid_t req = async_send_2(exch, DEV_IFACE_ID(AHCI_DEV_IFACE),
+	    IPC_M_AHCI_GET_SATA_DEVICE_NAME, sata_dev_name_length, NULL);
+	
+	async_data_read_start(exch, sata_dev_name, sata_dev_name_length);
+	
+	sysarg_t rc;
+	async_wait_for(req, &rc);
+	
+	return rc;
+}
+
+int ahci_get_num_blocks(async_sess_t *sess, uint64_t *blocks)
+{
+	async_exch_t *exch = async_exchange_begin(sess);
+	if (!exch)
+		return EINVAL;
+	
+	sysarg_t blocks_hi;
+	sysarg_t blocks_lo;
+	int rc = async_req_1_2(exch, DEV_IFACE_ID(AHCI_DEV_IFACE),
+	    IPC_M_AHCI_GET_NUM_BLOCKS, &blocks_hi, &blocks_lo);
+	
+	async_exchange_end(exch);
+	
+	if (rc == EOK) {
+		*blocks = (((uint64_t) blocks_hi) << 32)
+		    | (((uint64_t) blocks_lo) & 0xffffffff);
+	}
+	
+	return rc;
+}
+
+int ahci_get_block_size(async_sess_t *sess, size_t *blocks_size)
+{
+	async_exch_t *exch = async_exchange_begin(sess);
+	if (!exch)
+		return EINVAL;
+	
+	sysarg_t bs;
+	int rc = async_req_1_1(exch, DEV_IFACE_ID(AHCI_DEV_IFACE),
+	    IPC_M_AHCI_GET_BLOCK_SIZE, &bs);
+	
+	async_exchange_end(exch);
+	
+	if (rc == EOK)
+		*blocks_size = (size_t) bs;
+	
+	return rc;
+}
+
+int ahci_read_blocks(async_sess_t *sess, uint64_t blocknum, size_t count,
+    void *buf)
+{
+	async_exch_t *exch = async_exchange_begin(sess);
+	if (!exch)
+		return EINVAL;
+	
+	aid_t req;
+	req = async_send_4(exch, DEV_IFACE_ID(AHCI_DEV_IFACE),
+	    IPC_M_AHCI_READ_BLOCKS, HI(blocknum),  LO(blocknum), count, NULL);
+	
+	async_share_out_start(exch, buf, AS_AREA_READ | AS_AREA_WRITE);
+	
+	async_exchange_end(exch);
+	
+	sysarg_t rc;
+	async_wait_for(req, &rc);
+	
+	return rc;
+}
+
+int ahci_write_blocks(async_sess_t *sess, uint64_t blocknum, size_t count,
+    void* buf)
+{
+	async_exch_t *exch = async_exchange_begin(sess);
+	if (!exch)
+		return EINVAL;
+	
+	aid_t req = async_send_4(exch, DEV_IFACE_ID(AHCI_DEV_IFACE),
+	    IPC_M_AHCI_WRITE_BLOCKS, HI(blocknum),  LO(blocknum), count, NULL);
+	
+	async_share_out_start(exch, buf, AS_AREA_READ | AS_AREA_WRITE);
+	
+	async_exchange_end(exch);
+	
+	sysarg_t rc;
+	async_wait_for(req, &rc);
+	
+	return rc;
+}
+
+/** @}
+ */
Index: uspace/lib/c/generic/ipc.c
===================================================================
--- uspace/lib/c/generic/ipc.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/generic/ipc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -48,5 +48,4 @@
 #include <fibril.h>
 #include <macros.h>
-#include "private/libc.h"
 
 /**
@@ -83,101 +82,4 @@
 
 static atomic_t ipc_futex = FUTEX_INITIALIZER;
-
-/** Fast synchronous call.
- *
- * Only three payload arguments can be passed using this function. However,
- * this function is faster than the generic ipc_call_sync_slow() because
- * the payload is passed directly in registers.
- *
- * @param phoneid Phone handle for the call.
- * @param method  Requested method.
- * @param arg1    Service-defined payload argument.
- * @param arg2    Service-defined payload argument.
- * @param arg3    Service-defined payload argument.
- * @param result1 If non-NULL, the return ARG1 will be stored there.
- * @param result2 If non-NULL, the return ARG2 will be stored there.
- * @param result3 If non-NULL, the return ARG3 will be stored there.
- * @param result4 If non-NULL, the return ARG4 will be stored there.
- * @param result5 If non-NULL, the return ARG5 will be stored there.
- *
- * @return Negative values representing IPC errors.
- * @return Otherwise the RETVAL of the answer.
- *
- */
-int ipc_call_sync_fast(int phoneid, sysarg_t method, sysarg_t arg1,
-    sysarg_t arg2, sysarg_t arg3, sysarg_t *result1, sysarg_t *result2,
-    sysarg_t *result3, sysarg_t *result4, sysarg_t *result5)
-{
-	ipc_call_t resdata;
-	int callres = __SYSCALL6(SYS_IPC_CALL_SYNC_FAST, phoneid, method, arg1,
-	    arg2, arg3, (sysarg_t) &resdata);
-	if (callres)
-		return callres;
-	
-	if (result1)
-		*result1 = IPC_GET_ARG1(resdata);
-	if (result2)
-		*result2 = IPC_GET_ARG2(resdata);
-	if (result3)
-		*result3 = IPC_GET_ARG3(resdata);
-	if (result4)
-		*result4 = IPC_GET_ARG4(resdata);
-	if (result5)
-		*result5 = IPC_GET_ARG5(resdata);
-	
-	return IPC_GET_RETVAL(resdata);
-}
-
-/** Synchronous call transmitting 5 arguments of payload.
- *
- * @param phoneid Phone handle for the call.
- * @param imethod Requested interface and method.
- * @param arg1    Service-defined payload argument.
- * @param arg2    Service-defined payload argument.
- * @param arg3    Service-defined payload argument.
- * @param arg4    Service-defined payload argument.
- * @param arg5    Service-defined payload argument.
- * @param result1 If non-NULL, storage for the first return argument.
- * @param result2 If non-NULL, storage for the second return argument.
- * @param result3 If non-NULL, storage for the third return argument.
- * @param result4 If non-NULL, storage for the fourth return argument.
- * @param result5 If non-NULL, storage for the fifth return argument.
- *
- * @return Negative values representing IPC errors.
- * @return Otherwise the RETVAL of the answer.
- *
- */
-int ipc_call_sync_slow(int phoneid, sysarg_t imethod, sysarg_t arg1,
-    sysarg_t arg2, sysarg_t arg3, sysarg_t arg4, sysarg_t arg5,
-    sysarg_t *result1, sysarg_t *result2, sysarg_t *result3, sysarg_t *result4,
-    sysarg_t *result5)
-{
-	ipc_call_t data;
-	
-	IPC_SET_IMETHOD(data, imethod);
-	IPC_SET_ARG1(data, arg1);
-	IPC_SET_ARG2(data, arg2);
-	IPC_SET_ARG3(data, arg3);
-	IPC_SET_ARG4(data, arg4);
-	IPC_SET_ARG5(data, arg5);
-	
-	int callres = __SYSCALL3(SYS_IPC_CALL_SYNC_SLOW, phoneid,
-	    (sysarg_t) &data, (sysarg_t) &data);
-	if (callres)
-		return callres;
-	
-	if (result1)
-		*result1 = IPC_GET_ARG1(data);
-	if (result2)
-		*result2 = IPC_GET_ARG2(data);
-	if (result3)
-		*result3 = IPC_GET_ARG3(data);
-	if (result4)
-		*result4 = IPC_GET_ARG4(data);
-	if (result5)
-		*result5 = IPC_GET_ARG5(data);
-	
-	return IPC_GET_RETVAL(data);
-}
 
 /** Send asynchronous message via syscall.
@@ -611,98 +513,4 @@
 }
 
-/** Request callback connection.
- *
- * The @a task_id and @a phonehash identifiers returned
- * by the kernel can be used for connection tracking.
- *
- * @param phoneid   Phone handle used for contacting the other side.
- * @param arg1      User defined argument.
- * @param arg2      User defined argument.
- * @param arg3      User defined argument.
- * @param task_id   Identifier of the client task.
- * @param phonehash Opaque identifier of the phone that will
- *                  be used for incoming calls.
- *
- * @return Zero on success or a negative error code.
- *
- */
-int ipc_connect_to_me(int phoneid, sysarg_t arg1, sysarg_t arg2, sysarg_t arg3,
-    task_id_t *task_id, sysarg_t *phonehash)
-{
-	ipc_call_t data;
-	int rc = __SYSCALL6(SYS_IPC_CALL_SYNC_FAST, phoneid,
-	    IPC_M_CONNECT_TO_ME, arg1, arg2, arg3, (sysarg_t) &data);
-	if (rc == EOK) {
-		*task_id = data.in_task_id;
-		*phonehash = IPC_GET_ARG5(data);
-	}	
-	return rc;
-}
-
-/** Request cloned connection.
- *
- * @param phoneid Phone handle used for contacting the other side.
- *
- * @return Cloned phone handle on success or a negative error code.
- *
- */
-int ipc_clone_establish(int phoneid)
-{
-	sysarg_t newphid;
-	int res = ipc_call_sync_0_5(phoneid, IPC_M_CLONE_ESTABLISH, NULL,
-	    NULL, NULL, NULL, &newphid);
-	if (res)
-		return res;
-	
-	return newphid;
-}
-
-/** Request new connection.
- *
- * @param phoneid Phone handle used for contacting the other side.
- * @param arg1    User defined argument.
- * @param arg2    User defined argument.
- * @param arg3    User defined argument.
- *
- * @return New phone handle on success or a negative error code.
- *
- */
-int ipc_connect_me_to(int phoneid, sysarg_t arg1, sysarg_t arg2, sysarg_t arg3)
-{
-	sysarg_t newphid;
-	int res = ipc_call_sync_3_5(phoneid, IPC_M_CONNECT_ME_TO, arg1, arg2, arg3,
-	    NULL, NULL, NULL, NULL, &newphid);
-	if (res)
-		return res;
-	
-	return newphid;
-}
-
-/** Request new connection (blocking)
- *
- * If the connection is not available at the moment, the
- * call should block. This has to be, however, implemented
- * on the server side.
- *
- * @param phoneid Phone handle used for contacting the other side.
- * @param arg1    User defined argument.
- * @param arg2    User defined argument.
- * @param arg3    User defined argument.
- *
- * @return New phone handle on success or a negative error code.
- *
- */
-int ipc_connect_me_to_blocking(int phoneid, sysarg_t arg1, sysarg_t arg2,
-    sysarg_t arg3)
-{
-	sysarg_t newphid;
-	int res = ipc_call_sync_4_5(phoneid, IPC_M_CONNECT_ME_TO, arg1, arg2, arg3,
-	    IPC_FLAG_BLOCKING, NULL, NULL, NULL, NULL, &newphid);
-	if (res)
-		return res;
-	
-	return newphid;
-}
-
 /** Hang up a phone.
  *
@@ -758,148 +566,4 @@
 }
 
-/** Wrapper for IPC_M_SHARE_IN calls.
- *
- * @param phoneid Phone that will be used to contact the receiving side.
- * @param size    Size of the destination address space area.
- * @param arg     User defined argument.
- * @param flags   Storage for received flags. Can be NULL.
- * @param dst     Destination address space area base. Cannot be NULL.
- *
- * @return Zero on success or a negative error code from errno.h.
- *
- */
-int ipc_share_in_start(int phoneid, size_t size, sysarg_t arg,
-    unsigned int *flags, void **dst)
-{
-	sysarg_t _flags = 0;
-	sysarg_t _dst = (sysarg_t) -1;
-	int res = ipc_call_sync_2_4(phoneid, IPC_M_SHARE_IN, (sysarg_t) size,
-	    arg, NULL, &_flags, NULL, &_dst);
-	
-	if (flags)
-		*flags = (unsigned int) _flags;
-	
-	*dst = (void *) _dst;
-	return res;
-}
-
-/** Wrapper for answering the IPC_M_SHARE_IN calls.
- *
- * This wrapper only makes it more comfortable to answer IPC_M_SHARE_IN
- * calls so that the user doesn't have to remember the meaning of each
- * IPC argument.
- *
- * @param callid Hash of the IPC_M_DATA_READ call to answer.
- * @param src    Source address space base.
- * @param flags Flags to be used for sharing. Bits can be only cleared.
- *
- * @return Zero on success or a value from @ref errno.h on failure.
- *
- */
-int ipc_share_in_finalize(ipc_callid_t callid, void *src, unsigned int flags)
-{
-	return ipc_answer_3(callid, EOK, (sysarg_t) src, (sysarg_t) flags,
-	    (sysarg_t) __entry);
-}
-
-/** Wrapper for IPC_M_SHARE_OUT calls.
- *
- * @param phoneid Phone that will be used to contact the receiving side.
- * @param src     Source address space area base address.
- * @param flags   Flags to be used for sharing. Bits can be only cleared.
- *
- * @return Zero on success or a negative error code from errno.h.
- *
- */
-int ipc_share_out_start(int phoneid, void *src, unsigned int flags)
-{
-	return ipc_call_sync_3_0(phoneid, IPC_M_SHARE_OUT, (sysarg_t) src, 0,
-	    (sysarg_t) flags);
-}
-
-/** Wrapper for answering the IPC_M_SHARE_OUT calls.
- *
- * This wrapper only makes it more comfortable to answer IPC_M_SHARE_OUT
- * calls so that the user doesn't have to remember the meaning of each
- * IPC argument.
- *
- * @param callid Hash of the IPC_M_DATA_WRITE call to answer.
- * @param dst    Destination address space area base address.
- *
- * @return Zero on success or a value from @ref errno.h on failure.
- *
- */
-int ipc_share_out_finalize(ipc_callid_t callid, void **dst)
-{
-	return ipc_answer_2(callid, EOK, (sysarg_t) __entry, (sysarg_t) dst);
-}
-
-/** Wrapper for IPC_M_DATA_READ calls.
- *
- * @param phoneid Phone that will be used to contact the receiving side.
- * @param dst     Address of the beginning of the destination buffer.
- * @param size    Size of the destination buffer.
- *
- * @return Zero on success or a negative error code from errno.h.
- *
- */
-int ipc_data_read_start(int phoneid, void *dst, size_t size)
-{
-	return ipc_call_sync_2_0(phoneid, IPC_M_DATA_READ, (sysarg_t) dst,
-	    (sysarg_t) size);
-}
-
-/** Wrapper for answering the IPC_M_DATA_READ calls.
- *
- * This wrapper only makes it more comfortable to answer IPC_M_DATA_READ
- * calls so that the user doesn't have to remember the meaning of each
- * IPC argument.
- *
- * @param callid Hash of the IPC_M_DATA_READ call to answer.
- * @param src    Source address for the IPC_M_DATA_READ call.
- * @param size   Size for the IPC_M_DATA_READ call. Can be smaller than
- *               the maximum size announced by the sender.
- *
- * @return Zero on success or a value from @ref errno.h on failure.
- *
- */
-int ipc_data_read_finalize(ipc_callid_t callid, const void *src, size_t size)
-{
-	return ipc_answer_2(callid, EOK, (sysarg_t) src, (sysarg_t) size);
-}
-
-/** Wrapper for IPC_M_DATA_WRITE calls.
- *
- * @param phoneid Phone that will be used to contact the receiving side.
- * @param src     Address of the beginning of the source buffer.
- * @param size    Size of the source buffer.
- *
- * @return Zero on success or a negative error code from errno.h.
- *
- */
-int ipc_data_write_start(int phoneid, const void *src, size_t size)
-{
-	return ipc_call_sync_2_0(phoneid, IPC_M_DATA_WRITE, (sysarg_t) src,
-	    (sysarg_t) size);
-}
-
-/** Wrapper for answering the IPC_M_DATA_WRITE calls.
- *
- * This wrapper only makes it more comfortable to answer IPC_M_DATA_WRITE
- * calls so that the user doesn't have to remember the meaning of each
- * IPC argument.
- *
- * @param callid Hash of the IPC_M_DATA_WRITE call to answer.
- * @param dst    Final destination address for the IPC_M_DATA_WRITE call.
- * @param size   Final size for the IPC_M_DATA_WRITE call.
- *
- * @return Zero on success or a value from @ref errno.h on failure.
- *
- */
-int ipc_data_write_finalize(ipc_callid_t callid, void *dst, size_t size)
-{
-	return ipc_answer_2(callid, EOK, (sysarg_t) dst, (sysarg_t) size);
-}
-
 /** Connect to a task specified by id.
  *
Index: uspace/lib/c/generic/malloc.c
===================================================================
--- uspace/lib/c/generic/malloc.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/generic/malloc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -109,4 +109,7 @@
 	(((uintptr_t) (area)->end) - sizeof(heap_block_foot_t))
 
+#define AREA_LAST_BLOCK_HEAD(area) \
+	((uintptr_t) BLOCK_HEAD(((heap_block_foot_t *) AREA_LAST_BLOCK_FOOT(area))))
+
 /** Get header in heap block.
  *
@@ -346,8 +349,18 @@
 		return false;
 	
-	/* Add new free block */
-	size_t net_size = (size_t) (end - area->end);
-	if (net_size > 0)
-		block_init(area->end, net_size, true, area);
+	heap_block_head_t *last_head =
+	    (heap_block_head_t *) AREA_LAST_BLOCK_HEAD(area);
+	
+	if (last_head->free) {
+		/* Add the new space to the last block. */
+		size_t net_size = (size_t) (end - area->end) + last_head->size;
+		malloc_assert(net_size > 0);
+		block_init(last_head, net_size, true, area);
+	} else {
+		/* Add new free block */
+		size_t net_size = (size_t) (end - area->end);
+		if (net_size > 0)
+			block_init(area->end, net_size, true, area);
+	}
 	
 	/* Update heap area parameters */
@@ -355,27 +368,4 @@
 	
 	return true;
-}
-
-/** Try to enlarge any of the heap areas
- *
- * Should be called only inside the critical section.
- *
- * @param size Gross size of item to allocate (bytes).
- *
- */
-static bool heap_grow(size_t size)
-{
-	if (size == 0)
-		return true;
-	
-	/* First try to enlarge some existing area */
-	for (heap_area_t *area = first_heap_area; area != NULL;
-	    area = area->next) {
-		if (area_grow(area, size))
-			return true;
-	}
-	
-	/* Eventually try to create a new area */
-	return area_create(AREA_OVERHEAD(size));
 }
 
@@ -661,4 +651,50 @@
 }
 
+/** Try to enlarge any of the heap areas.
+ *
+ * If successful, allocate block of the given size in the area.
+ * Should be called only inside the critical section.
+ *
+ * @param size  Gross size of item to allocate (bytes).
+ * @param align Memory address alignment.
+ *
+ * @return Allocated block.
+ * @return NULL on failure.
+ *
+ */
+static void *heap_grow_and_alloc(size_t size, size_t align)
+{
+	if (size == 0)
+		return NULL;
+	
+	/* First try to enlarge some existing area */
+	for (heap_area_t *area = first_heap_area; area != NULL;
+	    area = area->next) {
+		
+		if (area_grow(area, size + align)) {
+			heap_block_head_t *first =
+			    (heap_block_head_t *) AREA_LAST_BLOCK_HEAD(area);
+			
+			void *addr =
+			    malloc_area(area, first, NULL, size, align);
+			malloc_assert(addr != NULL);
+			return addr;
+		}
+	}
+	
+	/* Eventually try to create a new area */
+	if (area_create(AREA_OVERHEAD(size + align))) {
+		heap_block_head_t *first =
+		    (heap_block_head_t *) AREA_FIRST_BLOCK_HEAD(last_heap_area);
+		
+		void *addr =
+		    malloc_area(last_heap_area, first, NULL, size, align);
+		malloc_assert(addr != NULL);
+		return addr;
+	}
+	
+	return NULL;
+}
+
 /** Allocate a memory block
  *
@@ -679,16 +715,22 @@
 	
 	size_t falign = lcm(align, BASE_ALIGN);
-	size_t real_size = GROSS_SIZE(ALIGN_UP(size, falign));
-	
-	bool retry = false;
-	heap_block_head_t *split;
-	
-loop:
+	
+	/* Check for integer overflow. */
+	if (falign < align)
+		return NULL;
+	
+	/*
+	 * The size of the allocated block needs to be naturally
+	 * aligned, because the footer structure also needs to reside
+	 * on a naturally aligned address in order to avoid unaligned
+	 * memory accesses.
+	 */
+	size_t gross_size = GROSS_SIZE(ALIGN_UP(size, BASE_ALIGN));
 	
 	/* Try the next fit approach */
-	split = next_fit;
+	heap_block_head_t *split = next_fit;
 	
 	if (split != NULL) {
-		void *addr = malloc_area(split->area, split, NULL, real_size,
+		void *addr = malloc_area(split->area, split, NULL, gross_size,
 		    falign);
 		
@@ -703,5 +745,5 @@
 		    AREA_FIRST_BLOCK_HEAD(area);
 		
-		void *addr = malloc_area(area, first, split, real_size,
+		void *addr = malloc_area(area, first, split, gross_size,
 		    falign);
 		
@@ -710,13 +752,6 @@
 	}
 	
-	if (!retry) {
-		/* Try to grow the heap space */
-		if (heap_grow(real_size)) {
-			retry = true;
-			goto loop;
-		}
-	}
-	
-	return NULL;
+	/* Finally, try to grow heap space and allocate in the new area. */
+	return heap_grow_and_alloc(gross_size, falign);
 }
 
@@ -731,4 +766,6 @@
 void *calloc(const size_t nmemb, const size_t size)
 {
+	// FIXME: Check for overflow
+	
 	void *block = malloc(nmemb * size);
 	if (block == NULL)
@@ -870,5 +907,5 @@
 	if (addr == NULL)
 		return;
-
+	
 	futex_down(&malloc_futex);
 	
Index: uspace/lib/c/generic/str.c
===================================================================
--- uspace/lib/c/generic/str.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/generic/str.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -428,12 +428,17 @@
  *
  * Do a char-by-char comparison of two NULL-terminated strings.
- * The strings are considered equal iff they consist of the same
- * characters on the minimum of their lengths.
+ * The strings are considered equal iff their length is equal
+ * and both strings consist of the same sequence of characters.
+ *
+ * A string S1 is less than another string S2 if it has a character with
+ * lower value at the first character position where the strings differ.
+ * If the strings differ in length, the shorter one is treated as if
+ * padded by characters with a value of zero.
  *
  * @param s1 First string to compare.
  * @param s2 Second string to compare.
  *
- * @return 0 if the strings are equal, -1 if first is smaller,
- *         1 if second smaller.
+ * @return 0 if the strings are equal, -1 if the first is less than the second,
+ *         1 if the second is less than the first.
  *
  */
@@ -466,6 +471,14 @@
  *
  * Do a char-by-char comparison of two NULL-terminated strings.
- * The strings are considered equal iff they consist of the same
- * characters on the minimum of their lengths and the length limit.
+ * The strings are considered equal iff
+ * min(str_length(s1), max_len) == min(str_length(s2), max_len)
+ * and both strings consist of the same sequence of characters,
+ * up to max_len characters.
+ *
+ * A string S1 is less than another string S2 if it has a character with
+ * lower value at the first character position where the strings differ.
+ * If the strings differ in length, the shorter one is treated as if
+ * padded by characters with a value of zero. Only the first max_len
+ * characters are considered.
  *
  * @param s1      First string to compare.
@@ -473,6 +486,6 @@
  * @param max_len Maximum number of characters to consider.
  *
- * @return 0 if the strings are equal, -1 if first is smaller,
- *         1 if second smaller.
+ * @return 0 if the strings are equal, -1 if the first is less than the second,
+ *         1 if the second is less than the first.
  *
  */
@@ -508,4 +521,40 @@
 	return 0;
 
+}
+
+/** Test whether p is a prefix of s.
+ *
+ * Do a char-by-char comparison of two NULL-terminated strings
+ * and determine if p is a prefix of s.
+ *
+ * @param s The string in which to look
+ * @param p The string to check if it is a prefix of s
+ *
+ * @return true iff p is prefix of s else false
+ *
+ */
+bool str_test_prefix(const char *s, const char *p)
+{
+	wchar_t c1 = 0;
+	wchar_t c2 = 0;
+	
+	size_t off1 = 0;
+	size_t off2 = 0;
+
+	while (true) {
+		c1 = str_decode(s, &off1, STR_NO_LIMIT);
+		c2 = str_decode(p, &off2, STR_NO_LIMIT);
+		
+		if (c2 == 0)
+			return true;
+
+		if (c1 != c2)
+			return false;
+		
+		if (c1 == 0)
+			break;
+	}
+
+	return false;
 }
 
@@ -1085,5 +1134,5 @@
 		c = (c >= 'a' ? c - 'a' + 10 : (c >= 'A' ? c - 'A' + 10 :
 		    (c <= '9' ? c - '0' : 0xff)));
-		if (c > base) {
+		if (c >= base) {
 			break;
 		}
Index: uspace/lib/c/include/device/ahci.h
===================================================================
--- uspace/lib/c/include/device/ahci.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/c/include/device/ahci.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libc
+ * @{
+ */
+/** @file
+ * @brief AHCI interface definition.
+ */
+
+#ifndef LIBC_DEVICE_AHCI_H_
+#define LIBC_DEVICE_AHCI_H_
+
+#include <async.h>
+#include <devman.h>
+
+extern async_sess_t* ahci_get_sess(devman_handle_t, char **);
+
+extern int ahci_get_sata_device_name(async_sess_t *, size_t, char *);
+extern int ahci_get_num_blocks(async_sess_t *, uint64_t *);
+extern int ahci_get_block_size(async_sess_t *, size_t *);
+extern int ahci_read_blocks(async_sess_t *, uint64_t, size_t, void *);
+extern int ahci_write_blocks(async_sess_t *, uint64_t, size_t, void *);
+
+#endif
+
+/** @}
+ */
Index: uspace/lib/c/include/ipc/dev_iface.h
===================================================================
--- uspace/lib/c/include/ipc/dev_iface.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/include/ipc/dev_iface.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -51,4 +51,6 @@
 	/** Interface provided by USB HID devices. */
 	USBHID_DEV_IFACE,
+	/** Interface provided by AHCI devices. */
+	AHCI_DEV_IFACE,
 
 	DEV_IFACE_MAX
Index: uspace/lib/c/include/ipc/ipc.h
===================================================================
--- uspace/lib/c/include/ipc/ipc.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/include/ipc/ipc.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -47,140 +47,4 @@
 
 typedef void (*ipc_async_callback_t)(void *, int, ipc_call_t *);
-
-/*
- * User-friendly wrappers for ipc_call_sync_fast() and ipc_call_sync_slow().
- * They are in the form ipc_call_sync_m_n(), where m denotes the number of
- * arguments of payload and n denotes number of return values. Whenever
- * possible, the fast version is used.
- */
-
-#define ipc_call_sync_0_0(phoneid, method) \
-	ipc_call_sync_fast((phoneid), (method), 0, 0, 0, 0, 0, 0, 0, 0)
-#define ipc_call_sync_0_1(phoneid, method, res1) \
-	ipc_call_sync_fast((phoneid), (method), 0, 0, 0, (res1), 0, 0, 0, 0)
-#define ipc_call_sync_0_2(phoneid, method, res1, res2) \
-	ipc_call_sync_fast((phoneid), (method), 0, 0, 0, (res1), (res2), 0, 0, 0)
-#define ipc_call_sync_0_3(phoneid, method, res1, res2, res3) \
-	ipc_call_sync_fast((phoneid), (method), 0, 0, 0, (res1), (res2), (res3), \
-	    0, 0)
-#define ipc_call_sync_0_4(phoneid, method, res1, res2, res3, res4) \
-	ipc_call_sync_fast((phoneid), (method), 0, 0, 0, (res1), (res2), (res3), \
-	    (res4), 0)
-#define ipc_call_sync_0_5(phoneid, method, res1, res2, res3, res4, res5) \
-	ipc_call_sync_fast((phoneid), (method), 0, 0, 0, (res1), (res2), (res3), \
-	    (res4), (res5))
-
-#define ipc_call_sync_1_0(phoneid, method, arg1) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), 0, 0, 0, 0, 0, 0, 0)
-#define ipc_call_sync_1_1(phoneid, method, arg1, res1) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), 0, 0, (res1), 0, 0, 0, 0)
-#define ipc_call_sync_1_2(phoneid, method, arg1, res1, res2) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), 0, 0, (res1), (res2), 0, \
-	    0, 0)
-#define ipc_call_sync_1_3(phoneid, method, arg1, res1, res2, res3) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), 0, 0, (res1), (res2), \
-	    (res3), 0, 0)
-#define ipc_call_sync_1_4(phoneid, method, arg1, res1, res2, res3, res4) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), 0, 0, (res1), (res2), \
-	    (res3), (res4), 0)
-#define ipc_call_sync_1_5(phoneid, method, arg1, res1, res2, res3, res4, \
-    res5) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), 0, 0, (res1), (res2), \
-	    (res3), (res4), (res5))
-
-#define ipc_call_sync_2_0(phoneid, method, arg1, arg2) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), 0, 0, 0, 0, \
-	    0, 0)
-#define ipc_call_sync_2_1(phoneid, method, arg1, arg2, res1) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), 0, (res1), 0, 0, \
-	    0, 0)
-#define ipc_call_sync_2_2(phoneid, method, arg1, arg2, res1, res2) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), 0, (res1), \
-	    (res2), 0, 0, 0)
-#define ipc_call_sync_2_3(phoneid, method, arg1, arg2, res1, res2, res3) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), 0, (res1), \
-	    (res2), (res3), 0, 0)
-#define ipc_call_sync_2_4(phoneid, method, arg1, arg2, res1, res2, res3, \
-    res4) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), 0, (res1), \
-	    (res2), (res3), (res4), 0)
-#define ipc_call_sync_2_5(phoneid, method, arg1, arg2, res1, res2, res3, \
-    res4, res5)\
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), 0, (res1), \
-	    (res2), (res3), (res4), (res5))
-
-#define ipc_call_sync_3_0(phoneid, method, arg1, arg2, arg3) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), (arg3), 0, 0, 0, \
-	    0, 0)
-#define ipc_call_sync_3_1(phoneid, method, arg1, arg2, arg3, res1) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), (arg3), (res1), \
-	    0, 0, 0, 0)
-#define ipc_call_sync_3_2(phoneid, method, arg1, arg2, arg3, res1, res2) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), (arg3), (res1), \
-	    (res2), 0, 0, 0)
-#define ipc_call_sync_3_3(phoneid, method, arg1, arg2, arg3, res1, res2, \
-    res3) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), (arg3), \
-	    (res1), (res2), (res3), 0, 0)
-#define ipc_call_sync_3_4(phoneid, method, arg1, arg2, arg3, res1, res2, \
-    res3, res4) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), (arg3), \
-	    (res1), (res2), (res3), (res4), 0)
-#define ipc_call_sync_3_5(phoneid, method, arg1, arg2, arg3, res1, res2, \
-    res3, res4, res5) \
-	ipc_call_sync_fast((phoneid), (method), (arg1), (arg2), (arg3), \
-	    (res1), (res2), (res3), (res4), (res5))
-
-#define ipc_call_sync_4_0(phoneid, method, arg1, arg2, arg3, arg4) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), (arg4), 0, \
-	    0, 0, 0, 0, 0)
-#define ipc_call_sync_4_1(phoneid, method, arg1, arg2, arg3, arg4, res1) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), (arg4), 0, \
-	    (res1), 0, 0, 0, 0)
-#define ipc_call_sync_4_2(phoneid, method, arg1, arg2, arg3, arg4, res1, res2) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), (arg4), 0, \
-	    (res1), (res2), 0, 0, 0)
-#define ipc_call_sync_4_3(phoneid, method, arg1, arg2, arg3, arg4, res1, res2, \
-    res3) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), \
-	    (arg4), 0, (res1), (res2), (res3), 0, 0)
-#define ipc_call_sync_4_4(phoneid, method, arg1, arg2, arg3, arg4, res1, res2, \
-    res3, res4) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), \
-	    (arg4), 0, (res1), (res2), (res3), (res4), 0)
-#define ipc_call_sync_4_5(phoneid, method, arg1, arg2, arg3, arg4, res1, res2, \
-    res3, res4, res5) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), \
-	    (arg4), 0, (res1), (res2), (res3), (res4), (res5))
-
-#define ipc_call_sync_5_0(phoneid, method, arg1, arg2, arg3, arg4, arg5) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), (arg4), \
-	    (arg5), 0, 0, 0, 0, 0)
-#define ipc_call_sync_5_1(phoneid, method, arg1, arg2, arg3, arg4, arg5, res1) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), (arg4), \
-	    (arg5), (res1), 0, 0, 0, 0)
-#define ipc_call_sync_5_2(phoneid, method, arg1, arg2, arg3, arg4, arg5, res1, \
-    res2) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), \
-	    (arg4), (arg5), (res1), (res2), 0, 0, 0)
-#define ipc_call_sync_5_3(phoneid, method, arg1, arg2, arg3, arg4, arg5, res1, \
-    res2, res3) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), \
-	    (arg4), (arg5), (res1), (res2), (res3), 0, 0)
-#define ipc_call_sync_5_4(phoneid, method, arg1, arg2, arg3, arg4, arg5, res1, \
-    res2, res3, res4) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), \
-	    (arg4), (arg5), (res1), (res2), (res3), (res4), 0)
-#define ipc_call_sync_5_5(phoneid, method, arg1, arg2, arg3, arg4, arg5, res1, \
-    res2, res3, res4, res5) \
-	ipc_call_sync_slow((phoneid), (method), (arg1), (arg2), (arg3), \
-	    (arg4), (arg5), (res1), (res2), (res3), (res4), (res5))
-
-extern int ipc_call_sync_fast(int, sysarg_t, sysarg_t, sysarg_t, sysarg_t,
-    sysarg_t *, sysarg_t *, sysarg_t *, sysarg_t *, sysarg_t *);
-
-extern int ipc_call_sync_slow(int, sysarg_t, sysarg_t, sysarg_t, sysarg_t,
-    sysarg_t, sysarg_t, sysarg_t *, sysarg_t *, sysarg_t *, sysarg_t *,
-    sysarg_t *);
 
 extern ipc_callid_t ipc_wait_cycle(ipc_call_t *, sysarg_t, unsigned int);
@@ -254,10 +118,4 @@
     sysarg_t, sysarg_t, void *, ipc_async_callback_t, bool);
 
-extern int ipc_clone_establish(int);
-extern int ipc_connect_to_me(int, sysarg_t, sysarg_t, sysarg_t, task_id_t *,
-    sysarg_t *);
-extern int ipc_connect_me_to(int, sysarg_t, sysarg_t, sysarg_t);
-extern int ipc_connect_me_to_blocking(int, sysarg_t, sysarg_t, sysarg_t);
-
 extern int ipc_hangup(int);
 
@@ -267,26 +125,4 @@
     sysarg_t, sysarg_t, sysarg_t, unsigned int);
 
-/*
- * User-friendly wrappers for ipc_share_in_start().
- */
-
-#define ipc_share_in_start_0_0(phoneid, size, dst) \
-	ipc_share_in_start((phoneid), (size), 0, NULL, (dst))
-#define ipc_share_in_start_0_1(phoneid, size, flags, dst) \
-	ipc_share_in_start((phoneid), (size), 0, (flags), (dst))
-#define ipc_share_in_start_1_0(phoneid, size, arg, dst) \
-	ipc_share_in_start((phoneid), (size), (arg), NULL, (dst))
-#define ipc_share_in_start_1_1(phoneid, size, arg, flags, dst) \
-	ipc_share_in_start((phoneid), (size), (arg), (flags), (dst))
-
-extern int ipc_share_in_start(int, size_t, sysarg_t, unsigned int *, void **);
-extern int ipc_share_in_finalize(ipc_callid_t, void *, unsigned int);
-extern int ipc_share_out_start(int, void *, unsigned int);
-extern int ipc_share_out_finalize(ipc_callid_t, void **);
-extern int ipc_data_read_start(int, void *, size_t);
-extern int ipc_data_read_finalize(ipc_callid_t, const void *, size_t);
-extern int ipc_data_write_start(int, const void *, size_t);
-extern int ipc_data_write_finalize(ipc_callid_t, void *, size_t);
-
 extern int ipc_connect_kbox(task_id_t);
 
Index: uspace/lib/c/include/str.h
===================================================================
--- uspace/lib/c/include/str.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/c/include/str.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -79,4 +79,6 @@
 extern int str_lcmp(const char *s1, const char *s2, size_t max_len);
 
+extern bool str_test_prefix(const char *s, const char *p);
+
 extern void str_cpy(char *dest, size_t size, const char *src);
 extern void str_ncpy(char *dest, size_t size, const char *src, size_t n);
Index: uspace/lib/clui/tinput.c
===================================================================
--- uspace/lib/clui/tinput.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/clui/tinput.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -601,5 +601,9 @@
 	
 	unsigned int cols = max(1, (ti->con_cols + 1) / (max_length + 1));
-	unsigned int col_width = ti->con_cols / cols;
+	unsigned int padding = 0;
+	if ((cols * max_length) + (cols - 1) < ti->con_cols) {
+		padding = ti->con_cols - (cols * max_length) - (cols - 1);
+	}
+	unsigned int col_width = max_length + padding / cols;
 	unsigned int rows = cnum / cols + ((cnum % cols) != 0);
 	
Index: uspace/lib/drv/Makefile
===================================================================
--- uspace/lib/drv/Makefile	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/drv/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -44,5 +44,6 @@
 	generic/remote_pci.c \
 	generic/remote_usbhc.c \
-	generic/remote_usbhid.c
+	generic/remote_usbhid.c \
+	generic/remote_ahci.c
 
 include $(USPACE_PREFIX)/Makefile.common
Index: uspace/lib/drv/generic/dev_iface.c
===================================================================
--- uspace/lib/drv/generic/dev_iface.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/drv/generic/dev_iface.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -46,4 +46,5 @@
 #include "remote_usbhid.h"
 #include "remote_pci.h"
+#include "remote_ahci.h"
 
 static iface_dipatch_table_t remote_ifaces = {
@@ -55,5 +56,6 @@
 		&remote_usb_iface,
 		&remote_usbhc_iface,
-		&remote_usbhid_iface
+		&remote_usbhid_iface,
+		&remote_ahci_iface
 	}
 };
Index: uspace/lib/drv/generic/remote_ahci.c
===================================================================
--- uspace/lib/drv/generic/remote_ahci.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/drv/generic/remote_ahci.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,208 @@
+/*
+  * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libdrv
+ * @{
+ */
+/** @file
+ */
+
+#include <async.h>
+#include <errno.h>
+#include <stdio.h>
+#include "ahci_iface.h"
+#include "ddf/driver.h"
+
+typedef enum {
+	IPC_M_AHCI_GET_SATA_DEVICE_NAME,
+	IPC_M_AHCI_GET_NUM_BLOCKS,
+	IPC_M_AHCI_GET_BLOCK_SIZE,
+	IPC_M_AHCI_READ_BLOCKS,
+	IPC_M_AHCI_WRITE_BLOCKS
+} ahci_iface_funcs_t;
+
+#define LO(ptr) \
+	((uint32_t) (((uint64_t) ((uintptr_t) (ptr))) & 0xffffffff))
+
+#define HI(ptr) \
+	((uint32_t) (((uint64_t) ((uintptr_t) (ptr))) >> 32))
+
+static void remote_ahci_get_sata_device_name(ddf_fun_t *, void *, ipc_callid_t,
+    ipc_call_t *);
+static void remote_ahci_get_num_blocks(ddf_fun_t *, void *, ipc_callid_t,
+    ipc_call_t *);
+static void remote_ahci_get_block_size(ddf_fun_t *, void *, ipc_callid_t,
+    ipc_call_t *);
+static void remote_ahci_read_blocks(ddf_fun_t *, void *, ipc_callid_t,
+    ipc_call_t *);
+static void remote_ahci_write_blocks(ddf_fun_t *, void *, ipc_callid_t,
+    ipc_call_t *);
+
+/** Remote AHCI interface operations. */
+static remote_iface_func_ptr_t remote_ahci_iface_ops [] = {
+	[IPC_M_AHCI_GET_SATA_DEVICE_NAME] = remote_ahci_get_sata_device_name,
+	[IPC_M_AHCI_GET_NUM_BLOCKS] = remote_ahci_get_num_blocks,
+	[IPC_M_AHCI_GET_BLOCK_SIZE] = remote_ahci_get_block_size,
+	[IPC_M_AHCI_READ_BLOCKS] = remote_ahci_read_blocks,
+	[IPC_M_AHCI_WRITE_BLOCKS] = remote_ahci_write_blocks
+};
+
+/** Remote AHCI interface structure.
+ */
+remote_iface_t remote_ahci_iface = {
+	.method_count = sizeof(remote_ahci_iface_ops) /
+	    sizeof(remote_ahci_iface_ops[0]),
+	.methods = remote_ahci_iface_ops
+};
+
+void remote_ahci_get_sata_device_name(ddf_fun_t *fun, void *iface,
+    ipc_callid_t callid, ipc_call_t *call)
+{
+	const ahci_iface_t *ahci_iface = (ahci_iface_t *) iface;
+	
+	if (ahci_iface->get_sata_device_name == NULL) {
+		async_answer_0(callid, ENOTSUP);
+		return;
+	}
+	
+	const size_t sata_dev_name_length =
+	    (size_t) DEV_IPC_GET_ARG1(*call);
+	
+	char* sata_dev_name = malloc(sata_dev_name_length);
+	
+	const int ret = ahci_iface->get_sata_device_name(fun,
+	    sata_dev_name_length, sata_dev_name);
+	
+	size_t real_size;
+	ipc_callid_t cid;
+	if ((async_data_read_receive(&cid, &real_size)) &&
+	    (real_size == sata_dev_name_length))
+		async_data_read_finalize(cid, sata_dev_name, sata_dev_name_length);
+	
+	async_answer_0(callid, ret);
+}
+
+static void remote_ahci_get_num_blocks(ddf_fun_t *fun, void *iface,
+    ipc_callid_t callid, ipc_call_t *call)
+{
+	const ahci_iface_t *ahci_iface = (ahci_iface_t *) iface;
+	
+	if (ahci_iface->get_num_blocks == NULL) {
+		async_answer_0(callid, ENOTSUP);
+		return;
+	}
+	
+	uint64_t blocks;
+	const int ret = ahci_iface->get_num_blocks(fun, &blocks);
+	
+	if (ret != EOK)
+		async_answer_0(callid, ret);
+	else
+		async_answer_2(callid, EOK, HI(blocks), LO(blocks));
+}
+
+static void remote_ahci_get_block_size(ddf_fun_t *fun, void *iface,
+    ipc_callid_t callid, ipc_call_t *call)
+{
+	const ahci_iface_t *ahci_iface = (ahci_iface_t *) iface;
+	
+	if (ahci_iface->get_block_size == NULL) {
+		async_answer_0(callid, ENOTSUP);
+		return;
+	}
+	
+	size_t blocks;
+	const int ret = ahci_iface->get_block_size(fun, &blocks);
+	
+	if (ret != EOK)
+		async_answer_0(callid, ret);
+	else
+		async_answer_1(callid, EOK, blocks);
+}
+
+void remote_ahci_read_blocks(ddf_fun_t *fun, void *iface,
+    ipc_callid_t callid, ipc_call_t *call)
+{
+	const ahci_iface_t *ahci_iface = (ahci_iface_t *) iface;
+	
+	if (ahci_iface->read_blocks == NULL) {
+		async_answer_0(callid, ENOTSUP);
+		return;
+	}
+	
+	size_t maxblock_size;
+	unsigned int flags;
+	
+	ipc_callid_t cid;
+	async_share_out_receive(&cid, &maxblock_size, &flags);
+	
+	void *buf;
+	async_share_out_finalize(cid, &buf);
+	
+	const uint64_t blocknum =
+	    (((uint64_t) (DEV_IPC_GET_ARG1(*call))) << 32) |
+	    (((uint64_t) (DEV_IPC_GET_ARG2(*call))) & 0xffffffff);
+	const size_t cnt = (size_t) DEV_IPC_GET_ARG3(*call);
+	
+	const int ret = ahci_iface->read_blocks(fun, blocknum, cnt, buf);
+	
+	async_answer_0(callid, ret);
+}
+
+void remote_ahci_write_blocks(ddf_fun_t *fun, void *iface, ipc_callid_t callid,
+    ipc_call_t *call)
+{
+	const ahci_iface_t *ahci_iface = (ahci_iface_t *) iface;
+	
+	if (ahci_iface->read_blocks == NULL) {
+		async_answer_0(callid, ENOTSUP);
+		return;
+	}
+	
+	size_t maxblock_size;
+	unsigned int flags;
+	
+	ipc_callid_t cid;
+	async_share_out_receive(&cid, &maxblock_size, &flags);
+	
+	void *buf;
+	async_share_out_finalize(cid, &buf);
+	
+	const uint64_t blocknum =
+	    (((uint64_t)(DEV_IPC_GET_ARG1(*call))) << 32) |
+	    (((uint64_t)(DEV_IPC_GET_ARG2(*call))) & 0xffffffff);
+	const size_t cnt = (size_t) DEV_IPC_GET_ARG3(*call);
+	
+	const int ret = ahci_iface->write_blocks(fun, blocknum, cnt, buf);
+	
+	async_answer_0(callid, ret);
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/drv/generic/remote_usb.c
===================================================================
--- uspace/lib/drv/generic/remote_usb.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/drv/generic/remote_usb.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -56,5 +56,5 @@
 {
 	if (!exch)
-		return EINVAL;
+		return EBADMEM;
 	sysarg_t addr;
 	const int ret = async_req_1_1(exch, DEV_IFACE_ID(USB_DEV_IFACE),
@@ -65,5 +65,5 @@
 	return ret;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Tell interface number given device can use.
  * @param[in] exch IPC communication exchange
@@ -75,5 +75,5 @@
 {
 	if (!exch)
-		return EINVAL;
+		return EBADMEM;
 	sysarg_t iface_no;
 	const int ret = async_req_1_1(exch, DEV_IFACE_ID(USB_DEV_IFACE),
@@ -83,5 +83,5 @@
 	return ret;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Tell devman handle of device host controller.
  * @param[in] exch IPC communication exchange
@@ -92,5 +92,5 @@
 {
 	if (!exch)
-		return EINVAL;
+		return EBADMEM;
 	devman_handle_t h;
 	const int ret = async_req_1_1(exch, DEV_IFACE_ID(USB_DEV_IFACE),
@@ -121,5 +121,5 @@
 };
 
-/*----------------------------------------------------------------------------*/
+
 void remote_usb_get_my_address(ddf_fun_t *fun, void *iface,
     ipc_callid_t callid, ipc_call_t *call)
@@ -140,5 +140,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 void remote_usb_get_my_interface(ddf_fun_t *fun, void *iface,
     ipc_callid_t callid, ipc_call_t *call)
@@ -159,5 +159,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 void remote_usb_get_hc_handle(ddf_fun_t *fun, void *iface,
     ipc_callid_t callid, ipc_call_t *call)
Index: uspace/lib/drv/generic/remote_usbhc.c
===================================================================
--- uspace/lib/drv/generic/remote_usbhc.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/drv/generic/remote_usbhc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -165,5 +165,5 @@
 {
 	if (!exch || !address)
-		return EINVAL;
+		return EBADMEM;
 	sysarg_t new_address;
 	const int ret = async_req_4_1(exch, DEV_IFACE_ID(USBHC_DEV_IFACE),
@@ -173,19 +173,19 @@
 	return ret;
 }
-/*----------------------------------------------------------------------------*/
+
 int usbhc_bind_address(async_exch_t *exch, usb_address_t address,
     devman_handle_t handle)
 {
 	if (!exch)
-		return EINVAL;
+		return EBADMEM;
 	return async_req_3_0(exch, DEV_IFACE_ID(USBHC_DEV_IFACE),
 	    IPC_M_USBHC_BIND_ADDRESS, address, handle);
 }
-/*----------------------------------------------------------------------------*/
+
 int usbhc_get_handle(async_exch_t *exch, usb_address_t address,
     devman_handle_t *handle)
 {
 	if (!exch)
-		return EINVAL;
+		return EBADMEM;
 	sysarg_t h;
 	const int ret = async_req_2_1(exch, DEV_IFACE_ID(USBHC_DEV_IFACE),
@@ -195,13 +195,13 @@
 	return ret;
 }
-/*----------------------------------------------------------------------------*/
+
 int usbhc_release_address(async_exch_t *exch, usb_address_t address)
 {
 	if (!exch)
-		return EINVAL;
+		return EBADMEM;
 	return async_req_2_0(exch, DEV_IFACE_ID(USBHC_DEV_IFACE),
 	    IPC_M_USBHC_RELEASE_ADDRESS, address);
 }
-/*----------------------------------------------------------------------------*/
+
 int usbhc_register_endpoint(async_exch_t *exch, usb_address_t address,
     usb_endpoint_t endpoint, usb_transfer_type_t type,
@@ -209,5 +209,5 @@
 {
 	if (!exch)
-		return EINVAL;
+		return EBADMEM;
 	const usb_target_t target =
 	    {{ .address = address, .endpoint = endpoint }};
@@ -220,23 +220,24 @@
 #undef _PACK2
 }
-/*----------------------------------------------------------------------------*/
+
 int usbhc_unregister_endpoint(async_exch_t *exch, usb_address_t address,
     usb_endpoint_t endpoint, usb_direction_t direction)
 {
 	if (!exch)
-		return EINVAL;
+		return EBADMEM;
 	return async_req_4_0(exch, DEV_IFACE_ID(USBHC_DEV_IFACE),
 	    IPC_M_USBHC_UNREGISTER_ENDPOINT, address, endpoint, direction);
 }
-/*----------------------------------------------------------------------------*/
+
 int usbhc_read(async_exch_t *exch, usb_address_t address,
     usb_endpoint_t endpoint, uint64_t setup, void *data, size_t size,
     size_t *rec_size)
 {
+	if (!exch)
+		return EBADMEM;
+
 	if (size == 0 && setup == 0)
 		return EOK;
 
-	if (!exch)
-		return EINVAL;
 	const usb_target_t target =
 	    {{ .address = address, .endpoint = endpoint }};
@@ -284,13 +285,14 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 int usbhc_write(async_exch_t *exch, usb_address_t address,
     usb_endpoint_t endpoint, uint64_t setup, const void *data, size_t size)
 {
+	if (!exch)
+		return EBADMEM;
+
 	if (size == 0 && setup == 0)
 		return EOK;
 
-	if (!exch)
-		return EINVAL;
 	const usb_target_t target =
 	    {{ .address = address, .endpoint = endpoint }};
@@ -319,5 +321,5 @@
 	return (int) opening_request_rc;
 }
-/*----------------------------------------------------------------------------*/
+
 
 static void remote_usbhc_request_address(ddf_fun_t *, void *, ipc_callid_t, ipc_call_t *);
@@ -384,5 +386,5 @@
 	return trans;
 }
-/*----------------------------------------------------------------------------*/
+
 void remote_usbhc_request_address(ddf_fun_t *fun, void *iface,
     ipc_callid_t callid, ipc_call_t *call)
@@ -406,5 +408,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 void remote_usbhc_bind_address(ddf_fun_t *fun, void *iface,
     ipc_callid_t callid, ipc_call_t *call)
@@ -423,5 +425,5 @@
 	async_answer_0(callid, ret);
 }
-/*----------------------------------------------------------------------------*/
+
 void remote_usbhc_get_handle(ddf_fun_t *fun, void *iface,
     ipc_callid_t callid, ipc_call_t *call)
@@ -444,5 +446,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 void remote_usbhc_release_address(ddf_fun_t *fun, void *iface,
     ipc_callid_t callid, ipc_call_t *call)
@@ -460,5 +462,5 @@
 	async_answer_0(callid, ret);
 }
-/*----------------------------------------------------------------------------*/
+
 static void callback_out(ddf_fun_t *fun,
     int outcome, void *arg)
@@ -470,5 +472,5 @@
 	async_transaction_destroy(trans);
 }
-/*----------------------------------------------------------------------------*/
+
 static void callback_in(ddf_fun_t *fun,
     int outcome, size_t actual_size, void *arg)
@@ -494,5 +496,5 @@
 	async_transaction_destroy(trans);
 }
-/*----------------------------------------------------------------------------*/
+
 void remote_usbhc_register_endpoint(ddf_fun_t *fun, void *iface,
     ipc_callid_t callid, ipc_call_t *call)
@@ -594,5 +596,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 void remote_usbhc_write(
     ddf_fun_t *fun, void *iface, ipc_callid_t callid, ipc_call_t *call)
Index: uspace/lib/drv/include/ahci_iface.h
===================================================================
--- uspace/lib/drv/include/ahci_iface.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/drv/include/ahci_iface.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libdrv
+ * @addtogroup ahci
+ * @{
+ */
+/** @file
+ * @brief AHCI interface definition.
+ */
+
+#ifndef LIBDRV_AHCI_IFACE_H_
+#define LIBDRV_AHCI_IFACE_H_
+
+#include "ddf/driver.h"
+#include <async.h>
+
+/** AHCI device communication interface. */
+typedef struct {
+	int (*get_sata_device_name)(ddf_fun_t *, size_t, char *);
+	int (*get_num_blocks)(ddf_fun_t *, uint64_t *);
+	int (*get_block_size)(ddf_fun_t *, size_t *);
+	int (*read_blocks)(ddf_fun_t *, uint64_t, size_t, void *);
+	int (*write_blocks)(ddf_fun_t *, uint64_t, size_t, void *);
+} ahci_iface_t;
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/drv/include/remote_ahci.h
===================================================================
--- uspace/lib/drv/include/remote_ahci.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/drv/include/remote_ahci.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libdrv
+ * @{
+ */
+/** @file
+ */
+
+#ifndef LIBDRV_REMOTE_AHCI_H_
+#define LIBDRV_REMOTE_AHCI_H_
+
+extern remote_iface_t remote_ahci_iface;
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/Makefile
===================================================================
--- uspace/lib/ext4/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,48 @@
+#
+# Copyright (c) 2012 Frantisek Princ
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+#   notice, this list of conditions and the following disclaimer.
+# - Redistributions in binary form must reproduce the above copyright
+#   notice, this list of conditions and the following disclaimer in the
+#   documentation and/or other materials provided with the distribution.
+# - The name of the author may not be used to endorse or promote products
+#   derived from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+USPACE_PREFIX = ../..
+LIBRARY = libext4
+EXTRA_CFLAGS = -I$(LIBBLOCK_PREFIX)
+LIBS = $(LIBBLOCK_PREFIX)/libblock.a
+
+SOURCES = \
+	libext4_balloc.c \
+	libext4_bitmap.c \
+	libext4_block_group.c \
+	libext4_crc.c \
+	libext4_directory.c \
+	libext4_directory_index.c \
+	libext4_extent.c \
+	libext4_filesystem.c \
+	libext4_hash.c \
+	libext4_ialloc.c \
+	libext4_inode.c \
+	libext4_superblock.c
+
+include $(USPACE_PREFIX)/Makefile.common
Index: uspace/lib/ext4/libext4.h
===================================================================
--- uspace/lib/ext4/libext4.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_H_
+#define LIBEXT4_LIBEXT4_H_
+
+#include "libext4_balloc.h"
+#include "libext4_bitmap.h"
+#include "libext4_block_group.h"
+#include "libext4_crc.h"
+#include "libext4_directory.h"
+#include "libext4_directory_index.h"
+#include "libext4_extent.h"
+#include "libext4_filesystem.h"
+#include "libext4_hash.h"
+#include "libext4_ialloc.h"
+#include "libext4_inode.h"
+#include "libext4_superblock.h"
+#include "libext4_types.h"
+
+#include <stdio.h>
+#define EXT4FS_DBG(format, ...) \
+	printf("ext4fs: %s: " format "\n", \
+	    __FUNCTION__, ##__VA_ARGS__) \
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_balloc.c
===================================================================
--- uspace/lib/ext4/libext4_balloc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_balloc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,667 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+/**
+ * @file  libext4_balloc.c
+ * @brief Physical block allocator.
+ */
+
+#include <errno.h>
+#include <sys/types.h>
+#include "libext4.h"
+
+/** Compute number of block group from block address.
+ *
+ * @param sb         Superblock pointer.
+ * @param block_addr Absolute address of block.
+ *
+ * @return Block group index
+ *
+ */
+static uint32_t ext4_balloc_get_bgid_of_block(ext4_superblock_t *sb,
+    uint32_t block_addr)
+{
+	uint32_t blocks_per_group =
+	    ext4_superblock_get_blocks_per_group(sb);
+	uint32_t first_block =
+	    ext4_superblock_get_first_data_block(sb);
+	
+	/* First block == 0 or 1 */
+	if (first_block == 0)
+		return block_addr / blocks_per_group;
+	else
+		return (block_addr - 1) / blocks_per_group;
+}
+
+/** Free block.
+ *
+ * @param inode_ref  Inode, where the block is allocated
+ * @param block_addr Absolute block address to free
+ *
+ * @return Error code
+ *
+ */
+int ext4_balloc_free_block(ext4_inode_ref_t *inode_ref, uint32_t block_addr)
+{
+	ext4_filesystem_t *fs = inode_ref->fs;
+	ext4_superblock_t *sb = fs->superblock;
+	
+	/* Compute indexes */
+	uint32_t block_group = ext4_balloc_get_bgid_of_block(sb, block_addr);
+	uint32_t index_in_group =
+	    ext4_filesystem_blockaddr2_index_in_group(sb, block_addr);
+	
+	/* Load block group reference */
+	ext4_block_group_ref_t *bg_ref;
+	int rc = ext4_filesystem_get_block_group_ref(fs, block_group, &bg_ref);
+	if (rc != EOK)
+		return rc;
+	
+	/* Load block with bitmap */
+	uint32_t bitmap_block_addr =
+	    ext4_block_group_get_block_bitmap(bg_ref->block_group, sb);
+	block_t *bitmap_block;
+	rc = block_get(&bitmap_block, fs->device, bitmap_block_addr, 0);
+	if (rc != EOK)
+		return rc;
+	
+	/* Modify bitmap */
+	ext4_bitmap_free_bit(bitmap_block->data, index_in_group);
+	bitmap_block->dirty = true;
+	
+	/* Release block with bitmap */
+	rc = block_put(bitmap_block);
+	if (rc != EOK) {
+		/* Error in saving bitmap */
+		ext4_filesystem_put_block_group_ref(bg_ref);
+		return rc;
+	}
+	
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	
+	/* Update superblock free blocks count */
+	uint32_t sb_free_blocks =
+	    ext4_superblock_get_free_blocks_count(sb);
+	sb_free_blocks++;
+	ext4_superblock_set_free_blocks_count(sb, sb_free_blocks);
+	
+	/* Update inode blocks count */
+	uint64_t ino_blocks =
+	    ext4_inode_get_blocks_count(sb, inode_ref->inode);
+	ino_blocks -= block_size / EXT4_INODE_BLOCK_SIZE;
+	ext4_inode_set_blocks_count(sb, inode_ref->inode, ino_blocks);
+	inode_ref->dirty = true;
+	
+	/* Update block group free blocks count */
+	uint32_t free_blocks =
+	    ext4_block_group_get_free_blocks_count(bg_ref->block_group, sb);
+	free_blocks++;
+	ext4_block_group_set_free_blocks_count(bg_ref->block_group,
+	    sb, free_blocks);
+	bg_ref->dirty = true;
+	
+	/* Release block group reference */
+	rc = ext4_filesystem_put_block_group_ref(bg_ref);
+	if (rc != EOK)
+		return rc;
+	
+	return EOK;
+}
+
+/** Free continuous set of blocks.
+ *
+ * @param inode_ref Inode, where the blocks are allocated
+ * @param first     First block to release
+ * @param count     Number of blocks to release
+ *
+ */
+int ext4_balloc_free_blocks(ext4_inode_ref_t *inode_ref,
+    uint32_t first, uint32_t count)
+{
+	ext4_filesystem_t *fs = inode_ref->fs;
+	ext4_superblock_t *sb = fs->superblock;
+	
+	/* Compute indexes */
+	uint32_t block_group_first =
+	    ext4_balloc_get_bgid_of_block(sb, first);
+	uint32_t block_group_last =
+	    ext4_balloc_get_bgid_of_block(sb, first + count - 1);
+	
+	assert(block_group_first == block_group_last);
+	
+	/* Load block group reference */
+	ext4_block_group_ref_t *bg_ref;
+	int rc = ext4_filesystem_get_block_group_ref(fs, block_group_first, &bg_ref);
+	if (rc != EOK)
+		return rc;
+	
+	uint32_t index_in_group_first =
+	    ext4_filesystem_blockaddr2_index_in_group(sb, first);
+	
+	/* Load block with bitmap */
+	uint32_t bitmap_block_addr =
+	    ext4_block_group_get_block_bitmap(bg_ref->block_group, sb);
+	
+	block_t *bitmap_block;
+	rc = block_get(&bitmap_block, fs->device, bitmap_block_addr, 0);
+	if (rc != EOK)
+		return rc;
+	
+	/* Modify bitmap */
+	ext4_bitmap_free_bits(bitmap_block->data, index_in_group_first, count);
+	bitmap_block->dirty = true;
+	
+	/* Release block with bitmap */
+	rc = block_put(bitmap_block);
+	if (rc != EOK) {
+		/* Error in saving bitmap */
+		ext4_filesystem_put_block_group_ref(bg_ref);
+		return rc;
+	}
+	
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	
+	/* Update superblock free blocks count */
+	uint32_t sb_free_blocks =
+	    ext4_superblock_get_free_blocks_count(sb);
+	sb_free_blocks += count;
+	ext4_superblock_set_free_blocks_count(sb, sb_free_blocks);
+	
+	/* Update inode blocks count */
+	uint64_t ino_blocks =
+	    ext4_inode_get_blocks_count(sb, inode_ref->inode);
+	ino_blocks -= count * (block_size / EXT4_INODE_BLOCK_SIZE);
+	ext4_inode_set_blocks_count(sb, inode_ref->inode, ino_blocks);
+	inode_ref->dirty = true;
+	
+	/* Update block group free blocks count */
+	uint32_t free_blocks =
+	    ext4_block_group_get_free_blocks_count(bg_ref->block_group, sb);
+	free_blocks += count;
+	ext4_block_group_set_free_blocks_count(bg_ref->block_group,
+	    sb, free_blocks);
+	bg_ref->dirty = true;
+	
+	/* Release block group reference */
+	rc = ext4_filesystem_put_block_group_ref(bg_ref);
+	if (rc != EOK)
+		return rc;
+	
+	return EOK;
+}
+
+/** Compute first block for data in block group.
+ *
+ * @param sb   Pointer to superblock
+ * @param bg   Pointer to block group
+ * @param bgid Index of block group
+ *
+ * @return Absolute block index of first block
+ *
+ */
+uint32_t ext4_balloc_get_first_data_block_in_group(ext4_superblock_t *sb,
+    ext4_block_group_ref_t *bg_ref)
+{
+	uint32_t block_group_count = ext4_superblock_get_block_group_count(sb);
+	uint32_t inode_table_first_block =
+	    ext4_block_group_get_inode_table_first_block(bg_ref->block_group, sb);
+	uint16_t inode_table_item_size = ext4_superblock_get_inode_size(sb);
+	uint32_t inodes_per_group = ext4_superblock_get_inodes_per_group(sb);
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	uint32_t inode_table_bytes;
+	
+	if (bg_ref->index < block_group_count - 1) {
+		inode_table_bytes = inodes_per_group * inode_table_item_size;
+	} else {
+		/* Last block group could be smaller */
+		uint32_t inodes_count_total = ext4_superblock_get_inodes_count(sb);
+		inode_table_bytes =
+		    (inodes_count_total - ((block_group_count - 1) * inodes_per_group)) *
+		    inode_table_item_size;
+	}
+	
+	uint32_t inode_table_blocks = inode_table_bytes / block_size;
+	
+	if (inode_table_bytes % block_size)
+		inode_table_blocks++;
+	
+	return inode_table_first_block + inode_table_blocks;
+}
+
+/** Compute 'goal' for allocation algorithm.
+ *
+ * @param inode_ref Reference to inode, to allocate block for
+ *
+ * @return Goal block number
+ *
+ */
+static uint32_t ext4_balloc_find_goal(ext4_inode_ref_t *inode_ref)
+{
+	uint32_t goal = 0;
+	
+	ext4_superblock_t *sb = inode_ref->fs->superblock;
+	
+	uint64_t inode_size = ext4_inode_get_size(sb, inode_ref->inode);
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	uint32_t inode_block_count = inode_size / block_size;
+	
+	if (inode_size % block_size != 0)
+		inode_block_count++;
+	
+	/* If inode has some blocks, get last block address + 1 */
+	if (inode_block_count > 0) {
+		int rc = ext4_filesystem_get_inode_data_block_index(inode_ref,
+		    inode_block_count - 1, &goal);
+		if (rc != EOK)
+			return 0;
+		
+		if (goal != 0) {
+			goal++;
+			return goal;
+		}
+		
+		/* If goal == 0, sparse file -> continue */
+	}
+	
+	/* Identify block group of inode */
+	uint32_t inodes_per_group = ext4_superblock_get_inodes_per_group(sb);
+	uint32_t block_group = (inode_ref->index - 1) / inodes_per_group;
+	block_size = ext4_superblock_get_block_size(sb);
+	
+	/* Load block group reference */
+	ext4_block_group_ref_t *bg_ref;
+	int rc = ext4_filesystem_get_block_group_ref(inode_ref->fs,
+	    block_group, &bg_ref);
+	if (rc != EOK)
+		return 0;
+	
+	/* Compute indexes */
+	uint32_t block_group_count = ext4_superblock_get_block_group_count(sb);
+	uint32_t inode_table_first_block =
+	    ext4_block_group_get_inode_table_first_block(bg_ref->block_group, sb);
+	uint16_t inode_table_item_size = ext4_superblock_get_inode_size(sb);
+	uint32_t inode_table_bytes;
+	
+	/* Check for last block group */
+	if (block_group < block_group_count - 1) {
+		inode_table_bytes = inodes_per_group * inode_table_item_size;
+	} else {
+		/* Last block group could be smaller */
+		uint32_t inodes_count_total = ext4_superblock_get_inodes_count(sb);
+		inode_table_bytes =
+		    (inodes_count_total - ((block_group_count - 1) * inodes_per_group)) *
+		    inode_table_item_size;
+	}
+	
+	uint32_t inode_table_blocks = inode_table_bytes / block_size;
+	
+	if (inode_table_bytes % block_size)
+		inode_table_blocks++;
+	
+	goal = inode_table_first_block + inode_table_blocks;
+	
+	ext4_filesystem_put_block_group_ref(bg_ref);
+	
+	return goal;
+}
+
+/** Data block allocation algorithm.
+ *
+ * @param inode_ref Inode to allocate block for
+ * @param fblock    Allocated block address
+ *
+ * @return Error code
+ *
+ */
+int ext4_balloc_alloc_block(ext4_inode_ref_t *inode_ref, uint32_t *fblock)
+{
+	uint32_t allocated_block = 0;
+	
+	uint32_t bitmap_block_addr;
+	block_t *bitmap_block;
+	uint32_t rel_block_idx = 0;
+	
+	/* Find GOAL */
+	uint32_t goal = ext4_balloc_find_goal(inode_ref);
+	if (goal == 0) {
+		/* no goal found => partition is full */
+		return ENOSPC;
+	}
+	
+	ext4_superblock_t *sb = inode_ref->fs->superblock;
+	
+	/* Load block group number for goal and relative index */
+	uint32_t block_group = ext4_balloc_get_bgid_of_block(sb, goal);
+	uint32_t index_in_group =
+	    ext4_filesystem_blockaddr2_index_in_group(sb, goal);
+	
+	/* Load block group reference */
+	ext4_block_group_ref_t *bg_ref;
+	int rc = ext4_filesystem_get_block_group_ref(inode_ref->fs,
+	    block_group, &bg_ref);
+	if (rc != EOK)
+		return rc;
+	
+	/* Compute indexes */
+	uint32_t first_in_group =
+	    ext4_balloc_get_first_data_block_in_group(sb, bg_ref);
+	
+	uint32_t first_in_group_index =
+	    ext4_filesystem_blockaddr2_index_in_group(sb, first_in_group);
+	
+	if (index_in_group < first_in_group_index)
+		index_in_group = first_in_group_index;
+	
+	/* Load block with bitmap */
+	bitmap_block_addr =
+	    ext4_block_group_get_block_bitmap(bg_ref->block_group, sb);
+	
+	rc = block_get(&bitmap_block, inode_ref->fs->device,
+	    bitmap_block_addr, BLOCK_FLAGS_NONE);
+	if (rc != EOK) {
+		ext4_filesystem_put_block_group_ref(bg_ref);
+		return rc;
+	}
+	
+	/* Check if goal is free */
+	if (ext4_bitmap_is_free_bit(bitmap_block->data, index_in_group)) {
+		ext4_bitmap_set_bit(bitmap_block->data, index_in_group);
+		bitmap_block->dirty = true;
+		rc = block_put(bitmap_block);
+		if (rc != EOK) {
+			ext4_filesystem_put_block_group_ref(bg_ref);
+			return rc;
+		}
+		
+		allocated_block =
+		    ext4_filesystem_index_in_group2blockaddr(sb, index_in_group,
+		    block_group);
+		
+		goto success;
+	}
+	
+	uint32_t blocks_in_group =
+	    ext4_superblock_get_blocks_in_group(sb, block_group);
+	
+	uint32_t end_idx = (index_in_group + 63) & ~63;
+	if (end_idx > blocks_in_group)
+		end_idx = blocks_in_group;
+	
+	/* Try to find free block near to goal */
+	for (uint32_t tmp_idx = index_in_group + 1; tmp_idx < end_idx;
+	    ++tmp_idx) {
+		if (ext4_bitmap_is_free_bit(bitmap_block->data, tmp_idx)) {
+			ext4_bitmap_set_bit(bitmap_block->data, tmp_idx);
+			bitmap_block->dirty = true;
+			rc = block_put(bitmap_block);
+			if (rc != EOK)
+				return rc;
+			
+			allocated_block =
+			    ext4_filesystem_index_in_group2blockaddr(sb, tmp_idx,
+			    block_group);
+			
+			goto success;
+		}
+	}
+	
+	/* Find free BYTE in bitmap */
+	rc = ext4_bitmap_find_free_byte_and_set_bit(bitmap_block->data,
+	    index_in_group, &rel_block_idx, blocks_in_group);
+	if (rc == EOK) {
+		bitmap_block->dirty = true;
+		rc = block_put(bitmap_block);
+		if (rc != EOK)
+			return rc;
+		
+		allocated_block =
+		    ext4_filesystem_index_in_group2blockaddr(sb, rel_block_idx,
+		    block_group);
+		
+		goto success;
+	}
+	
+	/* Find free bit in bitmap */
+	rc = ext4_bitmap_find_free_bit_and_set(bitmap_block->data,
+	    index_in_group, &rel_block_idx, blocks_in_group);
+	if (rc == EOK) {
+		bitmap_block->dirty = true;
+		rc = block_put(bitmap_block);
+		if (rc != EOK)
+			return rc;
+		
+		allocated_block =
+		    ext4_filesystem_index_in_group2blockaddr(sb, rel_block_idx,
+		    block_group);
+		
+		goto success;
+	}
+	
+	/* No free block found yet */
+	block_put(bitmap_block);
+	ext4_filesystem_put_block_group_ref(bg_ref);
+	
+	/* Try other block groups */
+	uint32_t block_group_count = ext4_superblock_get_block_group_count(sb);
+	
+	uint32_t bgid = (block_group + 1) % block_group_count;
+	uint32_t count = block_group_count;
+	
+	while (count > 0) {
+		rc = ext4_filesystem_get_block_group_ref(inode_ref->fs, bgid,
+		    &bg_ref);
+		if (rc != EOK)
+			return rc;
+		
+		/* Load block with bitmap */
+		bitmap_block_addr =
+		    ext4_block_group_get_block_bitmap(bg_ref->block_group, sb);
+		
+		rc = block_get(&bitmap_block, inode_ref->fs->device,
+		    bitmap_block_addr, 0);
+		if (rc != EOK) {
+			ext4_filesystem_put_block_group_ref(bg_ref);
+			return rc;
+		}
+		
+		/* Compute indexes */
+		first_in_group =
+		    ext4_balloc_get_first_data_block_in_group(sb, bg_ref);
+		index_in_group =
+		    ext4_filesystem_blockaddr2_index_in_group(sb, first_in_group);
+		blocks_in_group = ext4_superblock_get_blocks_in_group(sb, bgid);
+		
+		first_in_group_index =
+		    ext4_filesystem_blockaddr2_index_in_group(sb, first_in_group);
+		
+		if (index_in_group < first_in_group_index)
+			index_in_group = first_in_group_index;
+		
+		/* Try to find free byte in bitmap */
+		rc = ext4_bitmap_find_free_byte_and_set_bit(bitmap_block->data,
+		    index_in_group, &rel_block_idx, blocks_in_group);
+		if (rc == EOK) {
+			bitmap_block->dirty = true;
+			rc = block_put(bitmap_block);
+			if (rc != EOK)
+				return rc;
+			
+			allocated_block =
+			    ext4_filesystem_index_in_group2blockaddr(sb, rel_block_idx,
+			    bgid);
+			
+			goto success;
+		}
+		
+		/* Try to find free bit in bitmap */
+		rc = ext4_bitmap_find_free_bit_and_set(bitmap_block->data,
+		    index_in_group, &rel_block_idx, blocks_in_group);
+		if (rc == EOK) {
+			bitmap_block->dirty = true;
+			rc = block_put(bitmap_block);
+			if (rc != EOK)
+				return rc;
+			
+			allocated_block =
+			    ext4_filesystem_index_in_group2blockaddr(sb, rel_block_idx,
+			    bgid);
+			
+			goto success;
+		}
+		
+		block_put(bitmap_block);
+		ext4_filesystem_put_block_group_ref(bg_ref);
+		
+		/* Goto next group */
+		bgid = (bgid + 1) % block_group_count;
+		count--;
+	}
+	
+	return ENOSPC;
+	
+success:
+	/* Empty command - because of syntax */
+	;
+	
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	
+	/* Update superblock free blocks count */
+	uint32_t sb_free_blocks = ext4_superblock_get_free_blocks_count(sb);
+	sb_free_blocks--;
+	ext4_superblock_set_free_blocks_count(sb, sb_free_blocks);
+	
+	/* Update inode blocks (different block size!) count */
+	uint64_t ino_blocks =
+	    ext4_inode_get_blocks_count(sb, inode_ref->inode);
+	ino_blocks += block_size / EXT4_INODE_BLOCK_SIZE;
+	ext4_inode_set_blocks_count(sb, inode_ref->inode, ino_blocks);
+	inode_ref->dirty = true;
+	
+	/* Update block group free blocks count */
+	uint32_t bg_free_blocks =
+	    ext4_block_group_get_free_blocks_count(bg_ref->block_group, sb);
+	bg_free_blocks--;
+	ext4_block_group_set_free_blocks_count(bg_ref->block_group, sb,
+	    bg_free_blocks);
+	bg_ref->dirty = true;
+	
+	ext4_filesystem_put_block_group_ref(bg_ref);
+	
+	*fblock = allocated_block;
+	return EOK;
+}
+
+/** Try to allocate concrete block.
+ *
+ * @param inode_ref Inode to allocate block for
+ * @param fblock    Block address to allocate
+ * @param free      Output value - if target block is free
+ *
+ * @return Error code
+ *
+ */
+int ext4_balloc_try_alloc_block(ext4_inode_ref_t *inode_ref, uint32_t fblock,
+    bool *free)
+{
+	int rc = EOK;
+	
+	ext4_filesystem_t *fs = inode_ref->fs;
+	ext4_superblock_t *sb = fs->superblock;
+	
+	/* Compute indexes */
+	uint32_t block_group = ext4_balloc_get_bgid_of_block(sb, fblock);
+	uint32_t index_in_group =
+	    ext4_filesystem_blockaddr2_index_in_group(sb, fblock);
+	
+	/* Load block group reference */
+	ext4_block_group_ref_t *bg_ref;
+	rc = ext4_filesystem_get_block_group_ref(fs, block_group, &bg_ref);
+	if (rc != EOK)
+		return rc;
+	
+	/* Load block with bitmap */
+	uint32_t bitmap_block_addr =
+	    ext4_block_group_get_block_bitmap(bg_ref->block_group, sb);
+	block_t *bitmap_block;
+	rc = block_get(&bitmap_block, fs->device, bitmap_block_addr, 0);
+	if (rc != EOK)
+		return rc;
+	
+	/* Check if block is free */
+	*free = ext4_bitmap_is_free_bit(bitmap_block->data, index_in_group);
+	
+	/* Allocate block if possible */
+	if (*free) {
+		ext4_bitmap_set_bit(bitmap_block->data, index_in_group);
+		bitmap_block->dirty = true;
+	}
+	
+	/* Release block with bitmap */
+	rc = block_put(bitmap_block);
+	if (rc != EOK) {
+		/* Error in saving bitmap */
+		ext4_filesystem_put_block_group_ref(bg_ref);
+		return rc;
+	}
+	
+	/* If block is not free, return */
+	if (!(*free))
+		goto terminate;
+	
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	
+	/* Update superblock free blocks count */
+	uint32_t sb_free_blocks = ext4_superblock_get_free_blocks_count(sb);
+	sb_free_blocks--;
+	ext4_superblock_set_free_blocks_count(sb, sb_free_blocks);
+	
+	/* Update inode blocks count */
+	uint64_t ino_blocks =
+	    ext4_inode_get_blocks_count(sb, inode_ref->inode);
+	ino_blocks += block_size / EXT4_INODE_BLOCK_SIZE;
+	ext4_inode_set_blocks_count(sb, inode_ref->inode, ino_blocks);
+	inode_ref->dirty = true;
+	
+	/* Update block group free blocks count */
+	uint32_t free_blocks =
+	    ext4_block_group_get_free_blocks_count(bg_ref->block_group, sb);
+	free_blocks--;
+	ext4_block_group_set_free_blocks_count(bg_ref->block_group,
+	    sb, free_blocks);
+	bg_ref->dirty = true;
+	
+terminate:
+	return ext4_filesystem_put_block_group_ref(bg_ref);
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_balloc.h
===================================================================
--- uspace/lib/ext4/libext4_balloc.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_balloc.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_BALLOC_H_
+#define LIBEXT4_LIBEXT4_BALLOC_H_
+
+#include <sys/types.h>
+#include "libext4_types.h"
+
+extern int ext4_balloc_free_block(ext4_inode_ref_t *, uint32_t);
+extern int ext4_balloc_free_blocks(ext4_inode_ref_t *, uint32_t, uint32_t);
+extern uint32_t ext4_balloc_get_first_data_block_in_group(ext4_superblock_t *,
+    ext4_block_group_ref_t *);
+extern int ext4_balloc_alloc_block(ext4_inode_ref_t *, uint32_t *);
+extern int ext4_balloc_try_alloc_block(ext4_inode_ref_t *, uint32_t, bool *);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_bitmap.c
===================================================================
--- uspace/lib/ext4/libext4_bitmap.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_bitmap.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,269 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+/**
+ * @file  libext4_bitmap.c
+ * @brief Ext4 bitmap operations.
+ */
+
+#include <errno.h>
+#include <libblock.h>
+#include <sys/types.h>
+#include "libext4.h"
+
+/** Set bit in bitmap to 0 (free).
+ *
+ * Index must be checked by caller, if it's not out of bounds.
+ *
+ * @param bitmap Pointer to bitmap
+ * @param index  Index of bit in bitmap
+ *
+ */
+void ext4_bitmap_free_bit(uint8_t *bitmap, uint32_t index)
+{
+	uint32_t byte_index = index / 8;
+	uint32_t bit_index = index % 8;
+	
+	uint8_t *target = bitmap + byte_index;
+	
+	*target &= ~ (1 << bit_index);
+}
+
+/** Free continous set of bits (set to 0).
+ *
+ * Index and count must be checked by caller, if they aren't out of bounds.
+ *
+ * @param bitmap Pointer to bitmap
+ * @param index  Index of first bit to zeroed
+ * @param count  Number of bits to be zeroed
+ *
+ */
+void ext4_bitmap_free_bits(uint8_t *bitmap, uint32_t index, uint32_t count)
+{
+	uint8_t *target;
+	uint32_t idx = index;
+	uint32_t remaining = count;
+	uint32_t byte_index;
+	
+	/* Align index to multiple of 8 */
+	while (((idx % 8) != 0) && (remaining > 0)) {
+		byte_index = idx / 8;
+		uint32_t bit_index = idx % 8;
+		
+		target = bitmap + byte_index;
+		*target &= ~ (1 << bit_index);
+		
+		idx++;
+		remaining--;
+	}
+	
+	/* For < 8 bits this check necessary */
+	if (remaining == 0)
+		return;
+	
+	assert((idx % 8) == 0);
+	
+	byte_index = idx / 8;
+	target = bitmap + byte_index;
+	
+	/* Zero the whole bytes */
+	while (remaining >= 8) {
+		*target = 0;
+		
+		idx += 8;
+		remaining -= 8;
+		target++;
+	}
+	
+	assert(remaining < 8);
+	
+	/* Zero remaining bytes */
+	while (remaining != 0) {
+		byte_index = idx / 8;
+		uint32_t bit_index = idx % 8;
+		
+		target = bitmap + byte_index;
+		*target &= ~ (1 << bit_index);
+		
+		idx++;
+		remaining--;
+	}
+}
+
+/** Set bit in bitmap to 1 (used).
+ *
+ * @param bitmap Pointer to bitmap
+ * @param index  Index of bit to set
+ *
+ */
+void ext4_bitmap_set_bit(uint8_t *bitmap, uint32_t index)
+{
+	uint32_t byte_index = index / 8;
+	uint32_t bit_index = index % 8;
+	
+	uint8_t *target = bitmap + byte_index;
+	
+	*target |= 1 << bit_index;
+}
+
+/** Check if requested bit is free.
+ *
+ * @param bitmap Pointer to bitmap
+ * @param index  Index of bit to be checked
+ *
+ * @return True if bit is free, else false
+ *
+ */
+bool ext4_bitmap_is_free_bit(uint8_t *bitmap, uint32_t index)
+{
+	uint32_t byte_index = index / 8;
+	uint32_t bit_index = index % 8;
+	
+	uint8_t *target = bitmap + byte_index;
+	
+	if (*target & (1 << bit_index))
+		return false;
+	else
+		return true;
+}
+
+/** Try to find free byte and set the first bit as used.
+ *
+ * Walk through bitmap and try to find free byte (equal to 0).
+ * If byte found, set the first bit as used.
+ *
+ * @param bitmap Pointer to bitmap
+ * @param start  Index of bit, where the algorithm will begin
+ * @param index  Output value - index of bit (if found free byte)
+ * @param max    Maximum index of bit in bitmap
+ *
+ * @return Error code
+ *
+ */
+int ext4_bitmap_find_free_byte_and_set_bit(uint8_t *bitmap, uint32_t start,
+    uint32_t *index, uint32_t max)
+{
+	uint32_t idx;
+	
+	/* Align idx */
+	if (start % 8)
+		idx = start + (8 - (start % 8));
+	else
+		idx = start;
+	
+	uint8_t *pos = bitmap + (idx / 8);
+	
+	/* Try to find free byte */
+	while (idx < max) {
+		if (*pos == 0) {
+			*pos |= 1;
+			
+			*index = idx;
+			return EOK;
+		}
+		
+		idx += 8;
+		++pos;
+	}
+	
+	/* Free byte not found */
+	return ENOSPC;
+}
+
+/** Try to find free bit and set it as used (1).
+ *
+ * Walk through bitmap and try to find any free bit.
+ *
+ * @param bitmap    Pointer to bitmap
+ * @param start_idx Index of bit, where algorithm will begin
+ * @param index     Output value - index of set bit (if found)
+ * @param max       Maximum index of bit in bitmap
+ *
+ * @return Error code
+ *
+ */
+int ext4_bitmap_find_free_bit_and_set(uint8_t *bitmap, uint32_t start_idx,
+    uint32_t *index, uint32_t max)
+{
+	uint8_t *pos = bitmap + (start_idx / 8);
+	uint32_t idx = start_idx;
+	bool byte_part = false;
+	
+	/* Check the rest of first byte */
+	while ((idx % 8) != 0) {
+		byte_part = true;
+		
+		if ((*pos & (1 << (idx % 8))) == 0) {
+			*pos |= (1 << (idx % 8));
+			*index = idx;
+			return EOK;
+		}
+		
+		++idx;
+	}
+	
+	if (byte_part)
+		++pos;
+	
+	/* Check the whole bytes (255 = 11111111 binary) */
+	while (idx < max) {
+		if ((*pos & 255) != 255) {
+			/* Free bit found */
+			break;
+		}
+		
+		idx += 8;
+		++pos;
+	}
+	
+	/* If idx < max, some free bit found */
+	if (idx < max) {
+		/* Check which bit from byte is free */
+		for (uint8_t i = 0; i < 8; ++i) {
+			if ((*pos & (1 << i)) == 0) {
+				/* Free bit found */
+				*pos |= (1 << i);
+				
+				*index = idx;
+				return EOK;
+			}
+			
+			idx++;
+		}
+	}
+	
+	/* Free bit not found */
+	return ENOSPC;
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_bitmap.h
===================================================================
--- uspace/lib/ext4/libext4_bitmap.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_bitmap.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_BITMAP_H_
+#define LIBEXT4_LIBEXT4_BITMAP_H_
+
+#include <sys/types.h>
+
+extern void ext4_bitmap_free_bit(uint8_t *, uint32_t);
+extern void ext4_bitmap_free_bits(uint8_t *, uint32_t, uint32_t);
+extern void ext4_bitmap_set_bit(uint8_t *, uint32_t);
+extern bool ext4_bitmap_is_free_bit(uint8_t *, uint32_t);
+extern int ext4_bitmap_find_free_byte_and_set_bit(uint8_t *, uint32_t,
+    uint32_t *, uint32_t);
+extern int ext4_bitmap_find_free_bit_and_set(uint8_t *, uint32_t, uint32_t *,
+    uint32_t);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_block_group.c
===================================================================
--- uspace/lib/ext4/libext4_block_group.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_block_group.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,385 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+/**
+ * @file  libext4_block_group.c
+ * @brief Ext4 block group structure operations.
+ */
+
+#include <byteorder.h>
+#include "libext4.h"
+
+/** Get address of block with data block bitmap.
+ *
+ * @param bg Pointer to block group
+ * @param sb Pointer to superblock
+ *
+ * @return Address of block with block bitmap
+ *
+ */
+uint64_t ext4_block_group_get_block_bitmap(ext4_block_group_t *bg,
+    ext4_superblock_t *sb)
+{
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		return ((uint64_t) uint32_t_le2host(bg->block_bitmap_hi) << 32) |
+		    uint32_t_le2host(bg->block_bitmap_lo);
+	else
+		return uint32_t_le2host(bg->block_bitmap_lo);
+}
+
+/** Set address of block with data block bitmap.
+ *
+ * @param bg           Pointer to block group
+ * @param sb           Pointer to superblock
+ * @param block_bitmap Address of block with block bitmap
+ *
+ */
+void ext4_block_group_set_block_bitmap(ext4_block_group_t *bg,
+    ext4_superblock_t *sb, uint64_t block_bitmap)
+{
+	bg->block_bitmap_lo = host2uint32_t_le((block_bitmap << 32) >> 32);
+	
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		bg->block_bitmap_hi = host2uint32_t_le(block_bitmap >> 32);
+}
+
+/** Get address of block with i-node bitmap.
+ *
+ * @param bg Pointer to block group
+ * @param sb Pointer to superblock
+ *
+ * @return Address of block with i-node bitmap
+ *
+ */
+uint64_t ext4_block_group_get_inode_bitmap(ext4_block_group_t *bg,
+    ext4_superblock_t *sb)
+{
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		return ((uint64_t) uint32_t_le2host(bg->inode_bitmap_hi) << 32) |
+		    uint32_t_le2host(bg->inode_bitmap_lo);
+	else
+		return uint32_t_le2host(bg->inode_bitmap_lo);
+}
+
+/** Set address of block with i-node bitmap.
+ *
+ * @param bg           Pointer to block group
+ * @param sb           Pointer to superblock
+ * @param inode_bitmap Address of block with i-node bitmap
+ *
+ */
+void ext4_block_group_set_inode_bitmap(ext4_block_group_t *bg,
+    ext4_superblock_t *sb, uint64_t inode_bitmap)
+{
+	bg->inode_bitmap_lo = host2uint32_t_le((inode_bitmap << 32) >> 32);
+	
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		bg->inode_bitmap_hi = host2uint32_t_le(inode_bitmap >> 32);
+}
+
+/** Get address of the first block of the i-node table.
+ *
+ * @param bg Pointer to block group
+ * @param sb Pointer to superblock
+ *
+ * @return Address of first block of i-node table
+ *
+ */
+uint64_t ext4_block_group_get_inode_table_first_block(ext4_block_group_t *bg,
+    ext4_superblock_t *sb)
+{
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		return ((uint64_t)
+		    uint32_t_le2host(bg->inode_table_first_block_hi) << 32) |
+		    uint32_t_le2host(bg->inode_table_first_block_lo);
+	else
+		return uint32_t_le2host(bg->inode_table_first_block_lo);
+}
+
+/** Set address of the first block of the i-node table.
+ *
+ * @param bg                Pointer to block group
+ * @param sb                Pointer to superblock
+ * @param inode_table_first Address of first block of i-node table
+ *
+ */
+void ext4_block_group_set_inode_table_first_block(ext4_block_group_t *bg,
+    ext4_superblock_t *sb, uint64_t inode_table_first)
+{
+	bg->inode_table_first_block_lo =
+	    host2uint32_t_le((inode_table_first << 32) >> 32);
+	
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		bg->inode_table_first_block_hi =
+		    host2uint32_t_le(inode_table_first >> 32);
+}
+
+/** Get number of free blocks in block group.
+ *
+ * @param bg Pointer to block group
+ * @param sb Pointer to superblock
+ *
+ * @return Number of free blocks in block group
+ *
+ */
+uint32_t ext4_block_group_get_free_blocks_count(ext4_block_group_t *bg,
+    ext4_superblock_t *sb)
+{
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		return ((uint32_t)
+		    uint16_t_le2host(bg->free_blocks_count_hi) << 16) |
+		    uint16_t_le2host(bg->free_blocks_count_lo);
+	else
+		return uint16_t_le2host(bg->free_blocks_count_lo);
+}
+
+/** Set number of free blocks in block group.
+ *
+ * @param bg    Pointer to block group
+ * @param sb    Pointer to superblock
+ * @param value Number of free blocks in block group
+ *
+ */
+void ext4_block_group_set_free_blocks_count(ext4_block_group_t *bg,
+    ext4_superblock_t *sb, uint32_t value)
+{
+	bg->free_blocks_count_lo = host2uint16_t_le((value << 16) >> 16);
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		bg->free_blocks_count_hi = host2uint16_t_le(value >> 16);
+}
+
+/** Get number of free i-nodes in block group.
+ *
+ * @param bg Pointer to block group
+ * @param sb Pointer to superblock
+ *
+ * @return Number of free i-nodes in block group
+ *
+ */
+uint32_t ext4_block_group_get_free_inodes_count(ext4_block_group_t *bg,
+    ext4_superblock_t *sb)
+{
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		return ((uint32_t)
+		    uint16_t_le2host(bg->free_inodes_count_hi) << 16) |
+		    uint16_t_le2host(bg->free_inodes_count_lo);
+	else
+		return uint16_t_le2host(bg->free_inodes_count_lo);
+}
+
+/** Set number of free i-nodes in block group.
+ *
+ * @param bg    Pointer to block group
+ * @param sb    Pointer to superblock
+ * @param value Number of free i-nodes in block group
+ *
+ */
+void ext4_block_group_set_free_inodes_count(ext4_block_group_t *bg,
+    ext4_superblock_t *sb, uint32_t value)
+{
+	bg->free_inodes_count_lo = host2uint16_t_le((value << 16) >> 16);
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		bg->free_inodes_count_hi = host2uint16_t_le(value >> 16);
+}
+
+/** Get number of used directories in block group.
+ *
+ * @param bg Pointer to block group
+ * @param sb Pointer to superblock
+ *
+ * @return Number of used directories in block group
+ *
+ */
+uint32_t ext4_block_group_get_used_dirs_count(ext4_block_group_t *bg,
+    ext4_superblock_t *sb)
+{
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		return ((uint32_t)
+		    uint16_t_le2host(bg->used_dirs_count_hi) << 16) |
+		    uint16_t_le2host(bg->used_dirs_count_lo);
+	else
+		return uint16_t_le2host(bg->used_dirs_count_lo);
+}
+
+/** Set number of used directories in block group.
+ *
+ * @param bg    Pointer to block group
+ * @param sb    Pointer to superblock
+ * @param value Number of used directories in block group
+ *
+ */
+void ext4_block_group_set_used_dirs_count(ext4_block_group_t *bg,
+    ext4_superblock_t *sb, uint32_t count)
+{
+	bg->used_dirs_count_lo = host2uint16_t_le((count << 16) >> 16);
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		bg->used_dirs_count_hi = host2uint16_t_le(count >> 16);
+}
+
+/** Get flags of block group.
+ *
+ * @param bg Pointer to block group
+ *
+ * @return Flags of block group
+ *
+ */
+uint16_t ext4_block_group_get_flags(ext4_block_group_t *bg)
+{
+	return uint16_t_le2host(bg->flags);
+}
+
+/** Set flags for block group.
+ *
+ * @param bg    Pointer to block group
+ * @param flags Flags for block group
+ *
+ */
+void ext4_block_group_set_flags(ext4_block_group_t *bg, uint16_t flags)
+{
+	bg->flags = host2uint16_t_le(flags);
+}
+
+/** Get number of unused i-nodes.
+ *
+ * @param bg Pointer to block group
+ * @param sb Pointer to superblock
+ *
+ * @return Number of unused i-nodes
+ *
+ */
+uint32_t ext4_block_group_get_itable_unused(ext4_block_group_t *bg,
+    ext4_superblock_t *sb)
+{
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		return ((uint32_t)
+		    uint16_t_le2host(bg->itable_unused_hi) << 16) |
+		    uint16_t_le2host(bg->itable_unused_lo);
+	else
+		return uint16_t_le2host(bg->itable_unused_lo);
+}
+
+/** Set number of unused i-nodes.
+ *
+ * @param bg    Pointer to block group
+ * @param sb    Pointer to superblock
+ * @param value Number of unused i-nodes
+ *
+ */
+void ext4_block_group_set_itable_unused(ext4_block_group_t *bg,
+    ext4_superblock_t *sb, uint32_t value)
+{
+	bg->itable_unused_lo = host2uint16_t_le((value << 16) >> 16);
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		bg->itable_unused_hi = host2uint16_t_le(value >> 16);
+}
+
+/** Get checksum of block group.
+ *
+ * @param bg Pointer to block group
+ *
+ * @return checksum of block group
+ *
+ */
+uint16_t ext4_block_group_get_checksum(ext4_block_group_t *bg)
+{
+	return uint16_t_le2host(bg->checksum);
+}
+
+/** Set checksum of block group.
+ *
+ * @param bg       Pointer to block group
+ * @param checksum Cheksum of block group
+ *
+ */
+void ext4_block_group_set_checksum(ext4_block_group_t *bg, uint16_t checksum)
+{
+	bg->checksum = host2uint16_t_le(checksum);
+}
+
+/** Check if block group has a flag.
+ *
+ * @param bg   Pointer to block group
+ * @param flag Flag to be checked
+ *
+ * @return True if flag is set to 1
+ *
+ */
+bool ext4_block_group_has_flag(ext4_block_group_t *bg, uint32_t flag)
+{
+	if (ext4_block_group_get_flags(bg) & flag)
+		return true;
+	
+	return false;
+}
+
+/** Set (add) flag of block group.
+ *
+ * @param bg   Pointer to block group
+ * @param flag Flag to be set
+ *
+ */
+void ext4_block_group_set_flag(ext4_block_group_t *bg, uint32_t set_flag)
+{
+	uint32_t flags = ext4_block_group_get_flags(bg);
+	flags = flags | set_flag;
+	ext4_block_group_set_flags(bg, flags);
+}
+
+/** Clear (remove) flag of block group.
+ *
+ * @param bg   Pointer to block group
+ * @param flag Flag to be cleared
+ *
+ */
+void ext4_block_group_clear_flag(ext4_block_group_t *bg, uint32_t clear_flag)
+{
+	uint32_t flags = ext4_block_group_get_flags(bg);
+	flags = flags & (~clear_flag);
+	ext4_block_group_set_flags(bg, flags);
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_block_group.h
===================================================================
--- uspace/lib/ext4/libext4_block_group.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_block_group.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_BLOCK_GROUP_H_
+#define LIBEXT4_LIBEXT4_BLOCK_GROUP_H_
+
+#include <libblock.h>
+#include <sys/types.h>
+#include "libext4_types.h"
+
+extern uint64_t ext4_block_group_get_block_bitmap(ext4_block_group_t *,
+    ext4_superblock_t *);
+extern void ext4_block_group_set_block_bitmap(ext4_block_group_t *,
+    ext4_superblock_t *, uint64_t);
+extern uint64_t ext4_block_group_get_inode_bitmap(ext4_block_group_t *,
+    ext4_superblock_t *);
+extern void ext4_block_group_set_inode_bitmap(ext4_block_group_t *,
+    ext4_superblock_t *, uint64_t);
+extern uint64_t ext4_block_group_get_inode_table_first_block(
+    ext4_block_group_t *, ext4_superblock_t *);
+extern void ext4_block_group_set_inode_table_first_block(ext4_block_group_t *,
+    ext4_superblock_t *, uint64_t);
+extern uint32_t ext4_block_group_get_free_blocks_count(ext4_block_group_t *,
+    ext4_superblock_t *);
+extern void ext4_block_group_set_free_blocks_count(ext4_block_group_t *,
+    ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_block_group_get_free_inodes_count(ext4_block_group_t *,
+    ext4_superblock_t *);
+extern void ext4_block_group_set_free_inodes_count(ext4_block_group_t *,
+    ext4_superblock_t *, uint32_t);
+extern void ext4_block_group_set_free_inodes_count(ext4_block_group_t *,
+    ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_block_group_get_used_dirs_count(ext4_block_group_t *,
+    ext4_superblock_t *);
+extern void ext4_block_group_set_used_dirs_count(ext4_block_group_t *,
+    ext4_superblock_t *, uint32_t);
+extern uint16_t ext4_block_group_get_flags(ext4_block_group_t *);
+extern void ext4_block_group_set_flags(ext4_block_group_t *, uint16_t);
+extern uint32_t ext4_block_group_get_itable_unused(ext4_block_group_t *,
+    ext4_superblock_t *);
+extern void ext4_block_group_set_itable_unused(ext4_block_group_t *,
+    ext4_superblock_t *, uint32_t);
+extern uint16_t ext4_block_group_get_checksum(ext4_block_group_t *);
+extern void ext4_block_group_set_checksum(ext4_block_group_t *, uint16_t);
+
+extern bool ext4_block_group_has_flag(ext4_block_group_t *, uint32_t);
+extern void ext4_block_group_set_flag(ext4_block_group_t *, uint32_t);
+extern void ext4_block_group_clear_flag(ext4_block_group_t *, uint32_t);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_crc.c
===================================================================
--- uspace/lib/ext4/libext4_crc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_crc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+/**
+ * @file  libext4_crc.c
+ * @brief CRC checksumming implementation from Linux.
+ */
+
+#include <byteorder.h>
+#include "libext4.h"
+
+/** CRC table for the CRC-16.
+ *
+ * The poly is 0x8005 (x^16 + x^15 + x^2 + 1).
+ *
+ */
+uint16_t const crc16_table[256] = {
+	0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
+	0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
+	0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
+	0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
+	0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
+	0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
+	0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
+	0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
+	0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
+	0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
+	0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
+	0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
+	0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
+	0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
+	0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
+	0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
+	0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
+	0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
+	0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
+	0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
+	0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
+	0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
+	0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
+	0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
+	0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
+	0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
+	0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
+	0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
+	0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
+	0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
+	0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
+	0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
+};
+
+/** Modify CRC value.
+ *
+ * @param crc   Current CRC value
+ * @param data  New byte of data to be "added" to CRC
+ *
+ * @return Updated CRC value
+ *
+ */
+static inline uint16_t crc16_byte(uint16_t crc, const uint8_t data)
+{
+	return (crc >> 8) ^ crc16_table[(crc ^ data) & 0xff];
+}
+
+/** Compute the CRC-16 for the data buffer.
+ *
+ * @param crc    Previous CRC value
+ * @param buffer Data pointer
+ * @param len    Number of bytes in the buffer
+ *
+ * @return Updated CRC value
+ *
+ */
+uint16_t crc16(uint16_t crc, const uint8_t *buffer, size_t len)
+{
+	while (len--)
+		crc = crc16_byte(crc, *buffer++);
+	
+	return crc;
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_crc.h
===================================================================
--- uspace/lib/ext4/libext4_crc.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_crc.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_CRC_H_
+#define LIBEXT4_LIBEXT4_CRC_H_
+
+extern uint16_t crc16(uint16_t, const uint8_t *, size_t);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_directory.c
===================================================================
--- uspace/lib/ext4/libext4_directory.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_directory.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,765 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+/**
+ * @file  libext4_directory.c
+ * @brief Ext4 directory structure operations.
+ */
+
+#include <byteorder.h>
+#include <errno.h>
+#include <malloc.h>
+#include "libext4.h"
+
+/** Get i-node number from directory entry.
+ *
+ * @param de Directory entry
+ *
+ * @return I-node number
+ *
+ */
+uint32_t ext4_directory_entry_ll_get_inode(ext4_directory_entry_ll_t *de)
+{
+	return uint32_t_le2host(de->inode);
+}
+
+/** Set i-node number to directory entry.
+ *
+ * @param de    Directory entry
+ * @param inode I-node number
+ *
+ */
+void ext4_directory_entry_ll_set_inode(ext4_directory_entry_ll_t *de,
+    uint32_t inode)
+{
+	de->inode = host2uint32_t_le(inode);
+}
+
+/** Get directory entry length.
+ *
+ * @param de Directory entry
+ *
+ * @return Entry length
+ *
+ */
+uint16_t ext4_directory_entry_ll_get_entry_length(ext4_directory_entry_ll_t *de)
+{
+	return uint16_t_le2host(de->entry_length);
+}
+
+/** Set directory entry length.
+ *
+ * @param de     Directory entry
+ * @param length Entry length
+ *
+ */
+void ext4_directory_entry_ll_set_entry_length(ext4_directory_entry_ll_t *de,
+    uint16_t length)
+{
+	de->entry_length = host2uint16_t_le(length);
+}
+
+/** Get directory entry name length.
+ *
+ * @param sb Superblock
+ * @param de Directory entry
+ *
+ * @return Entry name length
+ *
+ */
+uint16_t ext4_directory_entry_ll_get_name_length(ext4_superblock_t *sb,
+    ext4_directory_entry_ll_t *de)
+{
+	if ((ext4_superblock_get_rev_level(sb) == 0) &&
+	    (ext4_superblock_get_minor_rev_level(sb) < 5))
+		return ((uint16_t)de->name_length_high) << 8 |
+		    ((uint16_t)de->name_length);
+	
+	return de->name_length;
+
+}
+
+/** Set directory entry name length.
+ *
+ * @param sb     Superblock
+ * @param de     Directory entry
+ * @param length Entry name length
+ *
+ */
+void ext4_directory_entry_ll_set_name_length(ext4_superblock_t *sb,
+    ext4_directory_entry_ll_t *de, uint16_t length)
+{
+	de->name_length = (length << 8) >> 8;
+	
+	if ((ext4_superblock_get_rev_level(sb) == 0) &&
+	    (ext4_superblock_get_minor_rev_level(sb) < 5))
+		de->name_length_high = length >> 8;
+	
+	/* Else do nothing */
+}
+
+/** Get i-node type of directory entry.
+ *
+ * @param sb Superblock
+ * @param de Directory entry
+ *
+ * @return I-node type (file, dir, etc.)
+ *
+ */
+uint8_t ext4_directory_entry_ll_get_inode_type(ext4_superblock_t *sb,
+    ext4_directory_entry_ll_t *de)
+{
+	if ((ext4_superblock_get_rev_level(sb) > 0) ||
+	    (ext4_superblock_get_minor_rev_level(sb) >= 5))
+		return de->inode_type;
+	
+	return EXT4_DIRECTORY_FILETYPE_UNKNOWN;
+}
+
+/** Set i-node type of directory entry.
+ *
+ * @param sb   Superblock
+ * @param de   Directory entry
+ * @param type I-node type (file, dir, etc.)
+ *
+ */
+void ext4_directory_entry_ll_set_inode_type(ext4_superblock_t *sb,
+    ext4_directory_entry_ll_t *de, uint8_t type)
+{
+	if ((ext4_superblock_get_rev_level(sb) > 0) ||
+	    (ext4_superblock_get_minor_rev_level(sb) >= 5))
+		de->inode_type = type;
+	
+	/* Else do nothing */
+}
+
+static int ext4_directory_iterator_seek(ext4_directory_iterator_t *, aoff64_t);
+static int ext4_directory_iterator_set(ext4_directory_iterator_t *, uint32_t);
+
+/** Initialize directory iterator.
+ *
+ * Set position to the first valid entry from the required position.
+ *
+ * @param it        Pointer to iterator to be initialized
+ * @param inode_ref Directory i-node
+ * @param pos       Position to start reading entries from
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_iterator_init(ext4_directory_iterator_t *it,
+    ext4_inode_ref_t *inode_ref, aoff64_t pos)
+{
+	it->inode_ref = inode_ref;
+	it->current = NULL;
+	it->current_offset = 0;
+	it->current_block = NULL;
+	
+	return ext4_directory_iterator_seek(it, pos);
+}
+
+/** Jump to the next valid entry
+ *
+ * @param it Initialized iterator
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_iterator_next(ext4_directory_iterator_t *it)
+{
+	assert(it->current != NULL);
+	
+	uint16_t skip = ext4_directory_entry_ll_get_entry_length(it->current);
+	
+	return ext4_directory_iterator_seek(it, it->current_offset + skip);
+}
+
+/** Seek to next valid directory entry.
+ *
+ * Here can be jumped to the next data block.
+ *
+ * @param it  Initialized iterator
+ * @param pos Position of the next entry
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_iterator_seek(ext4_directory_iterator_t *it, aoff64_t pos)
+{
+	uint64_t size = ext4_inode_get_size(it->inode_ref->fs->superblock,
+	    it->inode_ref->inode);
+	
+	/* The iterator is not valid until we seek to the desired position */
+	it->current = NULL;
+	
+	/* Are we at the end? */
+	if (pos >= size) {
+		if (it->current_block) {
+			int rc = block_put(it->current_block);
+			it->current_block = NULL;
+			
+			if (rc != EOK)
+				return rc;
+		}
+		
+		it->current_offset = pos;
+		return EOK;
+	}
+	
+	/* Compute next block address */
+	uint32_t block_size =
+	    ext4_superblock_get_block_size(it->inode_ref->fs->superblock);
+	aoff64_t current_block_idx = it->current_offset / block_size;
+	aoff64_t next_block_idx = pos / block_size;
+	
+	/*
+	 * If we don't have a block or are moving accross block boundary,
+	 * we need to get another block
+	 */
+	if ((it->current_block == NULL) ||
+	    (current_block_idx != next_block_idx)) {
+		if (it->current_block) {
+			int rc = block_put(it->current_block);
+			it->current_block = NULL;
+			
+			if (rc != EOK)
+				return rc;
+		}
+		
+		uint32_t next_block_phys_idx;
+		int rc = ext4_filesystem_get_inode_data_block_index(it->inode_ref,
+		    next_block_idx, &next_block_phys_idx);
+		if (rc != EOK)
+			return rc;
+		
+		rc = block_get(&it->current_block, it->inode_ref->fs->device,
+		    next_block_phys_idx, BLOCK_FLAGS_NONE);
+		if (rc != EOK) {
+			it->current_block = NULL;
+			return rc;
+		}
+	}
+	
+	it->current_offset = pos;
+	
+	return ext4_directory_iterator_set(it, block_size);
+}
+
+/** Do some checks before returning iterator.
+ *
+ * @param it         Iterator to be checked
+ * @param block_size Size of data block
+ *
+ * @return Error code
+ *
+ */
+static int ext4_directory_iterator_set(ext4_directory_iterator_t *it,
+    uint32_t block_size)
+{
+	it->current = NULL;
+	
+	uint32_t offset_in_block = it->current_offset % block_size;
+	
+	/* Ensure proper alignment */
+	if ((offset_in_block % 4) != 0)
+		return EIO;
+	
+	/* Ensure that the core of the entry does not overflow the block */
+	if (offset_in_block > block_size - 8)
+		return EIO;
+	
+	ext4_directory_entry_ll_t *entry =
+	    it->current_block->data + offset_in_block;
+	
+	/* Ensure that the whole entry does not overflow the block */
+	uint16_t length = ext4_directory_entry_ll_get_entry_length(entry);
+	if (offset_in_block + length > block_size)
+		return EIO;
+	
+	/* Ensure the name length is not too large */
+	if (ext4_directory_entry_ll_get_name_length(
+	    it->inode_ref->fs->superblock, entry) > length-8)
+		return EIO;
+	
+	/* Everything OK - "publish" the entry */
+	it->current = entry;
+	return EOK;
+}
+
+/** Uninitialize directory iterator.
+ *
+ * Release all allocated structures.
+ *
+ * @param it Iterator to be finished
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_iterator_fini(ext4_directory_iterator_t *it)
+{
+	it->inode_ref = NULL;
+	it->current = NULL;
+	
+	if (it->current_block)
+		return block_put(it->current_block);
+	
+	return EOK;
+}
+
+/** Write directory entry to concrete data block.
+ *
+ * @param sb        Superblock
+ * @param entry     Pointer to entry to be written
+ * @param entry_len Length of new entry
+ * @param child     Child i-node to be written to new entry
+ * @param name      Name of the new entry
+ * @param name_len  Length of entry name
+ *
+ */
+void ext4_directory_write_entry(ext4_superblock_t *sb,
+    ext4_directory_entry_ll_t *entry, uint16_t entry_len,
+    ext4_inode_ref_t *child, const char *name, size_t name_len)
+{
+	/* Check maximum entry length */
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	assert(entry_len <= block_size);
+	
+	/* Set basic attributes */
+	ext4_directory_entry_ll_set_inode(entry, child->index);
+	ext4_directory_entry_ll_set_entry_length(entry, entry_len);
+	ext4_directory_entry_ll_set_name_length(sb, entry, name_len);
+	
+	/* Write name */
+	memcpy(entry->name, name, name_len);
+	
+	/* Set type of entry */
+	if (ext4_inode_is_type(sb, child->inode, EXT4_INODE_MODE_DIRECTORY))
+		ext4_directory_entry_ll_set_inode_type(sb, entry,
+		    EXT4_DIRECTORY_FILETYPE_DIR);
+	else
+		ext4_directory_entry_ll_set_inode_type(sb, entry,
+		    EXT4_DIRECTORY_FILETYPE_REG_FILE);
+}
+
+/** Add new entry to the directory.
+ *
+ * @param parent Directory i-node
+ * @param name   Name of new entry
+ * @param child  I-node to be referenced from new entry
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_add_entry(ext4_inode_ref_t *parent, const char *name,
+    ext4_inode_ref_t *child)
+{
+	ext4_filesystem_t *fs = parent->fs;
+	
+	/* Index adding (if allowed) */
+	if ((ext4_superblock_has_feature_compatible(fs->superblock,
+	    EXT4_FEATURE_COMPAT_DIR_INDEX)) &&
+	    (ext4_inode_has_flag(parent->inode, EXT4_INODE_FLAG_INDEX))) {
+		int rc = ext4_directory_dx_add_entry(parent, child, name);
+		
+		/* Check if index is not corrupted */
+		if (rc != EXT4_ERR_BAD_DX_DIR) {
+			if (rc != EOK)
+				return rc;
+			
+			return EOK;
+		}
+		
+		/* Needed to clear dir index flag if corrupted */
+		ext4_inode_clear_flag(parent->inode, EXT4_INODE_FLAG_INDEX);
+		parent->dirty = true;
+	}
+	
+	/* Linear algorithm */
+	
+	uint32_t iblock = 0;
+	uint32_t fblock = 0;
+	uint32_t block_size = ext4_superblock_get_block_size(fs->superblock);
+	uint32_t inode_size = ext4_inode_get_size(fs->superblock, parent->inode);
+	uint32_t total_blocks = inode_size / block_size;
+	
+	uint32_t name_len = str_size(name);
+	
+	/* Find block, where is space for new entry and try to add */
+	bool success = false;
+	for (iblock = 0; iblock < total_blocks; ++iblock) {
+		int rc = ext4_filesystem_get_inode_data_block_index(parent,
+		    iblock, &fblock);
+		if (rc != EOK)
+			return rc;
+		
+		block_t *block;
+		rc = block_get(&block, fs->device, fblock, BLOCK_FLAGS_NONE);
+		if (rc != EOK)
+			return rc;
+		
+		/* If adding is successful, function can finish */
+		rc = ext4_directory_try_insert_entry(fs->superblock, block,
+		    child, name, name_len);
+		if (rc == EOK)
+			success = true;
+		
+		rc = block_put(block);
+		if (rc != EOK)
+			return rc;
+		
+		if (success)
+			return EOK;
+	}
+	
+	/* No free block found - needed to allocate next data block */
+	
+	iblock = 0;
+	fblock = 0;
+	int rc = ext4_filesystem_append_inode_block(parent, &fblock, &iblock);
+	if (rc != EOK)
+		return rc;
+	
+	/* Load new block */
+	block_t *new_block;
+	rc = block_get(&new_block, fs->device, fblock, BLOCK_FLAGS_NOREAD);
+	if (rc != EOK)
+		return rc;
+	
+	/* Fill block with zeroes */
+	memset(new_block->data, 0, block_size);
+	ext4_directory_entry_ll_t *block_entry = new_block->data;
+	ext4_directory_write_entry(fs->superblock, block_entry, block_size,
+	    child, name, name_len);
+	
+	/* Save new block */
+	new_block->dirty = true;
+	rc = block_put(new_block);
+	
+	return rc;
+}
+
+/** Find directory entry with passed name.
+ *
+ * @param result Result structure to be returned if entry found
+ * @param parent Directory i-node
+ * @param name   Name of entry to be found
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_find_entry(ext4_directory_search_result_t *result,
+    ext4_inode_ref_t *parent, const char *name)
+{
+	uint32_t name_len = str_size(name);
+	
+	ext4_superblock_t *sb = parent->fs->superblock;
+	
+	/* Index search */
+	if ((ext4_superblock_has_feature_compatible(sb,
+	    EXT4_FEATURE_COMPAT_DIR_INDEX)) &&
+	    (ext4_inode_has_flag(parent->inode, EXT4_INODE_FLAG_INDEX))) {
+		int rc = ext4_directory_dx_find_entry(result, parent, name_len,
+		    name);
+		
+		/* Check if index is not corrupted */
+		if (rc != EXT4_ERR_BAD_DX_DIR) {
+			if (rc != EOK)
+				return rc;
+			
+			return EOK;
+		}
+		
+		/* Needed to clear dir index flag if corrupted */
+		ext4_inode_clear_flag(parent->inode, EXT4_INODE_FLAG_INDEX);
+		parent->dirty = true;
+	}
+	
+	/* Linear algorithm */
+	
+	uint32_t iblock;
+	uint32_t fblock;
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	uint32_t inode_size = ext4_inode_get_size(sb, parent->inode);
+	uint32_t total_blocks = inode_size / block_size;
+	
+	/* Walk through all data blocks */
+	for (iblock = 0; iblock < total_blocks; ++iblock) {
+		/* Load block address */
+		int rc = ext4_filesystem_get_inode_data_block_index(parent, iblock,
+		    &fblock);
+		if (rc != EOK)
+			return rc;
+		
+		/* Load data block */
+		block_t *block;
+		rc = block_get(&block, parent->fs->device, fblock, BLOCK_FLAGS_NONE);
+		if (rc != EOK)
+			return rc;
+		
+		/* Try to find entry in block */
+		ext4_directory_entry_ll_t *res_entry;
+		rc = ext4_directory_find_in_block(block, sb, name_len, name,
+		    &res_entry);
+		if (rc == EOK) {
+			result->block = block;
+			result->dentry = res_entry;
+			return EOK;
+		}
+		
+		/* Entry not found - put block and continue to the next block */
+		
+		rc = block_put(block);
+		if (rc != EOK)
+			return rc;
+	}
+	
+	/* Entry was not found */
+	
+	result->block = NULL;
+	result->dentry =  NULL;
+	
+	return ENOENT;
+}
+
+/** Remove directory entry.
+ *
+ * @param parent Directory i-node
+ * @param name   Name of the entry to be removed
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_remove_entry(ext4_inode_ref_t *parent, const char *name)
+{
+	/* Check if removing from directory */
+	if (!ext4_inode_is_type(parent->fs->superblock, parent->inode,
+	    EXT4_INODE_MODE_DIRECTORY))
+		return ENOTDIR;
+	
+	/* Try to find entry */
+	ext4_directory_search_result_t result;
+	int rc = ext4_directory_find_entry(&result, parent, name);
+	if (rc != EOK)
+		return rc;
+	
+	/* Invalidate entry */
+	ext4_directory_entry_ll_set_inode(result.dentry, 0);
+	
+	/* Store entry position in block */
+	uint32_t pos = (void *) result.dentry - result.block->data;
+	
+	/*
+	 * If entry is not the first in block, it must be merged
+	 * with previous entry
+	 */
+	if (pos != 0) {
+		uint32_t offset = 0;
+		
+		/* Start from the first entry in block */
+		ext4_directory_entry_ll_t *tmp_dentry = result.block->data;
+		uint16_t tmp_dentry_length =
+		    ext4_directory_entry_ll_get_entry_length(tmp_dentry);
+		
+		/* Find direct predecessor of removed entry */
+		while ((offset + tmp_dentry_length) < pos) {
+			offset +=
+			    ext4_directory_entry_ll_get_entry_length(tmp_dentry);
+			tmp_dentry = result.block->data + offset;
+			tmp_dentry_length =
+			    ext4_directory_entry_ll_get_entry_length(tmp_dentry);
+		}
+		
+		assert(tmp_dentry_length + offset == pos);
+		
+		/* Add to removed entry length to predecessor's length */
+		uint16_t del_entry_length =
+		    ext4_directory_entry_ll_get_entry_length(result.dentry);
+		ext4_directory_entry_ll_set_entry_length(tmp_dentry,
+		    tmp_dentry_length + del_entry_length);
+	}
+	
+	result.block->dirty = true;
+	
+	return ext4_directory_destroy_result(&result);
+}
+
+/** Try to insert entry to concrete data block.
+ *
+ * @param sb           Superblock
+ * @param target_block Block to try to insert entry to
+ * @param child        Child i-node to be inserted by new entry
+ * @param name         Name of the new entry
+ * @param name_len     Length of the new entry name
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_try_insert_entry(ext4_superblock_t *sb,
+    block_t *target_block, ext4_inode_ref_t *child, const char *name,
+    uint32_t name_len)
+{
+	/* Compute required length entry and align it to 4 bytes */
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	uint16_t required_len = sizeof(ext4_fake_directory_entry_t) + name_len;
+	
+	if ((required_len % 4) != 0)
+		required_len += 4 - (required_len % 4);
+	
+	/* Initialize pointers, stop means to upper bound */
+	ext4_directory_entry_ll_t *dentry = target_block->data;
+	ext4_directory_entry_ll_t *stop = target_block->data + block_size;
+	
+	/*
+	 * Walk through the block and check for invalid entries
+	 * or entries with free space for new entry
+	 */
+	while (dentry < stop) {
+		uint32_t inode = ext4_directory_entry_ll_get_inode(dentry);
+		uint16_t rec_len = ext4_directory_entry_ll_get_entry_length(dentry);
+		
+		/* If invalid and large enough entry, use it */
+		if ((inode == 0) && (rec_len >= required_len)) {
+			ext4_directory_write_entry(sb, dentry, rec_len, child,
+			    name, name_len);
+			target_block->dirty = true;
+			
+			return EOK;
+		}
+		
+		/* Valid entry, try to split it */
+		if (inode != 0) {
+			uint16_t used_name_len =
+			    ext4_directory_entry_ll_get_name_length(sb, dentry);
+			
+			uint16_t used_space =
+			    sizeof(ext4_fake_directory_entry_t) + used_name_len;
+			
+			if ((used_name_len % 4) != 0)
+				used_space += 4 - (used_name_len % 4);
+			
+			uint16_t free_space = rec_len - used_space;
+			
+			/* There is free space for new entry */
+			if (free_space >= required_len) {
+				/* Cut tail of current entry */
+				ext4_directory_entry_ll_set_entry_length(dentry, used_space);
+				ext4_directory_entry_ll_t *new_entry =
+				    (void *) dentry + used_space;
+				ext4_directory_write_entry(sb, new_entry,
+				    free_space, child, name, name_len);
+				
+				target_block->dirty = true;
+				
+				return EOK;
+			}
+		}
+		
+		/* Jump to the next entry */
+		dentry = (void *) dentry + rec_len;
+	}
+	
+	/* No free space found for new entry */
+	return ENOSPC;
+}
+
+/** Try to find entry in block by name.
+ *
+ * @param block     Block containing entries
+ * @param sb        Superblock
+ * @param name_len  Length of entry name
+ * @param name      Name of entry to be found
+ * @param res_entry Output pointer to found entry, NULL if not found
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_find_in_block(block_t *block, ext4_superblock_t *sb,
+    size_t name_len, const char *name, ext4_directory_entry_ll_t **res_entry)
+{
+	/* Start from the first entry in block */
+	ext4_directory_entry_ll_t *dentry =
+	    (ext4_directory_entry_ll_t *) block->data;
+	
+	/* Set upper bound for cycling */
+	uint8_t *addr_limit = block->data + ext4_superblock_get_block_size(sb);
+	
+	/* Walk through the block and check entries */
+	while ((uint8_t *) dentry < addr_limit) {
+		/* Termination condition */
+		if ((uint8_t *) dentry + name_len > addr_limit)
+			break;
+		
+		/* Valid entry - check it */
+		if (dentry->inode != 0) {
+			/* For more effectivity compare firstly only lengths */
+			if (ext4_directory_entry_ll_get_name_length(sb, dentry) ==
+			    name_len) {
+				/* Compare names */
+				if (bcmp((uint8_t *) name, dentry->name, name_len) == 0) {
+					*res_entry = dentry;
+					return EOK;
+				}
+			}
+		}
+		
+		uint16_t dentry_len =
+		    ext4_directory_entry_ll_get_entry_length(dentry);
+		
+		/* Corrupted entry */
+		if (dentry_len == 0)
+			return EINVAL;
+		
+		/* Jump to next entry */
+		dentry = (ext4_directory_entry_ll_t *) ((uint8_t *) dentry + dentry_len);
+	}
+	
+	/* Entry not found */
+	return ENOENT;
+}
+
+/** Simple function to release allocated data from result.
+ *
+ * @param result Search result to destroy
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_destroy_result(ext4_directory_search_result_t *result)
+{
+	if (result->block)
+		return block_put(result->block);
+	
+	return EOK;
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_directory.h
===================================================================
--- uspace/lib/ext4/libext4_directory.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_directory.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_DIRECTORY_H_
+#define LIBEXT4_LIBEXT4_DIRECTORY_H_
+
+#include "libext4_types.h"
+
+extern uint32_t ext4_directory_entry_ll_get_inode(ext4_directory_entry_ll_t *);
+extern void ext4_directory_entry_ll_set_inode(ext4_directory_entry_ll_t *,
+    uint32_t);
+extern uint16_t ext4_directory_entry_ll_get_entry_length(
+    ext4_directory_entry_ll_t *);
+extern void ext4_directory_entry_ll_set_entry_length(ext4_directory_entry_ll_t *,
+    uint16_t);
+extern uint16_t ext4_directory_entry_ll_get_name_length(ext4_superblock_t *,
+    ext4_directory_entry_ll_t *);
+extern void ext4_directory_entry_ll_set_name_length(ext4_superblock_t *,
+    ext4_directory_entry_ll_t *, uint16_t);
+extern uint8_t ext4_directory_entry_ll_get_inode_type(ext4_superblock_t *,
+    ext4_directory_entry_ll_t *);
+extern void ext4_directory_entry_ll_set_inode_type(ext4_superblock_t *,
+    ext4_directory_entry_ll_t *, uint8_t);
+
+extern int ext4_directory_iterator_init(ext4_directory_iterator_t *,
+    ext4_inode_ref_t *, aoff64_t);
+extern int ext4_directory_iterator_next(ext4_directory_iterator_t *);
+extern int ext4_directory_iterator_fini(ext4_directory_iterator_t *);
+
+extern void ext4_directory_write_entry(ext4_superblock_t *,
+    ext4_directory_entry_ll_t *, uint16_t, ext4_inode_ref_t *,
+    const char *, size_t);
+extern int ext4_directory_add_entry(ext4_inode_ref_t *, const char *,
+    ext4_inode_ref_t *);
+extern int ext4_directory_find_entry(ext4_directory_search_result_t *,
+    ext4_inode_ref_t *, const char *);
+extern int ext4_directory_remove_entry(ext4_inode_ref_t *, const char *);
+
+extern int ext4_directory_try_insert_entry(ext4_superblock_t *, block_t *,
+    ext4_inode_ref_t *, const char *, uint32_t);
+
+extern int ext4_directory_find_in_block(block_t *, ext4_superblock_t *, size_t,
+    const char *, ext4_directory_entry_ll_t **);
+
+extern int ext4_directory_destroy_result(ext4_directory_search_result_t *);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_directory_index.c
===================================================================
--- uspace/lib/ext4/libext4_directory_index.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_directory_index.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,1159 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+/**
+ * @file  libext4_directory_index.c
+ * @brief Ext4 directory index operations.
+ */
+
+#include <byteorder.h>
+#include <errno.h>
+#include <malloc.h>
+#include <sort.h>
+#include "libext4.h"
+
+/** Type entry to pass to sorting algorithm.
+ *
+ */
+typedef struct ext4_dx_sort_entry {
+	uint32_t hash;
+	uint32_t rec_len;
+	void *dentry;
+} ext4_dx_sort_entry_t;
+
+/** Get hash version used in directory index.
+ *
+ * @param root_info Pointer to root info structure of index
+ *
+ * @return Hash algorithm version
+ *
+ */
+uint8_t ext4_directory_dx_root_info_get_hash_version(
+    ext4_directory_dx_root_info_t *root_info)
+{
+	return root_info->hash_version;
+}
+
+/** Set hash version, that will be used in directory index.
+ *
+ * @param root_info Pointer to root info structure of index
+ * @param version   Hash algorithm version
+ *
+ */
+void ext4_directory_dx_root_info_set_hash_version(
+    ext4_directory_dx_root_info_t *root_info, uint8_t version)
+{
+	root_info->hash_version = version;
+}
+
+/** Get length of root_info structure in bytes.
+ *
+ * @param root_info Pointer to root info structure of index
+ *
+ * @return Length of the structure
+ *
+ */
+uint8_t ext4_directory_dx_root_info_get_info_length(
+    ext4_directory_dx_root_info_t *root_info)
+{
+	return root_info->info_length;
+}
+
+/** Set length of root_info structure in bytes.
+ *
+ * @param root_info   Pointer to root info structure of index
+ * @param info_length Length of the structure
+ *
+ */
+void ext4_directory_dx_root_info_set_info_length(
+    ext4_directory_dx_root_info_t *root_info, uint8_t info_length)
+{
+	root_info->info_length = info_length;
+}
+
+/** Get number of indirect levels of HTree.
+ *
+ * @param root_info Pointer to root info structure of index
+ *
+ * @return Height of HTree (actually only 0 or 1)
+ *
+ */
+uint8_t ext4_directory_dx_root_info_get_indirect_levels(
+    ext4_directory_dx_root_info_t *root_info)
+{
+	return root_info->indirect_levels;
+}
+
+/** Set number of indirect levels of HTree.
+ *
+ * @param root_info Pointer to root info structure of index
+ * @param levels    Height of HTree (actually only 0 or 1)
+ *
+ */
+void ext4_directory_dx_root_info_set_indirect_levels(
+    ext4_directory_dx_root_info_t *root_info, uint8_t levels)
+{
+	root_info->indirect_levels = levels;
+}
+
+/** Get maximum number of index node entries.
+ *
+ * @param countlimit Pointer to counlimit structure
+ *
+ * @return Maximum of entries in node
+ *
+ */
+uint16_t ext4_directory_dx_countlimit_get_limit(
+    ext4_directory_dx_countlimit_t *countlimit)
+{
+	return uint16_t_le2host(countlimit->limit);
+}
+
+/** Set maximum number of index node entries.
+ *
+ * @param countlimit Pointer to counlimit structure
+ * @param limit      Maximum of entries in node
+ *
+ */
+void ext4_directory_dx_countlimit_set_limit(
+    ext4_directory_dx_countlimit_t *countlimit, uint16_t limit)
+{
+	countlimit->limit = host2uint16_t_le(limit);
+}
+
+/** Get current number of index node entries.
+ *
+ * @param countlimit Pointer to counlimit structure
+ *
+ * @return Number of entries in node
+ *
+ */
+uint16_t ext4_directory_dx_countlimit_get_count(
+    ext4_directory_dx_countlimit_t *countlimit)
+{
+	return uint16_t_le2host(countlimit->count);
+}
+
+/** Set current number of index node entries.
+ *
+ * @param countlimit Pointer to counlimit structure
+ * @param count      Number of entries in node
+ *
+ */
+void ext4_directory_dx_countlimit_set_count(
+    ext4_directory_dx_countlimit_t *countlimit, uint16_t count)
+{
+	countlimit->count = host2uint16_t_le(count);
+}
+
+/** Get hash value of index entry.
+ *
+ * @param entry Pointer to index entry
+ *
+ * @return Hash value
+ *
+ */
+uint32_t ext4_directory_dx_entry_get_hash(ext4_directory_dx_entry_t *entry)
+{
+	return uint32_t_le2host(entry->hash);
+}
+
+/** Set hash value of index entry.
+ *
+ * @param entry Pointer to index entry
+ * @param hash  Hash value
+ *
+ */
+void ext4_directory_dx_entry_set_hash(ext4_directory_dx_entry_t *entry,
+    uint32_t hash)
+{
+	entry->hash = host2uint32_t_le(hash);
+}
+
+/** Get block address where child node is located.
+ *
+ * @param entry Pointer to index entry
+ *
+ * @return Block address of child node
+ *
+ */
+uint32_t ext4_directory_dx_entry_get_block(ext4_directory_dx_entry_t *entry)
+{
+	return uint32_t_le2host(entry->block);
+}
+
+/** Set block address where child node is located.
+ *
+ * @param entry Pointer to index entry
+ * @param block Block address of child node
+ *
+ */
+void ext4_directory_dx_entry_set_block(ext4_directory_dx_entry_t *entry,
+    uint32_t block)
+{
+	entry->block = host2uint32_t_le(block);
+}
+
+/** Initialize index structure of new directory.
+ *
+ * @param dir Pointer to directory i-node
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_dx_init(ext4_inode_ref_t *dir)
+{
+	/* Load block 0, where will be index root located */
+	uint32_t fblock;
+	int rc = ext4_filesystem_get_inode_data_block_index(dir, 0,
+	    &fblock);
+	if (rc != EOK)
+		return rc;
+	
+	block_t *block;
+	rc = block_get(&block, dir->fs->device, fblock, BLOCK_FLAGS_NONE);
+	if (rc != EOK)
+		return rc;
+	
+	/* Initialize pointers to data structures */
+	ext4_directory_dx_root_t *root = block->data;
+	ext4_directory_dx_root_info_t *info = &(root->info);
+	
+	/* Initialize root info structure */
+	uint8_t hash_version =
+	    ext4_superblock_get_default_hash_version(dir->fs->superblock);
+	
+	ext4_directory_dx_root_info_set_hash_version(info, hash_version);
+	ext4_directory_dx_root_info_set_indirect_levels(info, 0);
+	ext4_directory_dx_root_info_set_info_length(info, 8);
+	
+	/* Set limit and current number of entries */
+	ext4_directory_dx_countlimit_t *countlimit =
+	    (ext4_directory_dx_countlimit_t *) &root->entries;
+	ext4_directory_dx_countlimit_set_count(countlimit, 1);
+	
+	uint32_t block_size =
+	    ext4_superblock_get_block_size(dir->fs->superblock);
+	uint32_t entry_space =
+	    block_size - 2 * sizeof(ext4_directory_dx_dot_entry_t) -
+	    sizeof(ext4_directory_dx_root_info_t);
+	uint16_t root_limit = entry_space / sizeof(ext4_directory_dx_entry_t);
+	ext4_directory_dx_countlimit_set_limit(countlimit, root_limit);
+	
+	/* Append new block, where will be new entries inserted in the future */
+	uint32_t iblock;
+	rc = ext4_filesystem_append_inode_block(dir, &fblock, &iblock);
+	if (rc != EOK) {
+		block_put(block);
+		return rc;
+	}
+	
+	block_t *new_block;
+	rc = block_get(&new_block, dir->fs->device, fblock, BLOCK_FLAGS_NOREAD);
+	if (rc != EOK) {
+		block_put(block);
+		return rc;
+	}
+	
+	/* Fill the whole block with empty entry */
+	ext4_directory_entry_ll_t *block_entry = new_block->data;
+	ext4_directory_entry_ll_set_entry_length(block_entry, block_size);
+	ext4_directory_entry_ll_set_inode(block_entry, 0);
+	
+	new_block->dirty = true;
+	rc = block_put(new_block);
+	if (rc != EOK) {
+		block_put(block);
+		return rc;
+	}
+	
+	/* Connect new block to the only entry in index */
+	ext4_directory_dx_entry_t *entry = root->entries;
+	ext4_directory_dx_entry_set_block(entry, iblock);
+	
+	block->dirty = true;
+	
+	return block_put(block);
+}
+
+/** Initialize hash info structure necessary for index operations.
+ *
+ * @param hinfo      Pointer to hinfo to be initialized
+ * @param root_block Root block (number 0) of index
+ * @param sb         Pointer to superblock
+ * @param name_len   Length of name to be computed hash value from
+ * @param name       Name to be computed hash value from
+ *
+ * @return Error code
+ *
+ */
+static int ext4_directory_hinfo_init(ext4_hash_info_t *hinfo,
+    block_t *root_block, ext4_superblock_t *sb, size_t name_len,
+    const char *name)
+{
+	ext4_directory_dx_root_t *root =
+	    (ext4_directory_dx_root_t *) root_block->data;
+	
+	if ((root->info.hash_version != EXT4_HASH_VERSION_TEA) &&
+	    (root->info.hash_version != EXT4_HASH_VERSION_HALF_MD4) &&
+	    (root->info.hash_version != EXT4_HASH_VERSION_LEGACY))
+		return EXT4_ERR_BAD_DX_DIR;
+	
+	/* Check unused flags */
+	if (root->info.unused_flags != 0)
+		return EXT4_ERR_BAD_DX_DIR;
+	
+	/* Check indirect levels */
+	if (root->info.indirect_levels > 1)
+		return EXT4_ERR_BAD_DX_DIR;
+	
+	/* Check if node limit is correct */
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	uint32_t entry_space = block_size;
+	entry_space -= 2 * sizeof(ext4_directory_dx_dot_entry_t);
+	entry_space -= sizeof(ext4_directory_dx_root_info_t);
+	entry_space = entry_space / sizeof(ext4_directory_dx_entry_t);
+	
+	uint16_t limit = ext4_directory_dx_countlimit_get_limit(
+	    (ext4_directory_dx_countlimit_t *) &root->entries);
+	if (limit != entry_space)
+		return EXT4_ERR_BAD_DX_DIR;
+	
+	/* Check hash version and modify if necessary */
+	hinfo->hash_version =
+	    ext4_directory_dx_root_info_get_hash_version(&root->info);
+	if ((hinfo->hash_version <= EXT4_HASH_VERSION_TEA) &&
+	    (ext4_superblock_has_flag(sb, EXT4_SUPERBLOCK_FLAGS_UNSIGNED_HASH))) {
+		/* 3 is magic from ext4 linux implementation */
+		hinfo->hash_version += 3;
+	}
+	
+	/* Load hash seed from superblock */
+	hinfo->seed = ext4_superblock_get_hash_seed(sb);
+	
+	/* Compute hash value of name */
+	if (name)
+		ext4_hash_string(hinfo, name_len, name);
+	
+	return EOK;
+}
+
+/** Walk through index tree and load leaf with corresponding hash value.
+ *
+ * @param hinfo      Initialized hash info structure
+ * @param inode_ref  Current i-node
+ * @param root_block Root block (iblock 0), where is root node located
+ * @param dx_block   Pointer to leaf node in dx_blocks array
+ * @param dx_blocks  Array with the whole path from root to leaf
+ *
+ * @return Error code
+ *
+ */
+static int ext4_directory_dx_get_leaf(ext4_hash_info_t *hinfo,
+    ext4_inode_ref_t *inode_ref, block_t *root_block,
+    ext4_directory_dx_block_t **dx_block, ext4_directory_dx_block_t *dx_blocks)
+{
+	ext4_directory_dx_block_t *tmp_dx_block = dx_blocks;
+	ext4_directory_dx_root_t *root =
+	    (ext4_directory_dx_root_t *) root_block->data;
+	ext4_directory_dx_entry_t *entries =
+	    (ext4_directory_dx_entry_t *) &root->entries;
+	
+	uint16_t limit = ext4_directory_dx_countlimit_get_limit(
+	    (ext4_directory_dx_countlimit_t *) entries);
+	uint8_t indirect_level =
+	    ext4_directory_dx_root_info_get_indirect_levels(&root->info);
+	
+	block_t *tmp_block = root_block;
+	ext4_directory_dx_entry_t *p;
+	ext4_directory_dx_entry_t *q;
+	ext4_directory_dx_entry_t *m;
+	ext4_directory_dx_entry_t *at;
+	
+	/* Walk through the index tree */
+	while (true) {
+		uint16_t count = ext4_directory_dx_countlimit_get_count(
+		    (ext4_directory_dx_countlimit_t *) entries);
+		if ((count == 0) || (count > limit))
+			return EXT4_ERR_BAD_DX_DIR;
+		
+		/* Do binary search in every node */
+		p = entries + 1;
+		q = entries + count - 1;
+		
+		while (p <= q) {
+			m = p + (q - p) / 2;
+			if (ext4_directory_dx_entry_get_hash(m) > hinfo->hash)
+				q = m - 1;
+			else
+				p = m + 1;
+		}
+		
+		at = p - 1;
+		
+		/* Write results */
+		tmp_dx_block->block = tmp_block;
+		tmp_dx_block->entries = entries;
+		tmp_dx_block->position = at;
+		
+		/* Is algorithm in the leaf? */
+		if (indirect_level == 0) {
+			*dx_block = tmp_dx_block;
+			return EOK;
+		}
+		
+		/* Goto child node */
+		uint32_t next_block = ext4_directory_dx_entry_get_block(at);
+		
+		indirect_level--;
+		
+		uint32_t fblock;
+		int rc = ext4_filesystem_get_inode_data_block_index(inode_ref,
+		    next_block, &fblock);
+		if (rc != EOK)
+			return rc;
+		
+		rc = block_get(&tmp_block, inode_ref->fs->device, fblock,
+		    BLOCK_FLAGS_NONE);
+		if (rc != EOK)
+			return rc;
+		
+		entries = ((ext4_directory_dx_node_t *) tmp_block->data)->entries;
+		limit = ext4_directory_dx_countlimit_get_limit(
+		    (ext4_directory_dx_countlimit_t *) entries);
+		
+		uint16_t entry_space =
+		    ext4_superblock_get_block_size(inode_ref->fs->superblock) -
+		    sizeof(ext4_directory_dx_dot_entry_t);
+		entry_space = entry_space / sizeof(ext4_directory_dx_entry_t);
+		
+		if (limit != entry_space) {
+			block_put(tmp_block);
+			return EXT4_ERR_BAD_DX_DIR;
+		}
+		
+		++tmp_dx_block;
+	}
+	
+	/* Unreachable */
+	return EOK;
+}
+
+/** Check if the the next block would be checked during entry search.
+ *
+ * @param inode_ref Directory i-node
+ * @param hash      Hash value to check
+ * @param dx_block  Current block
+ * @param dx_blocks Array with path from root to leaf node
+ *
+ * @return Error code
+ *
+ */
+static int ext4_directory_dx_next_block(ext4_inode_ref_t *inode_ref,
+    uint32_t hash, ext4_directory_dx_block_t *dx_block,
+    ext4_directory_dx_block_t *dx_blocks)
+{
+	uint32_t num_handles = 0;
+	ext4_directory_dx_block_t *p = dx_block;
+	
+	/* Try to find data block with next bunch of entries */
+	while (true) {
+		p->position++;
+		uint16_t count = ext4_directory_dx_countlimit_get_count(
+		    (ext4_directory_dx_countlimit_t *) p->entries);
+		
+		if (p->position < p->entries + count)
+			break;
+		
+		if (p == dx_blocks)
+			return EOK;
+		
+		num_handles++;
+		p--;
+	}
+	
+	/* Check hash collision (if not occured - no next block cannot be used) */
+	uint32_t current_hash = ext4_directory_dx_entry_get_hash(p->position);
+	if ((hash & 1) == 0) {
+		if ((current_hash & ~1) != hash)
+			return 0;
+	}
+	
+	/* Fill new path */
+	while (num_handles--) {
+		uint32_t block_idx =
+		    ext4_directory_dx_entry_get_block(p->position);
+		uint32_t block_addr;
+		
+		int rc = ext4_filesystem_get_inode_data_block_index(inode_ref,
+		    block_idx, &block_addr);
+		if (rc != EOK)
+			return rc;
+		
+		block_t *block;
+		rc = block_get(&block, inode_ref->fs->device, block_addr, BLOCK_FLAGS_NONE);
+		if (rc != EOK)
+			return rc;
+		
+		p++;
+		
+		/* Don't forget to put old block (prevent memory leak) */
+		block_put(p->block);
+		
+		p->block = block;
+		p->entries = ((ext4_directory_dx_node_t *) block->data)->entries;
+		p->position = p->entries;
+	}
+	
+	return ENOENT;
+}
+
+/** Try to find directory entry using directory index.
+ *
+ * @param result    Output value - if entry will be found,
+ *                  than will be passed through this parameter
+ * @param inode_ref Directory i-node
+ * @param name_len  Length of name to be found
+ * @param name      Name to be found
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_dx_find_entry(ext4_directory_search_result_t *result,
+    ext4_inode_ref_t *inode_ref, size_t name_len, const char *name)
+{
+	/* Load direct block 0 (index root) */
+	uint32_t root_block_addr;
+	int rc = ext4_filesystem_get_inode_data_block_index(inode_ref, 0,
+	    &root_block_addr);
+	if (rc != EOK)
+		return rc;
+	
+	ext4_filesystem_t *fs = inode_ref->fs;
+	
+	block_t *root_block;
+	rc = block_get(&root_block, fs->device, root_block_addr,
+	    BLOCK_FLAGS_NONE);
+	if (rc != EOK)
+		return rc;
+	
+	/* Initialize hash info (compute hash value) */
+	ext4_hash_info_t hinfo;
+	rc = ext4_directory_hinfo_init(&hinfo, root_block, fs->superblock,
+	    name_len, name);
+	if (rc != EOK) {
+		block_put(root_block);
+		return EXT4_ERR_BAD_DX_DIR;
+	}
+	
+	/*
+	 * Hardcoded number 2 means maximum height of index tree,
+	 * specified in the Linux driver.
+	 */
+	ext4_directory_dx_block_t dx_blocks[2];
+	ext4_directory_dx_block_t *dx_block;
+	ext4_directory_dx_block_t *tmp;
+	
+	rc = ext4_directory_dx_get_leaf(&hinfo, inode_ref, root_block,
+	    &dx_block, dx_blocks);
+	if (rc != EOK) {
+		block_put(root_block);
+		return EXT4_ERR_BAD_DX_DIR;
+	}
+	
+	do {
+		/* Load leaf block */
+		uint32_t leaf_block_idx =
+		    ext4_directory_dx_entry_get_block(dx_block->position);
+		uint32_t leaf_block_addr;
+		
+		rc = ext4_filesystem_get_inode_data_block_index(inode_ref,
+		    leaf_block_idx, &leaf_block_addr);
+		if (rc != EOK)
+			goto cleanup;
+		
+		block_t *leaf_block;
+		rc = block_get(&leaf_block, fs->device, leaf_block_addr,
+		    BLOCK_FLAGS_NONE);
+		if (rc != EOK)
+			goto cleanup;
+		
+		/* Linear search inside block */
+		ext4_directory_entry_ll_t *res_dentry;
+		rc = ext4_directory_find_in_block(leaf_block, fs->superblock,
+		    name_len, name, &res_dentry);
+		
+		/* Found => return it */
+		if (rc == EOK) {
+			result->block = leaf_block;
+			result->dentry = res_dentry;
+			goto cleanup;
+		}
+		
+		/* Not found, leave untouched */
+		block_put(leaf_block);
+		
+		if (rc != ENOENT)
+			goto cleanup;
+		
+		/* check if the next block could be checked */
+		rc = ext4_directory_dx_next_block(inode_ref, hinfo.hash,
+		    dx_block, &dx_blocks[0]);
+		if (rc < 0)
+			goto cleanup;
+	} while (rc == ENOENT);
+	
+	/* Entry not found */
+	rc = ENOENT;
+	
+cleanup:
+	/* The whole path must be released (preventing memory leak) */
+	tmp = dx_blocks;
+	
+	while (tmp <= dx_block) {
+		block_put(tmp->block);
+		++tmp;
+	}
+	
+	return rc;
+}
+
+/** Compare function used to pass in quicksort implementation.
+ *
+ * It can compare two entries by hash value.
+ *
+ * @param arg1  First entry
+ * @param arg2  Second entry
+ * @param dummy Unused parameter, can be NULL
+ *
+ * @return Classic compare result
+ *         (0: equal, -1: arg1 < arg2, 1: arg1 > arg2)
+ *
+ */
+static int ext4_directory_dx_entry_comparator(void *arg1, void *arg2, void *dummy)
+{
+	ext4_dx_sort_entry_t *entry1 = arg1;
+	ext4_dx_sort_entry_t *entry2 = arg2;
+	
+	if (entry1->hash == entry2->hash)
+		return 0;
+	
+	if (entry1->hash < entry2->hash)
+		return -1;
+	else
+		return 1;
+}
+
+/** Insert new index entry to block.
+ *
+ * Note that space for new entry must be checked by caller.
+ *
+ * @param index_block Block where to insert new entry
+ * @param hash        Hash value covered by child node
+ * @param iblock      Logical number of child block
+ *
+ */
+static void ext4_directory_dx_insert_entry(
+    ext4_directory_dx_block_t *index_block, uint32_t hash, uint32_t iblock)
+{
+	ext4_directory_dx_entry_t *old_index_entry = index_block->position;
+	ext4_directory_dx_entry_t *new_index_entry = old_index_entry + 1;
+	
+	ext4_directory_dx_countlimit_t *countlimit =
+	    (ext4_directory_dx_countlimit_t *) index_block->entries;
+	uint32_t count = ext4_directory_dx_countlimit_get_count(countlimit);
+	
+	ext4_directory_dx_entry_t *start_index = index_block->entries;
+	size_t bytes = (void *) (start_index + count) - (void *) (new_index_entry);
+	
+	memmove(new_index_entry + 1, new_index_entry, bytes);
+	
+	ext4_directory_dx_entry_set_block(new_index_entry, iblock);
+	ext4_directory_dx_entry_set_hash(new_index_entry, hash);
+	
+	ext4_directory_dx_countlimit_set_count(countlimit, count + 1);
+	
+	index_block->block->dirty = true;
+}
+
+/** Split directory entries to two parts preventing node overflow.
+ *
+ * @param inode_ref      Directory i-node
+ * @param hinfo          Hash info
+ * @param old_data_block Block with data to be split
+ * @param index_block    Block where index entries are located
+ * @param new_data_block Output value for newly allocated data block
+ *
+ */
+static int ext4_directory_dx_split_data(ext4_inode_ref_t *inode_ref,
+    ext4_hash_info_t *hinfo, block_t *old_data_block,
+    ext4_directory_dx_block_t *index_block, block_t **new_data_block)
+{
+	int rc = EOK;
+	
+	/* Allocate buffer for directory entries */
+	uint32_t block_size =
+	    ext4_superblock_get_block_size(inode_ref->fs->superblock);
+	void *entry_buffer = malloc(block_size);
+	if (entry_buffer == NULL)
+		return ENOMEM;
+	
+	/* dot entry has the smallest size available */
+	uint32_t max_entry_count =
+	    block_size / sizeof(ext4_directory_dx_dot_entry_t);
+	
+	/* Allocate sort entry */
+	ext4_dx_sort_entry_t *sort_array =
+	    malloc(max_entry_count * sizeof(ext4_dx_sort_entry_t));
+	if (sort_array == NULL) {
+		free(entry_buffer);
+		return ENOMEM;
+	}
+	
+	uint32_t idx = 0;
+	uint32_t real_size = 0;
+	
+	/* Initialize hinfo */
+	ext4_hash_info_t tmp_hinfo;
+	memcpy(&tmp_hinfo, hinfo, sizeof(ext4_hash_info_t));
+	
+	/* Load all valid entries to the buffer */
+	ext4_directory_entry_ll_t *dentry = old_data_block->data;
+	void *entry_buffer_ptr = entry_buffer;
+	while ((void *)dentry < old_data_block->data + block_size) {
+		/* Read only valid entries */
+		if (ext4_directory_entry_ll_get_inode(dentry) != 0) {
+			uint8_t len = ext4_directory_entry_ll_get_name_length(
+			    inode_ref->fs->superblock, dentry);
+			ext4_hash_string(&tmp_hinfo, len, (char *) dentry->name);
+			
+			uint32_t rec_len = 8 + len;
+			
+			if ((rec_len % 4) != 0)
+				rec_len += 4 - (rec_len % 4);
+			
+			memcpy(entry_buffer_ptr, dentry, rec_len);
+			
+			sort_array[idx].dentry = entry_buffer_ptr;
+			sort_array[idx].rec_len = rec_len;
+			sort_array[idx].hash = tmp_hinfo.hash;
+			
+			entry_buffer_ptr += rec_len;
+			real_size += rec_len;
+			idx++;
+		}
+		
+		dentry = (void *) dentry +
+		    ext4_directory_entry_ll_get_entry_length(dentry);
+	}
+	
+	/* Sort all entries */
+	qsort(sort_array, idx, sizeof(ext4_dx_sort_entry_t),
+	    ext4_directory_dx_entry_comparator, NULL);
+	
+	/* Allocate new block for store the second part of entries */
+	uint32_t new_fblock;
+	uint32_t new_iblock;
+	rc = ext4_filesystem_append_inode_block(inode_ref, &new_fblock,
+	    &new_iblock);
+	if (rc != EOK) {
+		free(sort_array);
+		free(entry_buffer);
+		return rc;
+	}
+	
+	/* Load new block */
+	block_t *new_data_block_tmp;
+	rc = block_get(&new_data_block_tmp, inode_ref->fs->device,
+	    new_fblock, BLOCK_FLAGS_NOREAD);
+	if (rc != EOK) {
+		free(sort_array);
+		free(entry_buffer);
+		return rc;
+	}
+	
+	/*
+	 * Distribute entries to two blocks (by size)
+	 * - compute the half
+	 */
+	uint32_t new_hash = 0;
+	uint32_t current_size = 0;
+	uint32_t mid = 0;
+	for (uint32_t i = 0; i < idx; ++i) {
+		if ((current_size + sort_array[i].rec_len) > (real_size / 2)) {
+			new_hash = sort_array[i].hash;
+			mid = i;
+			break;
+		}
+		
+		current_size += sort_array[i].rec_len;
+	}
+	
+	/* Check hash collision */
+	uint32_t continued = 0;
+	if (new_hash == sort_array[mid-1].hash)
+		continued = 1;
+	
+	uint32_t offset = 0;
+	void *ptr;
+	
+	/* First part - to the old block */
+	for (uint32_t i = 0; i < mid; ++i) {
+		ptr = old_data_block->data + offset;
+		memcpy(ptr, sort_array[i].dentry, sort_array[i].rec_len);
+		
+		ext4_directory_entry_ll_t *tmp = ptr;
+		if (i < (mid - 1))
+			ext4_directory_entry_ll_set_entry_length(tmp,
+			    sort_array[i].rec_len);
+		else
+			ext4_directory_entry_ll_set_entry_length(tmp,
+			    block_size - offset);
+		
+		offset += sort_array[i].rec_len;
+	}
+	
+	/* Second part - to the new block */
+	offset = 0;
+	for (uint32_t i = mid; i < idx; ++i) {
+		ptr = new_data_block_tmp->data + offset;
+		memcpy(ptr, sort_array[i].dentry, sort_array[i].rec_len);
+		
+		ext4_directory_entry_ll_t *tmp = ptr;
+		if (i < (idx - 1))
+			ext4_directory_entry_ll_set_entry_length(tmp,
+			    sort_array[i].rec_len);
+		else
+			ext4_directory_entry_ll_set_entry_length(tmp,
+			    block_size - offset);
+		
+		offset += sort_array[i].rec_len;
+	}
+	
+	/* Do some steps to finish operation */
+	old_data_block->dirty = true;
+	new_data_block_tmp->dirty = true;
+	
+	free(sort_array);
+	free(entry_buffer);
+	
+	ext4_directory_dx_insert_entry(index_block, new_hash + continued,
+	    new_iblock);
+	
+	*new_data_block = new_data_block_tmp;
+	
+	return EOK;
+}
+
+/** Split index node and maybe some parent nodes in the tree hierarchy.
+ *
+ * @param inode_ref Directory i-node
+ * @param dx_blocks Array with path from root to leaf node
+ * @param dx_block  Leaf block to be split if needed
+ *
+ * @return Error code
+ *
+ */
+static int ext4_directory_dx_split_index(ext4_inode_ref_t *inode_ref,
+		ext4_directory_dx_block_t *dx_blocks, ext4_directory_dx_block_t *dx_block)
+{
+	ext4_directory_dx_entry_t *entries;
+	if (dx_block == dx_blocks)
+		entries =
+		    ((ext4_directory_dx_root_t *) dx_block->block->data)->entries;
+	else
+		entries =
+		    ((ext4_directory_dx_node_t *) dx_block->block->data)->entries;
+	
+	ext4_directory_dx_countlimit_t *countlimit =
+	    (ext4_directory_dx_countlimit_t *) entries;
+	
+	uint16_t leaf_limit =
+	    ext4_directory_dx_countlimit_get_limit(countlimit);
+	uint16_t leaf_count =
+	    ext4_directory_dx_countlimit_get_count(countlimit);
+	
+	/* Check if is necessary to split index block */
+	if (leaf_limit == leaf_count) {
+		size_t levels = dx_block - dx_blocks;
+		
+		ext4_directory_dx_entry_t *root_entries =
+		    ((ext4_directory_dx_root_t *) dx_blocks[0].block->data)->entries;
+		
+		ext4_directory_dx_countlimit_t *root_countlimit =
+		    (ext4_directory_dx_countlimit_t *) root_entries;
+		uint16_t root_limit =
+		    ext4_directory_dx_countlimit_get_limit(root_countlimit);
+		uint16_t root_count =
+		    ext4_directory_dx_countlimit_get_count(root_countlimit);
+		
+		/* Linux limitation */
+		if ((levels > 0) && (root_limit == root_count))
+			return ENOSPC;
+		
+		/* Add new block to directory */
+		uint32_t new_fblock;
+		uint32_t new_iblock;
+		int rc = ext4_filesystem_append_inode_block(inode_ref,
+		    &new_fblock, &new_iblock);
+		if (rc != EOK)
+			return rc;
+		
+		/* load new block */
+		block_t *new_block;
+		rc = block_get(&new_block, inode_ref->fs->device,
+		    new_fblock, BLOCK_FLAGS_NOREAD);
+		if (rc != EOK)
+			return rc;
+		
+		ext4_directory_dx_node_t *new_node = new_block->data;
+		ext4_directory_dx_entry_t *new_entries = new_node->entries;
+		
+		uint32_t block_size =
+		    ext4_superblock_get_block_size(inode_ref->fs->superblock);
+		
+		/* Split leaf node */
+		if (levels > 0) {
+			uint32_t count_left = leaf_count / 2;
+			uint32_t count_right = leaf_count - count_left;
+			uint32_t hash_right =
+			    ext4_directory_dx_entry_get_hash(entries + count_left);
+			
+			/* Copy data to new node */
+			memcpy((void *) new_entries, (void *) (entries + count_left),
+			    count_right * sizeof(ext4_directory_dx_entry_t));
+			
+			/* Initialize new node */
+			ext4_directory_dx_countlimit_t *left_countlimit =
+			    (ext4_directory_dx_countlimit_t *) entries;
+			ext4_directory_dx_countlimit_t *right_countlimit =
+			    (ext4_directory_dx_countlimit_t *) new_entries;
+			
+			ext4_directory_dx_countlimit_set_count(left_countlimit, count_left);
+			ext4_directory_dx_countlimit_set_count(right_countlimit, count_right);
+			
+			uint32_t entry_space =
+			    block_size - sizeof(ext4_fake_directory_entry_t);
+			uint32_t node_limit =
+			    entry_space / sizeof(ext4_directory_dx_entry_t);
+			ext4_directory_dx_countlimit_set_limit(right_countlimit, node_limit);
+			
+			/* Which index block is target for new entry */
+			uint32_t position_index = (dx_block->position - dx_block->entries);
+			if (position_index >= count_left) {
+				dx_block->block->dirty = true;
+				
+				block_t *block_tmp = dx_block->block;
+				dx_block->block = new_block;
+				dx_block->position =
+				    new_entries + position_index - count_left;
+				dx_block->entries = new_entries;
+				
+				new_block = block_tmp;
+			}
+			
+			/* Finally insert new entry */
+			ext4_directory_dx_insert_entry(dx_blocks, hash_right, new_iblock);
+			
+			return block_put(new_block);
+		} else {
+			/* Create second level index */
+			
+			/* Copy data from root to child block */
+			memcpy((void *) new_entries, (void *) entries,
+			    leaf_count * sizeof(ext4_directory_dx_entry_t));
+			
+			ext4_directory_dx_countlimit_t *new_countlimit =
+			    (ext4_directory_dx_countlimit_t *) new_entries;
+			
+			uint32_t entry_space =
+			    block_size - sizeof(ext4_fake_directory_entry_t);
+			uint32_t node_limit =
+			    entry_space / sizeof(ext4_directory_dx_entry_t);
+			ext4_directory_dx_countlimit_set_limit(new_countlimit, node_limit);
+			
+			/* Set values in root node */
+			ext4_directory_dx_countlimit_t *new_root_countlimit =
+			    (ext4_directory_dx_countlimit_t *) entries;
+			
+			ext4_directory_dx_countlimit_set_count(new_root_countlimit, 1);
+			ext4_directory_dx_entry_set_block(entries, new_iblock);
+			
+			((ext4_directory_dx_root_t *)
+			    dx_blocks[0].block->data)->info.indirect_levels = 1;
+			
+			/* Add new entry to the path */
+			dx_block = dx_blocks + 1;
+			dx_block->position = dx_block->position - entries + new_entries;
+			dx_block->entries = new_entries;
+			dx_block->block = new_block;
+		}
+	}
+	
+	return EOK;
+}
+
+/** Add new entry to indexed directory
+ *
+ * @param parent Directory i-node
+ * @param child  I-node to be referenced from directory entry
+ * @param name   Name of new directory entry
+ *
+ * @return Error code
+ *
+ */
+int ext4_directory_dx_add_entry(ext4_inode_ref_t *parent,
+    ext4_inode_ref_t *child, const char *name)
+{
+	int rc2 = EOK;
+	
+	/* Get direct block 0 (index root) */
+	uint32_t root_block_addr;
+	int rc = ext4_filesystem_get_inode_data_block_index(parent, 0,
+	    &root_block_addr);
+	if (rc != EOK)
+		return rc;
+	
+	ext4_filesystem_t *fs = parent->fs;
+	
+	block_t *root_block;
+	rc = block_get(&root_block, fs->device, root_block_addr,
+	    BLOCK_FLAGS_NONE);
+	if (rc != EOK)
+		return rc;
+	
+	/* Initialize hinfo structure (mainly compute hash) */
+	uint32_t name_len = str_size(name);
+	ext4_hash_info_t hinfo;
+	rc = ext4_directory_hinfo_init(&hinfo, root_block, fs->superblock,
+	    name_len, name);
+	if (rc != EOK) {
+		block_put(root_block);
+		return EXT4_ERR_BAD_DX_DIR;
+	}
+	
+	/*
+	 * Hardcoded number 2 means maximum height of index
+	 * tree defined in Linux.
+	 */
+	ext4_directory_dx_block_t dx_blocks[2];
+	ext4_directory_dx_block_t *dx_block;
+	ext4_directory_dx_block_t *dx_it;
+	
+	rc = ext4_directory_dx_get_leaf(&hinfo, parent, root_block,
+	    &dx_block, dx_blocks);
+	if (rc != EOK) {
+		rc = EXT4_ERR_BAD_DX_DIR;
+		goto release_index;
+	}
+	
+	/* Try to insert to existing data block */
+	uint32_t leaf_block_idx =
+	    ext4_directory_dx_entry_get_block(dx_block->position);
+	uint32_t leaf_block_addr;
+	rc = ext4_filesystem_get_inode_data_block_index(parent, leaf_block_idx,
+	    &leaf_block_addr);
+	if (rc != EOK)
+		goto release_index;
+	
+	block_t *target_block;
+	rc = block_get(&target_block, fs->device, leaf_block_addr,
+	    BLOCK_FLAGS_NONE);
+	if (rc != EOK)
+		goto release_index;
+	
+	/* Check if insert operation passed */
+	rc = ext4_directory_try_insert_entry(fs->superblock, target_block, child,
+	    name, name_len);
+	if (rc == EOK)
+		goto release_target_index;
+	
+	/*
+	 * Check if there is needed to split index node
+	 * (and recursively also parent nodes)
+	 */
+	rc = ext4_directory_dx_split_index(parent, dx_blocks, dx_block);
+	if (rc != EOK)
+		goto release_target_index;
+	
+	/* Split entries to two blocks (includes sorting by hash value) */
+	block_t *new_block = NULL;
+	rc = ext4_directory_dx_split_data(parent, &hinfo, target_block,
+	    dx_block, &new_block);
+	if (rc != EOK) {
+		rc2 = rc;
+		goto release_target_index;
+	}
+	
+	/* Where to save new entry */
+	uint32_t new_block_hash =
+	    ext4_directory_dx_entry_get_hash(dx_block->position + 1);
+	if (hinfo.hash >= new_block_hash)
+		rc = ext4_directory_try_insert_entry(fs->superblock, new_block,
+		    child, name, name_len);
+	else
+		rc = ext4_directory_try_insert_entry(fs->superblock, target_block,
+		    child, name, name_len);
+	
+	/* Cleanup */
+	rc = block_put(new_block);
+	if (rc != EOK)
+		return rc;
+	
+	/* Cleanup operations */
+	
+release_target_index:
+	rc2 = rc;
+	
+	rc = block_put(target_block);
+	if (rc != EOK)
+		return rc;
+	
+release_index:
+	if (rc != EOK)
+		rc2 = rc;
+	
+	dx_it = dx_blocks;
+	
+	while (dx_it <= dx_block) {
+		rc = block_put(dx_it->block);
+		if (rc != EOK)
+			return rc;
+		
+		dx_it++;
+	}
+	
+	return rc2;
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_directory_index.h
===================================================================
--- uspace/lib/ext4/libext4_directory_index.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_directory_index.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_DIRECTORY_INDEX_H_
+#define LIBEXT4_LIBEXT4_DIRECTORY_INDEX_H_
+
+#include "libext4_types.h"
+
+extern uint8_t ext4_directory_dx_root_info_get_hash_version(
+    ext4_directory_dx_root_info_t *);
+extern void ext4_directory_dx_root_info_set_hash_version(
+    ext4_directory_dx_root_info_t *, uint8_t);
+extern uint8_t ext4_directory_dx_root_info_get_info_length(
+    ext4_directory_dx_root_info_t *);
+extern void ext4_directory_dx_root_info_set_info_length(
+    ext4_directory_dx_root_info_t *, uint8_t);
+extern uint8_t ext4_directory_dx_root_info_get_indirect_levels(
+    ext4_directory_dx_root_info_t *);
+extern void ext4_directory_dx_root_info_set_indirect_levels(
+    ext4_directory_dx_root_info_t *, uint8_t);
+
+extern uint16_t ext4_directory_dx_countlimit_get_limit(
+    ext4_directory_dx_countlimit_t *);
+extern void ext4_directory_dx_countlimit_set_limit(
+    ext4_directory_dx_countlimit_t *, uint16_t);
+extern uint16_t ext4_directory_dx_countlimit_get_count(
+    ext4_directory_dx_countlimit_t *);
+extern void ext4_directory_dx_countlimit_set_count(
+    ext4_directory_dx_countlimit_t *, uint16_t);
+
+extern uint32_t ext4_directory_dx_entry_get_hash(ext4_directory_dx_entry_t *);
+extern void ext4_directory_dx_entry_set_hash(ext4_directory_dx_entry_t *,
+    uint32_t);
+extern uint32_t ext4_directory_dx_entry_get_block(ext4_directory_dx_entry_t *);
+extern void ext4_directory_dx_entry_set_block(ext4_directory_dx_entry_t *,
+    uint32_t);
+
+extern int ext4_directory_dx_init(ext4_inode_ref_t *);
+extern int ext4_directory_dx_find_entry(ext4_directory_search_result_t *,
+    ext4_inode_ref_t *, size_t, const char *);
+extern int ext4_directory_dx_add_entry(ext4_inode_ref_t *, ext4_inode_ref_t *,
+    const char *);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_extent.c
===================================================================
--- uspace/lib/ext4/libext4_extent.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_extent.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,1084 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+/**
+ * @file  libext4_extent.c
+ * @brief Ext4 extent structures operations.
+ */
+
+#include <byteorder.h>
+#include <errno.h>
+#include <malloc.h>
+#include "libext4.h"
+
+/** Get logical number of the block covered by extent.
+ *
+ * @param extent Extent to load number from
+ *
+ * @return Logical number of the first block covered by extent
+ *
+ */
+uint32_t ext4_extent_get_first_block(ext4_extent_t *extent)
+{
+	return uint32_t_le2host(extent->first_block);
+}
+
+/** Set logical number of the first block covered by extent.
+ *
+ * @param extent Extent to set number to
+ * @param iblock Logical number of the first block covered by extent
+ *
+ */
+void ext4_extent_set_first_block(ext4_extent_t *extent, uint32_t iblock)
+{
+	extent->first_block = host2uint32_t_le(iblock);
+}
+
+/** Get number of blocks covered by extent.
+ *
+ * @param extent Extent to load count from
+ *
+ * @return Number of blocks covered by extent
+ *
+ */
+uint16_t ext4_extent_get_block_count(ext4_extent_t *extent)
+{
+	return uint16_t_le2host(extent->block_count);
+}
+
+/** Set number of blocks covered by extent.
+ *
+ * @param extent Extent to load count from
+ * @param count  Number of blocks covered by extent
+ *
+ */
+void ext4_extent_set_block_count(ext4_extent_t *extent, uint16_t count)
+{
+	extent->block_count = host2uint16_t_le(count);
+}
+
+/** Get physical number of the first block covered by extent.
+ *
+ * @param extent Extent to load number
+ *
+ * @return Physical number of the first block covered by extent
+ *
+ */
+uint64_t ext4_extent_get_start(ext4_extent_t *extent)
+{
+	return ((uint64_t)uint16_t_le2host(extent->start_hi)) << 32 |
+	    ((uint64_t)uint32_t_le2host(extent->start_lo));
+}
+
+/** Set physical number of the first block covered by extent.
+ *
+ * @param extent Extent to load number
+ * @param fblock Physical number of the first block covered by extent
+ *
+ */
+void ext4_extent_set_start(ext4_extent_t *extent, uint64_t fblock)
+{
+	extent->start_lo = host2uint32_t_le((fblock << 32) >> 32);
+	extent->start_hi = host2uint16_t_le((uint16_t)(fblock >> 32));
+}
+
+/** Get logical number of the block covered by extent index.
+ *
+ * @param index Extent index to load number from
+ *
+ * @return Logical number of the first block covered by extent index
+ *
+ */
+uint32_t ext4_extent_index_get_first_block(ext4_extent_index_t *index)
+{
+	return uint32_t_le2host(index->first_block);
+}
+
+/** Set logical number of the block covered by extent index.
+ *
+ * @param index  Extent index to set number to
+ * @param iblock Logical number of the first block covered by extent index
+ *
+ */
+void ext4_extent_index_set_first_block(ext4_extent_index_t *index,
+    uint32_t iblock)
+{
+	index->first_block = host2uint32_t_le(iblock);
+}
+
+/** Get physical number of block where the child node is located.
+ *
+ * @param index Extent index to load number from
+ *
+ * @return Physical number of the block with child node
+ *
+ */
+uint64_t ext4_extent_index_get_leaf(ext4_extent_index_t *index)
+{
+	return ((uint64_t) uint16_t_le2host(index->leaf_hi)) << 32 |
+	    ((uint64_t)uint32_t_le2host(index->leaf_lo));
+}
+
+/** Set physical number of block where the child node is located.
+ *
+ * @param index  Extent index to set number to
+ * @param fblock Ohysical number of the block with child node
+ *
+ */
+void ext4_extent_index_set_leaf(ext4_extent_index_t *index, uint64_t fblock)
+{
+	index->leaf_lo = host2uint32_t_le((fblock << 32) >> 32);
+	index->leaf_hi = host2uint16_t_le((uint16_t) (fblock >> 32));
+}
+
+/** Get magic value from extent header.
+ *
+ * @param header Extent header to load value from
+ *
+ * @return Magic value of extent header
+ *
+ */
+uint16_t ext4_extent_header_get_magic(ext4_extent_header_t *header)
+{
+	return uint16_t_le2host(header->magic);
+}
+
+/** Set magic value to extent header.
+ *
+ * @param header Extent header to set value to
+ * @param magic  Magic value of extent header
+ *
+ */
+void ext4_extent_header_set_magic(ext4_extent_header_t *header, uint16_t magic)
+{
+	header->magic = host2uint16_t_le(magic);
+}
+
+/** Get number of entries from extent header
+ *
+ * @param header Extent header to get value from
+ *
+ * @return Number of entries covered by extent header
+ *
+ */
+uint16_t ext4_extent_header_get_entries_count(ext4_extent_header_t *header)
+{
+	return uint16_t_le2host(header->entries_count);
+}
+
+/** Set number of entries to extent header
+ *
+ * @param header Extent header to set value to
+ * @param count  Number of entries covered by extent header
+ *
+ */
+void ext4_extent_header_set_entries_count(ext4_extent_header_t *header,
+    uint16_t count)
+{
+	header->entries_count = host2uint16_t_le(count);
+}
+
+/** Get maximum number of entries from extent header
+ *
+ * @param header Extent header to get value from
+ *
+ * @return Maximum number of entries covered by extent header
+ *
+ */
+uint16_t ext4_extent_header_get_max_entries_count(ext4_extent_header_t *header)
+{
+	return uint16_t_le2host(header->max_entries_count);
+}
+
+/** Set maximum number of entries to extent header
+ *
+ * @param header    Extent header to set value to
+ * @param max_count Maximum number of entries covered by extent header
+ *
+ */
+void ext4_extent_header_set_max_entries_count(ext4_extent_header_t *header,
+    uint16_t max_count)
+{
+	header->max_entries_count = host2uint16_t_le(max_count);
+}
+
+/** Get depth of extent subtree.
+ *
+ * @param header Extent header to get value from
+ *
+ * @return Depth of extent subtree
+ *
+ */
+uint16_t ext4_extent_header_get_depth(ext4_extent_header_t *header)
+{
+	return uint16_t_le2host(header->depth);
+}
+
+/** Set depth of extent subtree.
+ *
+ * @param header Extent header to set value to
+ * @param depth  Depth of extent subtree
+ *
+ */
+void ext4_extent_header_set_depth(ext4_extent_header_t *header, uint16_t depth)
+{
+	header->depth = host2uint16_t_le(depth);
+}
+
+/** Get generation from extent header
+ *
+ * @param header Extent header to get value from
+ *
+ * @return Generation
+ *
+ */
+uint32_t ext4_extent_header_get_generation(ext4_extent_header_t *header)
+{
+	return uint32_t_le2host(header->generation);
+}
+
+/** Set generation to extent header
+ *
+ * @param header     Extent header to set value to
+ * @param generation Generation
+ *
+ */
+void ext4_extent_header_set_generation(ext4_extent_header_t *header,
+    uint32_t generation)
+{
+	header->generation = host2uint32_t_le(generation);
+}
+
+/** Binary search in extent index node.
+ *
+ * @param header Extent header of index node
+ * @param index  Output value - found index will be set here
+ * @param iblock Logical block number to find in index node
+ *
+ */
+static void ext4_extent_binsearch_idx(ext4_extent_header_t *header,
+    ext4_extent_index_t **index, uint32_t iblock)
+{
+	ext4_extent_index_t *r;
+	ext4_extent_index_t *l;
+	ext4_extent_index_t *m;
+	
+	uint16_t entries_count =
+	    ext4_extent_header_get_entries_count(header);
+	
+	/* Initialize bounds */
+	l = EXT4_EXTENT_FIRST_INDEX(header) + 1;
+	r = EXT4_EXTENT_FIRST_INDEX(header) + entries_count - 1;
+	
+	/* Do binary search */
+	while (l <= r) {
+		m = l + (r - l) / 2;
+		uint32_t first_block = ext4_extent_index_get_first_block(m);
+		
+		if (iblock < first_block)
+			r = m - 1;
+		else
+			l = m + 1;
+	}
+	
+	/* Set output value */
+	*index = l - 1;
+}
+
+/** Binary search in extent leaf node.
+ *
+ * @param header Extent header of leaf node
+ * @param extent Output value - found extent will be set here,
+ *               or NULL if node is empty
+ * @param iblock Logical block number to find in leaf node
+ *
+ */
+static void ext4_extent_binsearch(ext4_extent_header_t *header,
+    ext4_extent_t **extent, uint32_t iblock)
+{
+	ext4_extent_t *r;
+	ext4_extent_t *l;
+	ext4_extent_t *m;
+	
+	uint16_t entries_count =
+	    ext4_extent_header_get_entries_count(header);
+	
+	if (entries_count == 0) {
+		/* this leaf is empty */
+		*extent = NULL;
+		return;
+	}
+	
+	/* Initialize bounds */
+	l = EXT4_EXTENT_FIRST(header) + 1;
+	r = EXT4_EXTENT_FIRST(header) + entries_count - 1;
+	
+	/* Do binary search */
+	while (l <= r) {
+		m = l + (r - l) / 2;
+		uint32_t first_block = ext4_extent_get_first_block(m);
+		
+		if (iblock < first_block)
+			r = m - 1;
+		else
+			l = m + 1;
+	}
+	
+	/* Set output value */
+	*extent = l - 1;
+}
+
+/** Find physical block in the extent tree by logical block number.
+ *
+ * There is no need to save path in the tree during this algorithm.
+ *
+ * @param inode_ref I-node to load block from
+ * @param iblock    Logical block number to find
+ * @param fblock    Output value for physical block number
+ *
+ * @return Error code
+ *
+ */
+int ext4_extent_find_block(ext4_inode_ref_t *inode_ref, uint32_t iblock,
+    uint32_t *fblock)
+{
+	/* Compute bound defined by i-node size */
+	uint64_t inode_size =
+	    ext4_inode_get_size(inode_ref->fs->superblock, inode_ref->inode);
+	
+	uint32_t block_size =
+	    ext4_superblock_get_block_size(inode_ref->fs->superblock);
+	
+	uint32_t last_idx = (inode_size - 1) / block_size;
+	
+	/* Check if requested iblock is not over size of i-node */
+	if (iblock > last_idx) {
+		*fblock = 0;
+		return EOK;
+	}
+	
+	block_t *block = NULL;
+	
+	/* Walk through extent tree */
+	ext4_extent_header_t *header =
+	    ext4_inode_get_extent_header(inode_ref->inode);
+	
+	while (ext4_extent_header_get_depth(header) != 0) {
+		/* Search index in node */
+		ext4_extent_index_t *index;
+		ext4_extent_binsearch_idx(header, &index, iblock);
+		
+		/* Load child node and set values for the next iteration */
+		uint64_t child = ext4_extent_index_get_leaf(index);
+		
+		if (block != NULL)
+			block_put(block);
+		
+		int rc = block_get(&block, inode_ref->fs->device, child,
+		    BLOCK_FLAGS_NONE);
+		if (rc != EOK)
+			return rc;
+		
+		header = (ext4_extent_header_t *)block->data;
+	}
+	
+	/* Search extent in the leaf block */
+	ext4_extent_t* extent = NULL;
+	ext4_extent_binsearch(header, &extent, iblock);
+	
+	/* Prevent empty leaf */
+	if (extent == NULL) {
+		*fblock = 0;
+	} else {
+		/* Compute requested physical block address */
+		uint32_t phys_block;
+		uint32_t first = ext4_extent_get_first_block(extent);
+		phys_block = ext4_extent_get_start(extent) + iblock - first;
+		
+		*fblock = phys_block;
+	}
+	
+	/* Cleanup */
+	if (block != NULL)
+		block_put(block);
+	
+	return EOK;
+}
+
+/** Find extent for specified iblock.
+ *
+ * This function is used for finding block in the extent tree with
+ * saving the path through the tree for possible future modifications.
+ *
+ * @param inode_ref I-node to read extent tree from
+ * @param iblock    Iblock to find extent for
+ * @param ret_path  Output value for loaded path from extent tree
+ *
+ * @return Error code
+ *
+ */
+static int ext4_extent_find_extent(ext4_inode_ref_t *inode_ref, uint32_t iblock,
+    ext4_extent_path_t **ret_path)
+{
+	ext4_extent_header_t *eh =
+	    ext4_inode_get_extent_header(inode_ref->inode);
+	
+	uint16_t depth = ext4_extent_header_get_depth(eh);
+	
+	ext4_extent_path_t *tmp_path;
+	
+	/* Added 2 for possible tree growing */
+	tmp_path = malloc(sizeof(ext4_extent_path_t) * (depth + 2));
+	if (tmp_path == NULL)
+		return ENOMEM;
+	
+	/* Initialize structure for algorithm start */
+	tmp_path[0].block = inode_ref->block;
+	tmp_path[0].header = eh;
+	
+	/* Walk through the extent tree */
+	uint16_t pos = 0;
+	int rc;
+	while (ext4_extent_header_get_depth(eh) != 0) {
+		/* Search index in index node by iblock */
+		ext4_extent_binsearch_idx(tmp_path[pos].header,
+		    &tmp_path[pos].index, iblock);
+		
+		tmp_path[pos].depth = depth;
+		tmp_path[pos].extent = NULL;
+		
+		assert(tmp_path[pos].index != NULL);
+		
+		/* Load information for the next iteration */
+		uint64_t fblock = ext4_extent_index_get_leaf(tmp_path[pos].index);
+		
+		block_t *block;
+		rc = block_get(&block, inode_ref->fs->device, fblock,
+		    BLOCK_FLAGS_NONE);
+		if (rc != EOK)
+			goto cleanup;
+		
+		pos++;
+		
+		eh = (ext4_extent_header_t *)block->data;
+		tmp_path[pos].block = block;
+		tmp_path[pos].header = eh;
+	}
+	
+	tmp_path[pos].depth = 0;
+	tmp_path[pos].extent = NULL;
+	tmp_path[pos].index = NULL;
+	
+	/* Find extent in the leaf node */
+	ext4_extent_binsearch(tmp_path[pos].header, &tmp_path[pos].extent, iblock);
+	*ret_path = tmp_path;
+	
+	return EOK;
+	
+cleanup:
+	/*
+	 * Put loaded blocks
+	 * From 1: 0 is a block with inode data
+	 */
+	for (uint16_t i = 1; i < tmp_path->depth; ++i) {
+		if (tmp_path[i].block)
+			block_put(tmp_path[i].block);
+	}
+	
+	/* Destroy temporary data structure */
+	free(tmp_path);
+	
+	return rc;
+}
+
+/** Release extent and all data blocks covered by the extent.
+ *
+ * @param inode_ref I-node to release extent and block from
+ * @param extent    Extent to release
+ *
+ * @return Error code
+ *
+ */
+static int ext4_extent_release(ext4_inode_ref_t *inode_ref,
+    ext4_extent_t *extent)
+{
+	/* Compute number of the first physical block to release */
+	uint64_t start = ext4_extent_get_start(extent);
+	uint16_t block_count = ext4_extent_get_block_count(extent);
+	
+	return ext4_balloc_free_blocks(inode_ref, start, block_count);
+}
+
+/** Recursively release the whole branch of the extent tree.
+ *
+ * For each entry of the node release the subbranch and finally release
+ * the node. In the leaf node all extents will be released.
+ *
+ * @param inode_ref I-node where the branch is released
+ * @param index     Index in the non-leaf node to be released
+ *                  with the whole subtree
+ *
+ * @return Error code
+ *
+ */
+static int ext4_extent_release_branch(ext4_inode_ref_t *inode_ref,
+		ext4_extent_index_t *index)
+{
+	uint32_t fblock = ext4_extent_index_get_leaf(index);
+	
+	block_t* block;
+	int rc = block_get(&block, inode_ref->fs->device, fblock, BLOCK_FLAGS_NONE);
+	if (rc != EOK)
+		return rc;
+	
+	ext4_extent_header_t *header = block->data;
+	
+	if (ext4_extent_header_get_depth(header)) {
+		/* The node is non-leaf, do recursion */
+		ext4_extent_index_t *idx = EXT4_EXTENT_FIRST_INDEX(header);
+		
+		/* Release all subbranches */
+		for (uint32_t i = 0;
+		    i < ext4_extent_header_get_entries_count(header);
+		    ++i, ++idx) {
+			rc = ext4_extent_release_branch(inode_ref, idx);
+			if (rc != EOK)
+				return rc;
+		}
+	} else {
+		/* Leaf node reached */
+		ext4_extent_t *ext = EXT4_EXTENT_FIRST(header);
+		
+		/* Release all extents and stop recursion */
+		for (uint32_t i = 0;
+		    i < ext4_extent_header_get_entries_count(header);
+		    ++i, ++ext) {
+			rc = ext4_extent_release(inode_ref, ext);
+			if (rc != EOK)
+				return rc;
+		}
+	}
+	
+	/* Release data block where the node was stored */
+	
+	rc = block_put(block);
+	if (rc != EOK)
+		return rc;
+	
+	ext4_balloc_free_block(inode_ref, fblock);
+	
+	return EOK;
+}
+
+/** Release all data blocks starting from specified logical block.
+ *
+ * @param inode_ref   I-node to release blocks from
+ * @param iblock_from First logical block to release
+ *
+ */
+int ext4_extent_release_blocks_from(ext4_inode_ref_t *inode_ref,
+    uint32_t iblock_from)
+{
+	/* Find the first extent to modify */
+	ext4_extent_path_t *path;
+	int rc = ext4_extent_find_extent(inode_ref, iblock_from, &path);
+	if (rc != EOK)
+		return rc;
+	
+	/* Jump to last item of the path (extent) */
+	ext4_extent_path_t *path_ptr = path;
+	while (path_ptr->depth != 0)
+		path_ptr++;
+	
+	assert(path_ptr->extent != NULL);
+	
+	/* First extent maybe released partially */
+	uint32_t first_iblock =
+	    ext4_extent_get_first_block(path_ptr->extent);
+	uint32_t first_fblock =
+	    ext4_extent_get_start(path_ptr->extent) + iblock_from - first_iblock;
+	
+	uint16_t block_count = ext4_extent_get_block_count(path_ptr->extent);
+	
+	uint16_t delete_count = block_count -
+	    (ext4_extent_get_start(path_ptr->extent) - first_fblock);
+	
+	/* Release all blocks */
+	rc = ext4_balloc_free_blocks(inode_ref, first_fblock, delete_count);
+	if (rc != EOK)
+		goto cleanup;
+	
+	/* Correct counter */
+	block_count -= delete_count;
+	ext4_extent_set_block_count(path_ptr->extent, block_count);
+	
+	/* Initialize the following loop */
+	uint16_t entries =
+	    ext4_extent_header_get_entries_count(path_ptr->header);
+	ext4_extent_t *tmp_ext = path_ptr->extent + 1;
+	ext4_extent_t *stop_ext = EXT4_EXTENT_FIRST(path_ptr->header) + entries;
+	
+	/* If first extent empty, release it */
+	if (block_count == 0)
+		entries--;
+	
+	/* Release all successors of the first extent in the same node */
+	while (tmp_ext < stop_ext) {
+		first_fblock = ext4_extent_get_start(tmp_ext);
+		delete_count = ext4_extent_get_block_count(tmp_ext);
+		
+		rc = ext4_balloc_free_blocks(inode_ref, first_fblock, delete_count);
+		if (rc != EOK)
+			goto cleanup;
+		
+		entries--;
+		tmp_ext++;
+	}
+	
+	ext4_extent_header_set_entries_count(path_ptr->header, entries);
+	path_ptr->block->dirty = true;
+	
+	/* If leaf node is empty, parent entry must be modified */
+	bool remove_parent_record = false;
+	
+	/* Don't release root block (including inode data) !!! */
+	if ((path_ptr != path) && (entries == 0)) {
+		rc = ext4_balloc_free_block(inode_ref, path_ptr->block->lba);
+		if (rc != EOK)
+			goto cleanup;
+		
+		remove_parent_record = true;
+	}
+	
+	/* Jump to the parent */
+	--path_ptr;
+	
+	/* Release all successors in all tree levels */
+	while (path_ptr >= path) {
+		entries = ext4_extent_header_get_entries_count(path_ptr->header);
+		ext4_extent_index_t *index = path_ptr->index + 1;
+		ext4_extent_index_t *stop =
+		    EXT4_EXTENT_FIRST_INDEX(path_ptr->header) + entries;
+		
+		/* Correct entries count because of changes in the previous iteration */
+		if (remove_parent_record)
+			entries--;
+		
+		/* Iterate over all entries and release the whole subtrees */
+		while (index < stop) {
+			rc = ext4_extent_release_branch(inode_ref, index);
+			if (rc != EOK)
+				goto cleanup;
+			
+			++index;
+			--entries;
+		}
+		
+		ext4_extent_header_set_entries_count(path_ptr->header, entries);
+		path_ptr->block->dirty = true;
+		
+		/* Free the node if it is empty */
+		if ((entries == 0) && (path_ptr != path)) {
+			rc = ext4_balloc_free_block(inode_ref, path_ptr->block->lba);
+			if (rc != EOK)
+				goto cleanup;
+			
+			/* Mark parent to be checked */
+			remove_parent_record = true;
+		} else
+			remove_parent_record = false;
+		
+		--path_ptr;
+	}
+	
+cleanup:
+	/*
+	 * Put loaded blocks
+	 * starting from 1: 0 is a block with inode data
+	 */
+	for (uint16_t i = 1; i <= path->depth; ++i) {
+		if (path[i].block)
+			block_put(path[i].block);
+	}
+	
+	/* Destroy temporary data structure */
+	free(path);
+	
+	return rc;
+}
+
+/** Append new extent to the i-node and do some splitting if necessary.
+ *
+ * @param inode_ref      I-node to append extent to
+ * @param path           Path in the extent tree for possible splitting
+ * @param last_path_item Input/output parameter for pointer to the last
+ *                       valid item in the extent tree path
+ * @param iblock         Logical index of block to append extent for
+ *
+ * @return Error code
+ *
+ */
+static int ext4_extent_append_extent(ext4_inode_ref_t *inode_ref,
+    ext4_extent_path_t *path, uint32_t iblock)
+{
+	ext4_extent_path_t *path_ptr = path + path->depth;
+	
+	uint32_t block_size =
+	    ext4_superblock_get_block_size(inode_ref->fs->superblock);
+	
+	/* Start splitting */
+	while (path_ptr > path) {
+		uint16_t entries =
+		    ext4_extent_header_get_entries_count(path_ptr->header);
+		uint16_t limit =
+		    ext4_extent_header_get_max_entries_count(path_ptr->header);
+		
+		if (entries == limit) {
+			/* Full node - allocate block for new one */
+			uint32_t fblock;
+			int rc = ext4_balloc_alloc_block(inode_ref, &fblock);
+			if (rc != EOK)
+				return rc;
+			
+			block_t *block;
+			rc = block_get(&block, inode_ref->fs->device, fblock,
+			    BLOCK_FLAGS_NOREAD);
+			if (rc != EOK) {
+				ext4_balloc_free_block(inode_ref, fblock);
+				return rc;
+			}
+			
+			/* Put back not modified old block */
+			block_put(path_ptr->block);
+			
+			/* Initialize newly allocated block and remember it */
+			memset(block->data, 0, block_size);
+			path_ptr->block = block;
+			
+			/* Update pointers in extent path structure */
+			path_ptr->header = block->data;
+			if (path_ptr->depth) {
+				path_ptr->index = EXT4_EXTENT_FIRST_INDEX(path_ptr->header);
+				ext4_extent_index_set_first_block(path_ptr->index, iblock);
+				ext4_extent_index_set_leaf(path_ptr->index, (path_ptr + 1)->block->lba);
+				limit = (block_size - sizeof(ext4_extent_header_t)) /
+				    sizeof(ext4_extent_index_t);
+			} else {
+				path_ptr->extent = EXT4_EXTENT_FIRST(path_ptr->header);
+				ext4_extent_set_first_block(path_ptr->extent, iblock);
+				limit = (block_size - sizeof(ext4_extent_header_t)) /
+				    sizeof(ext4_extent_t);
+			}
+			
+			/* Initialize on-disk structure (header) */
+			ext4_extent_header_set_entries_count(path_ptr->header, 1);
+			ext4_extent_header_set_max_entries_count(path_ptr->header, limit);
+			ext4_extent_header_set_magic(path_ptr->header, EXT4_EXTENT_MAGIC);
+			ext4_extent_header_set_depth(path_ptr->header, path_ptr->depth);
+			ext4_extent_header_set_generation(path_ptr->header, 0);
+			
+			path_ptr->block->dirty = true;
+			
+			/* Jump to the preceeding item */
+			path_ptr--;
+		} else {
+			/* Node with free space */
+			if (path_ptr->depth) {
+				path_ptr->index = EXT4_EXTENT_FIRST_INDEX(path_ptr->header) + entries;
+				ext4_extent_index_set_first_block(path_ptr->index, iblock);
+				ext4_extent_index_set_leaf(path_ptr->index, (path_ptr + 1)->block->lba);
+			} else {
+				path_ptr->extent = EXT4_EXTENT_FIRST(path_ptr->header) + entries;
+				ext4_extent_set_first_block(path_ptr->extent, iblock);
+			}
+			
+			ext4_extent_header_set_entries_count(path_ptr->header, entries + 1);
+			path_ptr->block->dirty = true;
+			
+			/* No more splitting needed */
+			return EOK;
+		}
+	}
+	
+	assert(path_ptr == path);
+	
+	/* Should be the root split too? */
+	
+	uint16_t entries = ext4_extent_header_get_entries_count(path->header);
+	uint16_t limit = ext4_extent_header_get_max_entries_count(path->header);
+	
+	if (entries == limit) {
+		uint32_t new_fblock;
+		int rc = ext4_balloc_alloc_block(inode_ref, &new_fblock);
+		if (rc != EOK)
+			return rc;
+		
+		block_t *block;
+		rc = block_get(&block, inode_ref->fs->device, new_fblock,
+		    BLOCK_FLAGS_NOREAD);
+		if (rc != EOK)
+			return rc;
+		
+		/* Initialize newly allocated block */
+		memset(block->data, 0, block_size);
+		
+		/* Move data from root to the new block */
+		memcpy(block->data, inode_ref->inode->blocks,
+		    EXT4_INODE_BLOCKS * sizeof(uint32_t));
+		
+		/* Data block is initialized */
+		
+		block_t *root_block = path->block;
+		uint16_t root_depth = path->depth;
+		ext4_extent_header_t *root_header = path->header;
+		
+		/* Make space for tree growing */
+		ext4_extent_path_t *new_root = path;
+		ext4_extent_path_t *old_root = path + 1;
+		
+		size_t nbytes = sizeof(ext4_extent_path_t) * (path->depth + 1);
+		memmove(old_root, new_root, nbytes);
+		memset(new_root, 0, sizeof(ext4_extent_path_t));
+		
+		/* Update old root structure */
+		old_root->block = block;
+		old_root->header = (ext4_extent_header_t *)block->data;
+		
+		/* Add new entry and update limit for entries */
+		if (old_root->depth) {
+			limit = (block_size - sizeof(ext4_extent_header_t)) /
+			    sizeof(ext4_extent_index_t);
+			old_root->index = EXT4_EXTENT_FIRST_INDEX(old_root->header) + entries;
+			ext4_extent_index_set_first_block(old_root->index, iblock);
+			ext4_extent_index_set_leaf(old_root->index, (old_root + 1)->block->lba);
+			old_root->extent = NULL;
+		} else {
+			limit = (block_size - sizeof(ext4_extent_header_t)) /
+			    sizeof(ext4_extent_t);
+			old_root->extent = EXT4_EXTENT_FIRST(old_root->header) + entries;
+			ext4_extent_set_first_block(old_root->extent, iblock);
+			old_root->index = NULL;
+		}
+		
+		ext4_extent_header_set_entries_count(old_root->header, entries + 1);
+		ext4_extent_header_set_max_entries_count(old_root->header, limit);
+		
+		old_root->block->dirty = true;
+		
+		/* Re-initialize new root metadata */
+		new_root->depth = root_depth + 1;
+		new_root->block = root_block;
+		new_root->header = root_header;
+		new_root->extent = NULL;
+		new_root->index = EXT4_EXTENT_FIRST_INDEX(new_root->header);
+		
+		ext4_extent_header_set_depth(new_root->header, new_root->depth);
+		
+		/* Create new entry in root */
+		ext4_extent_header_set_entries_count(new_root->header, 1);
+		ext4_extent_index_set_first_block(new_root->index, 0);
+		ext4_extent_index_set_leaf(new_root->index, new_fblock);
+		
+		new_root->block->dirty = true;
+	} else {
+		if (path->depth) {
+			path->index = EXT4_EXTENT_FIRST_INDEX(path->header) + entries;
+			ext4_extent_index_set_first_block(path->index, iblock);
+			ext4_extent_index_set_leaf(path->index, (path + 1)->block->lba);
+		} else {
+			path->extent = EXT4_EXTENT_FIRST(path->header) + entries;
+			ext4_extent_set_first_block(path->extent, iblock);
+		}
+		
+		ext4_extent_header_set_entries_count(path->header, entries + 1);
+		path->block->dirty = true;
+	}
+	
+	return EOK;
+}
+
+/** Append data block to the i-node.
+ *
+ * This function allocates data block, tries to append it
+ * to some existing extent or creates new extents.
+ * It includes possible extent tree modifications (splitting).
+ *<
+ * @param inode_ref I-node to append block to
+ * @param iblock    Output logical number of newly allocated block
+ * @param fblock    Output physical block address of newly allocated block
+ *
+ * @return Error code
+ *
+ */
+int ext4_extent_append_block(ext4_inode_ref_t *inode_ref, uint32_t *iblock,
+    uint32_t *fblock, bool update_size)
+{
+	ext4_superblock_t *sb = inode_ref->fs->superblock;
+	uint64_t inode_size = ext4_inode_get_size(sb, inode_ref->inode);
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	
+	/* Calculate number of new logical block */
+	uint32_t new_block_idx = 0;
+	if (inode_size > 0) {
+		if ((inode_size % block_size) != 0)
+			inode_size += block_size - (inode_size % block_size);
+		
+		new_block_idx = inode_size / block_size;
+	}
+	
+	/* Load the nearest leaf (with extent) */
+	ext4_extent_path_t *path;
+	int rc = ext4_extent_find_extent(inode_ref, new_block_idx, &path);
+	if (rc != EOK)
+		return rc;
+	
+	/* Jump to last item of the path (extent) */
+	ext4_extent_path_t *path_ptr = path;
+	while (path_ptr->depth != 0)
+		path_ptr++;
+	
+	/* Add new extent to the node if not present */
+	if (path_ptr->extent == NULL)
+		goto append_extent;
+	
+	uint16_t block_count = ext4_extent_get_block_count(path_ptr->extent);
+	uint16_t block_limit = (1 << 15);
+	
+	uint32_t phys_block = 0;
+	if (block_count < block_limit) {
+		/* There is space for new block in the extent */
+		if (block_count == 0) {
+			/* Existing extent is empty */
+			rc = ext4_balloc_alloc_block(inode_ref, &phys_block);
+			if (rc != EOK)
+				goto finish;
+			
+			/* Initialize extent */
+			ext4_extent_set_first_block(path_ptr->extent, new_block_idx);
+			ext4_extent_set_start(path_ptr->extent, phys_block);
+			ext4_extent_set_block_count(path_ptr->extent, 1);
+			
+			/* Update i-node */
+			if (update_size) {
+				ext4_inode_set_size(inode_ref->inode, inode_size + block_size);
+				inode_ref->dirty = true;
+			}
+			
+			path_ptr->block->dirty = true;
+			
+			goto finish;
+		} else {
+			/* Existing extent contains some blocks */
+			phys_block = ext4_extent_get_start(path_ptr->extent);
+			phys_block += ext4_extent_get_block_count(path_ptr->extent);
+			
+			/* Check if the following block is free for allocation */
+			bool free;
+			rc = ext4_balloc_try_alloc_block(inode_ref, phys_block, &free);
+			if (rc != EOK)
+				goto finish;
+			
+			if (!free) {
+				/* Target is not free, new block must be appended to new extent */
+				goto append_extent;
+			}
+			
+			/* Update extent */
+			ext4_extent_set_block_count(path_ptr->extent, block_count + 1);
+			
+			/* Update i-node */
+			if (update_size) {
+				ext4_inode_set_size(inode_ref->inode, inode_size + block_size);
+				inode_ref->dirty = true;
+			}
+			
+			path_ptr->block->dirty = true;
+			
+			goto finish;
+		}
+	}
+	
+	
+append_extent:
+	/* Append new extent to the tree */
+	phys_block = 0;
+	
+	/* Allocate new data block */
+	rc = ext4_balloc_alloc_block(inode_ref, &phys_block);
+	if (rc != EOK)
+		goto finish;
+	
+	/* Append extent for new block (includes tree splitting if needed) */
+	rc = ext4_extent_append_extent(inode_ref, path, new_block_idx);
+	if (rc != EOK) {
+		ext4_balloc_free_block(inode_ref, phys_block);
+		goto finish;
+	}
+	
+	uint32_t tree_depth = ext4_extent_header_get_depth(path->header);
+	path_ptr = path + tree_depth;
+	
+	/* Initialize newly created extent */
+	ext4_extent_set_block_count(path_ptr->extent, 1);
+	ext4_extent_set_first_block(path_ptr->extent, new_block_idx);
+	ext4_extent_set_start(path_ptr->extent, phys_block);
+	
+	/* Update i-node */
+	if (update_size) {
+		ext4_inode_set_size(inode_ref->inode, inode_size + block_size);
+		inode_ref->dirty = true;
+	}
+	
+	path_ptr->block->dirty = true;
+	
+finish:
+	/* Set return values */
+	*iblock = new_block_idx;
+	*fblock = phys_block;
+	
+	/*
+	 * Put loaded blocks
+	 * starting from 1: 0 is a block with inode data
+	 */
+	for (uint16_t i = 1; i <= path->depth; ++i) {
+		if (path[i].block)
+			block_put(path[i].block);
+	}
+	
+	/* Destroy temporary data structure */
+	free(path);
+	
+	return rc;
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_extent.h
===================================================================
--- uspace/lib/ext4/libext4_extent.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_extent.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_EXTENT_H_
+#define LIBEXT4_LIBEXT4_EXTENT_H_
+
+#include "libext4_types.h"
+
+extern uint32_t ext4_extent_get_first_block(ext4_extent_t *);
+extern void ext4_extent_set_first_block(ext4_extent_t *, uint32_t);
+extern uint16_t ext4_extent_get_block_count(ext4_extent_t *);
+extern void ext4_extent_set_block_count(ext4_extent_t *, uint16_t);
+extern uint64_t ext4_extent_get_start(ext4_extent_t *);
+extern void ext4_extent_set_start(ext4_extent_t *, uint64_t);
+
+extern uint32_t ext4_extent_index_get_first_block(ext4_extent_index_t *);
+extern void ext4_extent_index_set_first_block(ext4_extent_index_t *, uint32_t);
+extern uint64_t ext4_extent_index_get_leaf(ext4_extent_index_t *);
+extern void ext4_extent_index_set_leaf(ext4_extent_index_t *, uint64_t);
+
+extern uint16_t ext4_extent_header_get_magic(ext4_extent_header_t *);
+extern void ext4_extent_header_set_magic(ext4_extent_header_t *, uint16_t);
+extern uint16_t ext4_extent_header_get_entries_count(ext4_extent_header_t *);
+extern void ext4_extent_header_set_entries_count(ext4_extent_header_t *,
+    uint16_t);
+extern uint16_t ext4_extent_header_get_max_entries_count(ext4_extent_header_t *);
+extern void ext4_extent_header_set_max_entries_count(ext4_extent_header_t *,
+    uint16_t);
+extern uint16_t ext4_extent_header_get_depth(ext4_extent_header_t *);
+extern void ext4_extent_header_set_depth(ext4_extent_header_t *, uint16_t);
+extern uint32_t ext4_extent_header_get_generation(ext4_extent_header_t *);
+extern void ext4_extent_header_set_generation(ext4_extent_header_t *, uint32_t);
+
+extern int ext4_extent_find_block(ext4_inode_ref_t *, uint32_t, uint32_t *);
+extern int ext4_extent_release_blocks_from(ext4_inode_ref_t *, uint32_t);
+
+extern int ext4_extent_append_block(ext4_inode_ref_t *, uint32_t *, uint32_t *,
+    bool);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_filesystem.c
===================================================================
--- uspace/lib/ext4/libext4_filesystem.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_filesystem.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,1384 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+/**
+ * @file  libext4_filesystem.c
+ * @brief More complex filesystem operations.
+ */
+
+#include <byteorder.h>
+#include <errno.h>
+#include <malloc.h>
+#include "libext4.h"
+
+/** Initialize filesystem and read all needed data.
+ *
+ * @param fs         Filesystem instance to be initialized
+ * @param service_id Identifier if device with the filesystem
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_init(ext4_filesystem_t *fs, service_id_t service_id,
+    enum cache_mode cmode)
+{
+	fs->device = service_id;
+	
+	/* Initialize block library (4096 is size of communication channel) */
+	int rc = block_init(EXCHANGE_SERIALIZE, fs->device, 4096);
+	if (rc != EOK)
+		return rc;
+	
+	/* Read superblock from device to memory */
+	ext4_superblock_t *temp_superblock;
+	rc = ext4_superblock_read_direct(fs->device, &temp_superblock);
+	if (rc != EOK) {
+		block_fini(fs->device);
+		return rc;
+	}
+	
+	/* Read block size from superblock and check */
+	uint32_t block_size = ext4_superblock_get_block_size(temp_superblock);
+	if (block_size > EXT4_MAX_BLOCK_SIZE) {
+		block_fini(fs->device);
+		return ENOTSUP;
+	}
+	
+	/* Initialize block caching by libblock */
+	rc = block_cache_init(service_id, block_size, 0, cmode);
+	if (rc != EOK) {
+		block_fini(fs->device);
+		return rc;
+	}
+	
+	/* Compute limits for indirect block levels */
+	uint32_t block_ids_per_block = block_size / sizeof(uint32_t);
+	fs->inode_block_limits[0] = EXT4_INODE_DIRECT_BLOCK_COUNT;
+	fs->inode_blocks_per_level[0] = 1;
+	for (unsigned int i = 1; i < 4; i++) {
+		fs->inode_blocks_per_level[i] = fs->inode_blocks_per_level[i - 1] *
+		    block_ids_per_block;
+		fs->inode_block_limits[i] = fs->inode_block_limits[i - 1] +
+		    fs->inode_blocks_per_level[i];
+	}
+	
+	/* Return loaded superblock */
+	fs->superblock = temp_superblock;
+	
+	uint16_t state = ext4_superblock_get_state(fs->superblock);
+	
+	if (((state & EXT4_SUPERBLOCK_STATE_VALID_FS) !=
+	    EXT4_SUPERBLOCK_STATE_VALID_FS) ||
+	    ((state & EXT4_SUPERBLOCK_STATE_ERROR_FS) ==
+	    EXT4_SUPERBLOCK_STATE_ERROR_FS)) {
+		block_cache_fini(fs->device);
+		block_fini(fs->device);
+		return ENOTSUP;
+	}
+	
+	/* Mark system as mounted */
+	ext4_superblock_set_state(fs->superblock, EXT4_SUPERBLOCK_STATE_ERROR_FS);
+	rc = ext4_superblock_write_direct(fs->device, fs->superblock);
+	if (rc != EOK) {
+		block_cache_fini(fs->device);
+		block_fini(fs->device);
+		return rc;
+	}
+	
+	uint16_t mnt_count = ext4_superblock_get_mount_count(fs->superblock);
+	ext4_superblock_set_mount_count(fs->superblock, mnt_count + 1);
+	
+	return EOK;
+}
+
+/** Destroy filesystem instance (used by unmount operation).
+ *
+ * @param fs Filesystem to be destroyed
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_fini(ext4_filesystem_t *fs)
+{
+	/* Write the superblock to the device */
+	ext4_superblock_set_state(fs->superblock, EXT4_SUPERBLOCK_STATE_VALID_FS);
+	int rc = ext4_superblock_write_direct(fs->device, fs->superblock);
+	
+	/* Release memory space for superblock */
+	free(fs->superblock);
+	
+	/* Finish work with block library */
+	block_cache_fini(fs->device);
+	block_fini(fs->device);
+	
+	return rc;
+}
+
+/** Check sanity of the filesystem.
+ *
+ * Main is the check of the superblock structure.
+ *
+ * @param fs Filesystem to be checked
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_check_sanity(ext4_filesystem_t *fs)
+{
+	/* Check superblock */
+	return ext4_superblock_check_sanity(fs->superblock);
+}
+
+/** Check filesystem's features, if supported by this driver
+ *
+ * Function can return EOK and set read_only flag. It mean's that
+ * there are some not-supported features, that can cause problems
+ * during some write operations.
+ *
+ * @param fs        Filesystem to be checked
+ * @param read_only Flag if filesystem should be mounted only for reading
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_check_features(ext4_filesystem_t *fs, bool *read_only)
+{
+	/* Feature flags are present only in higher revisions */
+	if (ext4_superblock_get_rev_level(fs->superblock) == 0) {
+		*read_only = false;
+		return EOK;
+	}
+	
+	/*
+	 * Check incompatible features - if filesystem has some,
+	 * volume can't be mounted
+	 */
+	uint32_t incompatible_features;
+	incompatible_features =
+	    ext4_superblock_get_features_incompatible(fs->superblock);
+	incompatible_features &= ~EXT4_FEATURE_INCOMPAT_SUPP;
+	if (incompatible_features > 0)
+		return ENOTSUP;
+	
+	/*
+	 * Check read-only features, if filesystem has some,
+	 * volume can be mount only in read-only mode
+	 */
+	uint32_t compatible_read_only;
+	compatible_read_only =
+	    ext4_superblock_get_features_read_only(fs->superblock);
+	compatible_read_only &= ~EXT4_FEATURE_RO_COMPAT_SUPP;
+	if (compatible_read_only > 0) {
+		*read_only = true;
+		return EOK;
+	}
+	
+	return EOK;
+}
+
+
+/** Convert block address to relative index in block group.
+ *
+ * @param sb         Superblock pointer
+ * @param block_addr Block number to convert
+ *
+ * @return Relative number of block
+ *
+ */
+uint32_t ext4_filesystem_blockaddr2_index_in_group(ext4_superblock_t *sb,
+    uint32_t block_addr)
+{
+	uint32_t blocks_per_group = ext4_superblock_get_blocks_per_group(sb);
+	uint32_t first_block = ext4_superblock_get_first_data_block(sb);
+	
+	/* First block == 0 or 1 */
+	if (first_block == 0)
+		return block_addr % blocks_per_group;
+	else
+		return (block_addr - 1) % blocks_per_group;
+}
+
+
+/** Convert relative block address in group to absolute address.
+ *
+ * @param sb Superblock pointer
+ *
+ * @return Absolute block address
+ *
+ */
+uint32_t ext4_filesystem_index_in_group2blockaddr(ext4_superblock_t *sb,
+    uint32_t index, uint32_t bgid)
+{
+	uint32_t blocks_per_group = ext4_superblock_get_blocks_per_group(sb);
+	
+	if (ext4_superblock_get_first_data_block(sb) == 0)
+		return bgid * blocks_per_group + index;
+	else
+		return bgid * blocks_per_group + index + 1;
+}
+
+/** Initialize block bitmap in block group.
+ *
+ * @param bg_ref Reference to block group
+ *
+ * @return Error code
+ *
+ */
+static int ext4_filesystem_init_block_bitmap(ext4_block_group_ref_t *bg_ref)
+{
+	/* Load bitmap */
+	uint32_t bitmap_block_addr = ext4_block_group_get_block_bitmap(
+	    bg_ref->block_group, bg_ref->fs->superblock);
+	
+	block_t *bitmap_block;
+	int rc = block_get(&bitmap_block, bg_ref->fs->device,
+	    bitmap_block_addr, BLOCK_FLAGS_NOREAD);
+	if (rc != EOK)
+		return rc;
+	
+	uint8_t *bitmap = bitmap_block->data;
+	
+	/* Initialize all bitmap bits to zero */
+	uint32_t block_size = ext4_superblock_get_block_size(bg_ref->fs->superblock);
+	memset(bitmap, 0, block_size);
+	
+	/* Determine first block and first data block in group */
+	uint32_t first_idx = 0;
+	
+	uint32_t first_data = ext4_balloc_get_first_data_block_in_group(
+	    bg_ref->fs->superblock, bg_ref);
+	uint32_t first_data_idx = ext4_filesystem_blockaddr2_index_in_group(
+	    bg_ref->fs->superblock, first_data);
+	
+	/* Set bits from to first block to first data block - 1 to one (allocated) */
+	for (uint32_t block = first_idx; block < first_data_idx; ++block)
+		ext4_bitmap_set_bit(bitmap, block);
+	
+	bitmap_block->dirty = true;
+	
+	/* Save bitmap */
+	return block_put(bitmap_block);
+}
+
+/** Initialize i-node bitmap in block group.
+ *
+ * @param bg_ref Reference to block group
+ *
+ * @return Error code
+ *
+ */
+static int ext4_filesystem_init_inode_bitmap(ext4_block_group_ref_t *bg_ref)
+{
+	/* Load bitmap */
+	uint32_t bitmap_block_addr = ext4_block_group_get_inode_bitmap(
+	    bg_ref->block_group, bg_ref->fs->superblock);
+	block_t *bitmap_block;
+	
+	int rc = block_get(&bitmap_block, bg_ref->fs->device,
+	    bitmap_block_addr, BLOCK_FLAGS_NOREAD);
+	if (rc != EOK)
+		return rc;
+	
+	uint8_t *bitmap = bitmap_block->data;
+	
+	/* Initialize all bitmap bits to zero */
+	uint32_t block_size = ext4_superblock_get_block_size(bg_ref->fs->superblock);
+	uint32_t inodes_per_group =
+	    ext4_superblock_get_inodes_per_group(bg_ref->fs->superblock);
+	memset(bitmap, 0, (inodes_per_group + 7) / 8);
+	
+	uint32_t start_bit = inodes_per_group;
+	uint32_t end_bit = block_size * 8;
+	
+	uint32_t i;
+	for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
+		ext4_bitmap_set_bit(bitmap, i);
+	
+	if (i < end_bit)
+		memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
+	
+	bitmap_block->dirty = true;
+	
+	/* Save bitmap */
+	return block_put(bitmap_block);
+}
+
+/** Initialize i-node table in block group.
+ *
+ * @param bg_ref Reference to block group
+ *
+ * @return Error code
+ *
+ */
+static int ext4_filesystem_init_inode_table(ext4_block_group_ref_t *bg_ref)
+{
+	ext4_superblock_t *sb = bg_ref->fs->superblock;
+	
+	uint32_t inode_size = ext4_superblock_get_inode_size(sb);
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	uint32_t inodes_per_block = block_size / inode_size;
+	
+	uint32_t inodes_in_group =
+	    ext4_superblock_get_inodes_in_group(sb, bg_ref->index);
+	
+	uint32_t table_blocks = inodes_in_group / inodes_per_block;
+	
+	if (inodes_in_group % inodes_per_block)
+		table_blocks++;
+	
+	/* Compute initialization bounds */
+	uint32_t first_block = ext4_block_group_get_inode_table_first_block(
+	    bg_ref->block_group, sb);
+	
+	uint32_t last_block = first_block + table_blocks - 1;
+	
+	/* Initialization of all itable blocks */
+	for (uint32_t fblock = first_block; fblock <= last_block; ++fblock) {
+		block_t *block;
+		int rc = block_get(&block, bg_ref->fs->device, fblock,
+		    BLOCK_FLAGS_NOREAD);
+		if (rc != EOK)
+			return rc;
+		
+		memset(block->data, 0, block_size);
+		block->dirty = true;
+		
+		rc = block_put(block);
+		if (rc != EOK)
+			return rc;
+	}
+	
+	return EOK;
+}
+
+/** Get reference to block group specified by index.
+ *
+ * @param fs   Filesystem to find block group on
+ * @param bgid Index of block group to load
+ * @param ref  Output pointer for reference
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_get_block_group_ref(ext4_filesystem_t *fs, uint32_t bgid,
+    ext4_block_group_ref_t **ref)
+{
+	/* Allocate memory for new structure */
+	ext4_block_group_ref_t *newref =
+	    malloc(sizeof(ext4_block_group_ref_t));
+	if (newref == NULL)
+		return ENOMEM;
+	
+	/* Compute number of descriptors, that fits in one data block */
+	uint32_t descriptors_per_block =
+	    ext4_superblock_get_block_size(fs->superblock) /
+	    ext4_superblock_get_desc_size(fs->superblock);
+	
+	/* Block group descriptor table starts at the next block after superblock */
+	aoff64_t block_id =
+	    ext4_superblock_get_first_data_block(fs->superblock) + 1;
+	
+	/* Find the block containing the descriptor we are looking for */
+	block_id += bgid / descriptors_per_block;
+	uint32_t offset = (bgid % descriptors_per_block) *
+	    ext4_superblock_get_desc_size(fs->superblock);
+	
+	/* Load block with descriptors */
+	int rc = block_get(&newref->block, fs->device, block_id, 0);
+	if (rc != EOK) {
+		free(newref);
+		return rc;
+	}
+	
+	/* Inititialize in-memory representation */
+	newref->block_group = newref->block->data + offset;
+	newref->fs = fs;
+	newref->index = bgid;
+	newref->dirty = false;
+	
+	*ref = newref;
+	
+	if (ext4_block_group_has_flag(newref->block_group,
+	    EXT4_BLOCK_GROUP_BLOCK_UNINIT)) {
+		rc = ext4_filesystem_init_block_bitmap(newref);
+		if (rc != EOK) {
+			block_put(newref->block);
+			free(newref);
+			return rc;
+		}
+		
+		ext4_block_group_clear_flag(newref->block_group,
+		    EXT4_BLOCK_GROUP_BLOCK_UNINIT);
+		
+		newref->dirty = true;
+	}
+	
+	if (ext4_block_group_has_flag(newref->block_group,
+	    EXT4_BLOCK_GROUP_INODE_UNINIT)) {
+		rc = ext4_filesystem_init_inode_bitmap(newref);
+		if (rc != EOK) {
+			block_put(newref->block);
+			free(newref);
+			return rc;
+		}
+		
+		ext4_block_group_clear_flag(newref->block_group,
+		    EXT4_BLOCK_GROUP_INODE_UNINIT);
+		
+		if (!ext4_block_group_has_flag(newref->block_group,
+		    EXT4_BLOCK_GROUP_ITABLE_ZEROED)) {
+			rc = ext4_filesystem_init_inode_table(newref);
+			if (rc != EOK)
+				return rc;
+			
+			ext4_block_group_set_flag(newref->block_group,
+			    EXT4_BLOCK_GROUP_ITABLE_ZEROED);
+		}
+		
+		newref->dirty = true;
+	}
+	
+	return EOK;
+}
+
+/** Compute checksum of block group descriptor.
+ *
+ * It uses crc functions from Linux kernel implementation.
+ *
+ * @param sb   Superblock
+ * @param bgid Index of block group in the filesystem
+ * @param bg   Block group to compute checksum for
+ *
+ * @return Checksum value
+ *
+ */
+static uint16_t ext4_filesystem_bg_checksum(ext4_superblock_t *sb, uint32_t bgid,
+    ext4_block_group_t *bg)
+{
+	/* If checksum not supported, 0 will be returned */
+	uint16_t crc = 0;
+	
+	/* Compute the checksum only if the filesystem supports it */
+	if (ext4_superblock_has_feature_read_only(sb,
+	    EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
+		void *base = bg;
+		void *checksum = &bg->checksum;
+		
+		uint32_t offset = (uint32_t) (checksum - base);
+		
+		/* Convert block group index to little endian */
+		uint32_t le_group = host2uint32_t_le(bgid);
+		
+		/* Initialization */
+		crc = crc16(~0, sb->uuid, sizeof(sb->uuid));
+		
+		/* Include index of block group */
+		crc = crc16(crc, (uint8_t *) &le_group, sizeof(le_group));
+		
+		/* Compute crc from the first part (stop before checksum field) */
+		crc = crc16(crc, (uint8_t *) bg, offset);
+		
+		/* Skip checksum */
+		offset += sizeof(bg->checksum);
+		
+		/* Checksum of the rest of block group descriptor */
+		if ((ext4_superblock_has_feature_incompatible(sb,
+		    EXT4_FEATURE_INCOMPAT_64BIT)) &&
+		    (offset < ext4_superblock_get_desc_size(sb)))
+			crc = crc16(crc, ((uint8_t *) bg) + offset,
+			    ext4_superblock_get_desc_size(sb) - offset);
+	}
+	
+	return crc;
+}
+
+/** Put reference to block group.
+ *
+ * @oaram ref Pointer for reference to be put back
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_put_block_group_ref(ext4_block_group_ref_t *ref)
+{
+	/* Check if reference modified */
+	if (ref->dirty) {
+		/* Compute new checksum of block group */
+		uint16_t checksum =
+		    ext4_filesystem_bg_checksum(ref->fs->superblock, ref->index,
+		    ref->block_group);
+		ext4_block_group_set_checksum(ref->block_group, checksum);
+		
+		/* Mark block dirty for writing changes to physical device */
+		ref->block->dirty = true;
+	}
+	
+	/* Put back block, that contains block group descriptor */
+	int rc = block_put(ref->block);
+	free(ref);
+	
+	return rc;
+}
+
+/** Get reference to i-node specified by index.
+ *
+ * @param fs    Filesystem to find i-node on
+ * @param index Index of i-node to load
+ * @oaram ref   Output pointer for reference
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_get_inode_ref(ext4_filesystem_t *fs, uint32_t index,
+    ext4_inode_ref_t **ref)
+{
+	/* Allocate memory for new structure */
+	ext4_inode_ref_t *newref =
+	    malloc(sizeof(ext4_inode_ref_t));
+	if (newref == NULL)
+		return ENOMEM;
+	
+	/* Compute number of i-nodes, that fits in one data block */
+	uint32_t inodes_per_group =
+	    ext4_superblock_get_inodes_per_group(fs->superblock);
+	
+	/*
+	 * Inode numbers are 1-based, but it is simpler to work with 0-based
+	 * when computing indices
+	 */
+	index -= 1;
+	uint32_t block_group = index / inodes_per_group;
+	uint32_t offset_in_group = index % inodes_per_group;
+	
+	/* Load block group, where i-node is located */
+	ext4_block_group_ref_t *bg_ref;
+	int rc = ext4_filesystem_get_block_group_ref(fs, block_group, &bg_ref);
+	if (rc != EOK) {
+		free(newref);
+		return rc;
+	}
+	
+	/* Load block address, where i-node table is located */
+	uint32_t inode_table_start =
+	    ext4_block_group_get_inode_table_first_block(bg_ref->block_group,
+	    fs->superblock);
+	
+	/* Put back block group reference (not needed more) */
+	rc = ext4_filesystem_put_block_group_ref(bg_ref);
+	if (rc != EOK) {
+		free(newref);
+		return rc;
+	}
+	
+	/* Compute position of i-node in the block group */
+	uint16_t inode_size = ext4_superblock_get_inode_size(fs->superblock);
+	uint32_t block_size = ext4_superblock_get_block_size(fs->superblock);
+	uint32_t byte_offset_in_group = offset_in_group * inode_size;
+	
+	/* Compute block address */
+	aoff64_t block_id = inode_table_start + (byte_offset_in_group / block_size);
+	rc = block_get(&newref->block, fs->device, block_id, 0);
+	if (rc != EOK) {
+		free(newref);
+		return rc;
+	}
+	
+	/* Compute position of i-node in the data block */
+	uint32_t offset_in_block = byte_offset_in_group % block_size;
+	newref->inode = newref->block->data + offset_in_block;
+	
+	/* We need to store the original value of index in the reference */
+	newref->index = index + 1;
+	newref->fs = fs;
+	newref->dirty = false;
+	
+	*ref = newref;
+	
+	return EOK;
+}
+
+/** Put reference to i-node.
+ *
+ * @param ref Pointer for reference to be put back
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_put_inode_ref(ext4_inode_ref_t *ref)
+{
+	/* Check if reference modified */
+	if (ref->dirty) {
+		/* Mark block dirty for writing changes to physical device */
+		ref->block->dirty = true;
+	}
+	
+	/* Put back block, that contains i-node */
+	int rc = block_put(ref->block);
+	free(ref);
+	
+	return rc;
+}
+
+/** Allocate new i-node in the filesystem.
+ *
+ * @param fs        Filesystem to allocated i-node on
+ * @param inode_ref Output pointer to return reference to allocated i-node
+ * @param flags     Flags to be set for newly created i-node
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_alloc_inode(ext4_filesystem_t *fs,
+    ext4_inode_ref_t **inode_ref, int flags)
+{
+	/* Check if newly allocated i-node will be a directory */
+	bool is_dir = false;
+	if (flags & L_DIRECTORY)
+		is_dir = true;
+	
+	/* Allocate inode by allocation algorithm */
+	uint32_t index;
+	int rc = ext4_ialloc_alloc_inode(fs, &index, is_dir);
+	if (rc != EOK)
+		return rc;
+	
+	/* Load i-node from on-disk i-node table */
+	rc = ext4_filesystem_get_inode_ref(fs, index, inode_ref);
+	if (rc != EOK) {
+		ext4_ialloc_free_inode(fs, index, is_dir);
+		return rc;
+	}
+	
+	/* Initialize i-node */
+	ext4_inode_t *inode = (*inode_ref)->inode;
+	
+	uint16_t mode;
+	if (is_dir) {
+		/*
+		 * Default directory permissions to be compatible with other systems
+		 * 0777 (octal) == rwxrwxrwx
+		 */
+		
+		mode = 0777;
+		mode |= EXT4_INODE_MODE_DIRECTORY;
+		ext4_inode_set_mode(fs->superblock, inode, mode);
+		ext4_inode_set_links_count(inode, 1);  /* '.' entry */
+	} else {
+		/*
+		 * Default file permissions to be compatible with other systems
+		 * 0666 (octal) == rw-rw-rw-
+		 */
+		
+		mode = 0666;
+		mode |= EXT4_INODE_MODE_FILE;
+		ext4_inode_set_mode(fs->superblock, inode, mode);
+		ext4_inode_set_links_count(inode, 0);
+	}
+	
+	ext4_inode_set_uid(inode, 0);
+	ext4_inode_set_gid(inode, 0);
+	ext4_inode_set_size(inode, 0);
+	ext4_inode_set_access_time(inode, 0);
+	ext4_inode_set_change_inode_time(inode, 0);
+	ext4_inode_set_modification_time(inode, 0);
+	ext4_inode_set_deletion_time(inode, 0);
+	ext4_inode_set_blocks_count(fs->superblock, inode, 0);
+	ext4_inode_set_flags(inode, 0);
+	ext4_inode_set_generation(inode, 0);
+	
+	/* Reset blocks array */
+	for (uint32_t i = 0; i < EXT4_INODE_BLOCKS; i++)
+		inode->blocks[i] = 0;
+	
+	/* Initialize extents if needed */
+	if (ext4_superblock_has_feature_incompatible(
+	    fs->superblock, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
+		ext4_inode_set_flag(inode, EXT4_INODE_FLAG_EXTENTS);
+		
+		/* Initialize extent root header */
+		ext4_extent_header_t *header = ext4_inode_get_extent_header(inode);
+		ext4_extent_header_set_depth(header, 0);
+		ext4_extent_header_set_entries_count(header, 0);
+		ext4_extent_header_set_generation(header, 0);
+		ext4_extent_header_set_magic(header, EXT4_EXTENT_MAGIC);
+		
+		uint16_t max_entries = (EXT4_INODE_BLOCKS * sizeof(uint32_t) -
+		    sizeof(ext4_extent_header_t)) / sizeof(ext4_extent_t);
+		
+		ext4_extent_header_set_max_entries_count(header, max_entries);
+	}
+	
+	(*inode_ref)->dirty = true;
+	
+	return EOK;
+}
+
+/** Release i-node and mark it as free.
+ *
+ * @param inode_ref I-node to be released
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_free_inode(ext4_inode_ref_t *inode_ref)
+{
+	ext4_filesystem_t *fs = inode_ref->fs;
+	
+	/* For extents must be data block destroyed by other way */
+	if ((ext4_superblock_has_feature_incompatible(fs->superblock,
+	    EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
+	    (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
+		/* Data structures are released during truncate operation... */
+		goto finish;
+	}
+	
+	/* Release all indirect (no data) blocks */
+	
+	/* 1) Single indirect */
+	uint32_t fblock = ext4_inode_get_indirect_block(inode_ref->inode, 0);
+	if (fblock != 0) {
+		int rc = ext4_balloc_free_block(inode_ref, fblock);
+		if (rc != EOK)
+			return rc;
+		
+		ext4_inode_set_indirect_block(inode_ref->inode, 0, 0);
+	}
+	
+	block_t *block;
+	uint32_t block_size = ext4_superblock_get_block_size(fs->superblock);
+	uint32_t count = block_size / sizeof(uint32_t);
+	
+	/* 2) Double indirect */
+	fblock = ext4_inode_get_indirect_block(inode_ref->inode, 1);
+	if (fblock != 0) {
+		int rc = block_get(&block, fs->device, fblock, BLOCK_FLAGS_NONE);
+		if (rc != EOK)
+			return rc;
+		
+		uint32_t ind_block;
+		for (uint32_t offset = 0; offset < count; ++offset) {
+			ind_block = uint32_t_le2host(((uint32_t *) block->data)[offset]);
+			
+			if (ind_block != 0) {
+				rc = ext4_balloc_free_block(inode_ref, ind_block);
+				if (rc != EOK) {
+					block_put(block);
+					return rc;
+				}
+			}
+		}
+		
+		block_put(block);
+		rc = ext4_balloc_free_block(inode_ref, fblock);
+		if (rc != EOK)
+			return rc;
+		
+		ext4_inode_set_indirect_block(inode_ref->inode, 1, 0);
+	}
+	
+	/* 3) Tripple indirect */
+	block_t *subblock;
+	fblock = ext4_inode_get_indirect_block(inode_ref->inode, 2);
+	if (fblock != 0) {
+		int rc = block_get(&block, fs->device, fblock, BLOCK_FLAGS_NONE);
+		if (rc != EOK)
+			return rc;
+		
+		uint32_t ind_block;
+		for (uint32_t offset = 0; offset < count; ++offset) {
+			ind_block = uint32_t_le2host(((uint32_t *) block->data)[offset]);
+			
+			if (ind_block != 0) {
+				rc = block_get(&subblock, fs->device, ind_block,
+				    BLOCK_FLAGS_NONE);
+				if (rc != EOK) {
+					block_put(block);
+					return rc;
+				}
+				
+				uint32_t ind_subblock;
+				for (uint32_t suboffset = 0; suboffset < count;
+				    ++suboffset) {
+					ind_subblock = uint32_t_le2host(((uint32_t *)
+					    subblock->data)[suboffset]);
+					
+					if (ind_subblock != 0) {
+						rc = ext4_balloc_free_block(inode_ref, ind_subblock);
+						if (rc != EOK) {
+							block_put(subblock);
+							block_put(block);
+							return rc;
+						}
+					}
+				}
+				
+				block_put(subblock);
+			}
+			
+			rc = ext4_balloc_free_block(inode_ref, ind_block);
+			if (rc != EOK) {
+				block_put(block);
+				return rc;
+			}
+		}
+		
+		block_put(block);
+		rc = ext4_balloc_free_block(inode_ref, fblock);
+		if (rc != EOK)
+			return rc;
+		
+		ext4_inode_set_indirect_block(inode_ref->inode, 2, 0);
+	}
+	
+finish:
+	/* Mark inode dirty for writing to the physical device */
+	inode_ref->dirty = true;
+	
+	/* Free block with extended attributes if present */
+	uint32_t xattr_block = ext4_inode_get_file_acl(
+	    inode_ref->inode, fs->superblock);
+	if (xattr_block) {
+		int rc = ext4_balloc_free_block(inode_ref, xattr_block);
+		if (rc != EOK)
+			return rc;
+		
+		ext4_inode_set_file_acl(inode_ref->inode, fs->superblock, 0);
+	}
+	
+	/* Free inode by allocator */
+	int rc;
+	if (ext4_inode_is_type(fs->superblock, inode_ref->inode,
+	    EXT4_INODE_MODE_DIRECTORY))
+		rc = ext4_ialloc_free_inode(fs, inode_ref->index, true);
+	else
+		rc = ext4_ialloc_free_inode(fs, inode_ref->index, false);
+	
+	return rc;
+}
+
+/** Truncate i-node data blocks.
+ *
+ * @param inode_ref I-node to be truncated
+ * @param new_size  New size of inode (must be < current size)
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_truncate_inode(ext4_inode_ref_t *inode_ref,
+    aoff64_t new_size)
+{
+	ext4_superblock_t *sb = inode_ref->fs->superblock;
+	
+	/* Check flags, if i-node can be truncated */
+	if (!ext4_inode_can_truncate(sb, inode_ref->inode))
+		return EINVAL;
+	
+	/* If sizes are equal, nothing has to be done. */
+	aoff64_t old_size = ext4_inode_get_size(sb, inode_ref->inode);
+	if (old_size == new_size)
+		return EOK;
+	
+	/* It's not suppported to make the larger file by truncate operation */
+	if (old_size < new_size)
+		return EINVAL;
+	
+	/* Compute how many blocks will be released */
+	aoff64_t size_diff = old_size - new_size;
+	uint32_t block_size  = ext4_superblock_get_block_size(sb);
+	uint32_t diff_blocks_count = size_diff / block_size;
+	if (size_diff % block_size != 0)
+		diff_blocks_count++;
+	
+	uint32_t old_blocks_count = old_size / block_size;
+	if (old_size % block_size != 0)
+		old_blocks_count++;
+	
+	if ((ext4_superblock_has_feature_incompatible(inode_ref->fs->superblock,
+	    EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
+	    (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
+		/* Extents require special operation */
+		int rc = ext4_extent_release_blocks_from(inode_ref,
+		    old_blocks_count - diff_blocks_count);
+		if (rc != EOK)
+			return rc;
+	} else {
+		/* Release data blocks from the end of file */
+		
+		/* Starting from 1 because of logical blocks are numbered from 0 */
+		for (uint32_t i = 1; i <= diff_blocks_count; ++i) {
+			int rc = ext4_filesystem_release_inode_block(inode_ref,
+			    old_blocks_count - i);
+			if (rc != EOK)
+				return rc;
+		}
+	}
+	
+	/* Update i-node */
+	ext4_inode_set_size(inode_ref->inode, new_size);
+	inode_ref->dirty = true;
+	
+	return EOK;
+}
+
+/** Get physical block address by logical index of the block.
+ *
+ * @param inode_ref I-node to read block address from
+ * @param iblock    Logical index of block
+ * @param fblock    Output pointer for return physical block address
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_get_inode_data_block_index(ext4_inode_ref_t *inode_ref,
+    aoff64_t iblock, uint32_t *fblock)
+{
+	ext4_filesystem_t *fs = inode_ref->fs;
+	
+	/* For empty file is situation simple */
+	if (ext4_inode_get_size(fs->superblock, inode_ref->inode) == 0) {
+		*fblock = 0;
+		return EOK;
+	}
+	
+	uint32_t current_block;
+	
+	/* Handle i-node using extents */
+	if ((ext4_superblock_has_feature_incompatible(fs->superblock,
+	    EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
+	    (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
+		int rc = ext4_extent_find_block(inode_ref, iblock, &current_block);
+		if (rc != EOK)
+			return rc;
+		
+		*fblock = current_block;
+		return EOK;
+	}
+	
+	ext4_inode_t *inode = inode_ref->inode;
+	
+	/* Direct block are read directly from array in i-node structure */
+	if (iblock < EXT4_INODE_DIRECT_BLOCK_COUNT) {
+		current_block = ext4_inode_get_direct_block(inode, (uint32_t) iblock);
+		*fblock = current_block;
+		return EOK;
+	}
+	
+	/* Determine indirection level of the target block */
+	unsigned int level = 0;
+	for (unsigned int i = 1; i < 4; i++) {
+		if (iblock < fs->inode_block_limits[i]) {
+			level = i;
+			break;
+		}
+	}
+	
+	if (level == 0)
+		return EIO;
+	
+	/* Compute offsets for the topmost level */
+	aoff64_t block_offset_in_level =
+	    iblock - fs->inode_block_limits[level - 1];
+	current_block = ext4_inode_get_indirect_block(inode, level - 1);
+	uint32_t offset_in_block =
+	    block_offset_in_level / fs->inode_blocks_per_level[level - 1];
+	
+	/* Sparse file */
+	if (current_block == 0) {
+		*fblock = 0;
+		return EOK;
+	}
+	
+	block_t *block;
+	
+	/*
+	 * Navigate through other levels, until we find the block number
+	 * or find null reference meaning we are dealing with sparse file
+	 */
+	while (level > 0) {
+		/* Load indirect block */
+		int rc = block_get(&block, fs->device, current_block, 0);
+		if (rc != EOK)
+			return rc;
+		
+		/* Read block address from indirect block */
+		current_block =
+		    uint32_t_le2host(((uint32_t *) block->data)[offset_in_block]);
+		
+		/* Put back indirect block untouched */
+		rc = block_put(block);
+		if (rc != EOK)
+			return rc;
+		
+		/* Check for sparse file */
+		if (current_block == 0) {
+			*fblock = 0;
+			return EOK;
+		}
+		
+		/* Jump to the next level */
+		level--;
+		
+		/* Termination condition - we have address of data block loaded */
+		if (level == 0)
+			break;
+		
+		/* Visit the next level */
+		block_offset_in_level %= fs->inode_blocks_per_level[level];
+		offset_in_block =
+		    block_offset_in_level / fs->inode_blocks_per_level[level - 1];
+	}
+	
+	*fblock = current_block;
+	
+	return EOK;
+}
+
+/** Set physical block address for the block logical address into the i-node.
+ *
+ * @param inode_ref I-node to set block address to
+ * @param iblock    Logical index of block
+ * @param fblock    Physical block address
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_set_inode_data_block_index(ext4_inode_ref_t *inode_ref,
+    aoff64_t iblock, uint32_t fblock)
+{
+	ext4_filesystem_t *fs = inode_ref->fs;
+	
+	/* Handle inode using extents */
+	if ((ext4_superblock_has_feature_compatible(fs->superblock,
+	    EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
+	    (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
+		/* Not reachable */
+		return ENOTSUP;
+	}
+	
+	/* Handle simple case when we are dealing with direct reference */
+	if (iblock < EXT4_INODE_DIRECT_BLOCK_COUNT) {
+		ext4_inode_set_direct_block(inode_ref->inode, (uint32_t) iblock, fblock);
+		inode_ref->dirty = true;
+		
+		return EOK;
+	}
+	
+	/* Determine the indirection level needed to get the desired block */
+	unsigned int level = 0;
+	for (unsigned int i = 1; i < 4; i++) {
+		if (iblock < fs->inode_block_limits[i]) {
+			level = i;
+			break;
+		}
+	}
+	
+	if (level == 0)
+		return EIO;
+	
+	uint32_t block_size = ext4_superblock_get_block_size(fs->superblock);
+	
+	/* Compute offsets for the topmost level */
+	aoff64_t block_offset_in_level =
+	    iblock - fs->inode_block_limits[level - 1];
+	uint32_t current_block =
+	    ext4_inode_get_indirect_block(inode_ref->inode, level - 1);
+	uint32_t offset_in_block =
+	    block_offset_in_level / fs->inode_blocks_per_level[level - 1];
+	
+	uint32_t new_block_addr;
+	block_t *block;
+	block_t *new_block;
+	
+	/* Is needed to allocate indirect block on the i-node level */
+	if (current_block == 0) {
+		/* Allocate new indirect block */
+		int rc = ext4_balloc_alloc_block(inode_ref, &new_block_addr);
+		if (rc != EOK)
+			return rc;
+		
+		/* Update i-node */
+		ext4_inode_set_indirect_block(inode_ref->inode, level - 1,
+		    new_block_addr);
+		inode_ref->dirty = true;
+		
+		/* Load newly allocated block */
+		rc = block_get(&new_block, fs->device, new_block_addr,
+		    BLOCK_FLAGS_NOREAD);
+		if (rc != EOK) {
+			ext4_balloc_free_block(inode_ref, new_block_addr);
+			return rc;
+		}
+		
+		/* Initialize new block */
+		memset(new_block->data, 0, block_size);
+		new_block->dirty = true;
+		
+		/* Put back the allocated block */
+		rc = block_put(new_block);
+		if (rc != EOK)
+			return rc;
+		
+		current_block = new_block_addr;
+	}
+	
+	/*
+	 * Navigate through other levels, until we find the block number
+	 * or find null reference meaning we are dealing with sparse file
+	 */
+	while (level > 0) {
+		int rc = block_get(&block, fs->device, current_block, 0);
+		if (rc != EOK)
+			return rc;
+		
+		current_block =
+		    uint32_t_le2host(((uint32_t *) block->data)[offset_in_block]);
+		
+		if ((level > 1) && (current_block == 0)) {
+			/* Allocate new block */
+			rc = ext4_balloc_alloc_block(inode_ref, &new_block_addr);
+			if (rc != EOK) {
+				block_put(block);
+				return rc;
+			}
+			
+			/* Load newly allocated block */
+			rc = block_get(&new_block, fs->device, new_block_addr,
+			    BLOCK_FLAGS_NOREAD);
+			if (rc != EOK) {
+				block_put(block);
+				return rc;
+			}
+			
+			/* Initialize allocated block */
+			memset(new_block->data, 0, block_size);
+			new_block->dirty = true;
+			
+			rc = block_put(new_block);
+			if (rc != EOK) {
+				block_put(block);
+				return rc;
+			}
+			
+			/* Write block address to the parent */
+			((uint32_t *) block->data)[offset_in_block] =
+			    host2uint32_t_le(new_block_addr);
+			block->dirty = true;
+			current_block = new_block_addr;
+		}
+		
+		/* Will be finished, write the fblock address */
+		if (level == 1) {
+			((uint32_t *) block->data)[offset_in_block] =
+			    host2uint32_t_le(fblock);
+			block->dirty = true;
+		}
+		
+		rc = block_put(block);
+		if (rc != EOK)
+			return rc;
+		
+		level--;
+		
+		/*
+		 * If we are on the last level, break here as
+		 * there is no next level to visit
+		 */
+		if (level == 0)
+			break;
+		
+		/* Visit the next level */
+		block_offset_in_level %= fs->inode_blocks_per_level[level];
+		offset_in_block =
+		    block_offset_in_level / fs->inode_blocks_per_level[level - 1];
+	}
+	
+	return EOK;
+}
+
+/** Release data block from i-node
+ *
+ * @param inode_ref I-node to release block from
+ * @param iblock    Logical block to be released
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_release_inode_block(ext4_inode_ref_t *inode_ref,
+    uint32_t iblock)
+{
+	uint32_t fblock;
+	
+	ext4_filesystem_t *fs = inode_ref->fs;
+	
+	/* Extents are handled otherwise = there is not support in this function */
+	assert(!(ext4_superblock_has_feature_incompatible(fs->superblock,
+	    EXT4_FEATURE_INCOMPAT_EXTENTS) &&
+	    (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))));
+	
+	ext4_inode_t *inode = inode_ref->inode;
+	
+	/* Handle simple case when we are dealing with direct reference */
+	if (iblock < EXT4_INODE_DIRECT_BLOCK_COUNT) {
+		fblock = ext4_inode_get_direct_block(inode, iblock);
+		
+		/* Sparse file */
+		if (fblock == 0)
+			return EOK;
+		
+		ext4_inode_set_direct_block(inode, iblock, 0);
+		return ext4_balloc_free_block(inode_ref, fblock);
+	}
+	
+	/* Determine the indirection level needed to get the desired block */
+	unsigned int level = 0;
+	for (unsigned int i = 1; i < 4; i++) {
+		if (iblock < fs->inode_block_limits[i]) {
+			level = i;
+			break;
+		}
+	}
+	
+	if (level == 0)
+		return EIO;
+	
+	/* Compute offsets for the topmost level */
+	aoff64_t block_offset_in_level =
+	    iblock - fs->inode_block_limits[level - 1];
+	uint32_t current_block =
+	    ext4_inode_get_indirect_block(inode, level - 1);
+	uint32_t offset_in_block =
+	    block_offset_in_level / fs->inode_blocks_per_level[level - 1];
+	
+	/*
+	 * Navigate through other levels, until we find the block number
+	 * or find null reference meaning we are dealing with sparse file
+	 */
+	block_t *block;
+	while (level > 0) {
+		int rc = block_get(&block, fs->device, current_block, 0);
+		if (rc != EOK)
+			return rc;
+		
+		current_block =
+		    uint32_t_le2host(((uint32_t *) block->data)[offset_in_block]);
+		
+		/* Set zero if physical data block address found */
+		if (level == 1) {
+			((uint32_t *) block->data)[offset_in_block] =
+			    host2uint32_t_le(0);
+			block->dirty = true;
+		}
+		
+		rc = block_put(block);
+		if (rc != EOK)
+			return rc;
+		
+		level--;
+		
+		/*
+		 * If we are on the last level, break here as
+		 * there is no next level to visit
+		 */
+		if (level == 0)
+			break;
+		
+		/* Visit the next level */
+		block_offset_in_level %= fs->inode_blocks_per_level[level];
+		offset_in_block =
+		    block_offset_in_level / fs->inode_blocks_per_level[level - 1];
+	}
+	
+	fblock = current_block;
+	if (fblock == 0)
+		return EOK;
+	
+	/* Physical block is not referenced, it can be released */
+	return ext4_balloc_free_block(inode_ref, fblock);
+}
+
+/** Append following logical block to the i-node.
+ *
+ * @param inode_ref I-node to append block to
+ * @param fblock    Output physical block address of newly allocated block
+ * @param iblock    Output logical number of newly allocated block
+ *
+ * @return Error code
+ *
+ */
+int ext4_filesystem_append_inode_block(ext4_inode_ref_t *inode_ref,
+    uint32_t *fblock, uint32_t *iblock)
+{
+	/* Handle extents separately */
+	if ((ext4_superblock_has_feature_incompatible(inode_ref->fs->superblock,
+	    EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
+	    (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS)))
+		return ext4_extent_append_block(inode_ref, iblock, fblock, true);
+	
+	ext4_superblock_t *sb = inode_ref->fs->superblock;
+	
+	/* Compute next block index and allocate data block */
+	uint64_t inode_size = ext4_inode_get_size(sb, inode_ref->inode);
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	
+	/* Align size i-node size */
+	if ((inode_size % block_size) != 0)
+		inode_size += block_size - (inode_size % block_size);
+	
+	/* Logical blocks are numbered from 0 */
+	uint32_t new_block_idx = inode_size / block_size;
+	
+	/* Allocate new physical block */
+	uint32_t phys_block;
+	int rc = ext4_balloc_alloc_block(inode_ref, &phys_block);
+	if (rc != EOK)
+		return rc;
+	
+	/* Add physical block address to the i-node */
+	rc = ext4_filesystem_set_inode_data_block_index(inode_ref,
+	    new_block_idx, phys_block);
+	if (rc != EOK) {
+		ext4_balloc_free_block(inode_ref, phys_block);
+		return rc;
+	}
+	
+	/* Update i-node */
+	ext4_inode_set_size(inode_ref->inode, inode_size + block_size);
+	inode_ref->dirty = true;
+	
+	*fblock = phys_block;
+	*iblock = new_block_idx;
+	
+	return EOK;
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_filesystem.h
===================================================================
--- uspace/lib/ext4/libext4_filesystem.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_filesystem.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_FILESYSTEM_H_
+#define LIBEXT4_LIBEXT4_FILESYSTEM_H_
+
+#include <libblock.h>
+#include "libext4_types.h"
+
+extern int ext4_filesystem_init(ext4_filesystem_t *, service_id_t,
+    enum cache_mode);
+extern int ext4_filesystem_fini(ext4_filesystem_t *);
+extern int ext4_filesystem_check_sanity(ext4_filesystem_t *);
+extern int ext4_filesystem_check_features(ext4_filesystem_t *, bool *);
+extern uint32_t ext4_filesystem_blockaddr2_index_in_group(ext4_superblock_t *,
+    uint32_t);
+extern uint32_t ext4_filesystem_index_in_group2blockaddr(ext4_superblock_t *,
+    uint32_t, uint32_t);
+extern int ext4_filesystem_get_block_group_ref(ext4_filesystem_t *, uint32_t,
+    ext4_block_group_ref_t **);
+extern int ext4_filesystem_put_block_group_ref(ext4_block_group_ref_t *);
+extern int ext4_filesystem_get_inode_ref(ext4_filesystem_t *, uint32_t,
+    ext4_inode_ref_t **);
+extern int ext4_filesystem_put_inode_ref(ext4_inode_ref_t *);
+extern int ext4_filesystem_alloc_inode(ext4_filesystem_t *, ext4_inode_ref_t **,
+    int);
+extern int ext4_filesystem_free_inode(ext4_inode_ref_t *);
+extern int ext4_filesystem_truncate_inode(ext4_inode_ref_t *, aoff64_t);
+extern int ext4_filesystem_get_inode_data_block_index(ext4_inode_ref_t *,
+    aoff64_t iblock, uint32_t *);
+extern int ext4_filesystem_set_inode_data_block_index(ext4_inode_ref_t *,
+    aoff64_t, uint32_t);
+extern int ext4_filesystem_release_inode_block(ext4_inode_ref_t *, uint32_t);
+extern int ext4_filesystem_append_inode_block(ext4_inode_ref_t *, uint32_t *,
+    uint32_t *);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_hash.c
===================================================================
--- uspace/lib/ext4/libext4_hash.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_hash.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,322 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+/**
+ * @file  libext4_hash.c
+ * @brief Hashing algorithms for ext4 HTree.
+ */
+
+#include <errno.h>
+#include <mem.h>
+#include "libext4.h"
+
+#define TEA_DELTA  0x9E3779B9
+
+/* F, G and H are basic MD4 functions: selection, majority, parity */
+#define F(x, y, z)  ((z) ^ ((x) & ((y) ^ (z))))
+#define G(x, y, z)  (((x) & (y)) + (((x) ^ (y)) & (z)))
+#define H(x, y, z)  ((x) ^ (y) ^ (z))
+
+/*
+ * The generic round function.  The application is so specific that
+ * we don't bother protecting all the arguments with parens, as is generally
+ * good macro practice, in favor of extra legibility.
+ * Rotation is separate from addition to prevent recomputation
+ */
+#define ROUND(f, a, b, c, d, x, s) \
+	(a += f(b, c, d) + x, a = (a << s) | (a >> (32 - s)))
+
+#define K1  0
+#define K2  013240474631UL
+#define K3  015666365641UL
+
+static void tea_transform(uint32_t buf[4], uint32_t const in[])
+{
+	uint32_t sum = 0;
+	uint32_t b0 = buf[0];
+	uint32_t b1 = buf[1];
+	uint32_t a = in[0];
+	uint32_t b = in[1];
+	uint32_t c = in[2];
+	uint32_t d = in[3];
+	
+	int n = 16;
+	
+	do {
+		sum += TEA_DELTA;
+		b0 += ((b1 << 4) + a) ^ (b1 + sum) ^ ((b1 >> 5) + b);
+		b1 += ((b0 << 4) + c) ^ (b0 + sum) ^ ((b0 >> 5) + d);
+	} while (--n);
+	
+	buf[0] += b0;
+	buf[1] += b1;
+}
+
+
+static void half_md4_transform(uint32_t buf[4], const uint32_t in[8])
+{
+	uint32_t a = buf[0], b = buf[1], c = buf[2], d = buf[3];
+	
+	/* Round 1 */
+	ROUND(F, a, b, c, d, in[0] + K1,  3);
+	ROUND(F, d, a, b, c, in[1] + K1,  7);
+	ROUND(F, c, d, a, b, in[2] + K1, 11);
+	ROUND(F, b, c, d, a, in[3] + K1, 19);
+	ROUND(F, a, b, c, d, in[4] + K1,  3);
+	ROUND(F, d, a, b, c, in[5] + K1,  7);
+	ROUND(F, c, d, a, b, in[6] + K1, 11);
+	ROUND(F, b, c, d, a, in[7] + K1, 19);
+	
+	/* Round 2 */
+	ROUND(G, a, b, c, d, in[1] + K2,  3);
+	ROUND(G, d, a, b, c, in[3] + K2,  5);
+	ROUND(G, c, d, a, b, in[5] + K2,  9);
+	ROUND(G, b, c, d, a, in[7] + K2, 13);
+	ROUND(G, a, b, c, d, in[0] + K2,  3);
+	ROUND(G, d, a, b, c, in[2] + K2,  5);
+	ROUND(G, c, d, a, b, in[4] + K2,  9);
+	ROUND(G, b, c, d, a, in[6] + K2, 13);
+	
+	/* Round 3 */
+	ROUND(H, a, b, c, d, in[3] + K3,  3);
+	ROUND(H, d, a, b, c, in[7] + K3,  9);
+	ROUND(H, c, d, a, b, in[2] + K3, 11);
+	ROUND(H, b, c, d, a, in[6] + K3, 15);
+	ROUND(H, a, b, c, d, in[1] + K3,  3);
+	ROUND(H, d, a, b, c, in[5] + K3,  9);
+	ROUND(H, c, d, a, b, in[0] + K3, 11);
+	ROUND(H, b, c, d, a, in[4] + K3, 15);
+	
+	buf[0] += a;
+	buf[1] += b;
+	buf[2] += c;
+	buf[3] += d;
+}
+
+static uint32_t hash_unsigned(const char *name, int len)
+{
+	uint32_t hash;
+	uint32_t hash0 = 0x12a3fe2d;
+	uint32_t hash1 = 0x37abe8f9;
+	const unsigned char *ucp = (const unsigned char *) name;
+	
+	while (len--) {
+		hash = hash1 + (hash0 ^ (((int) *ucp++) * 7152373));
+		
+		if (hash & 0x80000000)
+			hash -= 0x7fffffff;
+		
+		hash1 = hash0;
+		hash0 = hash;
+	}
+	
+	return hash0 << 1;
+}
+
+static uint32_t hash_signed(const char *name, int len)
+{
+	uint32_t hash;
+	uint32_t hash0 = 0x12a3fe2d;
+	uint32_t hash1 = 0x37abe8f9;
+	const signed char *scp = (const signed char *) name;
+	
+	while (len--) {
+		hash = hash1 + (hash0 ^ (((int) *scp++) * 7152373));
+		
+		if (hash & 0x80000000)
+			hash -= 0x7fffffff;
+		
+		hash1 = hash0;
+		hash0 = hash;
+	}
+	
+	return hash0 << 1;
+}
+
+static void str2hashbuf_signed(const char *msg, int len, uint32_t *buf, int num)
+{
+	uint32_t pad, val;
+	int i;
+	const signed char *scp = (const signed char *) msg;
+	
+	pad = (uint32_t) len | ((uint32_t) len << 8);
+	pad |= pad << 16;
+	
+	val = pad;
+	if (len > num * 4)
+		len = num * 4;
+	
+	for (i = 0; i < len; i++) {
+		if ((i % 4) == 0)
+			val = pad;
+		
+		val = ((int) scp[i]) + (val << 8);
+		if ((i % 4) == 3) {
+			*buf++ = val;
+			val = pad;
+			num--;
+		}
+	}
+	
+	if (--num >= 0)
+		*buf++ = val;
+	
+	while (--num >= 0)
+		*buf++ = pad;
+}
+
+static void str2hashbuf_unsigned(const char *msg, int len, uint32_t *buf,
+    int num)
+{
+	uint32_t pad, val;
+	int i;
+	const unsigned char *ucp = (const unsigned char *) msg;
+	
+	pad = (uint32_t) len | ((uint32_t) len << 8);
+	pad |= pad << 16;
+	
+	val = pad;
+	if (len > num * 4)
+		len = num * 4;
+	
+	for (i = 0; i < len; i++) {
+		if ((i % 4) == 0)
+			val = pad;
+		
+		val = ((int) ucp[i]) + (val << 8);
+		if ((i % 4) == 3) {
+			*buf++ = val;
+			val = pad;
+			num--;
+		}
+	}
+	
+	if (--num >= 0)
+		*buf++ = val;
+	
+	while (--num >= 0)
+		*buf++ = pad;
+}
+
+/** Compute hash value of the string.
+ *
+ * @param hinfo Hash info structure with information about
+ *              the algorithm, hash seed and with the place
+ *              for the output hash value
+ * @param len  Length of the name
+ * @param name Name to be hashed
+ *
+ * @return Error code
+ *
+ */
+int ext4_hash_string(ext4_hash_info_t *hinfo, int len, const char *name)
+{
+	uint32_t hash = 0;
+	uint32_t minor_hash = 0;
+	const char *p;
+	int i;
+	uint32_t in[8], buf[4];
+	void (*str2hashbuf)(const char *, int, uint32_t *, int) =
+	    str2hashbuf_signed;
+	
+	/* Initialize the default seed for the hash checksum functions */
+	buf[0] = 0x67452301;
+	buf[1] = 0xefcdab89;
+	buf[2] = 0x98badcfe;
+	buf[3] = 0x10325476;
+	
+	/* Check if the seed is all zero's */
+	if (hinfo->seed) {
+		for (i = 0; i < 4; i++) {
+			if (hinfo->seed[i] != 0)
+				break;
+			
+		}
+		
+		if (i < 4)
+			memcpy(buf, hinfo->seed, sizeof(buf));
+	}
+	
+	switch (hinfo->hash_version) {
+	case EXT4_HASH_VERSION_LEGACY_UNSIGNED:
+		hash = hash_unsigned(name, len);
+		break;
+	case EXT4_HASH_VERSION_LEGACY:
+		hash = hash_signed(name, len);
+		break;
+	case EXT4_HASH_VERSION_HALF_MD4_UNSIGNED:
+		str2hashbuf = str2hashbuf_unsigned;
+	case EXT4_HASH_VERSION_HALF_MD4:
+		p = name;
+		
+		while (len > 0) {
+			(*str2hashbuf)(p, len, in, 8);
+			half_md4_transform(buf, in);
+			len -= 32;
+			p += 32;
+		}
+		
+		minor_hash = buf[2];
+		hash = buf[1];
+		break;
+	case EXT4_HASH_VERSION_TEA_UNSIGNED:
+		str2hashbuf = str2hashbuf_unsigned;
+	case EXT4_HASH_VERSION_TEA:
+		p = name;
+		
+		while (len > 0) {
+			(*str2hashbuf)(p, len, in, 4);
+			tea_transform(buf, in);
+			len -= 16;
+			p += 16;
+		}
+		
+		hash = buf[0];
+		minor_hash = buf[1];
+		break;
+	default:
+		hinfo->hash = 0;
+		return EINVAL;
+	}
+	
+	hash = hash & ~1;
+	if (hash == (EXT4_DIRECTORY_HTREE_EOF << 1))
+		hash = (EXT4_DIRECTORY_HTREE_EOF - 1) << 1;
+	
+	hinfo->hash = hash;
+	hinfo->minor_hash = minor_hash;
+	
+	return EOK;
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_hash.h
===================================================================
--- uspace/lib/ext4/libext4_hash.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_hash.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_HASH_H_
+#define LIBEXT4_LIBEXT4_HASH_H_
+
+#include <sys/types.h>
+#include "libext4_types.h"
+
+extern int ext4_hash_string(ext4_hash_info_t *, int, const char *);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_ialloc.c
===================================================================
--- uspace/lib/ext4/libext4_ialloc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_ialloc.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,283 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+/**
+ * @file  libext4_ialloc.c
+ * @brief I-node (de)allocation operations.
+ */
+
+#include <errno.h>
+#include <time.h>
+#include "libext4.h"
+
+
+/** Convert i-node number to relative index in block group.
+ *
+ * @param sb    Superblock
+ * @param inode I-node number to be converted
+ *
+ * @return Index of the i-node in the block group
+ *
+ */
+static uint32_t ext4_ialloc_inode2index_in_group(ext4_superblock_t *sb,
+    uint32_t inode)
+{
+	uint32_t inodes_per_group = ext4_superblock_get_inodes_per_group(sb);
+	return (inode - 1) % inodes_per_group;
+}
+
+/** Convert relative index of i-node to absolute i-node number.
+ *
+ * @param sb    Superblock
+ * @param inode Index to be converted
+ *
+ * @return Absolute number of the i-node
+ *
+ */
+static uint32_t ext4_ialloc_index_in_group2inode(ext4_superblock_t *sb,
+    uint32_t index, uint32_t bgid)
+{
+	uint32_t inodes_per_group = ext4_superblock_get_inodes_per_group(sb);
+	return bgid * inodes_per_group + (index + 1);
+}
+
+/** Compute block group number from the i-node number.
+ *
+ * @param sb    Superblock
+ * @param inode I-node number to be found the block group for
+ *
+ * @return Block group number computed from i-node number
+ *
+ */
+static uint32_t ext4_ialloc_get_bgid_of_inode(ext4_superblock_t *sb,
+    uint32_t inode)
+{
+	uint32_t inodes_per_group = ext4_superblock_get_inodes_per_group(sb);
+	return (inode - 1) / inodes_per_group;
+}
+
+
+/** Free i-node number and modify filesystem data structers.
+ *
+ * @param fs     Filesystem, where the i-node is located
+ * @param index  Index of i-node to be release
+ * @param is_dir Flag us for information whether i-node is directory or not
+ *
+ */
+int ext4_ialloc_free_inode(ext4_filesystem_t *fs, uint32_t index, bool is_dir)
+{
+	ext4_superblock_t *sb = fs->superblock;
+	
+	/* Compute index of block group and load it */
+	uint32_t block_group = ext4_ialloc_get_bgid_of_inode(sb, index);
+	
+	ext4_block_group_ref_t *bg_ref;
+	int rc = ext4_filesystem_get_block_group_ref(fs, block_group, &bg_ref);
+	if (rc != EOK)
+		return rc;
+	
+	/* Load i-node bitmap */
+	uint32_t bitmap_block_addr = ext4_block_group_get_inode_bitmap(
+	    bg_ref->block_group, sb);
+	block_t *bitmap_block;
+	rc = block_get(&bitmap_block, fs->device, bitmap_block_addr,
+	    BLOCK_FLAGS_NONE);
+	if (rc != EOK)
+		return rc;
+	
+	/* Free i-node in the bitmap */
+	uint32_t index_in_group = ext4_ialloc_inode2index_in_group(sb, index);
+	ext4_bitmap_free_bit(bitmap_block->data, index_in_group);
+	bitmap_block->dirty = true;
+	
+	/* Put back the block with bitmap */
+	rc = block_put(bitmap_block);
+	if (rc != EOK) {
+		/* Error in saving bitmap */
+		ext4_filesystem_put_block_group_ref(bg_ref);
+		return rc;
+	}
+	
+	/* If released i-node is a directory, decrement used directories count */
+	if (is_dir) {
+		uint32_t bg_used_dirs = ext4_block_group_get_used_dirs_count(
+		    bg_ref->block_group, sb);
+		bg_used_dirs--;
+		ext4_block_group_set_used_dirs_count(bg_ref->block_group, sb,
+		    bg_used_dirs);
+	}
+	
+	/* Update block group free inodes count */
+	uint32_t free_inodes = ext4_block_group_get_free_inodes_count(
+	    bg_ref->block_group, sb);
+	free_inodes++;
+	ext4_block_group_set_free_inodes_count(bg_ref->block_group, sb,
+	    free_inodes);
+	
+	bg_ref->dirty = true;
+	
+	/* Put back the modified block group */
+	rc = ext4_filesystem_put_block_group_ref(bg_ref);
+	if (rc != EOK)
+		return rc;
+	
+	/* Update superblock free inodes count */
+	uint32_t sb_free_inodes =
+	    ext4_superblock_get_free_inodes_count(sb);
+	sb_free_inodes++;
+	ext4_superblock_set_free_inodes_count(sb, sb_free_inodes);
+	
+	return EOK;
+}
+
+/** I-node allocation algorithm.
+ *
+ * This is more simple algorithm, than Orlov allocator used
+ * in the Linux kernel.
+ *
+ * @param fs     Filesystem to allocate i-node on
+ * @param index  Output value - allocated i-node number
+ * @param is_dir Flag if allocated i-node will be file or directory
+ *
+ * @return Error code
+ *
+ */
+int ext4_ialloc_alloc_inode(ext4_filesystem_t *fs, uint32_t *index, bool is_dir)
+{
+	ext4_superblock_t *sb = fs->superblock;
+	
+	uint32_t bgid = 0;
+	uint32_t bg_count = ext4_superblock_get_block_group_count(sb);
+	uint32_t sb_free_inodes = ext4_superblock_get_free_inodes_count(sb);
+	uint32_t avg_free_inodes = sb_free_inodes / bg_count;
+	
+	/* Try to find free i-node in all block groups */
+	while (bgid < bg_count) {
+		/* Load block group to check */
+		ext4_block_group_ref_t *bg_ref;
+		int rc = ext4_filesystem_get_block_group_ref(fs, bgid, &bg_ref);
+		if (rc != EOK)
+			return rc;
+		
+		ext4_block_group_t *bg = bg_ref->block_group;
+		
+		/* Read necessary values for algorithm */
+		uint32_t free_blocks = ext4_block_group_get_free_blocks_count(bg, sb);
+		uint32_t free_inodes = ext4_block_group_get_free_inodes_count(bg, sb);
+		uint32_t used_dirs = ext4_block_group_get_used_dirs_count(bg, sb);
+		
+		/* Check if this block group is good candidate for allocation */
+		if ((free_inodes >= avg_free_inodes) && (free_blocks > 0)) {
+			/* Load block with bitmap */
+			uint32_t bitmap_block_addr = ext4_block_group_get_inode_bitmap(
+			    bg_ref->block_group, sb);
+			
+			block_t *bitmap_block;
+			rc = block_get(&bitmap_block, fs->device, bitmap_block_addr,
+			    BLOCK_FLAGS_NONE);
+			if (rc != EOK)
+				return rc;
+			
+			/* Try to allocate i-node in the bitmap */
+			uint32_t inodes_in_group = ext4_superblock_get_inodes_in_group(sb, bgid);
+			uint32_t index_in_group;
+			rc = ext4_bitmap_find_free_bit_and_set(bitmap_block->data,
+			    0, &index_in_group, inodes_in_group);
+			
+			/* Block group has not any free i-node */
+			if (rc == ENOSPC) {
+				block_put(bitmap_block);
+				ext4_filesystem_put_block_group_ref(bg_ref);
+				continue;
+			}
+			
+			/* Free i-node found, save the bitmap */
+			bitmap_block->dirty = true;
+			
+			rc = block_put(bitmap_block);
+			if (rc != EOK)
+				return rc;
+			
+			/* Modify filesystem counters */
+			free_inodes--;
+			ext4_block_group_set_free_inodes_count(bg, sb, free_inodes);
+			
+			/* Increment used directories counter */
+			if (is_dir) {
+				used_dirs++;
+				ext4_block_group_set_used_dirs_count(bg, sb, used_dirs);
+			}
+			
+			/* Decrease unused inodes count */
+			if (ext4_block_group_has_flag(bg,
+			    EXT4_BLOCK_GROUP_ITABLE_ZEROED)) {
+				uint32_t unused =
+				    ext4_block_group_get_itable_unused(bg, sb);
+				
+				uint32_t inodes_in_group =
+				    ext4_superblock_get_inodes_in_group(sb, bgid);
+				
+				uint32_t free = inodes_in_group - unused;
+				
+				if (index_in_group >= free) {
+					unused = inodes_in_group - (index_in_group + 1);
+					ext4_block_group_set_itable_unused(bg, sb, unused);
+				}
+			}
+			
+			/* Save modified block group */
+			bg_ref->dirty = true;
+			
+			rc = ext4_filesystem_put_block_group_ref(bg_ref);
+			if (rc != EOK)
+				return rc;
+			
+			/* Update superblock */
+			sb_free_inodes--;
+			ext4_superblock_set_free_inodes_count(sb, sb_free_inodes);
+			
+			/* Compute the absolute i-nodex number */
+			*index = ext4_ialloc_index_in_group2inode(sb, index_in_group, bgid);
+			
+			return EOK;
+		}
+		
+		/* Block group not modified, put it and jump to the next block group */
+		ext4_filesystem_put_block_group_ref(bg_ref);
+		++bgid;
+	}
+	
+	return ENOSPC;
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_ialloc.h
===================================================================
--- uspace/lib/ext4/libext4_ialloc.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_ialloc.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_IALLOC_H_
+#define LIBEXT4_LIBEXT4_IALLOC_H_
+
+#include "libext4_types.h"
+
+extern int ext4_ialloc_free_inode(ext4_filesystem_t *, uint32_t, bool);
+extern int ext4_ialloc_alloc_inode(ext4_filesystem_t *, uint32_t *, bool);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_inode.c
===================================================================
--- uspace/lib/ext4/libext4_inode.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_inode.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,593 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+/**
+ * @file  libext4_inode.c
+ * @brief Ext4 i-node structure operations.
+ */
+
+#include <byteorder.h>
+#include <errno.h>
+#include <libblock.h>
+#include "libext4.h"
+
+/** Compute number of bits for block count.
+ *
+ *  @param block_size Filesystem block_size
+ *
+ *  @return Number of bits
+ *
+ */
+static uint32_t ext4_inode_block_bits_count(uint32_t block_size)
+{
+	uint32_t bits = 8;
+	uint32_t size = block_size;
+	
+	do {
+		bits++;
+		size = size >> 1;
+	} while (size > 256);
+	
+	return bits;
+}
+
+/** Get mode of the i-node.
+ *
+ * @param sb    Superblock
+ * @param inode I-node to load mode from
+ *
+ * @return Mode of the i-node
+ *
+ */
+uint32_t ext4_inode_get_mode(ext4_superblock_t *sb, ext4_inode_t *inode)
+{
+	if (ext4_superblock_get_creator_os(sb) == EXT4_SUPERBLOCK_OS_HURD) {
+		return ((uint32_t) uint16_t_le2host(inode->osd2.hurd2.mode_high)) << 16 |
+		    ((uint32_t) uint16_t_le2host(inode->mode));
+	}
+	
+	return uint16_t_le2host(inode->mode);
+}
+
+/** Set mode of the i-node.
+ *
+ * @param sb    Superblock
+ * @param inode I-node to set mode to
+ * @param mode  Mode to set to i-node
+ *
+ */
+void ext4_inode_set_mode(ext4_superblock_t *sb, ext4_inode_t *inode, uint32_t mode)
+{
+	inode->mode = host2uint16_t_le((mode << 16) >> 16);
+	
+	if (ext4_superblock_get_creator_os(sb) == EXT4_SUPERBLOCK_OS_HURD)
+		inode->osd2.hurd2.mode_high = host2uint16_t_le(mode >> 16);
+}
+
+/** Get ID of the i-node owner (user id).
+ *
+ * @param inode I-node to load uid from
+ *
+ * @return User ID of the i-node owner
+ *
+ */
+uint32_t ext4_inode_get_uid(ext4_inode_t *inode)
+{
+	return uint32_t_le2host(inode->uid);
+}
+
+/** Set ID of the i-node owner.
+ *
+ * @param inode I-node to set uid to
+ * @param uid   ID of the i-node owner
+ *
+ */
+void ext4_inode_set_uid(ext4_inode_t *inode, uint32_t uid)
+{
+	inode->uid = host2uint32_t_le(uid);
+}
+
+/** Get real i-node size.
+ *
+ * @param sb    Superblock
+ * @param inode I-node to load size from
+ *
+ * @return Real size of i-node
+ *
+ */
+uint64_t ext4_inode_get_size(ext4_superblock_t *sb, ext4_inode_t *inode)
+{
+	uint32_t major_rev = ext4_superblock_get_rev_level(sb);
+	
+	if ((major_rev > 0) &&
+	    (ext4_inode_is_type(sb, inode, EXT4_INODE_MODE_FILE)))
+		return ((uint64_t)uint32_t_le2host(inode->size_hi)) << 32 |
+		    ((uint64_t)uint32_t_le2host(inode->size_lo));
+	
+	return uint32_t_le2host(inode->size_lo);
+}
+
+/** Set real i-node size.
+ *
+ * @param inode I-node to set size to
+ * @param size  Size of the i-node
+ *
+ */
+void ext4_inode_set_size(ext4_inode_t *inode, uint64_t size)
+{
+	inode->size_lo = host2uint32_t_le((size << 32) >> 32);
+	inode->size_hi = host2uint32_t_le(size >> 32);
+}
+
+/** Get time, when i-node was last accessed.
+ *
+ * @param inode I-node
+ *
+ * @return Time of the last access (POSIX)
+ *
+ */
+uint32_t ext4_inode_get_access_time(ext4_inode_t *inode)
+{
+	return uint32_t_le2host(inode->access_time);
+}
+
+/** Set time, when i-node was last accessed.
+ *
+ * @param inode I-node
+ * @param time  Time of the last access (POSIX)
+ *
+ */
+void ext4_inode_set_access_time(ext4_inode_t *inode, uint32_t time)
+{
+	inode->access_time = host2uint32_t_le(time);
+}
+
+/** Get time, when i-node was last changed.
+ *
+ * @param inode I-node
+ *
+ * @return Time of the last change (POSIX)
+ *
+ */
+uint32_t ext4_inode_get_change_inode_time(ext4_inode_t *inode)
+{
+	return uint32_t_le2host(inode->change_inode_time);
+}
+
+/** Set time, when i-node was last changed.
+ *
+ * @param inode I-node
+ * @param time  Time of the last change (POSIX)
+ *
+ */
+void ext4_inode_set_change_inode_time(ext4_inode_t *inode, uint32_t time)
+{
+	inode->change_inode_time = host2uint32_t_le(time);
+}
+
+/** Get time, when i-node content was last modified.
+ *
+ * @param inode I-node
+ *
+ * @return Time of the last content modification (POSIX)
+ *
+ */
+uint32_t ext4_inode_get_modification_time(ext4_inode_t *inode)
+{
+	return uint32_t_le2host(inode->modification_time);
+}
+
+/** Set time, when i-node content was last modified.
+ *
+ * @param inode I-node
+ * @param time  Time of the last content modification (POSIX)
+ *
+ */
+void ext4_inode_set_modification_time(ext4_inode_t *inode, uint32_t time)
+{
+	inode->modification_time = host2uint32_t_le(time);
+}
+
+/** Get time, when i-node was deleted.
+ *
+ * @param inode I-node
+ *
+ * @return Time of the delete action (POSIX)
+ *
+ */
+uint32_t ext4_inode_get_deletion_time(ext4_inode_t *inode)
+{
+	return uint32_t_le2host(inode->deletion_time);
+}
+
+/** Set time, when i-node was deleted.
+ *
+ * @param inode I-node
+ * @param time  Time of the delete action (POSIX)
+ *
+ */
+void ext4_inode_set_deletion_time(ext4_inode_t *inode, uint32_t time)
+{
+	inode->deletion_time = host2uint32_t_le(time);
+}
+
+/** Get ID of the i-node owner's group.
+ *
+ * @param inode I-node to load gid from
+ *
+ * @return Group ID of the i-node owner
+ *
+ */
+uint32_t ext4_inode_get_gid(ext4_inode_t *inode)
+{
+	return uint32_t_le2host(inode->gid);
+}
+
+/** Set ID ot the i-node owner's group.
+ *
+ * @param inode I-node to set gid to
+ * @param gid   Group ID of the i-node owner
+ *
+ */
+void ext4_inode_set_gid(ext4_inode_t *inode, uint32_t gid)
+{
+	inode->gid = host2uint32_t_le(gid);
+}
+
+/** Get number of links to i-node.
+ *
+ * @param inode I-node to load number of links from
+ *
+ * @return Number of links to i-node
+ *
+ */
+uint16_t ext4_inode_get_links_count(ext4_inode_t *inode)
+{
+	return uint16_t_le2host(inode->links_count);
+}
+
+/** Set number of links to i-node.
+ *
+ * @param inode I-node to set number of links to
+ * @param count Number of links to i-node
+ *
+ */
+void ext4_inode_set_links_count(ext4_inode_t *inode, uint16_t count)
+{
+	inode->links_count = host2uint16_t_le(count);
+}
+
+/** Get number of 512-bytes blocks used for i-node.
+ *
+ * @param sb    Superblock
+ * @param inode I-node
+ *
+ * @return Number of 512-bytes blocks
+ *
+ */
+uint64_t ext4_inode_get_blocks_count(ext4_superblock_t *sb, ext4_inode_t *inode)
+{
+	if (ext4_superblock_has_feature_read_only(sb,
+	    EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
+		/* 48-bit field */
+		uint64_t count = ((uint64_t)
+		    uint16_t_le2host(inode->osd2.linux2.blocks_high)) << 32 |
+		    uint32_t_le2host(inode->blocks_count_lo);
+		
+		if (ext4_inode_has_flag(inode, EXT4_INODE_FLAG_HUGE_FILE)) {
+			uint32_t block_size = ext4_superblock_get_block_size(sb);
+			uint32_t block_bits = ext4_inode_block_bits_count(block_size);
+			return count << (block_bits - 9);
+		} else
+			return count;
+	} else
+		return uint32_t_le2host(inode->blocks_count_lo);
+}
+
+/** Set number of 512-bytes blocks used for i-node.
+ *
+ * @param sb    Superblock
+ * @param inode I-node
+ * @param count Number of 512-bytes blocks
+ *
+ * @return Error code
+ *
+ */
+int ext4_inode_set_blocks_count(ext4_superblock_t *sb, ext4_inode_t *inode,
+    uint64_t count)
+{
+	/* 32-bit maximum */
+	uint64_t max = 0;
+	max = ~max >> 32;
+	
+	if (count <= max) {
+		inode->blocks_count_lo = host2uint32_t_le(count);
+		inode->osd2.linux2.blocks_high = 0;
+		ext4_inode_clear_flag(inode, EXT4_INODE_FLAG_HUGE_FILE);
+		
+		return EOK;
+	}
+	
+	/* Check if there can be used huge files (many blocks) */
+	if (!ext4_superblock_has_feature_read_only(sb,
+	    EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
+		return EINVAL;
+	
+	/* 48-bit maximum */
+	max = 0;
+	max = ~max >> 16;
+	
+	if (count <= max) {
+		inode->blocks_count_lo = host2uint32_t_le(count);
+		inode->osd2.linux2.blocks_high = host2uint16_t_le(count >> 32);
+		ext4_inode_clear_flag(inode, EXT4_INODE_FLAG_HUGE_FILE);
+	} else {
+		uint32_t block_size = ext4_superblock_get_block_size(sb);
+		uint32_t block_bits = ext4_inode_block_bits_count(block_size);
+		ext4_inode_set_flag(inode, EXT4_INODE_FLAG_HUGE_FILE);
+		count = count >> (block_bits - 9);
+		inode->blocks_count_lo = host2uint32_t_le(count);
+		inode->osd2.linux2.blocks_high = host2uint16_t_le(count >> 32);
+	}
+	
+	return EOK;
+}
+
+/** Get flags (features) of i-node.
+ *
+ * @param inode I-node to get flags from
+ *
+ * @return Flags (bitmap)
+ *
+ */
+uint32_t ext4_inode_get_flags(ext4_inode_t *inode)
+{
+	return uint32_t_le2host(inode->flags);
+}
+
+/** Set flags (features) of i-node.
+ *
+ * @param inode I-node to set flags to
+ * @param flags Flags to set to i-node
+ *
+ */
+void ext4_inode_set_flags(ext4_inode_t *inode, uint32_t flags)
+{
+	inode->flags = host2uint32_t_le(flags);
+}
+
+/** Get file generation (used by NFS).
+ *
+ * @param inode I-node
+ *
+ * @return File generation
+ *
+ */
+uint32_t ext4_inode_get_generation(ext4_inode_t *inode)
+{
+	return uint32_t_le2host(inode->generation);
+}
+
+/** Set file generation (used by NFS).
+ *
+ * @param inode      I-node
+ * @param generation File generation
+ *
+ */
+void ext4_inode_set_generation(ext4_inode_t *inode, uint32_t generation)
+{
+	inode->generation = host2uint32_t_le(generation);
+}
+
+/** Get address of block, where are extended attributes located.
+ *
+ * @param inode I-node
+ * @param sb    Superblock
+ *
+ * @return Block address
+ *
+ */
+uint64_t ext4_inode_get_file_acl(ext4_inode_t *inode, ext4_superblock_t *sb)
+{
+	if (ext4_superblock_get_creator_os(sb) == EXT4_SUPERBLOCK_OS_LINUX)
+		return ((uint32_t)
+		    uint16_t_le2host(inode->osd2.linux2.file_acl_high)) << 16 |
+		    (uint32_t_le2host(inode->file_acl_lo));
+	
+	return uint32_t_le2host(inode->file_acl_lo);
+}
+
+/** Set address of block, where are extended attributes located.
+ *
+ * @param inode    I-node
+ * @param sb       Superblock
+ * @param file_acl Block address
+ *
+ */
+void ext4_inode_set_file_acl(ext4_inode_t *inode, ext4_superblock_t *sb,
+    uint64_t file_acl)
+{
+	inode->file_acl_lo = host2uint32_t_le((file_acl << 32) >> 32);
+	
+	if (ext4_superblock_get_creator_os(sb) == EXT4_SUPERBLOCK_OS_LINUX)
+		inode->osd2.linux2.file_acl_high = host2uint16_t_le(file_acl >> 32);
+}
+
+/** Get block address of specified direct block.
+ *
+ * @param inode I-node to load block from
+ * @param idx   Index of logical block
+ *
+ * @return Physical block address
+ *
+ */
+uint32_t ext4_inode_get_direct_block(ext4_inode_t *inode, uint32_t idx)
+{
+	assert(idx < EXT4_INODE_DIRECT_BLOCK_COUNT);
+	
+	return uint32_t_le2host(inode->blocks[idx]);
+}
+
+/** Set block address of specified direct block.
+ *
+ * @param inode  I-node to set block address to
+ * @param idx    Index of logical block
+ * @param fblock Physical block address
+ *
+ */
+void ext4_inode_set_direct_block(ext4_inode_t *inode, uint32_t idx, uint32_t fblock)
+{
+	assert(idx < EXT4_INODE_DIRECT_BLOCK_COUNT);
+	
+	inode->blocks[idx] = host2uint32_t_le(fblock);
+}
+
+/** Get block address of specified indirect block.
+ *
+ * @param inode I-node to get block address from
+ * @param idx   Index of indirect block 
+ *
+ * @return Physical block address
+ *
+ */
+uint32_t ext4_inode_get_indirect_block(ext4_inode_t *inode, uint32_t idx)
+{
+	return uint32_t_le2host(inode->blocks[idx + EXT4_INODE_INDIRECT_BLOCK]);
+}
+
+/** Set block address of specified indirect block.
+ *
+ * @param inode  I-node to set block address to
+ * @param idx    Index of indirect block
+ * @param fblock Physical block address
+ *
+ */
+void ext4_inode_set_indirect_block(ext4_inode_t *inode, uint32_t idx,
+    uint32_t fblock)
+{
+	inode->blocks[idx + EXT4_INODE_INDIRECT_BLOCK] =
+	    host2uint32_t_le(fblock);
+}
+
+/** Check if i-node has specified type.
+ *
+ * @param sb    Superblock
+ * @param inode I-node to check type of
+ * @param type  Type to check
+ *
+ * @return Result of check operation
+ *
+ */
+bool ext4_inode_is_type(ext4_superblock_t *sb, ext4_inode_t *inode,
+    uint32_t type)
+{
+	uint32_t mode = ext4_inode_get_mode(sb, inode);
+	return (mode & EXT4_INODE_MODE_TYPE_MASK) == type;
+}
+
+/** Get extent header from the root of the extent tree.
+ *
+ * @param inode I-node to get extent header from
+ *
+ * @return Pointer to extent header of the root node
+ *
+ */
+ext4_extent_header_t * ext4_inode_get_extent_header(ext4_inode_t *inode)
+{
+	return (ext4_extent_header_t *) inode->blocks;
+}
+
+/** Check if i-node has specified flag.
+ *
+ * @param inode I-node to check flags of
+ * @param flag  Flag to check
+ *
+ * @return Result of check operation
+ *
+ */
+bool ext4_inode_has_flag(ext4_inode_t *inode, uint32_t flag)
+{
+	if (ext4_inode_get_flags(inode) & flag)
+		return true;
+	
+	return false;
+}
+
+/** Remove specified flag from i-node.
+ *
+ * @param inode      I-node to clear flag on
+ * @param clear_flag Flag to be cleared
+ *
+ */
+void ext4_inode_clear_flag(ext4_inode_t *inode, uint32_t clear_flag)
+{
+	uint32_t flags = ext4_inode_get_flags(inode);
+	flags = flags & (~clear_flag);
+	ext4_inode_set_flags(inode, flags);
+}
+
+/** Set specified flag to i-node.
+ *
+ * @param inode    I-node to set flag on
+ * @param set_flag Flag to be set
+ *
+ */
+void ext4_inode_set_flag(ext4_inode_t *inode, uint32_t set_flag)
+{
+	uint32_t flags = ext4_inode_get_flags(inode);
+	flags = flags | set_flag;
+	ext4_inode_set_flags(inode, flags);
+}
+
+/** Check if i-node can be truncated.
+ *
+ * @param sb    Superblock
+ * @param inode I-node to check
+ *
+ * @return Result of the check operation
+ *
+ */
+bool ext4_inode_can_truncate(ext4_superblock_t *sb, ext4_inode_t *inode)
+{
+	if ((ext4_inode_has_flag(inode, EXT4_INODE_FLAG_APPEND)) ||
+	    (ext4_inode_has_flag(inode, EXT4_INODE_FLAG_IMMUTABLE)))
+		return false;
+	
+	if ((ext4_inode_is_type(sb, inode, EXT4_INODE_MODE_FILE)) ||
+	    (ext4_inode_is_type(sb, inode, EXT4_INODE_MODE_DIRECTORY)))
+		return true;
+	
+	return false;
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_inode.h
===================================================================
--- uspace/lib/ext4/libext4_inode.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_inode.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_INODE_H_
+#define LIBEXT4_LIBEXT4_INODE_H_
+
+#include <libblock.h>
+#include <sys/types.h>
+#include "libext4_types.h"
+
+extern uint32_t ext4_inode_get_mode(ext4_superblock_t *, ext4_inode_t *);
+extern void ext4_inode_set_mode(ext4_superblock_t *, ext4_inode_t *, uint32_t);
+extern uint32_t ext4_inode_get_uid(ext4_inode_t *);
+extern void ext4_inode_set_uid(ext4_inode_t *, uint32_t);
+extern uint64_t ext4_inode_get_size(ext4_superblock_t *, ext4_inode_t *);
+extern void ext4_inode_set_size(ext4_inode_t *, uint64_t);
+extern uint32_t ext4_inode_get_access_time(ext4_inode_t *);
+extern void ext4_inode_set_access_time(ext4_inode_t *, uint32_t);
+extern uint32_t ext4_inode_get_change_inode_time(ext4_inode_t *);
+extern void ext4_inode_set_change_inode_time(ext4_inode_t *, uint32_t);
+extern uint32_t ext4_inode_get_modification_time(ext4_inode_t *);
+extern void ext4_inode_set_modification_time(ext4_inode_t *, uint32_t);
+extern uint32_t ext4_inode_get_deletion_time(ext4_inode_t *);
+extern void ext4_inode_set_deletion_time(ext4_inode_t *, uint32_t);
+extern uint32_t ext4_inode_get_gid(ext4_inode_t *);
+extern void ext4_inode_set_gid(ext4_inode_t *, uint32_t);
+extern uint16_t ext4_inode_get_links_count(ext4_inode_t *);
+extern void ext4_inode_set_links_count(ext4_inode_t *, uint16_t);
+extern uint64_t ext4_inode_get_blocks_count(ext4_superblock_t *,
+    ext4_inode_t *);
+extern int ext4_inode_set_blocks_count(ext4_superblock_t *, ext4_inode_t *,
+    uint64_t);
+extern uint32_t ext4_inode_get_flags(ext4_inode_t *);
+extern void ext4_inode_set_flags(ext4_inode_t *, uint32_t);
+extern uint32_t ext4_inode_get_generation(ext4_inode_t *);
+extern void ext4_inode_set_generation(ext4_inode_t *, uint32_t);
+extern uint64_t ext4_inode_get_file_acl(ext4_inode_t *, ext4_superblock_t *);
+extern void ext4_inode_set_file_acl(ext4_inode_t *, ext4_superblock_t *,
+    uint64_t);
+
+extern uint32_t ext4_inode_get_direct_block(ext4_inode_t *, uint32_t);
+extern void ext4_inode_set_direct_block(ext4_inode_t *, uint32_t, uint32_t);
+extern uint32_t ext4_inode_get_indirect_block(ext4_inode_t *, uint32_t);
+extern void ext4_inode_set_indirect_block(ext4_inode_t *, uint32_t, uint32_t);
+extern ext4_extent_header_t * ext4_inode_get_extent_header(ext4_inode_t *);
+extern bool ext4_inode_is_type(ext4_superblock_t *, ext4_inode_t *, uint32_t);
+extern bool ext4_inode_has_flag(ext4_inode_t *, uint32_t);
+extern void ext4_inode_clear_flag(ext4_inode_t *, uint32_t);
+extern void ext4_inode_set_flag(ext4_inode_t *, uint32_t);
+extern bool ext4_inode_can_truncate(ext4_superblock_t *, ext4_inode_t *);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_superblock.c
===================================================================
--- uspace/lib/ext4/libext4_superblock.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_superblock.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,1291 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+/**
+ * @file  libext4_superblock.c
+ * @brief Ext4 superblock operations.
+ */
+
+#include <byteorder.h>
+#include <errno.h>
+#include <libblock.h>
+#include <malloc.h>
+#include "libext4.h"
+
+/** Get number of i-nodes in the whole filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Number of i-nodes
+ *
+ */
+uint32_t ext4_superblock_get_inodes_count(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->inodes_count);
+}
+
+/** Set number of i-nodes in the whole filesystem.
+ *
+ * @param sb    Superblock
+ * @param count Number of i-nodes
+ *
+ */
+void ext4_superblock_set_inodes_count(ext4_superblock_t *sb, uint32_t count)
+{
+	sb->inodes_count = host2uint32_t_le(count);
+}
+
+/** Get number of data blocks in the whole filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Number of data blocks
+ *
+ */
+uint64_t ext4_superblock_get_blocks_count(ext4_superblock_t *sb)
+{
+	return ((uint64_t) uint32_t_le2host(sb->blocks_count_hi) << 32) |
+	    uint32_t_le2host(sb->blocks_count_lo);
+}
+
+/** Set number of data blocks in the whole filesystem.
+ *
+ * @param sb    Superblock
+ * @param count Number of data blocks
+ *
+ */
+void ext4_superblock_set_blocks_count(ext4_superblock_t *sb, uint64_t count)
+{
+	sb->blocks_count_lo = host2uint32_t_le((count << 32) >> 32);
+	sb->blocks_count_hi = host2uint32_t_le(count >> 32);
+}
+
+/** Get number of reserved data blocks in the whole filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Number of reserved data blocks
+ *
+ */
+uint64_t ext4_superblock_get_reserved_blocks_count(ext4_superblock_t *sb)
+{
+	return ((uint64_t)
+	    uint32_t_le2host(sb->reserved_blocks_count_hi) << 32) |
+	    uint32_t_le2host(sb->reserved_blocks_count_lo);
+}
+
+/** Set number of reserved data blocks in the whole filesystem.
+ *
+ * @param sb    Superblock
+ * @param count Number of reserved data blocks
+ *
+ */
+void ext4_superblock_set_reserved_blocks_count(ext4_superblock_t *sb,
+    uint64_t count)
+{
+	sb->reserved_blocks_count_lo = host2uint32_t_le((count << 32) >> 32);
+	sb->reserved_blocks_count_hi = host2uint32_t_le(count >> 32);
+}
+
+/** Get number of free data blocks in the whole filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Number of free data blocks
+ *
+ */
+uint64_t ext4_superblock_get_free_blocks_count(ext4_superblock_t *sb)
+{
+	return ((uint64_t)
+	    uint32_t_le2host(sb->free_blocks_count_hi) << 32) |
+	    uint32_t_le2host(sb->free_blocks_count_lo);
+}
+
+/** Set number of free data blocks in the whole filesystem.
+ *
+ * @param sb    Superblock
+ * @param count Number of free data blocks
+ *
+ */
+void ext4_superblock_set_free_blocks_count(ext4_superblock_t *sb,
+    uint64_t count)
+{
+	sb->free_blocks_count_lo = host2uint32_t_le((count << 32) >> 32);
+	sb->free_blocks_count_hi = host2uint32_t_le(count >> 32);
+}
+
+/** Get number of free i-nodes in the whole filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Number of free i-nodes
+ *
+ */
+uint32_t ext4_superblock_get_free_inodes_count(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->free_inodes_count);
+}
+
+/** Set number of free i-nodes in the whole filesystem.
+ *
+ * @param sb    Superblock
+ * @param count Number of free i-nodes
+ *
+ */
+void ext4_superblock_set_free_inodes_count(ext4_superblock_t *sb,
+    uint32_t count)
+{
+	sb->free_inodes_count = host2uint32_t_le(count);
+}
+
+/** Get index of first data block (block where the superblock is located)
+ *
+ * @param sb Superblock
+ *
+ * @return Index of the first data block
+ *
+ */
+uint32_t ext4_superblock_get_first_data_block(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->first_data_block);
+}
+
+/** Set index of first data block (block where the superblock is located)
+ *
+ * @param sb    Superblock
+ * @param first Index of the first data block
+ *
+ */
+void ext4_superblock_set_first_data_block(ext4_superblock_t *sb,
+    uint32_t first)
+{
+	sb->first_data_block = host2uint32_t_le(first);
+}
+
+/** Get logarithmic block size (1024 << size == block_size)
+ *
+ * @param sb Superblock
+ *
+ * @return Logarithmic block size
+ *
+ */
+uint32_t ext4_superblock_get_log_block_size(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->log_block_size);
+}
+
+/** Set logarithmic block size (1024 << size == block_size)
+ *
+ * @param sb Superblock
+ *
+ * @return Logarithmic block size
+ *
+ */
+void ext4_superblock_set_log_block_size(ext4_superblock_t *sb,
+    uint32_t log_size)
+{
+	sb->log_block_size = host2uint32_t_le(log_size);
+}
+
+/** Get size of data block (in bytes).
+ *
+ * @param sb Superblock
+ *
+ * @return Size of data block
+ *
+ */
+uint32_t ext4_superblock_get_block_size(ext4_superblock_t *sb)
+{
+	return 1024 << ext4_superblock_get_log_block_size(sb);
+}
+
+/** Set size of data block (in bytes).
+ *
+ * @param sb   Superblock
+ * @param size Size of data block (must be power of 2, at least 1024)
+ *
+ */
+void ext4_superblock_set_block_size(ext4_superblock_t *sb, uint32_t size)
+{
+	uint32_t log = 0;
+	uint32_t tmp = size / EXT4_MIN_BLOCK_SIZE;
+	
+	tmp >>= 1;
+	while (tmp) {
+		log++;
+		tmp >>= 1;
+	}
+	
+	ext4_superblock_set_log_block_size(sb, log);
+}
+
+/** Get logarithmic fragment size (1024 << size)
+ *
+ * @param sb Superblock
+ *
+ * @return Logarithmic fragment size
+ *
+ */
+uint32_t ext4_superblock_get_log_frag_size(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->log_frag_size);
+}
+
+/** Set logarithmic fragment size (1024 << size)
+ *
+ * @param sb        Superblock
+ * @param frag_size Logarithmic fragment size
+ *
+ */
+void ext4_superblock_set_log_frag_size(ext4_superblock_t *sb,
+    uint32_t frag_size)
+{
+	sb->log_frag_size = host2uint32_t_le(frag_size);
+}
+
+/** Get size of fragment (in bytes).
+ *
+ * @param sb Superblock
+ *
+ * @return Size of fragment
+ *
+ */
+uint32_t ext4_superblock_get_frag_size(ext4_superblock_t *sb)
+{
+	return 1024 << ext4_superblock_get_log_frag_size(sb);
+}
+
+/** Set size of fragment (in bytes).
+ *
+ * @param sb   Superblock
+ * @param size Size of fragment (must be power of 2, at least 1024)
+ *
+ */
+void ext4_superblock_set_frag_size(ext4_superblock_t *sb, uint32_t size)
+{
+	uint32_t log = 0;
+	uint32_t tmp = size / EXT4_MIN_BLOCK_SIZE;
+	
+	tmp >>= 1;
+	while (tmp) {
+		log++;
+		tmp >>= 1;
+	}
+	
+	ext4_superblock_set_log_frag_size(sb, log);
+}
+
+/** Get number of data blocks per block group (except last BG)
+ *
+ * @param sb Superblock
+ *
+ * @return Data blocks per block group
+ *
+ */
+uint32_t ext4_superblock_get_blocks_per_group(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->blocks_per_group);
+}
+
+/** Set number of data blocks per block group (except last BG)
+ *
+ * @param sb     Superblock
+ * @param blocks Data blocks per block group
+ *
+ */
+void ext4_superblock_set_blocks_per_group(ext4_superblock_t *sb,
+    uint32_t blocks)
+{
+	sb->blocks_per_group = host2uint32_t_le(blocks);
+}
+
+/** Get number of fragments per block group (except last BG)
+ *
+ * @param sb Superblock
+ *
+ * @return Fragments per block group
+ *
+ */
+uint32_t ext4_superblock_get_frags_per_group(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->frags_per_group);
+}
+
+/** Set number of fragment per block group (except last BG)
+ *
+ * @param sb    Superblock
+ * @param frags Fragments per block group
+ */
+void ext4_superblock_set_frags_per_group(ext4_superblock_t *sb, uint32_t frags)
+{
+	sb->frags_per_group = host2uint32_t_le(frags);
+}
+
+/** Get number of i-nodes per block group (except last BG)
+ *
+ * @param sb Superblock
+ *
+ * @return I-nodes per block group
+ *
+ */
+uint32_t ext4_superblock_get_inodes_per_group(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->inodes_per_group);
+}
+
+/** Set number of i-nodes per block group (except last BG)
+ *
+ * @param sb     Superblock
+ * @param inodes I-nodes per block group
+ *
+ */
+void ext4_superblock_set_inodes_per_group(ext4_superblock_t *sb,
+    uint32_t inodes)
+{
+	sb->inodes_per_group = host2uint32_t_le(inodes);
+}
+
+/** Get time when filesystem was mounted (POSIX time).
+ *
+ * @param sb Superblock
+ *
+ * @return Mount time
+ *
+ */
+uint32_t ext4_superblock_get_mount_time(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->mount_time);
+}
+
+/** Set time when filesystem was mounted (POSIX time).
+ *
+ * @param sb   Superblock
+ * @param time Mount time
+ *
+ */
+void ext4_superblock_set_mount_time(ext4_superblock_t *sb, uint32_t time)
+{
+	sb->mount_time = host2uint32_t_le(time);
+}
+
+/** Get time when filesystem was last accesed by write operation (POSIX time).
+ *
+ * @param sb Superblock
+ *
+ * @return Write time
+ *
+ */
+uint32_t ext4_superblock_get_write_time(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->write_time);
+}
+
+/** Set time when filesystem was last accesed by write operation (POSIX time).
+ *
+ * @param sb   Superblock
+ * @param time Write time
+ *
+ */
+void ext4_superblock_set_write_time(ext4_superblock_t *sb, uint32_t time)
+{
+	sb->write_time = host2uint32_t_le(time);
+}
+
+/** Get number of mount from last filesystem check.
+ *
+ * @param sb Superblock
+ *
+ * @return Number of mounts
+ *
+ */
+uint16_t ext4_superblock_get_mount_count(ext4_superblock_t *sb)
+{
+	return uint16_t_le2host(sb->mount_count);
+}
+
+/** Set number of mount from last filesystem check.
+ *
+ * @param sb    Superblock
+ * @param count Number of mounts
+ *
+ */
+void ext4_superblock_set_mount_count(ext4_superblock_t *sb, uint16_t count)
+{
+	sb->mount_count = host2uint16_t_le(count);
+}
+
+/** Get maximum number of mount from last filesystem check.
+ *
+ * @param sb Superblock
+ *
+ * @return Maximum number of mounts
+ *
+ */
+uint16_t ext4_superblock_get_max_mount_count(ext4_superblock_t *sb)
+{
+	return uint16_t_le2host(sb->max_mount_count);
+}
+
+/** Set maximum number of mount from last filesystem check.
+ *
+ * @param sb    Superblock
+ * @param count Maximum number of mounts
+ *
+ */
+void ext4_superblock_set_max_mount_count(ext4_superblock_t *sb, uint16_t count)
+{
+	sb->max_mount_count = host2uint16_t_le(count);
+}
+
+/** Get superblock magic value.
+ *
+ * @param sb Superblock
+ *
+ * @return Magic value
+ *
+ */
+uint16_t ext4_superblock_get_magic(ext4_superblock_t *sb)
+{
+	return uint16_t_le2host(sb->magic);
+}
+
+/** Set superblock magic value.
+ *
+ * @param sb    Superblock
+ * @param magic Magic value
+ *
+ */
+void ext4_superblock_set_magic(ext4_superblock_t *sb, uint16_t magic)
+{
+	sb->magic = host2uint16_t_le(magic);
+}
+
+/** Get filesystem state.
+ *
+ * @param sb Superblock
+ *
+ * @return Filesystem state
+ *
+ */
+uint16_t ext4_superblock_get_state(ext4_superblock_t *sb)
+{
+	return uint16_t_le2host(sb->state);
+}
+
+/** Set filesystem state.
+ *
+ * @param sb    Superblock
+ * @param state Filesystem state
+ *
+ */
+void ext4_superblock_set_state(ext4_superblock_t *sb, uint16_t state)
+{
+	sb->state = host2uint16_t_le(state);
+}
+
+/** Get behavior code when errors detected.
+ *
+ * @param sb Superblock
+ *
+ * @return Behavior code
+ *
+ */
+uint16_t ext4_superblock_get_errors(ext4_superblock_t *sb)
+{
+	return uint16_t_le2host(sb->errors);
+}
+
+/** Set behavior code when errors detected.
+ *
+ * @param sb     Superblock
+ * @param errors Behavior code
+ *
+ */
+void ext4_superblock_set_errors(ext4_superblock_t *sb, uint16_t errors)
+{
+	sb->errors = host2uint16_t_le(errors);
+}
+
+/** Get minor revision level of the filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Minor revision level
+ *
+ */
+uint16_t ext4_superblock_get_minor_rev_level(ext4_superblock_t *sb)
+{
+	return uint16_t_le2host(sb->minor_rev_level);
+}
+
+/** Set minor revision level of the filesystem.
+ *
+ * @param sb    Superblock
+ * @param level Minor revision level
+ *
+ */
+void ext4_superblock_set_minor_rev_level(ext4_superblock_t *sb, uint16_t level)
+{
+	sb->minor_rev_level = host2uint16_t_le(level);
+}
+
+/** Get time of the last filesystem check.
+ *
+ * @param sb Superblock
+ *
+ * @return Time of the last check (POSIX)
+ *
+ */
+uint32_t ext4_superblock_get_last_check_time(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->last_check_time);
+}
+
+/** Set time of the last filesystem check.
+ *
+ * @param sb   Superblock
+ * @param time Time of the last check (POSIX)
+ *
+ */
+void ext4_superblock_set_last_check_time(ext4_superblock_t *sb, uint32_t time)
+{
+	sb->state = host2uint32_t_le(time);
+}
+
+/** Get maximum time interval between two filesystem checks.
+ *
+ * @param sb Superblock
+ *
+ * @return Time interval between two check (POSIX)
+ *
+ */
+uint32_t ext4_superblock_get_check_interval(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->check_interval);
+}
+
+/** Set maximum time interval between two filesystem checks.
+ *
+ * @param sb       Superblock
+ * @param interval Time interval between two check (POSIX)
+ *
+ */
+void ext4_superblock_set_check_interval(ext4_superblock_t *sb, uint32_t interval)
+{
+	sb->check_interval = host2uint32_t_le(interval);
+}
+
+/** Get operation system identifier, on which the filesystem was created.
+ *
+ * @param sb Superblock
+ *
+ * @return Operation system identifier
+ *
+ */
+uint32_t ext4_superblock_get_creator_os(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->creator_os);
+}
+
+/** Set operation system identifier, on which the filesystem was created.
+ *
+ * @param sb Superblock
+ * @param os Operation system identifier
+ *
+ */
+void ext4_superblock_set_creator_os(ext4_superblock_t *sb, uint32_t os)
+{
+	sb->creator_os = host2uint32_t_le(os);
+}
+
+/** Get revision level of the filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Revision level
+ *
+ */
+uint32_t ext4_superblock_get_rev_level(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->rev_level);
+}
+
+/** Set revision level of the filesystem.
+ *
+ * @param sb    Superblock
+ * @param level Revision level
+ *
+ */
+void ext4_superblock_set_rev_level(ext4_superblock_t *sb, uint32_t level)
+{
+	sb->rev_level = host2uint32_t_le(level);
+}
+
+/** Get default user id for reserved blocks.
+ *
+ * @param sb Superblock
+ *
+ * @return Default user id for reserved blocks.
+ *
+ */
+uint16_t ext4_superblock_get_def_resuid(ext4_superblock_t *sb)
+{
+	return uint16_t_le2host(sb->def_resuid);
+}
+
+/** Set default user id for reserved blocks.
+ *
+ * @param sb  Superblock
+ * @param uid Default user id for reserved blocks.
+ *
+ */
+void ext4_superblock_set_def_resuid(ext4_superblock_t *sb, uint16_t uid)
+{
+	sb->def_resuid = host2uint16_t_le(uid);
+}
+
+/** Get default group id for reserved blocks.
+ *
+ * @param sb Superblock
+ *
+ * @return Default group id for reserved blocks.
+ *
+ */
+uint16_t ext4_superblock_get_def_resgid(ext4_superblock_t *sb)
+{
+	return uint16_t_le2host(sb->def_resgid);
+}
+
+/** Set default group id for reserved blocks.
+ *
+ * @param sb  Superblock
+ * @param gid Default group id for reserved blocks.
+ *
+ */
+void ext4_superblock_set_def_resgid(ext4_superblock_t *sb, uint16_t gid)
+{
+	sb->def_resgid = host2uint16_t_le(gid);
+}
+
+/** Get index of the first i-node, which can be used for allocation.
+ *
+ * @param sb Superblock
+ *
+ * @return I-node index
+ *
+ */
+uint32_t ext4_superblock_get_first_inode(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->first_inode);
+}
+
+/** Set index of the first i-node, which can be used for allocation.
+ *
+ * @param sb          Superblock
+ * @param first_inode I-node index
+ *
+ */
+void ext4_superblock_set_first_inode(ext4_superblock_t *sb,
+    uint32_t first_inode)
+{
+	sb->first_inode = host2uint32_t_le(first_inode);
+}
+
+/** Get size of i-node structure.
+ *
+ * For the oldest revision return constant number.
+ *
+ * @param sb Superblock
+ *
+ * @return Size of i-node structure
+ *
+ */
+uint16_t ext4_superblock_get_inode_size(ext4_superblock_t *sb)
+{
+	if (ext4_superblock_get_rev_level(sb) == 0)
+		return EXT4_REV0_INODE_SIZE;
+	
+	return uint16_t_le2host(sb->inode_size);
+}
+
+/** Set size of i-node structure.
+ *
+ * @param sb   Superblock
+ * @param size Size of i-node structure
+ *
+ */
+void ext4_superblock_set_inode_size(ext4_superblock_t *sb, uint16_t size)
+{
+	sb->inode_size = host2uint16_t_le(size);
+}
+
+/** Get index of block group, where superblock copy is located.
+ *
+ * @param sb Superblock
+ *
+ * @return Block group index
+ *
+ */
+uint16_t ext4_superblock_get_block_group_index(ext4_superblock_t *sb)
+{
+	return uint16_t_le2host(sb->block_group_index);
+}
+
+/** Set index of block group, where superblock copy is located.
+ *
+ * @param sb   Superblock
+ * @param bgid Block group index
+ *
+ */
+void ext4_superblock_set_block_group_index(ext4_superblock_t *sb, uint16_t bgid)
+{
+	sb->block_group_index = host2uint16_t_le(bgid);
+}
+
+/** Get compatible features supported by the filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Compatible features bitmap
+ *
+ */
+uint32_t ext4_superblock_get_features_compatible(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->features_compatible);
+}
+
+/** Set compatible features supported by the filesystem.
+ *
+ * @param sb       Superblock
+ * @param features Compatible features bitmap
+ *
+ */
+void ext4_superblock_set_features_compatible(ext4_superblock_t *sb,
+    uint32_t features)
+{
+	sb->features_compatible = host2uint32_t_le(features);
+}
+
+/** Get incompatible features supported by the filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Incompatible features bitmap
+ *
+ */
+uint32_t ext4_superblock_get_features_incompatible(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->features_incompatible);
+}
+
+/** Set incompatible features supported by the filesystem.
+ *
+ * @param sb       Superblock
+ * @param features Incompatible features bitmap
+ *
+ */
+void ext4_superblock_set_features_incompatible(ext4_superblock_t *sb,
+    uint32_t features)
+{
+	sb->features_incompatible = host2uint32_t_le(features);
+}
+
+/** Get compatible features supported by the filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Read-only compatible features bitmap
+ *
+ */
+uint32_t ext4_superblock_get_features_read_only(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->features_read_only);
+}
+
+/** Set compatible features supported by the filesystem.
+ *
+ * @param sb      Superblock
+ * @param feature Read-only compatible features bitmap
+ *
+ */
+void ext4_superblock_set_features_read_only(ext4_superblock_t *sb,
+    uint32_t features)
+{
+	sb->features_read_only = host2uint32_t_le(features);
+}
+
+/** Get UUID of the filesystem.
+ *
+ * @param sb superblock
+ *
+ * @return Pointer to UUID array
+ *
+ */
+const uint8_t *ext4_superblock_get_uuid(ext4_superblock_t *sb)
+{
+	return sb->uuid;
+}
+
+/** Set UUID of the filesystem.
+ *
+ * @param sb   Superblock
+ * @param uuid Pointer to UUID array
+ *
+ */
+void ext4_superblock_set_uuid(ext4_superblock_t *sb, const uint8_t *uuid)
+{
+	memcpy(sb->uuid, uuid, sizeof(sb->uuid));
+}
+
+/** Get name of the filesystem volume.
+ *
+ * @param sb Superblock
+ *
+ * @return Name of the volume
+ *
+ */
+const char *ext4_superblock_get_volume_name(ext4_superblock_t *sb)
+{
+	return sb->volume_name;
+}
+
+/** Set name of the filesystem volume.
+ *
+ * @param sb   Superblock
+ * @param name New name of the volume
+ */
+void ext4_superblock_set_volume_name(ext4_superblock_t *sb, const char *name)
+{
+	memcpy(sb->volume_name, name, sizeof(sb->volume_name));
+}
+
+/** Get name of the directory, where this filesystem was mounted at last.
+ *
+ * @param sb Superblock
+ *
+ * @return Directory name
+ *
+ */
+const char *ext4_superblock_get_last_mounted(ext4_superblock_t *sb)
+{
+	return sb->last_mounted;
+}
+
+/** Set name of the directory, where this filesystem was mounted at last.
+ *
+ * @param sb   Superblock
+ * @param last Directory name
+ *
+ */
+void ext4_superblock_set_last_mounted(ext4_superblock_t *sb, const char *last)
+{
+	memcpy(sb->last_mounted, last, sizeof(sb->last_mounted));
+}
+
+/** Get last orphaned i-node index.
+ *
+ * Orphans are stored in linked list.
+ *
+ * @param sb Superblock
+ *
+ * @return Last orphaned i-node index
+ *
+ */
+uint32_t ext4_superblock_get_last_orphan(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->last_orphan);
+}
+
+/** Set last orphaned i-node index.
+ *
+ * Orphans are stored in linked list.
+ *
+ * @param sb          Superblock
+ * @param last_orphan Last orphaned i-node index
+ *
+ */
+void ext4_superblock_set_last_orphan(ext4_superblock_t *sb,
+    uint32_t last_orphan)
+{
+	sb->last_orphan = host2uint32_t_le(last_orphan);
+}
+
+/** Get hash seed for directory index hash function.
+ *
+ * @param sb Superblock
+ *
+ * @return Hash seed pointer
+ *
+ */
+const uint32_t *ext4_superblock_get_hash_seed(ext4_superblock_t *sb)
+{
+	return sb->hash_seed;
+}
+
+/** Set hash seed for directory index hash function.
+ *
+ * @param sb   Superblock
+ * @param seed Hash seed pointer
+ *
+ */
+void ext4_superblock_set_hash_seed(ext4_superblock_t *sb, const uint32_t *seed)
+{
+	memcpy(sb->hash_seed, seed, sizeof(sb->hash_seed));
+}
+
+/** Get default version of the hash algorithm version for directory index.
+ *
+ * @param sb Superblock
+ *
+ * @return Default hash version
+ *
+ */
+uint8_t ext4_superblock_get_default_hash_version(ext4_superblock_t *sb)
+{
+	return sb->default_hash_version;
+}
+
+/** Set default version of the hash algorithm version for directory index.
+ *
+ * @param sb      Superblock
+ * @param version Default hash version
+ *
+ */
+void ext4_superblock_set_default_hash_version(ext4_superblock_t *sb,
+    uint8_t version)
+{
+	sb->default_hash_version = version;
+}
+
+/** Get size of block group descriptor structure.
+ *
+ * Output value is checked for minimal size.
+ *
+ * @param sb Superblock
+ *
+ * @return Size of block group descriptor
+ *
+ */
+uint16_t ext4_superblock_get_desc_size(ext4_superblock_t *sb)
+{
+	uint16_t size = uint16_t_le2host(sb->desc_size);
+	
+	if (size < EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		size = EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE;
+	
+	return size;
+}
+
+/** Set size of block group descriptor structure.
+ *
+ * Input value is checked for minimal size.
+ *
+ * @param sb   Superblock
+ * @param size Size of block group descriptor
+ *
+ */
+void ext4_superblock_set_desc_size(ext4_superblock_t *sb, uint16_t size)
+{
+	if (size < EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		sb->desc_size =
+		    host2uint16_t_le(EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE);
+	
+	sb->desc_size = host2uint16_t_le(size);
+}
+
+/** Get superblock flags.
+ *
+ * @param sb Superblock
+ *
+ * @return Flags from the superblock
+ *
+ */
+uint32_t ext4_superblock_get_flags(ext4_superblock_t *sb)
+{
+	return uint32_t_le2host(sb->flags);
+}
+
+/** Set superblock flags.
+ *
+ * @param sb    Superblock
+ * @param flags Flags for the superblock
+ *
+ */
+void ext4_superblock_set_flags(ext4_superblock_t *sb, uint32_t flags)
+{
+	sb->flags = host2uint32_t_le(flags);
+}
+
+/*
+ * More complex superblock operations
+ */
+
+/** Check if superblock has specified flag.
+ *
+ * @param sb   Superblock
+ * @param flag Flag to be checked
+ *
+ * @return True, if superblock has the flag
+ *
+ */
+bool ext4_superblock_has_flag(ext4_superblock_t *sb, uint32_t flag)
+{
+	if (ext4_superblock_get_flags(sb) & flag)
+		return true;
+	
+	return false;
+}
+
+/** Check if filesystem supports compatible feature.
+ *
+ * @param sb      Superblock
+ * @param feature Feature to be checked
+ *
+ * @return True, if filesystem supports the feature
+ *
+ */
+bool ext4_superblock_has_feature_compatible(ext4_superblock_t *sb,
+    uint32_t feature)
+{
+	if (ext4_superblock_get_features_compatible(sb) & feature)
+		return true;
+	
+	return false;
+}
+
+/** Check if filesystem supports incompatible feature.
+ *
+ * @param sb      Superblock
+ * @param feature Feature to be checked
+ *
+ * @return True, if filesystem supports the feature
+ *
+ */
+bool ext4_superblock_has_feature_incompatible(ext4_superblock_t *sb,
+    uint32_t feature)
+{
+	if (ext4_superblock_get_features_incompatible(sb) & feature)
+		return true;
+	
+	return false;
+}
+
+/** Check if filesystem supports read-only compatible feature.
+ *
+ * @param sb      Superblock
+ * @param feature Feature to be checked
+ *
+ * @return True, if filesystem supports the feature
+ *
+ */
+bool ext4_superblock_has_feature_read_only(ext4_superblock_t *sb,
+    uint32_t feature)
+{
+	if (ext4_superblock_get_features_read_only(sb) & feature)
+		return true;
+	
+	return false;
+}
+
+/** Read superblock directly from block device.
+ *
+ * @param service_id Block device identifier
+ * @param sb         Output pointer to memory structure
+ *
+ * @return Eerror code.
+ *
+ */
+int ext4_superblock_read_direct(service_id_t service_id, ext4_superblock_t **sb)
+{
+	/* Allocated memory for superblock structure */
+	void *data = malloc(EXT4_SUPERBLOCK_SIZE);
+	if (data == NULL)
+		return ENOMEM;
+	
+	/* Read data from block device */
+	int rc = block_read_bytes_direct(service_id, EXT4_SUPERBLOCK_OFFSET,
+	    EXT4_SUPERBLOCK_SIZE, data);
+	
+	if (rc != EOK) {
+		free(data);
+		return rc;
+	}
+	
+	/* Set output value */
+	(*sb) = data;
+	
+	return EOK;
+}
+
+/** Write superblock structure directly to block device.
+ *
+ * @param service_id Block device identifier
+ * @param sb         Superblock to be written
+ *
+ * @return Error code
+ *
+ */
+int ext4_superblock_write_direct(service_id_t service_id, ext4_superblock_t *sb)
+{
+	/* Load physical block size from block device */
+	size_t phys_block_size;
+	int rc = block_get_bsize(service_id, &phys_block_size);
+	if (rc != EOK)
+		return rc;
+	
+	/* Compute address of the first block */
+	uint64_t first_block = EXT4_SUPERBLOCK_OFFSET / phys_block_size;
+	
+	/* Compute number of block to write */
+	size_t block_count = EXT4_SUPERBLOCK_SIZE / phys_block_size;
+	
+	/* Check alignment */
+	if (EXT4_SUPERBLOCK_SIZE % phys_block_size)
+		block_count++;
+	
+	/* Write data */
+	return block_write_direct(service_id, first_block, block_count, sb);
+}
+
+/** Check sanity of the superblock.
+ *
+ * This check is performed at mount time.
+ * Checks are described by one-line comments in the code.
+ *
+ * @param sb Superblock to check
+ *
+ * @return Error code
+ *
+ */
+int ext4_superblock_check_sanity(ext4_superblock_t *sb)
+{
+	if (ext4_superblock_get_magic(sb) != EXT4_SUPERBLOCK_MAGIC)
+		return ENOTSUP;
+	
+	if (ext4_superblock_get_inodes_count(sb) == 0)
+		return ENOTSUP;
+	
+	if (ext4_superblock_get_blocks_count(sb) == 0)
+		return ENOTSUP;
+	
+	if (ext4_superblock_get_blocks_per_group(sb) == 0)
+		return ENOTSUP;
+	
+	if (ext4_superblock_get_inodes_per_group(sb) == 0)
+		return ENOTSUP;
+	
+	if (ext4_superblock_get_inode_size(sb) < 128)
+		return ENOTSUP;
+	
+	if (ext4_superblock_get_first_inode(sb) < 11)
+		return ENOTSUP;
+	
+	if (ext4_superblock_get_desc_size(sb) <
+	    EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		return ENOTSUP;
+	
+	if (ext4_superblock_get_desc_size(sb) >
+	    EXT4_MAX_BLOCK_GROUP_DESCRIPTOR_SIZE)
+		return ENOTSUP;
+	
+	return EOK;
+}
+
+/** Compute number of block groups in the filesystem.
+ *
+ * @param sb Superblock
+ *
+ * @return Number of block groups
+ *
+ */
+uint32_t ext4_superblock_get_block_group_count(ext4_superblock_t *sb)
+{
+	uint64_t blocks_count = ext4_superblock_get_blocks_count(sb);
+	uint32_t blocks_per_group = ext4_superblock_get_blocks_per_group(sb);
+	
+	uint32_t block_groups_count = blocks_count / blocks_per_group;
+	
+	if (blocks_count % blocks_per_group)
+		block_groups_count++;
+	
+	return block_groups_count;
+}
+
+/** Compute number of blocks in specified block group.
+ *
+ * @param sb   Superblock
+ * @param bgid Block group index
+ *
+ * @return Number of blocks
+ *
+ */
+uint32_t ext4_superblock_get_blocks_in_group(ext4_superblock_t *sb, uint32_t bgid)
+{
+	uint32_t block_group_count =
+	    ext4_superblock_get_block_group_count(sb);
+	uint32_t blocks_per_group =
+	    ext4_superblock_get_blocks_per_group(sb);
+	uint64_t total_blocks =
+	    ext4_superblock_get_blocks_count(sb);
+	
+	if (bgid < block_group_count - 1)
+		return blocks_per_group;
+	else
+		return (total_blocks - ((block_group_count - 1) * blocks_per_group));
+}
+
+/** Compute number of i-nodes in specified block group.
+ *
+ * @param sb   Superblock
+ * @param bgid Block group index
+ *
+ * @return Number of i-nodes
+ *
+ */
+uint32_t ext4_superblock_get_inodes_in_group(ext4_superblock_t *sb, uint32_t bgid)
+{
+	uint32_t block_group_count =
+	    ext4_superblock_get_block_group_count(sb);
+	uint32_t inodes_per_group =
+	    ext4_superblock_get_inodes_per_group(sb);
+	uint32_t total_inodes =
+	    ext4_superblock_get_inodes_count(sb);
+	
+	if (bgid < block_group_count - 1)
+		return inodes_per_group;
+	else
+		return (total_inodes - ((block_group_count - 1) * inodes_per_group));
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_superblock.h
===================================================================
--- uspace/lib/ext4/libext4_superblock.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_superblock.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_SUPERBLOCK_H_
+#define LIBEXT4_LIBEXT4_SUPERBLOCK_H_
+
+#include <libblock.h>
+#include <sys/types.h>
+#include "libext4_types.h"
+
+extern uint32_t ext4_superblock_get_inodes_count(ext4_superblock_t *);
+extern void ext4_superblock_set_inodes_count(ext4_superblock_t *, uint32_t);
+extern uint64_t ext4_superblock_get_blocks_count(ext4_superblock_t *);
+extern void ext4_superblock_set_blocks_count(ext4_superblock_t *, uint64_t);
+extern uint64_t ext4_superblock_get_reserved_blocks_count(ext4_superblock_t *);
+extern void ext4_superblock_set_reserved_blocks_count(ext4_superblock_t *,
+    uint64_t);
+extern uint64_t ext4_superblock_get_free_blocks_count(ext4_superblock_t *);
+extern void ext4_superblock_set_free_blocks_count(ext4_superblock_t *,
+    uint64_t);
+extern uint32_t ext4_superblock_get_free_inodes_count(ext4_superblock_t *);
+extern void ext4_superblock_set_free_inodes_count(ext4_superblock_t *,
+    uint32_t);
+extern uint32_t ext4_superblock_get_first_data_block(ext4_superblock_t *);
+extern void ext4_superblock_set_first_data_block(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_log_block_size(ext4_superblock_t *);
+extern void ext4_superblock_set_log_block_size(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_block_size(ext4_superblock_t *);
+extern void ext4_superblock_set_block_size(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_log_frag_size(ext4_superblock_t *);
+extern void ext4_superblock_set_log_frag_size(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_frag_size(ext4_superblock_t *);
+extern void ext4_superblock_set_frag_size(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_blocks_per_group(ext4_superblock_t *);
+extern void ext4_superblock_set_blocks_per_group(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_frags_per_group(ext4_superblock_t *);
+extern void ext4_superblock_set_frags_per_group(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_inodes_per_group(ext4_superblock_t *);
+extern void ext4_superblock_set_inodes_per_group(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_mount_time(ext4_superblock_t *);
+extern void ext4_superblock_set_mount_time(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_write_time(ext4_superblock_t *);
+extern void ext4_superblock_set_write_time(ext4_superblock_t *, uint32_t);
+extern uint16_t ext4_superblock_get_mount_count(ext4_superblock_t *);
+extern void ext4_superblock_set_mount_count(ext4_superblock_t *, uint16_t);
+extern uint16_t ext4_superblock_get_max_mount_count(ext4_superblock_t *);
+extern void ext4_superblock_set_max_mount_count(ext4_superblock_t *, uint16_t);
+extern uint16_t ext4_superblock_get_magic(ext4_superblock_t *);
+extern void ext4_superblock_set_magic(ext4_superblock_t *sb, uint16_t magic);
+extern uint16_t ext4_superblock_get_state(ext4_superblock_t *);
+extern void ext4_superblock_set_state(ext4_superblock_t *, uint16_t);
+extern uint16_t ext4_superblock_get_errors(ext4_superblock_t *);
+extern void ext4_superblock_set_errors(ext4_superblock_t *, uint16_t);
+extern uint16_t ext4_superblock_get_minor_rev_level(ext4_superblock_t *);
+extern void ext4_superblock_set_minor_rev_level(ext4_superblock_t *, uint16_t);
+extern uint32_t ext4_superblock_get_last_check_time(ext4_superblock_t *);
+extern void ext4_superblock_set_last_check_time(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_check_interval(ext4_superblock_t *);
+extern void ext4_superblock_set_check_interval(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_creator_os(ext4_superblock_t *);
+extern void ext4_superblock_set_creator_os(ext4_superblock_t *, uint32_t);
+extern uint32_t ext4_superblock_get_rev_level(ext4_superblock_t *);
+extern void ext4_superblock_set_rev_level(ext4_superblock_t *, uint32_t);
+extern uint16_t ext4_superblock_get_def_resuid(ext4_superblock_t *);
+extern void ext4_superblock_set_def_resuid(ext4_superblock_t *, uint16_t);
+extern uint16_t ext4_superblock_get_def_resgid(ext4_superblock_t *);
+extern void ext4_superblock_set_def_resgid(ext4_superblock_t *, uint16_t);
+extern uint32_t ext4_superblock_get_first_inode(ext4_superblock_t *);
+extern void ext4_superblock_set_first_inode(ext4_superblock_t *, uint32_t);
+extern uint16_t ext4_superblock_get_inode_size(ext4_superblock_t *);
+extern void ext4_superblock_set_inode_size(ext4_superblock_t *, uint16_t);
+extern uint16_t ext4_superblock_get_block_group_index(ext4_superblock_t *);
+extern void ext4_superblock_set_block_group_index(ext4_superblock_t *,
+    uint16_t);
+extern uint32_t ext4_superblock_get_features_compatible(ext4_superblock_t *);
+extern void ext4_superblock_set_features_compatible(ext4_superblock_t *,
+    uint32_t);
+extern uint32_t ext4_superblock_get_features_incompatible(ext4_superblock_t *);
+extern void ext4_superblock_set_features_incompatible(ext4_superblock_t *,
+    uint32_t);
+extern uint32_t ext4_superblock_get_features_read_only(ext4_superblock_t *);
+extern void ext4_superblock_set_features_read_only(ext4_superblock_t *,
+    uint32_t);
+
+extern const uint8_t * ext4_superblock_get_uuid(ext4_superblock_t *);
+extern void ext4_superblock_set_uuid(ext4_superblock_t *, const uint8_t *);
+extern const char * ext4_superblock_get_volume_name(ext4_superblock_t *);
+extern void ext4_superblock_set_volume_name(ext4_superblock_t *, const char *);
+extern const char * ext4_superblock_get_last_mounted(ext4_superblock_t *);
+extern void ext4_superblock_set_last_mounted(ext4_superblock_t *, const char *);
+
+extern uint32_t ext4_superblock_get_last_orphan(ext4_superblock_t *);
+extern void ext4_superblock_set_last_orphan(ext4_superblock_t *, uint32_t);
+extern const uint32_t * ext4_superblock_get_hash_seed(ext4_superblock_t *);
+extern void ext4_superblock_set_hash_seed(ext4_superblock_t *,
+    const uint32_t *);
+extern uint8_t ext4_superblock_get_default_hash_version(ext4_superblock_t *);
+extern void ext4_superblock_set_default_hash_version(ext4_superblock_t *,
+    uint8_t);
+
+extern uint16_t ext4_superblock_get_desc_size(ext4_superblock_t *);
+extern void ext4_superblock_set_desc_size(ext4_superblock_t *, uint16_t);
+
+extern uint32_t ext4_superblock_get_flags(ext4_superblock_t *);
+extern void ext4_superblock_set_flags(ext4_superblock_t *, uint32_t);
+
+/* More complex superblock functions */
+extern bool ext4_superblock_has_flag(ext4_superblock_t *, uint32_t);
+extern bool ext4_superblock_has_feature_compatible(ext4_superblock_t *,
+    uint32_t);
+extern bool ext4_superblock_has_feature_incompatible(ext4_superblock_t *,
+    uint32_t);
+extern bool ext4_superblock_has_feature_read_only(ext4_superblock_t *,
+    uint32_t);
+extern int ext4_superblock_read_direct(service_id_t, ext4_superblock_t **);
+extern int ext4_superblock_write_direct(service_id_t, ext4_superblock_t *);
+extern int ext4_superblock_check_sanity(ext4_superblock_t *);
+
+extern uint32_t ext4_superblock_get_block_group_count(ext4_superblock_t *);
+extern uint32_t ext4_superblock_get_blocks_in_group(ext4_superblock_t *,
+    uint32_t);
+extern uint32_t ext4_superblock_get_inodes_in_group(ext4_superblock_t *,
+    uint32_t);
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/ext4/libext4_types.h
===================================================================
--- uspace/lib/ext4/libext4_types.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/lib/ext4/libext4_types.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,546 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup libext4
+ * @{
+ */
+
+#ifndef LIBEXT4_LIBEXT4_TYPES_H_
+#define LIBEXT4_LIBEXT4_TYPES_H_
+
+#include <libblock.h>
+
+/*
+ * Structure of the super block
+ */
+typedef struct ext4_superblock {
+	uint32_t inodes_count;              /* I-nodes count */
+	uint32_t blocks_count_lo;           /* Blocks count */
+	uint32_t reserved_blocks_count_lo;  /* Reserved blocks count */
+	uint32_t free_blocks_count_lo;      /* Free blocks count */
+	uint32_t free_inodes_count;         /* Free inodes count */
+	uint32_t first_data_block;          /* First Data Block */
+	uint32_t log_block_size;            /* Block size */
+	uint32_t log_frag_size;             /* Obsoleted fragment size */
+	uint32_t blocks_per_group;          /* Number of blocks per group */
+	uint32_t frags_per_group;           /* Obsoleted fragments per group */
+	uint32_t inodes_per_group;          /* Number of inodes per group */
+	uint32_t mount_time;                /* Mount time */
+	uint32_t write_time;                /* Write time */
+	uint16_t mount_count;               /* Mount count */
+	uint16_t max_mount_count;           /* Maximal mount count */
+	uint16_t magic;                     /* Magic signature */
+	uint16_t state;                     /* File system state */
+	uint16_t errors;                    /* Behaviour when detecting errors */
+	uint16_t minor_rev_level;           /* Minor revision level */
+	uint32_t last_check_time;           /* Time of last check */
+	uint32_t check_interval;            /* Maximum time between checks */
+	uint32_t creator_os;                /* Creator OS */
+	uint32_t rev_level;                 /* Revision level */
+	uint16_t def_resuid;                /* Default uid for reserved blocks */
+	uint16_t def_resgid;                /* Default gid for reserved blocks */
+	
+	/* Fields for EXT4_DYNAMIC_REV superblocks only. */
+	uint32_t first_inode;             /* First non-reserved inode */
+	uint16_t inode_size;              /* Size of inode structure */
+	uint16_t block_group_index;       /* Block group index of this superblock */
+	uint32_t features_compatible;     /* Compatible feature set */
+	uint32_t features_incompatible;   /* Incompatible feature set */
+	uint32_t features_read_only;      /* Readonly-compatible feature set */
+	uint8_t uuid[16];                 /* 128-bit uuid for volume */
+	char volume_name[16];             /* Volume name */
+	char last_mounted[64];            /* Directory where last mounted */
+	uint32_t algorithm_usage_bitmap;  /* For compression */
+	
+	/*
+	 * Performance hints. Directory preallocation should only
+	 * happen if the EXT4_FEATURE_COMPAT_DIR_PREALLOC flag is on.
+	 */
+	uint8_t s_prealloc_blocks;       /* Number of blocks to try to preallocate */
+	uint8_t s_prealloc_dir_blocks;   /* Number to preallocate for dirs */
+	uint16_t s_reserved_gdt_blocks;  /* Per group desc for online growth */
+	
+	/*
+	 * Journaling support valid if EXT4_FEATURE_COMPAT_HAS_JOURNAL set.
+	 */
+	uint8_t journal_uuid[16];       /* UUID of journal superblock */
+	uint32_t journal_inode_number;  /* Inode number of journal file */
+	uint32_t journal_dev;           /* Device number of journal file */
+	uint32_t last_orphan;           /* Head of list of inodes to delete */
+	uint32_t hash_seed[4];          /* HTREE hash seed */
+	uint8_t default_hash_version;   /* Default hash version to use */
+	uint8_t journal_backup_type;
+	uint16_t desc_size;             /* Size of group descriptor */
+	uint32_t default_mount_opts;    /* Default mount options */
+	uint32_t first_meta_bg;         /* First metablock block group */
+	uint32_t mkfs_time;             /* When the filesystem was created */
+	uint32_t journal_blocks[17];    /* Backup of the journal inode */
+
+	/* 64bit support valid if EXT4_FEATURE_COMPAT_64BIT */
+	uint32_t blocks_count_hi;           /* Blocks count */
+	uint32_t reserved_blocks_count_hi;  /* Reserved blocks count */
+	uint32_t free_blocks_count_hi;      /* Free blocks count */
+	uint16_t min_extra_isize;           /* All inodes have at least # bytes */
+	uint16_t want_extra_isize;          /* New inodes should reserve # bytes */
+	uint32_t flags;                     /* Miscellaneous flags */
+	uint16_t raid_stride;               /* RAID stride */
+	uint16_t mmp_interval;              /* # seconds to wait in MMP checking */
+	uint64_t mmp_block;                 /* Block for multi-mount protection */
+	uint32_t raid_stripe_width;         /* Blocks on all data disks (N * stride) */
+	uint8_t log_groups_per_flex;        /* FLEX_BG group size */
+	uint8_t reserved_char_pad;
+	uint16_t reserved_pad;
+	uint64_t kbytes_written;            /* Number of lifetime kilobytes written */
+	uint32_t snapshot_inum;             /* I-node number of active snapshot */
+	uint32_t snapshot_id;               /* Sequential ID of active snapshot */
+	uint64_t snapshot_r_blocks_count;   /* Reserved blocks for active snapshot's future use */
+	uint32_t snapshot_list;             /* I-node number of the head of the on-disk snapshot list */
+	uint32_t error_count;               /* Number of file system errors */
+	uint32_t first_error_time;          /* First time an error happened */
+	uint32_t first_error_ino;           /* I-node involved in first error */
+	uint64_t first_error_block;         /* Block involved of first error */
+	uint8_t first_error_func[32];       /* Function where the error happened */
+	uint32_t first_error_line;          /* Line number where error happened */
+	uint32_t last_error_time;           /* Most recent time of an error */
+	uint32_t last_error_ino;            /* I-node involved in last error */
+	uint32_t last_error_line;           /* Line number where error happened */
+	uint64_t last_error_block;          /* Block involved of last error */
+	uint8_t last_error_func[32];        /* Function where the error happened */
+	uint8_t mount_opts[64];
+	uint32_t padding[112];              /* Padding to the end of the block */
+} __attribute__((packed)) ext4_superblock_t;
+
+
+#define EXT4_SUPERBLOCK_MAGIC   0xEF53
+#define EXT4_SUPERBLOCK_SIZE    1024
+#define EXT4_SUPERBLOCK_OFFSET  1024
+
+#define EXT4_SUPERBLOCK_OS_LINUX  0
+#define EXT4_SUPERBLOCK_OS_HURD   1
+
+/*
+ * Misc. filesystem flags
+ */
+#define EXT4_SUPERBLOCK_FLAGS_SIGNED_HASH    0x0001  /* Signed dirhash in use */
+#define EXT4_SUPERBLOCK_FLAGS_UNSIGNED_HASH  0x0002  /* Unsigned dirhash in use */
+#define EXT4_SUPERBLOCK_FLAGS_TEST_FILESYS   0x0004  /* to test development code */
+
+/*
+ * Filesystem states
+ */
+#define EXT4_SUPERBLOCK_STATE_VALID_FS   0x0001  /* Unmounted cleanly */
+#define EXT4_SUPERBLOCK_STATE_ERROR_FS   0x0002  /* Errors detected */
+#define EXT4_SUPERBLOCK_STATE_ORPHAN_FS  0x0004  /* Orphans being recovered */
+
+/*
+ * Behaviour when errors detected
+ */
+#define EXT4_SUPERBLOCK_ERRORS_CONTINUE  1  /* Continue execution */
+#define EXT4_SUPERBLOCK_ERRORS_RO        2  /* Remount fs read-only */
+#define EXT4_SUPERBLOCK_ERRORS_PANIC     3  /* Panic */
+#define EXT4_SUPERBLOCK_ERRORS_DEFAULT   EXT4_ERRORS_CONTINUE
+
+/*
+ * Compatible features
+ */
+#define EXT4_FEATURE_COMPAT_DIR_PREALLOC   0x0001
+#define EXT4_FEATURE_COMPAT_IMAGIC_INODES  0x0002
+#define EXT4_FEATURE_COMPAT_HAS_JOURNAL    0x0004
+#define EXT4_FEATURE_COMPAT_EXT_ATTR       0x0008
+#define EXT4_FEATURE_COMPAT_RESIZE_INODE   0x0010
+#define EXT4_FEATURE_COMPAT_DIR_INDEX      0x0020
+
+/*
+ * Read-only compatible features
+ */
+#define EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER  0x0001
+#define EXT4_FEATURE_RO_COMPAT_LARGE_FILE    0x0002
+#define EXT4_FEATURE_RO_COMPAT_BTREE_DIR     0x0004
+#define EXT4_FEATURE_RO_COMPAT_HUGE_FILE     0x0008
+#define EXT4_FEATURE_RO_COMPAT_GDT_CSUM      0x0010
+#define EXT4_FEATURE_RO_COMPAT_DIR_NLINK     0x0020
+#define EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE   0x0040
+
+/*
+ * Incompatible features
+ */
+#define EXT4_FEATURE_INCOMPAT_COMPRESSION  0x0001
+#define EXT4_FEATURE_INCOMPAT_FILETYPE     0x0002
+#define EXT4_FEATURE_INCOMPAT_RECOVER      0x0004  /* Needs recovery */
+#define EXT4_FEATURE_INCOMPAT_JOURNAL_DEV  0x0008  /* Journal device */
+#define EXT4_FEATURE_INCOMPAT_META_BG      0x0010
+#define EXT4_FEATURE_INCOMPAT_EXTENTS      0x0040  /* extents support */
+#define EXT4_FEATURE_INCOMPAT_64BIT        0x0080
+#define EXT4_FEATURE_INCOMPAT_MMP          0x0100
+#define EXT4_FEATURE_INCOMPAT_FLEX_BG      0x0200
+#define EXT4_FEATURE_INCOMPAT_EA_INODE     0x0400  /* EA in inode */
+#define EXT4_FEATURE_INCOMPAT_DIRDATA      0x1000  /* data in dirent */
+
+#define EXT4_FEATURE_COMPAT_SUPP  (EXT4_FEATURE_COMPAT_DIR_INDEX)
+
+#define EXT4_FEATURE_INCOMPAT_SUPP \
+	(EXT4_FEATURE_INCOMPAT_FILETYPE | \
+	EXT4_FEATURE_INCOMPAT_EXTENTS | \
+	EXT4_FEATURE_INCOMPAT_64BIT)
+
+#define EXT4_FEATURE_RO_COMPAT_SUPP \
+	(EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER | \
+	EXT4_FEATURE_RO_COMPAT_DIR_NLINK | \
+	EXT4_FEATURE_RO_COMPAT_HUGE_FILE | \
+	EXT4_FEATURE_RO_COMPAT_LARGE_FILE | \
+	EXT4_FEATURE_RO_COMPAT_GDT_CSUM | \
+	EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)
+
+typedef struct ext4_filesystem {
+	service_id_t device;
+	ext4_superblock_t *superblock;
+	aoff64_t inode_block_limits[4];
+	aoff64_t inode_blocks_per_level[4];
+} ext4_filesystem_t;
+
+
+#define EXT4_BLOCK_GROUP_INODE_UNINIT   0x0001  /* Inode table/bitmap not in use */
+#define EXT4_BLOCK_GROUP_BLOCK_UNINIT   0x0002  /* Block bitmap not in use */
+#define EXT4_BLOCK_GROUP_ITABLE_ZEROED  0x0004  /* On-disk itable initialized to zero */
+
+/*
+ * Structure of a blocks group descriptor
+ */
+typedef struct ext4_block_group {
+	uint32_t block_bitmap_lo;             /* Blocks bitmap block */
+	uint32_t inode_bitmap_lo;             /* Inodes bitmap block */
+	uint32_t inode_table_first_block_lo;  /* Inodes table block */
+	uint16_t free_blocks_count_lo;        /* Free blocks count */
+	uint16_t free_inodes_count_lo;        /* Free inodes count */
+	uint16_t used_dirs_count_lo;          /* Directories count */
+	uint16_t flags;                       /* EXT4_BG_flags (INODE_UNINIT, etc) */
+	uint32_t reserved[2];                 /* Likely block/inode bitmap checksum */
+	uint16_t itable_unused_lo;            /* Unused inodes count */
+	uint16_t checksum;                    /* crc16(sb_uuid+group+desc) */
+	
+	uint32_t block_bitmap_hi;             /* Blocks bitmap block MSB */
+	uint32_t inode_bitmap_hi;             /* I-nodes bitmap block MSB */
+	uint32_t inode_table_first_block_hi;  /* I-nodes table block MSB */
+	uint16_t free_blocks_count_hi;        /* Free blocks count MSB */
+	uint16_t free_inodes_count_hi;        /* Free i-nodes count MSB */
+	uint16_t used_dirs_count_hi;          /* Directories count MSB */
+	uint16_t itable_unused_hi;            /* Unused inodes count MSB */
+	uint32_t reserved2[3];                /* Padding */
+} ext4_block_group_t;
+
+typedef struct ext4_block_group_ref {
+	block_t *block;                   /* Reference to a block containing this block group descr */
+	ext4_block_group_t *block_group;
+	ext4_filesystem_t *fs;
+	uint32_t index;
+	bool dirty;
+} ext4_block_group_ref_t;
+
+#define EXT4_MIN_BLOCK_GROUP_DESCRIPTOR_SIZE  32
+#define EXT4_MAX_BLOCK_GROUP_DESCRIPTOR_SIZE  64
+
+#define EXT4_MIN_BLOCK_SIZE   1024   /* 1 KiB */
+#define EXT4_MAX_BLOCK_SIZE   65536  /* 64 KiB */
+#define EXT4_REV0_INODE_SIZE  128
+
+#define EXT4_INODE_BLOCK_SIZE  512
+
+#define EXT4_INODE_DIRECT_BLOCK_COUNT      12
+#define EXT4_INODE_INDIRECT_BLOCK          EXT4_INODE_DIRECT_BLOCK_COUNT
+#define EXT4_INODE_DOUBLE_INDIRECT_BLOCK   (EXT4_INODE_INDIRECT_BLOCK + 1)
+#define EXT4_INODE_TRIPPLE_INDIRECT_BLOCK  (EXT4_INODE_DOUBLE_INDIRECT_BLOCK + 1)
+#define EXT4_INODE_BLOCKS                  (EXT4_INODE_TRIPPLE_INDIRECT_BLOCK + 1)
+#define EXT4_INODE_INDIRECT_BLOCK_COUNT    (EXT4_INODE_BLOCKS - EXT4_INODE_DIRECT_BLOCK_COUNT)
+
+/*
+ * Structure of an inode on the disk
+ */
+typedef struct ext4_inode {
+	uint16_t mode;                       /* File mode */
+	uint16_t uid;                        /* Low 16 bits of owner uid */
+	uint32_t size_lo;                    /* Size in bytes */
+	uint32_t access_time;                /* Access time */
+	uint32_t change_inode_time;          /* I-node change time */
+	uint32_t modification_time;          /* Modification time */
+	uint32_t deletion_time;              /* Deletion time */
+	uint16_t gid;                        /* Low 16 bits of group id */
+	uint16_t links_count;                /* Links count */
+	uint32_t blocks_count_lo;            /* Blocks count */
+	uint32_t flags;                      /* File flags */
+	uint32_t unused_osd1;                /* OS dependent - not used in HelenOS */
+	uint32_t blocks[EXT4_INODE_BLOCKS];  /* Pointers to blocks */
+	uint32_t generation;                 /* File version (for NFS) */
+	uint32_t file_acl_lo;                /* File ACL */
+	uint32_t size_hi;
+	uint32_t obso_faddr;                 /* Obsoleted fragment address */
+	
+	union {
+		struct {
+			uint16_t blocks_high;
+			uint16_t file_acl_high;
+			uint16_t uid_high;
+			uint16_t gid_high;
+			uint32_t reserved2;
+		} linux2;
+		struct {
+			uint16_t reserved1;
+			uint16_t mode_high;
+			uint16_t uid_high;
+			uint16_t gid_high;
+			uint32_t author;
+		} hurd2;
+	} __attribute__ ((packed)) osd2;
+	
+	uint16_t extra_isize;
+	uint16_t pad1;
+	uint32_t ctime_extra;   /* Extra change time (nsec << 2 | epoch) */
+	uint32_t mtime_extra;   /* Extra Modification time (nsec << 2 | epoch) */
+	uint32_t atime_extra;   /* Extra Access time (nsec << 2 | epoch) */
+	uint32_t crtime;        /* File creation time */
+	uint32_t crtime_extra;  /* Extra file creation time (nsec << 2 | epoch) */
+	uint32_t version_hi;    /* High 32 bits for 64-bit version */
+} __attribute__ ((packed)) ext4_inode_t;
+
+#define EXT4_INODE_MODE_FIFO       0x1000
+#define EXT4_INODE_MODE_CHARDEV    0x2000
+#define EXT4_INODE_MODE_DIRECTORY  0x4000
+#define EXT4_INODE_MODE_BLOCKDEV   0x6000
+#define EXT4_INODE_MODE_FILE       0x8000
+#define EXT4_INODE_MODE_SOFTLINK   0xA000
+#define EXT4_INODE_MODE_SOCKET     0xC000
+#define EXT4_INODE_MODE_TYPE_MASK  0xF000
+
+/*
+ * Inode flags
+ */
+#define EXT4_INODE_FLAG_SECRM      0x00000001  /* Secure deletion */
+#define EXT4_INODE_FLAG_UNRM       0x00000002  /* Undelete */
+#define EXT4_INODE_FLAG_COMPR      0x00000004  /* Compress file */
+#define EXT4_INODE_FLAG_SYNC       0x00000008  /* Synchronous updates */
+#define EXT4_INODE_FLAG_IMMUTABLE  0x00000010  /* Immutable file */
+#define EXT4_INODE_FLAG_APPEND     0x00000020  /* writes to file may only append */
+#define EXT4_INODE_FLAG_NODUMP     0x00000040  /* do not dump file */
+#define EXT4_INODE_FLAG_NOATIME    0x00000080  /* do not update atime */
+
+/* Compression flags */
+#define EXT4_INODE_FLAG_DIRTY     0x00000100
+#define EXT4_INODE_FLAG_COMPRBLK  0x00000200  /* One or more compressed clusters */
+#define EXT4_INODE_FLAG_NOCOMPR   0x00000400  /* Don't compress */
+#define EXT4_INODE_FLAG_ECOMPR    0x00000800  /* Compression error */
+
+#define EXT4_INODE_FLAG_INDEX         0x00001000  /* hash-indexed directory */
+#define EXT4_INODE_FLAG_IMAGIC        0x00002000  /* AFS directory */
+#define EXT4_INODE_FLAG_JOURNAL_DATA  0x00004000  /* File data should be journaled */
+#define EXT4_INODE_FLAG_NOTAIL        0x00008000  /* File tail should not be merged */
+#define EXT4_INODE_FLAG_DIRSYNC       0x00010000  /* Dirsync behaviour (directories only) */
+#define EXT4_INODE_FLAG_TOPDIR        0x00020000  /* Top of directory hierarchies */
+#define EXT4_INODE_FLAG_HUGE_FILE     0x00040000  /* Set to each huge file */
+#define EXT4_INODE_FLAG_EXTENTS       0x00080000  /* Inode uses extents */
+#define EXT4_INODE_FLAG_EA_INODE      0x00200000  /* Inode used for large EA */
+#define EXT4_INODE_FLAG_EOFBLOCKS     0x00400000  /* Blocks allocated beyond EOF */
+#define EXT4_INODE_FLAG_RESERVED      0x80000000  /* reserved for ext4 lib */
+
+#define EXT4_INODE_ROOT_INDEX  2
+
+typedef struct ext4_inode_ref {
+	block_t *block;         /* Reference to a block containing this inode */
+	ext4_inode_t *inode;
+	ext4_filesystem_t *fs;
+	uint32_t index;         /* Index number of this inode */
+	bool dirty;
+} ext4_inode_ref_t;
+
+
+#define EXT4_DIRECTORY_FILENAME_LEN  255
+
+#define EXT4_DIRECTORY_FILETYPE_UNKNOWN   0
+#define EXT4_DIRECTORY_FILETYPE_REG_FILE  1
+#define EXT4_DIRECTORY_FILETYPE_DIR       2
+#define EXT4_DIRECTORY_FILETYPE_CHRDEV    3
+#define EXT4_DIRECTORY_FILETYPE_BLKDEV    4
+#define EXT4_DIRECTORY_FILETYPE_FIFO      5
+#define EXT4_DIRECTORY_FILETYPE_SOCK      6
+#define EXT4_DIRECTORY_FILETYPE_SYMLINK   7
+
+/**
+ * Linked list directory entry structure
+ */
+typedef struct ext4_directory_entry_ll {
+	uint32_t inode;         /* I-node for the entry */
+	uint16_t entry_length;  /* Distance to the next directory entry */
+	uint8_t name_length;    /* Lower 8 bits of name length */
+	
+	union {
+		uint8_t name_length_high;  /* Higher 8 bits of name length */
+		uint8_t inode_type;        /* Type of referenced inode (in rev >= 0.5) */
+	} __attribute__ ((packed));
+	
+	uint8_t name[EXT4_DIRECTORY_FILENAME_LEN];  /* Entry name */
+} __attribute__((packed)) ext4_directory_entry_ll_t;
+
+typedef struct ext4_directory_iterator {
+	ext4_inode_ref_t *inode_ref;
+	block_t *current_block;
+	aoff64_t current_offset;
+	ext4_directory_entry_ll_t *current;
+} ext4_directory_iterator_t;
+
+typedef struct ext4_directory_search_result {
+	block_t *block;
+	ext4_directory_entry_ll_t *dentry;
+} ext4_directory_search_result_t;
+
+/* Structures for indexed directory */
+
+typedef struct ext4_directory_dx_countlimit {
+	uint16_t limit;
+	uint16_t count;
+} ext4_directory_dx_countlimit_t;
+
+typedef struct ext4_directory_dx_dot_entry {
+	uint32_t inode;
+	uint16_t entry_length;
+	uint8_t name_length;
+	uint8_t inode_type;
+	uint8_t name[4];
+} ext4_directory_dx_dot_entry_t;
+
+typedef struct ext4_directory_dx_root_info {
+	uint32_t reserved_zero;
+	uint8_t hash_version;
+	uint8_t info_length;
+	uint8_t indirect_levels;
+	uint8_t unused_flags;
+} ext4_directory_dx_root_info_t;
+
+typedef struct ext4_directory_dx_entry {
+	uint32_t hash;
+	uint32_t block;
+} ext4_directory_dx_entry_t;
+
+typedef struct ext4_directory_dx_root {
+	ext4_directory_dx_dot_entry_t dots[2];
+	ext4_directory_dx_root_info_t info;
+	ext4_directory_dx_entry_t entries[0];
+} ext4_directory_dx_root_t;
+
+typedef struct ext4_fake_directory_entry {
+	uint32_t inode;
+	uint16_t entry_length;
+	uint8_t name_length;
+	uint8_t inode_type;
+} ext4_fake_directory_entry_t;
+
+typedef struct ext4_directory_dx_node {
+	ext4_fake_directory_entry_t fake;
+	ext4_directory_dx_entry_t entries[0];
+} ext4_directory_dx_node_t;
+
+typedef struct ext4_directory_dx_block {
+	block_t *block;
+	ext4_directory_dx_entry_t *entries;
+	ext4_directory_dx_entry_t *position;
+} ext4_directory_dx_block_t;
+
+#define EXT4_ERR_BAD_DX_DIR       (-75000)
+#define EXT4_DIRECTORY_HTREE_EOF  UINT32_C(0x7fffffff)
+
+/*
+ * This is the extent on-disk structure.
+ * It's used at the bottom of the tree.
+ */
+typedef struct ext4_extent {
+	uint32_t first_block;  /* First logical block extent covers */
+	uint16_t block_count;  /* Number of blocks covered by extent */
+	uint16_t start_hi;     /* High 16 bits of physical block */
+	uint32_t start_lo;     /* Low 32 bits of physical block */
+} ext4_extent_t;
+
+/*
+ * This is index on-disk structure.
+ * It's used at all the levels except the bottom.
+ */
+typedef struct ext4_extent_index {
+	uint32_t first_block;  /* Index covers logical blocks from 'block' */
+	
+	/**
+	 * Pointer to the physical block of the next
+	 * level. leaf or next index could be there
+	 * high 16 bits of physical block
+	 */
+	uint32_t leaf_lo;
+	uint16_t leaf_hi;
+	uint16_t padding;
+} ext4_extent_index_t;
+
+/*
+ * Each block (leaves and indexes), even inode-stored has header.
+ */
+typedef struct ext4_extent_header {
+	uint16_t magic;
+	uint16_t entries_count;      /* Number of valid entries */
+	uint16_t max_entries_count;  /* Capacity of store in entries */
+	uint16_t depth;              /* Has tree real underlying blocks? */
+	uint32_t generation;         /* generation of the tree */
+} ext4_extent_header_t;
+
+typedef struct ext4_extent_path {
+	block_t *block;
+	uint16_t depth;
+	ext4_extent_header_t *header;
+	ext4_extent_index_t *index;
+	ext4_extent_t *extent;
+} ext4_extent_path_t;
+
+#define EXT4_EXTENT_MAGIC  0xF30A
+
+#define	EXT4_EXTENT_FIRST(header) \
+	((ext4_extent_t *) (((void *) (header)) + sizeof(ext4_extent_header_t)))
+
+#define	EXT4_EXTENT_FIRST_INDEX(header) \
+	((ext4_extent_index_t *) (((void *) (header)) + sizeof(ext4_extent_header_t)))
+
+#define EXT4_HASH_VERSION_LEGACY             0
+#define EXT4_HASH_VERSION_HALF_MD4           1
+#define EXT4_HASH_VERSION_TEA                2
+#define EXT4_HASH_VERSION_LEGACY_UNSIGNED    3
+#define EXT4_HASH_VERSION_HALF_MD4_UNSIGNED  4
+#define EXT4_HASH_VERSION_TEA_UNSIGNED       5
+
+typedef struct ext4_hash_info {
+	uint32_t hash;
+	uint32_t minor_hash;
+	uint32_t hash_version;
+	const uint32_t *seed;
+} ext4_hash_info_t;
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/usbdev/include/usb/dev/usb_device_connection.h
===================================================================
--- uspace/lib/usbdev/include/usb/dev/usb_device_connection.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbdev/include/usb/dev/usb_device_connection.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -72,5 +72,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Register endpoint on the device.
  * @param instance device connection structure to use.
@@ -91,5 +91,5 @@
 	    instance->address, ep, type, direction, packet_size, interval);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Unregister endpoint on the device.
  * @param instance device connection structure
@@ -105,5 +105,5 @@
 	    instance->address, ep, dir);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Get data from the device.
  * @param[in] instance device connection structure to use.
@@ -122,5 +122,5 @@
 	    instance->address, ep, setup, data, size, rsize);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Send data to the device.
  * @param instance device connection structure to use.
@@ -138,5 +138,5 @@
 	    instance->address, ep, setup, data, size);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Wrapper for read calls with no setup stage.
  * @param[in] instance device connection structure.
@@ -153,5 +153,5 @@
 	return usb_device_control_read(instance, ep, 0, data, size, real_size);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Wrapper for write calls with no setup stage.
  * @param instance device connection structure.
Index: uspace/lib/usbdev/src/devdrv.c
===================================================================
--- uspace/lib/usbdev/src/devdrv.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbdev/src/devdrv.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -74,5 +74,5 @@
 	return ddf_driver_main(&generic_driver);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Count number of pipes the driver expects.
  *
@@ -87,5 +87,5 @@
 	return count;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Callback when a new device is supposed to be controlled by this driver.
  *
@@ -124,5 +124,5 @@
 	return rc;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Callback when a device is supposed to be removed from the system.
  *
@@ -146,5 +146,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Callback when a device was removed from the system.
  *
@@ -167,5 +167,5 @@
 	return ret;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Destroy existing pipes of a USB device.
  *
@@ -178,5 +178,5 @@
 	dev->pipes_count = 0;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Change interface setting of a device.
  * This function selects new alternate setting of an interface by issuing
Index: uspace/lib/usbdev/src/pipes.c
===================================================================
--- uspace/lib/usbdev/src/pipes.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbdev/src/pipes.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -54,5 +54,5 @@
 	return usb_hc_connection_open(pipe->wire->hc_connection);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Terminate a long transfer on a pipe.
  * @param pipe Pipe where to end the long transfer.
@@ -67,5 +67,5 @@
 	return usb_hc_connection_close(pipe->wire->hc_connection);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Try to clear endpoint halt of default control pipe.
  *
@@ -85,5 +85,5 @@
 	pipe->auto_reset_halt = true;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Request a control read transfer on an endpoint pipe.
  *
@@ -135,5 +135,5 @@
 	return rc;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Request a control write transfer on an endpoint pipe.
  *
@@ -182,5 +182,5 @@
 	return rc;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Request a read (in) transfer on an endpoint pipe.
  *
@@ -227,5 +227,5 @@
 	return rc;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Request a write (out) transfer on an endpoint pipe.
  *
@@ -259,5 +259,5 @@
 	    pipe->endpoint_no, buffer, size);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize USB endpoint pipe.
  *
@@ -287,5 +287,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize USB endpoint pipe as the default zero control pipe.
  *
@@ -307,5 +307,5 @@
 	return rc;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Register endpoint with the host controller.
  *
@@ -323,5 +323,5 @@
 	   pipe->direction, pipe->max_packet_size, interval);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Revert endpoint registration with the host controller.
  *
Index: uspace/lib/usbdev/src/pipesinit.c
===================================================================
--- uspace/lib/usbdev/src/pipesinit.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbdev/src/pipesinit.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -154,5 +154,5 @@
     usb_endpoint_mapping_t *mapping, size_t mapping_count,
     usb_standard_interface_descriptor_t *interface,
-    usb_standard_endpoint_descriptor_t *endpoint,
+    usb_standard_endpoint_descriptor_t *endpoint_desc,
     usb_device_connection_t *wire)
 {
@@ -163,13 +163,13 @@
 
 	/* Actual endpoint number is in bits 0..3 */
-	const usb_endpoint_t ep_no = endpoint->endpoint_address & 0x0F;
+	const usb_endpoint_t ep_no = endpoint_desc->endpoint_address & 0x0F;
 
 	const usb_endpoint_description_t description = {
 		/* Endpoint direction is set by bit 7 */
-		.direction = (endpoint->endpoint_address & 128)
+		.direction = (endpoint_desc->endpoint_address & 128)
 		    ? USB_DIRECTION_IN : USB_DIRECTION_OUT,
 		/* Transfer type is in bits 0..2 and
 		 * the enum values corresponds 1:1 */
-		.transfer_type = endpoint->attributes & 3,
+		.transfer_type = endpoint_desc->attributes & 3,
 
 		/* Get interface characteristics. */
@@ -194,5 +194,6 @@
 
 	int rc = usb_pipe_initialize(&ep_mapping->pipe, wire,
-	    ep_no, description.transfer_type, endpoint->max_packet_size,
+	    ep_no, description.transfer_type,
+	    uint16_usb2host(endpoint_desc->max_packet_size),
 	    description.direction);
 	if (rc != EOK) {
@@ -201,5 +202,5 @@
 
 	ep_mapping->present = true;
-	ep_mapping->descriptor = endpoint;
+	ep_mapping->descriptor = endpoint_desc;
 	ep_mapping->interface = interface;
 
Index: uspace/lib/usbdev/src/request.c
===================================================================
--- uspace/lib/usbdev/src/request.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbdev/src/request.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -114,5 +114,5 @@
   * 	(in native endianness).
   * @param actual_data_size Actual size of transfered data
-  * 	(in native endianness).
+  *        (in native endianness).
   * @return Error code.
   * @retval EBADMEM @p pipe is NULL.
@@ -147,7 +147,7 @@
 		    | (request_type << 5) | recipient,
 		.request = request,
-		.value = value,
-		.index = index,
-		.length = (uint16_t) data_size,
+		.value = uint16_host2usb(value),
+		.index = uint16_host2usb(index),
+		.length = uint16_host2usb(data_size),
 	};
 
@@ -375,5 +375,5 @@
 	usb_standard_device_descriptor_t descriptor_tmp;
 	int rc = usb_request_get_descriptor(pipe,
-	    USB_REQUEST_TYPE_STANDARD, USB_REQUEST_RECIPIENT_DEVICE, 
+	    USB_REQUEST_TYPE_STANDARD, USB_REQUEST_RECIPIENT_DEVICE,
 	    USB_DESCTYPE_DEVICE, 0, 0,
 	    &descriptor_tmp, sizeof(descriptor_tmp),
@@ -435,5 +435,4 @@
 	/* Everything is okay, copy the descriptor. */
 	memcpy(descriptor, &descriptor_tmp, sizeof(descriptor_tmp));
-
 	return EOK;
 }
@@ -495,9 +494,11 @@
 		return ENOENT;
 	}
-	if (bare_config.total_length < sizeof(bare_config)) {
+
+	const size_t total_length = uint16_usb2host(bare_config.total_length);
+	if (total_length < sizeof(bare_config)) {
 		return ELIMIT;
 	}
 
-	void *buffer = malloc(bare_config.total_length);
+	void *buffer = malloc(total_length);
 	if (buffer == NULL) {
 		return ENOMEM;
@@ -506,5 +507,5 @@
 	size_t transferred = 0;
 	rc = usb_request_get_full_configuration_descriptor(pipe, index,
-	    buffer, bare_config.total_length, &transferred);
+	    buffer, total_length, &transferred);
 	if (rc != EOK) {
 		free(buffer);
@@ -512,5 +513,5 @@
 	}
 
-	if (transferred != bare_config.total_length) {
+	if (transferred != total_length) {
 		free(buffer);
 		return ELIMIT;
@@ -522,5 +523,5 @@
 
 	if (descriptor_size != NULL) {
-		*descriptor_size = bare_config.total_length;
+		*descriptor_size = total_length;
 	}
 
Index: uspace/lib/usbhid/include/usb/hid/hid_report_items.h
===================================================================
--- uspace/lib/usbhid/include/usb/hid/hid_report_items.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhid/include/usb/hid/hid_report_items.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -38,5 +38,5 @@
 #include <stdint.h>
 
-/*---------------------------------------------------------------------------*/
+
 /*
  * Item prefix
@@ -56,5 +56,5 @@
 #define USB_HID_ITEM_IS_LONG(data)	(data == 0xFE)
 
-/*---------------------------------------------------------------------------*/
+
 /*
  * Extended usage macros
@@ -70,5 +70,5 @@
 #define USB_HID_EXTENDED_USAGE(usage)		(usage & 0xFFFF)
 
-/*---------------------------------------------------------------------------*/
+
 /*
  * Input/Output/Feature Item flags
@@ -142,5 +142,5 @@
 #define USB_HID_ITEM_FLAG_BUFFERED(flags)	((flags & 0x100) == 0x100)
 
-/*---------------------------------------------------------------------------*/
+
 
 /* MAIN ITEMS */
@@ -185,5 +185,5 @@
 #define USB_HID_REPORT_TAG_END_COLLECTION	0xC
 
-/*---------------------------------------------------------------------------*/
+
 
 /* GLOBAL ITEMS */
@@ -272,5 +272,5 @@
 #define USB_HID_REPORT_TAG_POP			0xB
 
-/*---------------------------------------------------------------------------*/
+
 
 /* LOCAL ITEMS */
@@ -347,5 +347,5 @@
 #define USB_HID_REPORT_TAG_DELIMITER		0xA
 
-/*---------------------------------------------------------------------------*/
+
 
 #endif
Index: uspace/lib/usbhid/include/usb/hid/hidpath.h
===================================================================
--- uspace/lib/usbhid/include/usb/hid/hidpath.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhid/include/usb/hid/hidpath.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -41,5 +41,5 @@
 
 
-/*---------------------------------------------------------------------------*/
+
 /*
  * Flags of usage paths comparison modes.
@@ -73,5 +73,5 @@
 #define USB_HID_PATH_COMPARE_ANYWHERE		8
 
-/*----------------------------------------------------------------------------*/
+
 /** 
  * Item of usage path structure. Last item of linked list describes one item
@@ -93,5 +93,5 @@
 
 
-/*---------------------------------------------------------------------------*/
+
 /** 
  * USB HID usage path structure.
@@ -112,5 +112,5 @@
 } usb_hid_report_path_t;
 
-/*---------------------------------------------------------------------------*/
+
 usb_hid_report_path_t *usb_hid_report_path(void);
 
Index: uspace/lib/usbhid/include/usb/hid/hidtypes.h
===================================================================
--- uspace/lib/usbhid/include/usb/hid/hidtypes.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhid/include/usb/hid/hidtypes.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -39,5 +39,5 @@
 #include <adt/list.h>
 
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -69,5 +69,5 @@
 	(((x) < 0 ) ? ((1 << (size)) + (x)) : (x))
 
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -86,5 +86,5 @@
 } usb_hid_report_type_t;
 
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -111,5 +111,5 @@
 	
 } usb_hid_report_t;
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -135,5 +135,5 @@
 	link_t reports_link;
 } usb_hid_report_description_t;
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -202,5 +202,5 @@
 } usb_hid_report_field_t;
 
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -287,5 +287,5 @@
 	int in_delimiter;
 } usb_hid_report_item_t;
-/*---------------------------------------------------------------------------*/
+
 /**
  * Enum of the keyboard modifiers 
@@ -314,5 +314,5 @@
 	USB_HID_MOD_RGUI
 };
-/*---------------------------------------------------------------------------*/
+
 
 
Index: uspace/lib/usbhid/include/usb/hid/request.h
===================================================================
--- uspace/lib/usbhid/include/usb/hid/request.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhid/include/usb/hid/request.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -42,5 +42,5 @@
 #include <usb/dev/pipes.h>
 
-/*----------------------------------------------------------------------------*/
+
 
 int usbhid_req_set_report(usb_pipe_t *ctrl_pipe, int iface_no,
@@ -61,5 +61,5 @@
 int usbhid_req_get_idle(usb_pipe_t *ctrl_pipe, int iface_no, uint8_t *duration);
 
-/*----------------------------------------------------------------------------*/
+
 
 #endif /* USB_KBD_HIDREQ_H_ */
Index: uspace/lib/usbhid/src/hiddescriptor.c
===================================================================
--- uspace/lib/usbhid/src/hiddescriptor.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhid/src/hiddescriptor.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -41,5 +41,5 @@
 #include <assert.h>
 
-/*---------------------------------------------------------------------------*/
+
 /*
  * Constants defining current parsing mode for correct parsing of the set of
@@ -61,5 +61,5 @@
 #define INSIDE_DELIMITER_SET	2
 
-/*---------------------------------------------------------------------------*/
+
 	
 /** The new report item flag. Used to determine when the item is completly
@@ -78,5 +78,5 @@
 #define USB_HID_UNKNOWN_TAG		-99
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Checks if given collection path is already present in report structure and
@@ -124,5 +124,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Initialize the report descriptor parser structure
@@ -147,5 +147,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -314,5 +314,5 @@
 	return EOK;
 }
-/*---------------------------------------------------------------------------*/
+
 /**
  * Finds description of report with given report_id and of given type in
@@ -348,5 +348,5 @@
 	return NULL;
 }
-/*---------------------------------------------------------------------------*/
+
 
 /** Parse HID report descriptor.
@@ -536,5 +536,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -871,5 +871,5 @@
 	return EOK;
 }
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -892,5 +892,5 @@
 	return result;
 }
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -941,5 +941,5 @@
 
 }
-/*---------------------------------------------------------------------------*/
+
 
 /**
@@ -972,5 +972,5 @@
 	}
 }
-/*---------------------------------------------------------------------------*/
+
 
 
@@ -1022,5 +1022,5 @@
 	return;
 }
-/*---------------------------------------------------------------------------*/
+
 
 /**
Index: uspace/lib/usbhid/src/hidparser.c
===================================================================
--- uspace/lib/usbhid/src/hidparser.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhid/src/hidparser.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -41,5 +41,5 @@
 #include <assert.h>
 
-/*---------------------------------------------------------------------------*/
+
 /*
  * Data translation private functions
@@ -52,5 +52,5 @@
 	int32_t value);
 
-/*---------------------------------------------------------------------------*/
+
 
 static int usb_pow(int a, int b)
@@ -68,5 +68,5 @@
 	}
 }
-/*---------------------------------------------------------------------------*/
+
 
 /** Returns size of report of specified report id and type in items
@@ -117,5 +117,5 @@
 	}
 }
-/*---------------------------------------------------------------------------*/
+
 
 /** Parse and act upon a HID report.
@@ -192,5 +192,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Translate data from the report as specified in report descriptor item
@@ -274,5 +274,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /* OUTPUT API */
 
@@ -431,5 +431,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Translate given data for putting them into the outoput report
@@ -476,5 +476,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Clones given state table
@@ -497,5 +497,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Function for sequence walking through the report. Returns next field in the
@@ -552,5 +552,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Returns next report_id of report of specified type. If zero is given than
@@ -600,5 +600,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Reset all local items in given state table
Index: uspace/lib/usbhid/src/hidpath.c
===================================================================
--- uspace/lib/usbhid/src/hidpath.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhid/src/hidpath.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -41,5 +41,5 @@
 #include <assert.h>
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Compares two usages if they are same or not or one of the usages is not
@@ -63,5 +63,5 @@
 	((page1 == page2) || (page1 == 0) || (page2 == 0))
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Appends one item (couple of usage_path and usage) into the usage path
@@ -93,5 +93,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Removes last item from the usage path structure
@@ -114,5 +114,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Nulls last item of the usage path structure.
@@ -133,5 +133,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Modifies last item of usage path structure by given usage page or usage
@@ -164,5 +164,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  *
@@ -188,5 +188,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Compares two usage paths structures
@@ -354,5 +354,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Allocates and initializes new usage path structure.
@@ -376,5 +376,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Releases given usage path structure.
@@ -395,5 +395,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Clone content of given usage path to the new one
@@ -441,5 +441,5 @@
 }
 
-/*---------------------------------------------------------------------------*/
+
 /**
  * Sets report id in usage path structure
Index: uspace/lib/usbhid/src/hidreport.c
===================================================================
--- uspace/lib/usbhid/src/hidreport.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhid/src/hidreport.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -50,5 +50,5 @@
 #include <usb/hid/hidreport.h>
 
-static int usb_hid_get_report_descriptor(usb_device_t *dev, 
+static int usb_hid_get_report_descriptor(usb_device_t *dev,
     uint8_t **report_desc, size_t *size)
 {
@@ -69,6 +69,6 @@
 	 * First nested descriptor of the configuration descriptor.
 	 */
-	const uint8_t *d = 
-	    usb_dp_get_nested_descriptor(&parser, &parser_data, 
+	const uint8_t *d =
+	    usb_dp_get_nested_descriptor(&parser, &parser_data,
 	    dev->descriptors.configuration);
 	
@@ -78,5 +78,5 @@
 	int i = 0;
 	while (d != NULL && i < dev->interface_no) {
-		d = usb_dp_get_sibling_descriptor(&parser, &parser_data, 
+		d = usb_dp_get_sibling_descriptor(&parser, &parser_data,
 		    dev->descriptors.configuration, d);
 		++i;
@@ -99,5 +99,5 @@
 	 */
 	while (d != NULL && *(d + 1) != USB_DESCTYPE_HID) {
-		d = usb_dp_get_sibling_descriptor(&parser, &parser_data, 
+		d = usb_dp_get_sibling_descriptor(&parser, &parser_data,
 		    iface_desc, d);
 	}
@@ -114,8 +114,8 @@
 	}
 	
-	usb_standard_hid_descriptor_t *hid_desc = 
+	usb_standard_hid_descriptor_t *hid_desc =
 	    (usb_standard_hid_descriptor_t *)d;
 	
-	uint16_t length =  hid_desc->report_desc_info.length;
+	uint16_t length = uint16_usb2host(hid_desc->report_desc_info.length);
 	size_t actual_size = 0;
 
@@ -161,5 +161,5 @@
 }
 
-/*----------------------------------------------------------------------------*/
+
 
 int usb_hid_process_report_descriptor(usb_device_t *dev, 
Index: uspace/lib/usbhid/src/hidreq.c
===================================================================
--- uspace/lib/usbhid/src/hidreq.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhid/src/hidreq.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -45,5 +45,5 @@
 #include <usb/hid/request.h>
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * Send Set Report request to the HID device.
@@ -97,5 +97,5 @@
 }
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * Send Set Protocol request to the HID device.
@@ -145,5 +145,5 @@
 }
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * Send Set Idle request to the HID device.
@@ -195,5 +195,5 @@
 }
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * Send Get Report request to the HID device.
@@ -251,5 +251,5 @@
 }
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * Send Get Protocol request to the HID device.
@@ -310,5 +310,5 @@
 }
 
-/*----------------------------------------------------------------------------*/
+
 /**
  * Send Get Idle request to the HID device.
@@ -373,5 +373,5 @@
 }
 
-/*----------------------------------------------------------------------------*/
+
 
 /**
Index: uspace/lib/usbhost/src/endpoint.c
===================================================================
--- uspace/lib/usbhost/src/endpoint.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhost/src/endpoint.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -72,5 +72,5 @@
 	return instance;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Properly dispose of endpoint_t structure.
  * @param instance endpoint_t structure.
@@ -84,5 +84,5 @@
 	free(instance);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Set device specific data and hooks.
  * @param instance endpoint_t structure.
@@ -101,5 +101,5 @@
 	fibril_mutex_unlock(&instance->guard);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Clear device specific data and hooks.
  * @param instance endpoint_t structure.
@@ -115,5 +115,5 @@
 	fibril_mutex_unlock(&instance->guard);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Mark the endpoint as active and block access for further fibrils.
  * @param instance endpoint_t structure.
@@ -128,5 +128,5 @@
 	fibril_mutex_unlock(&instance->guard);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Mark the endpoint as inactive and allow access for further fibrils.
  * @param instance endpoint_t structure.
@@ -140,5 +140,5 @@
 	fibril_condvar_signal(&instance->avail);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Get the value of toggle bit.
  * @param instance endpoint_t structure.
@@ -156,5 +156,5 @@
 	return ret;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Set the value of toggle bit.
  * @param instance endpoint_t structure.
Index: uspace/lib/usbhost/src/usb_device_manager.c
===================================================================
--- uspace/lib/usbhost/src/usb_device_manager.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhost/src/usb_device_manager.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -61,5 +61,5 @@
 	return new_address;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize device manager structure.
  *
@@ -82,5 +82,5 @@
 	fibril_mutex_initialize(&instance->guard);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Request USB address.
  * @param instance usb_device_manager
@@ -124,5 +124,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Bind USB address to devman handle.
  *
@@ -156,5 +156,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Release used USB address.
  *
@@ -182,5 +182,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Find USB address associated with the device.
  *
@@ -205,5 +205,5 @@
 	return ENOENT;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Find devman handle and speed assigned to USB address.
  *
Index: uspace/lib/usbhost/src/usb_endpoint_manager.c
===================================================================
--- uspace/lib/usbhost/src/usb_endpoint_manager.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhost/src/usb_endpoint_manager.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -61,5 +61,5 @@
 	    && (address == ep->address);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Get list that holds endpoints for given address.
  * @param instance usb_endpoint_manager structure, non-null.
@@ -73,5 +73,5 @@
 	return &instance->endpoint_lists[addr % ENDPOINT_LIST_COUNT];
 }
-/*----------------------------------------------------------------------------*/
+
 /** Internal search function, works on locked structure.
  * @param instance usb_endpoint_manager structure, non-null.
@@ -97,5 +97,5 @@
 	return NULL;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Calculate bandwidth that needs to be reserved for communication with EP.
  * Calculation follows USB 1.1 specification.
@@ -145,5 +145,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /** Initialize to default state.
  * You need to provide valid bw_count function if you plan to use
@@ -168,5 +168,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Check setup packet data for signs of toggle reset.
  *
@@ -227,5 +227,5 @@
 	}
 }
-/*----------------------------------------------------------------------------*/
+
 /** Register endpoint structure.
  * Checks for duplicates.
@@ -262,5 +262,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Unregister endpoint structure.
  * Checks for duplicates.
@@ -286,5 +286,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Find endpoint_t representing the given communication route.
  * @param instance usb_endpoint_manager, non-null.
@@ -301,5 +301,5 @@
 	return ep;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Create and register new endpoint_t structure.
  * @param instance usb_endpoint_manager structure, non-null.
@@ -364,5 +364,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Unregister and destroy endpoint_t structure representing given route.
  * @param instance usb_endpoint_manager structure, non-null.
@@ -395,5 +395,5 @@
 	return EOK;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Unregister and destroy all endpoints using given address.
  * @param instance usb_endpoint_manager structure, non-null.
Index: uspace/lib/usbhost/src/usb_transfer_batch.c
===================================================================
--- uspace/lib/usbhost/src/usb_transfer_batch.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/lib/usbhost/src/usb_transfer_batch.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -96,5 +96,5 @@
 	return instance;
 }
-/*----------------------------------------------------------------------------*/
+
 /** Correctly dispose all used data structures.
  *
@@ -116,5 +116,5 @@
 	free(instance);
 }
-/*----------------------------------------------------------------------------*/
+
 /** Prepare data and call the right callback.
  *
Index: uspace/srv/bd/sata_bd/Makefile
===================================================================
--- uspace/srv/bd/sata_bd/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/srv/bd/sata_bd/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,35 @@
+#
+# Copyright (c) 2012 Petr Jerman
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+#   notice, this list of conditions and the following disclaimer.
+# - Redistributions in binary form must reproduce the above copyright
+#   notice, this list of conditions and the following disclaimer in the
+#   documentation and/or other materials provided with the distribution.
+# - The name of the author may not be used to endorse or promote products
+#   derived from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+USPACE_PREFIX = ../../..
+BINARY = sata_bd
+
+SOURCES = \
+	sata_bd.c
+
+include $(USPACE_PREFIX)/Makefile.common
Index: uspace/srv/bd/sata_bd/sata_bd.c
===================================================================
--- uspace/srv/bd/sata_bd/sata_bd.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/srv/bd/sata_bd/sata_bd.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup bd
+ * @{
+ */
+
+/**
+ * @file
+ * @brief SATA disk driver
+ *
+ */
+
+#include <sys/types.h>
+#include <errno.h>
+#include <stdio.h>
+#include <ipc/bd.h>
+#include <str.h>
+#include <loc.h>
+#include <macros.h>
+
+#include <device/ahci.h>
+#include "sata_bd.h"
+
+#define NAME       "sata_bd"
+#define NAMESPACE  "bd"
+
+/** Maximum number of disks handled */
+#define MAXDISKS  256
+
+static sata_bd_dev_t disk[MAXDISKS];
+static int disk_count;
+
+/** Find SATA devices in device tree.
+ *
+ *  @param Device manager handle describing container for searching.  
+ *
+ *  @return EOK if succeed, error code otherwise.
+ *
+ */
+static int scan_device_tree(devman_handle_t funh)
+{
+	devman_handle_t devh;
+	devman_handle_t *cfuns;
+	size_t count, i;
+	int rc;
+		
+	/* If device is SATA, add device to the disk array. */
+	disk[disk_count].sess = ahci_get_sess(funh, &disk[disk_count].dev_name);
+	if(disk[disk_count].sess != NULL) {
+		
+		ahci_get_sata_device_name(disk[disk_count].sess,
+		    SATA_DEV_NAME_LENGTH, disk[disk_count].sata_dev_name);
+		
+		ahci_get_block_size(disk[disk_count].sess,
+		    &disk[disk_count].block_size);
+		
+		ahci_get_num_blocks(disk[disk_count].sess, &disk[disk_count].blocks);
+				
+		printf("Device %s - %s , blocks: %lu, block_size: %lu\n", 
+		    disk[disk_count].dev_name, disk[disk_count].sata_dev_name,
+			    (long unsigned int) disk[disk_count].blocks,
+				(long unsigned int) disk[disk_count].block_size);
+
+		++disk_count;
+	}
+	
+	/* search children */
+	rc = devman_fun_get_child(funh, &devh);
+	if (rc == ENOENT)
+		return EOK;
+
+	if (rc != EOK) {
+		printf(NAME ": Failed getting child device for function %s.\n", "xxx");
+		return rc;
+	}
+
+	rc = devman_dev_get_functions(devh, &cfuns, &count);
+	if (rc != EOK) {
+		printf(NAME ": Failed getting list of functions for device %s.\n",
+		    "xxx");
+		return rc;
+	}
+
+	for (i = 0; i < count; i++)
+		scan_device_tree(cfuns[i]);
+
+	free(cfuns);
+	return EOK;
+}
+
+/** Find sata devices in device tree from root.
+ *
+ *  @return EOK if succeed, error code otherwise.
+ *
+ */
+static int get_sata_disks()
+{
+	devman_handle_t root_fun;
+	int rc;
+	
+	disk_count = 0;
+
+	rc = devman_fun_get_handle("/", &root_fun, 0);
+	if (rc != EOK) {
+		printf(NAME ": Error resolving root function.\n");
+		return EIO;
+	}
+	
+	scan_device_tree(root_fun);
+	
+	return EOK;
+}
+
+/** Block device connection handler. */
+static void sata_bd_connection(ipc_callid_t iid, ipc_call_t *icall, void *arg)
+{
+	void *fs_va = NULL;
+	ipc_callid_t callid;
+	ipc_call_t call;
+	sysarg_t method;
+	service_id_t dsid;
+	/* Size of the communication area. */
+	size_t comm_size;	
+	unsigned int flags;
+	int retval = 0;
+	uint64_t ba;
+	size_t cnt;
+	int disk_id, i;
+
+	/* Get the device service ID. */
+	dsid = IPC_GET_ARG1(*icall);
+
+	/* Determine which disk device is the client connecting to. */
+	disk_id = -1;
+	for (i = 0; i < MAXDISKS; i++)
+		if (disk[i].service_id == dsid)
+			disk_id = i;
+
+	if (disk_id < 0) {
+		async_answer_0(iid, EINVAL);
+		return;
+	}
+
+	/* Answer the IPC_M_CONNECT_ME_TO call. */
+	async_answer_0(iid, EOK);
+
+	if (!async_share_out_receive(&callid, &comm_size, &flags)) {
+		async_answer_0(callid, EHANGUP);
+		return;
+	}
+
+	(void) async_share_out_finalize(callid, &fs_va);
+	if (fs_va == (void *) -1) {
+		async_answer_0(callid, EHANGUP);
+		return;
+	}
+
+	while (true) {
+		callid = async_get_call(&call);
+		method = IPC_GET_IMETHOD(call);
+		
+		if (!method) {
+			/* The other side has hung up. */
+			async_answer_0(callid, EOK);
+			return;
+		}
+		
+		switch (method) {
+			case BD_READ_BLOCKS:
+				ba = MERGE_LOUP32(IPC_GET_ARG1(call), IPC_GET_ARG2(call));
+				cnt = IPC_GET_ARG3(call);
+				if (cnt * disk[disk_id].block_size > comm_size) {
+					retval = ELIMIT;
+					break;
+				}
+				retval = ahci_read_blocks(disk[disk_id].sess, ba, cnt, fs_va);
+				break;
+			case BD_WRITE_BLOCKS:
+				ba = MERGE_LOUP32(IPC_GET_ARG1(call), IPC_GET_ARG2(call));
+				cnt = IPC_GET_ARG3(call);
+				if (cnt * disk[disk_id].block_size > comm_size) {
+					retval = ELIMIT;
+					break;
+				}
+				retval = ahci_write_blocks(disk[disk_id].sess, ba, cnt, fs_va);
+				break;
+			case BD_GET_BLOCK_SIZE:
+				async_answer_1(callid, EOK, disk[disk_id].block_size);
+				continue;
+			case BD_GET_NUM_BLOCKS:
+				async_answer_2(callid, EOK, LOWER32(disk[disk_id].blocks),
+				    UPPER32(disk[disk_id].blocks));
+				break;
+			default:
+				retval = EINVAL;
+				break;
+			}
+		async_answer_0(callid, retval);
+	}
+}
+
+int main(int argc, char **argv)
+{
+	int rc;
+	
+	async_set_client_connection(sata_bd_connection);
+	rc = loc_server_register(NAME);
+	if (rc < 0) {
+		printf(NAME ": Unable to register driver.\n");
+		return rc;
+	}
+	
+	rc = get_sata_disks();
+	if (rc != EOK) {
+		return rc;
+	}
+
+	for(int i=0; i < disk_count; i++) {
+		char name[1024];
+		snprintf(name, 1024, "%s/%s", NAMESPACE, disk[i].dev_name);
+		rc = loc_service_register(name, &disk[i].service_id);
+		if (rc != EOK) {
+			printf(NAME ": Unable to register device %s.\n", name);
+			return rc;
+		}
+	}
+		
+	printf(NAME ": Accepting connections\n");
+	task_retval(0);
+	async_manager();
+
+	/* Not reached */
+	return 0;
+}
+
+/**
+ * @}
+ */
Index: uspace/srv/bd/sata_bd/sata_bd.h
===================================================================
--- uspace/srv/bd/sata_bd/sata_bd.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/srv/bd/sata_bd/sata_bd.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2012 Petr Jerman
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup bd
+ * @{
+ */
+/** @file SATA block device driver definitions.
+ */
+
+#ifndef __SATA_BD_H__
+#define __SATA_BD_H__
+
+#define SATA_DEV_NAME_LENGTH 256
+
+#include <sys/types.h>
+#include <loc.h>
+
+/** SATA Block Device. */
+typedef struct {
+	/** Device name in device tree. */ 
+	char* dev_name; 
+	/** SATA Device name. */ 
+	char sata_dev_name[SATA_DEV_NAME_LENGTH]; 
+	/** Session to device methods. */
+	async_sess_t* sess; 
+	/** Loc service id. */
+	service_id_t service_id;
+	/** Number of blocks. */
+	uint64_t blocks; 
+	/** Size of block. */
+	size_t block_size; 
+} sata_bd_dev_t;
+
+#endif
+
+/** @}
+ */
Index: uspace/srv/devman/devman.c
===================================================================
--- uspace/srv/devman/devman.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/srv/devman/devman.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -1052,5 +1052,4 @@
 }
 
-
 /** Find the device node structure of the device witch has the specified handle.
  *
@@ -1142,4 +1141,5 @@
 	fun->state = FUN_INIT;
 	atomic_set(&fun->refcnt, 0);
+	fibril_mutex_initialize(&fun->busy_lock);
 	link_initialize(&fun->dev_functions);
 	list_initialize(&fun->match_ids.ids);
@@ -1184,4 +1184,16 @@
 	if (atomic_predec(&fun->refcnt) == 0)
 		delete_fun_node(fun);
+}
+
+/** Make function busy for reconfiguration operations. */
+void fun_busy_lock(fun_node_t *fun)
+{
+	fibril_mutex_lock(&fun->busy_lock);
+}
+
+/** Mark end of reconfiguration operation. */
+void fun_busy_unlock(fun_node_t *fun)
+{
+	fibril_mutex_unlock(&fun->busy_lock);
 }
 
Index: uspace/srv/devman/devman.h
===================================================================
--- uspace/srv/devman/devman.h	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/srv/devman/devman.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -174,4 +174,6 @@
 	/** State */
 	fun_state_t state;
+	/** Locked while performing reconfiguration operations */
+	fibril_mutex_t busy_lock;
 	
 	/** The global unique identifier of the function */
@@ -279,4 +281,5 @@
 extern void dev_add_ref(dev_node_t *);
 extern void dev_del_ref(dev_node_t *);
+
 extern dev_node_t *find_dev_node_no_lock(dev_tree_t *tree,
     devman_handle_t handle);
@@ -290,4 +293,6 @@
 extern void fun_add_ref(fun_node_t *);
 extern void fun_del_ref(fun_node_t *);
+extern void fun_busy_lock(fun_node_t *);
+extern void fun_busy_unlock(fun_node_t *);
 extern fun_node_t *find_fun_node_no_lock(dev_tree_t *tree,
     devman_handle_t handle);
Index: uspace/srv/devman/main.c
===================================================================
--- uspace/srv/devman/main.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/srv/devman/main.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -432,10 +432,20 @@
 	
 	fun_node_t *fun = create_fun_node();
+	/* One reference for creation, one for us */
+	fun_add_ref(fun);
 	fun_add_ref(fun);
 	fun->ftype = ftype;
+	
+	/*
+	 * We can lock the function here even when holding the tree because
+	 * we know it cannot be held by anyone else yet.
+	 */
+	fun_busy_lock(fun);
 	
 	if (!insert_fun_node(&device_tree, fun, fun_name, pdev)) {
 		fibril_rwlock_write_unlock(&tree->rwlock);
 		dev_del_ref(pdev);
+		fun_busy_unlock(fun);
+		fun_del_ref(fun);
 		delete_fun_node(fun);
 		async_answer_0(callid, ENOMEM);
@@ -450,8 +460,13 @@
 	rc = online_function(fun);
 	if (rc != EOK) {
-		/* XXX clean up */
+		/* XXX Set some failed state? */
+		fun_busy_unlock(fun);
+		fun_del_ref(fun);
 		async_answer_0(callid, rc);
 		return;
 	}
+	
+	fun_busy_unlock(fun);
+	fun_del_ref(fun);
 	
 	/* Return device handle to parent's driver. */
@@ -522,7 +537,10 @@
 	}
 	
+	fun_busy_lock(fun);
+	
 	fibril_rwlock_read_lock(&device_tree.rwlock);
 	if (fun->dev == NULL || fun->dev->drv != drv) {
 		fibril_rwlock_read_unlock(&device_tree.rwlock);
+		fun_busy_unlock(fun);
 		fun_del_ref(fun);
 		async_answer_0(iid, ENOENT);
@@ -533,4 +551,5 @@
 	rc = online_function(fun);
 	if (rc != EOK) {
+		fun_busy_unlock(fun);
 		fun_del_ref(fun);
 		async_answer_0(iid, (sysarg_t) rc);
@@ -538,4 +557,5 @@
 	}
 	
+	fun_busy_unlock(fun);
 	fun_del_ref(fun);
 	
@@ -559,6 +579,9 @@
 	}
 	
+	fun_busy_lock(fun);
+	
 	fibril_rwlock_write_lock(&device_tree.rwlock);
 	if (fun->dev == NULL || fun->dev->drv != drv) {
+		fun_busy_unlock(fun);
 		fun_del_ref(fun);
 		async_answer_0(iid, ENOENT);
@@ -569,4 +592,5 @@
 	rc = offline_function(fun);
 	if (rc != EOK) {
+		fun_busy_unlock(fun);
 		fun_del_ref(fun);
 		async_answer_0(iid, (sysarg_t) rc);
@@ -574,4 +598,5 @@
 	}
 	
+	fun_busy_unlock(fun);
 	fun_del_ref(fun);
 	async_answer_0(iid, (sysarg_t) EOK);
@@ -591,4 +616,6 @@
 	}
 	
+	fun_busy_lock(fun);
+	
 	fibril_rwlock_write_lock(&tree->rwlock);
 	
@@ -598,4 +625,6 @@
 	if (fun->state == FUN_REMOVED) {
 		fibril_rwlock_write_unlock(&tree->rwlock);
+		fun_busy_unlock(fun);
+		fun_del_ref(fun);
 		async_answer_0(callid, ENOENT);
 		return;
@@ -638,4 +667,6 @@
 				if (gone_rc == EOK)
 					gone_rc = ENOTSUP;
+				fun_busy_unlock(fun);
+				fun_del_ref(fun);
 				async_answer_0(callid, gone_rc);
 				return;
@@ -664,4 +695,5 @@
 				    "service.");
 				fibril_rwlock_write_unlock(&tree->rwlock);
+				fun_busy_unlock(fun);
 				fun_del_ref(fun);
 				async_answer_0(callid, EIO);
@@ -673,4 +705,5 @@
 	remove_fun_node(&device_tree, fun);
 	fibril_rwlock_write_unlock(&tree->rwlock);
+	fun_busy_unlock(fun);
 	
 	/* Delete ref added when inserting function into tree */
Index: uspace/srv/fs/ext4fs/Makefile
===================================================================
--- uspace/srv/fs/ext4fs/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/srv/fs/ext4fs/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,38 @@
+#
+# Copyright (c) 2012 Frantisek Princ
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+#   notice, this list of conditions and the following disclaimer.
+# - Redistributions in binary form must reproduce the above copyright
+#   notice, this list of conditions and the following disclaimer in the
+#   documentation and/or other materials provided with the distribution.
+# - The name of the author may not be used to endorse or promote products
+#   derived from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+USPACE_PREFIX = ../../..
+LIBS = $(LIBBLOCK_PREFIX)/libblock.a $(LIBFS_PREFIX)/libfs.a $(LIBEXT4_PREFIX)/libext4.a
+EXTRA_CFLAGS += -I$(LIBBLOCK_PREFIX) -I$(LIBFS_PREFIX) -I$(LIBEXT4_PREFIX)
+BINARY = ext4fs
+
+SOURCES = \
+	ext4fs.c \
+	ext4fs_ops.c
+
+include $(USPACE_PREFIX)/Makefile.common
Index: uspace/srv/fs/ext4fs/ext4fs.c
===================================================================
--- uspace/srv/fs/ext4fs/ext4fs.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/srv/fs/ext4fs/ext4fs.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup fs
+ * @{
+ */
+/**
+ * @file  ext4fs.c
+ * @brief Ext4 file system driver for HelenOS.
+ */
+
+#include <async.h>
+#include <errno.h>
+#include <libfs.h>
+#include <ns.h>
+#include <stdio.h>
+#include <task.h>
+#include <ipc/services.h>
+#include "ext4fs.h"
+#include "../../vfs/vfs.h"
+
+#define NAME  "ext4fs"
+
+vfs_info_t ext4fs_vfs_info = {
+	.name = NAME,
+	.instance = 0
+};
+
+int main(int argc, char **argv)
+{
+	printf("%s: HelenOS ext4 file system server\n", NAME);
+	
+	if (argc == 3) {
+		if (!str_cmp(argv[1], "--instance"))
+			ext4fs_vfs_info.instance = strtol(argv[2], NULL, 10);
+		else {
+			printf("%s: Unrecognized parameters\n", NAME);
+			return 1;
+		}
+	}
+	
+	async_sess_t *vfs_sess = service_connect_blocking(EXCHANGE_SERIALIZE,
+	    SERVICE_VFS, 0, 0);
+	if (!vfs_sess) {
+		printf("%s: Failed to connect to VFS\n", NAME);
+		return 2;
+	}
+	
+	int rc = ext4fs_global_init();
+	if (rc != EOK) {
+		printf("%s: Global initialization failed\n", NAME);
+		return rc;
+	}
+	
+	rc = fs_register(vfs_sess, &ext4fs_vfs_info, &ext4fs_ops,
+	    &ext4fs_libfs_ops);
+	if (rc != EOK) {
+		printf("%s: Failed to register file system\n", NAME);
+		return rc;
+	}
+	
+	printf("%s: Accepting connections\n", NAME);
+	task_retval(0);
+	async_manager();
+	
+	/* Not reached */
+	return 0;
+}
+
+/**
+ * @}
+ */
Index: uspace/srv/fs/ext4fs/ext4fs.h
===================================================================
--- uspace/srv/fs/ext4fs/ext4fs.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/srv/fs/ext4fs/ext4fs.h	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup fs
+ * @{
+ */
+
+#ifndef EXT4FS_EXT4FS_H_
+#define EXT4FS_EXT4FS_H_
+
+#include <libfs.h>
+
+extern vfs_out_ops_t ext4fs_ops;
+extern libfs_ops_t ext4fs_libfs_ops;
+
+extern int ext4fs_global_init(void);
+extern int ext4fs_global_fini(void);
+
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/srv/fs/ext4fs/ext4fs_ops.c
===================================================================
--- uspace/srv/fs/ext4fs/ext4fs_ops.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/srv/fs/ext4fs/ext4fs_ops.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,1511 @@
+/*
+ * Copyright (c) 2012 Frantisek Princ
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - The name of the author may not be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** @addtogroup fs
+ * @{
+ */
+/**
+ * @file  ext4fs_ops.c
+ * @brief VFS operations for ext4 filesystem.
+ */
+
+#include <errno.h>
+#include <fibril_synch.h>
+#include <libext4.h>
+#include <libfs.h>
+#include <macros.h>
+#include <malloc.h>
+#include <adt/hash_table.h>
+#include <ipc/loc.h>
+#include "ext4fs.h"
+#include "../../vfs/vfs.h"
+
+#define EXT4FS_NODE(node) \
+	((node) ? (ext4fs_node_t *) (node)->data : NULL)
+
+#define OPEN_NODES_KEYS  2
+
+#define OPEN_NODES_DEV_HANDLE_KEY  0
+#define OPEN_NODES_INODE_KEY       1
+
+#define OPEN_NODES_BUCKETS  256
+
+/**
+ * Type for holding an instance of mounted partition.
+ */
+typedef struct ext4fs_instance {
+	link_t link;
+	service_id_t service_id;
+	ext4_filesystem_t *filesystem;
+	unsigned int open_nodes_count;
+} ext4fs_instance_t;
+
+/**
+ * Type for wrapping common fs_node and add some useful pointers.
+ */
+typedef struct ext4fs_node {
+	ext4fs_instance_t *instance;
+	ext4_inode_ref_t *inode_ref;
+	fs_node_t *fs_node;
+	link_t link;
+	unsigned int references;
+} ext4fs_node_t;
+
+/* Forward declarations of auxiliary functions */
+
+static int ext4fs_read_directory(ipc_callid_t, aoff64_t, size_t,
+    ext4fs_instance_t *, ext4_inode_ref_t *, size_t *);
+static int ext4fs_read_file(ipc_callid_t, aoff64_t, size_t, ext4fs_instance_t *,
+    ext4_inode_ref_t *, size_t *);
+static bool ext4fs_is_dots(const uint8_t *, size_t);
+static int ext4fs_instance_get(service_id_t, ext4fs_instance_t **);
+static int ext4fs_node_get_core(fs_node_t **, ext4fs_instance_t *, fs_index_t);
+static int ext4fs_node_put_core(ext4fs_node_t *);
+
+/* Forward declarations of ext4 libfs operations. */
+
+static int ext4fs_root_get(fs_node_t **, service_id_t);
+static int ext4fs_match(fs_node_t **, fs_node_t *, const char *);
+static int ext4fs_node_get(fs_node_t **, service_id_t, fs_index_t);
+static int ext4fs_node_open(fs_node_t *);
+static int ext4fs_node_put(fs_node_t *);
+static int ext4fs_create_node(fs_node_t **, service_id_t, int);
+static int ext4fs_destroy_node(fs_node_t *);
+static int ext4fs_link(fs_node_t *, fs_node_t *, const char *);
+static int ext4fs_unlink(fs_node_t *, fs_node_t *, const char *);
+static int ext4fs_has_children(bool *, fs_node_t *);
+static fs_index_t ext4fs_index_get(fs_node_t *);
+static aoff64_t ext4fs_size_get(fs_node_t *);
+static unsigned ext4fs_lnkcnt_get(fs_node_t *);
+static bool ext4fs_is_directory(fs_node_t *);
+static bool ext4fs_is_file(fs_node_t *node);
+static service_id_t ext4fs_service_get(fs_node_t *node);
+
+/* Static variables */
+
+static LIST_INITIALIZE(instance_list);
+static FIBRIL_MUTEX_INITIALIZE(instance_list_mutex);
+static hash_table_t open_nodes;
+static FIBRIL_MUTEX_INITIALIZE(open_nodes_lock);
+
+/* Hash table interface for open nodes hash table */
+static hash_index_t open_nodes_hash(unsigned long key[])
+{
+	/* TODO: This is very simple and probably can be improved */
+	return key[OPEN_NODES_INODE_KEY] % OPEN_NODES_BUCKETS;
+}
+
+/** Compare given item with values in hash table.
+ *
+ */
+static int open_nodes_compare(unsigned long key[], hash_count_t keys,
+    link_t *item)
+{
+	assert(keys > 0);
+	
+	ext4fs_node_t *enode =
+	    hash_table_get_instance(item, ext4fs_node_t, link);
+	
+	if (enode->instance->service_id !=
+	    ((service_id_t) key[OPEN_NODES_DEV_HANDLE_KEY]))
+		return false;
+	
+	if (keys == 1)
+		return true;
+	
+	assert(keys == 2);
+	
+	return (enode->inode_ref->index == key[OPEN_NODES_INODE_KEY]);
+}
+
+/** Empty callback to correct hash table initialization.
+ *
+ */
+static void open_nodes_remove_cb(link_t *link)
+{
+	/* We don't use remove callback for this hash table */
+}
+
+static hash_table_operations_t open_nodes_ops = {
+	.hash = open_nodes_hash,
+	.compare = open_nodes_compare,
+	.remove_callback = open_nodes_remove_cb,
+};
+
+/** Basic initialization of the driver.
+ *
+ * This is only needed to create the hash table
+ * for storing open nodes.
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_global_init(void)
+{
+	if (!hash_table_create(&open_nodes, OPEN_NODES_BUCKETS,
+	    OPEN_NODES_KEYS, &open_nodes_ops))
+		return ENOMEM;
+	
+	return EOK;
+}
+
+/* Finalization of the driver.
+ *
+ * This is only needed to destroy the hash table.
+ *
+ * @return Error code
+ */
+int ext4fs_global_fini(void)
+{
+	hash_table_destroy(&open_nodes);
+	return EOK;
+}
+
+/*
+ * Ext4 libfs operations.
+ */
+
+/** Get instance from internal table by service_id.
+ *
+ * @param service_id Device identifier
+ * @param inst       Output instance if successful operation
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_instance_get(service_id_t service_id, ext4fs_instance_t **inst)
+{
+	fibril_mutex_lock(&instance_list_mutex);
+	
+	if (list_empty(&instance_list)) {
+		fibril_mutex_unlock(&instance_list_mutex);
+		return EINVAL;
+	}
+	
+	list_foreach(instance_list, link) {
+		ext4fs_instance_t *tmp =
+		    list_get_instance(link, ext4fs_instance_t, link);
+		
+		if (tmp->service_id == service_id) {
+			*inst = tmp;
+			fibril_mutex_unlock(&instance_list_mutex);
+			return EOK;
+		}
+	}
+	
+	fibril_mutex_unlock(&instance_list_mutex);
+	return EINVAL;
+}
+
+/** Get root node of filesystem specified by service_id.
+ * 
+ * @param rfn        Output pointer to loaded node
+ * @param service_id Device to load root node from
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_root_get(fs_node_t **rfn, service_id_t service_id)
+{
+	return ext4fs_node_get(rfn, service_id, EXT4_INODE_ROOT_INDEX);
+}
+
+/** Check if specified name (component) matches with any directory entry.
+ * 
+ * If match is found, load and return matching node.
+ *
+ * @param rfn       Output pointer to node if operation successful
+ * @param pfn       Parent directory node
+ * @param component Name to check directory for
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_match(fs_node_t **rfn, fs_node_t *pfn, const char *component)
+{
+	ext4fs_node_t *eparent = EXT4FS_NODE(pfn);
+	ext4_filesystem_t *fs = eparent->instance->filesystem;
+	
+	if (!ext4_inode_is_type(fs->superblock, eparent->inode_ref->inode,
+	    EXT4_INODE_MODE_DIRECTORY))
+		return ENOTDIR;
+	
+	/* Try to find entry */
+	ext4_directory_search_result_t result;
+	int rc = ext4_directory_find_entry(&result, eparent->inode_ref,
+	    component);
+	if (rc != EOK) {
+		if (rc == ENOENT) {
+			*rfn = NULL;
+			return EOK;
+		}
+		
+		return rc;
+	}
+	
+	/* Load node from search result */
+	uint32_t inode = ext4_directory_entry_ll_get_inode(result.dentry);
+	rc = ext4fs_node_get_core(rfn, eparent->instance, inode);
+	if (rc != EOK)
+		return rc;
+	
+	/* Destroy search result structure */
+	return ext4_directory_destroy_result(&result);
+}
+
+/** Get node specified by index
+ *
+ * It's wrapper for node_put_core operation
+ *
+ * @param rfn        Output pointer to loaded node if operation successful
+ * @param service_id Device identifier
+ * @param index      Node index (here i-node number)
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_node_get(fs_node_t **rfn, service_id_t service_id, fs_index_t index)
+{
+	ext4fs_instance_t *inst;
+	int rc = ext4fs_instance_get(service_id, &inst);
+	if (rc != EOK)
+		return rc;
+	
+	return ext4fs_node_get_core(rfn, inst, index);
+}
+
+/** Main function for getting node from the filesystem. 
+ *
+ * @param rfn   Output point to loaded node if operation successful
+ * @param inst  Instance of filesystem
+ * @param index Index of node (i-node number)
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_node_get_core(fs_node_t **rfn, ext4fs_instance_t *inst,
+    fs_index_t index)
+{
+	fibril_mutex_lock(&open_nodes_lock);
+	
+	/* Check if the node is not already open */
+	unsigned long key[] = {
+		[OPEN_NODES_DEV_HANDLE_KEY] = inst->service_id,
+		[OPEN_NODES_INODE_KEY] = index
+	};
+	
+	link_t *already_open = hash_table_find(&open_nodes, key);
+	ext4fs_node_t *enode = NULL;
+	if (already_open) {
+		enode = hash_table_get_instance(already_open, ext4fs_node_t, link);
+		*rfn = enode->fs_node;
+		enode->references++;
+		
+		fibril_mutex_unlock(&open_nodes_lock);
+		return EOK;
+	}
+	
+	/* Prepare new enode */
+	enode = malloc(sizeof(ext4fs_node_t));
+	if (enode == NULL) {
+		fibril_mutex_unlock(&open_nodes_lock);
+		return ENOMEM;
+	}
+	
+	/* Prepare new fs_node and initialize */
+	fs_node_t *fs_node = malloc(sizeof(fs_node_t));
+	if (fs_node == NULL) {
+		free(enode);
+		fibril_mutex_unlock(&open_nodes_lock);
+		return ENOMEM;
+	}
+	
+	fs_node_initialize(fs_node);
+	
+	/* Load i-node from filesystem */
+	ext4_inode_ref_t *inode_ref;
+	int rc = ext4_filesystem_get_inode_ref(inst->filesystem, index,
+	    &inode_ref);
+	if (rc != EOK) {
+		free(enode);
+		free(fs_node);
+		fibril_mutex_unlock(&open_nodes_lock);
+		return rc;
+	}
+	
+	/* Initialize enode */
+	enode->inode_ref = inode_ref;
+	enode->instance = inst;
+	enode->references = 1;
+	enode->fs_node = fs_node;
+	link_initialize(&enode->link);
+	
+	fs_node->data = enode;
+	*rfn = fs_node;
+	
+	hash_table_insert(&open_nodes, key, &enode->link);
+	inst->open_nodes_count++;
+	
+	fibril_mutex_unlock(&open_nodes_lock);
+	
+	return EOK;
+}
+
+/** Put previously loaded node.
+ *
+ * @param enode Node to put back
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_node_put_core(ext4fs_node_t *enode)
+{
+	unsigned long key[] = {
+		[OPEN_NODES_DEV_HANDLE_KEY] = enode->instance->service_id,
+		[OPEN_NODES_INODE_KEY] = enode->inode_ref->index
+	};
+	
+	hash_table_remove(&open_nodes, key, OPEN_NODES_KEYS);
+	assert(enode->instance->open_nodes_count > 0);
+	enode->instance->open_nodes_count--;
+	
+	/* Put inode back in filesystem */
+	int rc = ext4_filesystem_put_inode_ref(enode->inode_ref);
+	if (rc != EOK)
+		return rc;
+	
+	/* Destroy data structure */
+	free(enode->fs_node);
+	free(enode);
+	
+	return EOK;
+}
+
+/** Open node.
+ *
+ * This operation is stateless in this driver.
+ *
+ * @param fn Node to open
+ *
+ * @return EOK
+ *
+ */
+int ext4fs_node_open(fs_node_t *fn)
+{
+	/* Stateless operation */
+	return EOK;
+}
+
+/** Put previously loaded node.
+ *
+ * A wrapper for node_put_core operation
+ *
+ * @param fn Node to put back
+ * @return Error code
+ *
+ */
+int ext4fs_node_put(fs_node_t *fn)
+{
+	fibril_mutex_lock(&open_nodes_lock);
+	
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	assert(enode->references > 0);
+	enode->references--;
+	if (enode->references == 0) {
+		int rc = ext4fs_node_put_core(enode);
+		if (rc != EOK) {
+			fibril_mutex_unlock(&open_nodes_lock);
+			return rc;
+		}
+	}
+	
+	fibril_mutex_unlock(&open_nodes_lock);
+	
+	return EOK;
+}
+
+/** Create new node in filesystem.
+ *
+ * @param rfn        Output pointer to newly created node if successful
+ * @param service_id Device identifier, where the filesystem is
+ * @param flags      Flags for specification of new node parameters
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_create_node(fs_node_t **rfn, service_id_t service_id, int flags)
+{
+	/* Allocate enode */
+	ext4fs_node_t *enode;
+	enode = malloc(sizeof(ext4fs_node_t));
+	if (enode == NULL)
+		return ENOMEM;
+	
+	/* Allocate fs_node */
+	fs_node_t *fs_node;
+	fs_node = malloc(sizeof(fs_node_t));
+	if (fs_node == NULL) {
+		free(enode);
+		return ENOMEM;
+	}
+	
+	/* Load instance */
+	ext4fs_instance_t *inst;
+	int rc = ext4fs_instance_get(service_id, &inst);
+	if (rc != EOK) {
+		free(enode);
+		free(fs_node);
+		return rc;
+	}
+	
+	/* Allocate new i-node in filesystem */
+	ext4_inode_ref_t *inode_ref;
+	rc = ext4_filesystem_alloc_inode(inst->filesystem, &inode_ref, flags);
+	if (rc != EOK) {
+		free(enode);
+		free(fs_node);
+		return rc;
+	}
+	
+	/* Do some interconnections in references */
+	enode->inode_ref = inode_ref;
+	enode->instance = inst;
+	enode->references = 1;
+	
+	link_initialize(&enode->link);
+	
+	unsigned long key[] = {
+		[OPEN_NODES_DEV_HANDLE_KEY] = inst->service_id,
+		[OPEN_NODES_INODE_KEY] = inode_ref->index
+	};
+	
+	fibril_mutex_lock(&open_nodes_lock);
+	hash_table_insert(&open_nodes, key, &enode->link);
+	fibril_mutex_unlock(&open_nodes_lock);
+	inst->open_nodes_count++;
+	
+	enode->inode_ref->dirty = true;
+	
+	fs_node_initialize(fs_node);
+	fs_node->data = enode;
+	enode->fs_node = fs_node;
+	*rfn = fs_node;
+	
+	return EOK;
+}
+
+/** Destroy existing node.
+ *
+ * @param fs Node to destroy
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_destroy_node(fs_node_t *fn)
+{
+	/* If directory, check for children */
+	bool has_children;
+	int rc = ext4fs_has_children(&has_children, fn);
+	if (rc != EOK) {
+		ext4fs_node_put(fn);
+		return rc;
+	}
+	
+	if (has_children) {
+		ext4fs_node_put(fn);
+		return EINVAL;
+	}
+	
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	ext4_inode_ref_t *inode_ref = enode->inode_ref;
+	
+	/* Release data blocks */
+	rc = ext4_filesystem_truncate_inode(inode_ref, 0);
+	if (rc != EOK) {
+		ext4fs_node_put(fn);
+		return rc;
+	}
+	
+	/*
+	 * TODO: Sset real deletion time when it will be supported.
+	 * Temporary set fake deletion time.
+	 */
+	ext4_inode_set_deletion_time(inode_ref->inode, 0xdeadbeef);
+	inode_ref->dirty = true;
+	
+	/* Free inode */
+	rc = ext4_filesystem_free_inode(inode_ref);
+	if (rc != EOK) {
+		ext4fs_node_put(fn);
+		return rc;
+	}
+	
+	return ext4fs_node_put(fn);
+}
+
+/** Link the specfied node to directory.
+ *
+ * @param pfn  Parent node to link in
+ * @param cfn  Node to be linked
+ * @param name Name which will be assigned to directory entry
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_link(fs_node_t *pfn, fs_node_t *cfn, const char *name)
+{
+	/* Check maximum name length */
+	if (str_size(name) > EXT4_DIRECTORY_FILENAME_LEN)
+		return ENAMETOOLONG;
+	
+	ext4fs_node_t *parent = EXT4FS_NODE(pfn);
+	ext4fs_node_t *child = EXT4FS_NODE(cfn);
+	ext4_filesystem_t *fs = parent->instance->filesystem;
+	
+	/* Add entry to parent directory */
+	int rc = ext4_directory_add_entry(parent->inode_ref, name,
+	    child->inode_ref);
+	if (rc != EOK)
+		return rc;
+	
+	/* Fill new dir -> add '.' and '..' entries */
+	if (ext4_inode_is_type(fs->superblock, child->inode_ref->inode,
+	    EXT4_INODE_MODE_DIRECTORY)) {
+		rc = ext4_directory_add_entry(child->inode_ref, ".",
+		    child->inode_ref);
+		if (rc != EOK) {
+			ext4_directory_remove_entry(parent->inode_ref, name);
+			return rc;
+		}
+		
+		rc = ext4_directory_add_entry(child->inode_ref, "..",
+		    parent->inode_ref);
+		if (rc != EOK) {
+			ext4_directory_remove_entry(parent->inode_ref, name);
+			ext4_directory_remove_entry(child->inode_ref, ".");
+			return rc;
+		}
+		
+		/* Initialize directory index if supported */
+		if (ext4_superblock_has_feature_compatible(fs->superblock,
+		    EXT4_FEATURE_COMPAT_DIR_INDEX)) {
+			rc = ext4_directory_dx_init(child->inode_ref);
+			if (rc != EOK)
+				return rc;
+			
+			ext4_inode_set_flag(child->inode_ref->inode,
+			    EXT4_INODE_FLAG_INDEX);
+			child->inode_ref->dirty = true;
+		}
+	
+		uint16_t parent_links =
+		    ext4_inode_get_links_count(parent->inode_ref->inode);
+		parent_links++;
+		ext4_inode_set_links_count(parent->inode_ref->inode, parent_links);
+		
+		parent->inode_ref->dirty = true;
+	}
+	
+	uint16_t child_links =
+	    ext4_inode_get_links_count(child->inode_ref->inode);
+	child_links++;
+	ext4_inode_set_links_count(child->inode_ref->inode, child_links);
+	
+	child->inode_ref->dirty = true;
+	
+	return EOK;
+}
+
+/** Unlink node from specified directory.
+ *
+ * @param pfn  Parent node to delete node from
+ * @param cfn  Child node to be unlinked from directory
+ * @param name Name of entry that will be removed
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_unlink(fs_node_t *pfn, fs_node_t *cfn, const char *name)
+{
+	bool has_children;
+	int rc = ext4fs_has_children(&has_children, cfn);
+	if (rc != EOK)
+		return rc;
+	
+	/* Cannot unlink non-empty node */
+	if (has_children)
+		return ENOTEMPTY;
+	
+	/* Remove entry from parent directory */
+	ext4_inode_ref_t *parent = EXT4FS_NODE(pfn)->inode_ref;
+	rc = ext4_directory_remove_entry(parent, name);
+	if (rc != EOK)
+		return rc;
+	
+	/* Decrement links count */
+	ext4_inode_ref_t *child_inode_ref = EXT4FS_NODE(cfn)->inode_ref;
+	
+	uint32_t lnk_count =
+	    ext4_inode_get_links_count(child_inode_ref->inode);
+	lnk_count--;
+	
+	/* If directory - handle links from parent */
+	if ((lnk_count <= 1) && (ext4fs_is_directory(cfn))) {
+		assert(lnk_count == 1);
+		
+		lnk_count--;
+		
+		ext4_inode_ref_t *parent_inode_ref = EXT4FS_NODE(pfn)->inode_ref;
+		
+		uint32_t parent_lnk_count = ext4_inode_get_links_count(
+		    parent_inode_ref->inode);
+		
+		parent_lnk_count--;
+		ext4_inode_set_links_count(parent_inode_ref->inode, parent_lnk_count);
+		
+		parent->dirty = true;
+	}
+
+	/*
+	 * TODO: Update timestamps of the parent
+	 * (when we have wall-clock time).
+	 *
+	 * ext4_inode_set_change_inode_time(parent->inode, (uint32_t) now);
+	 * ext4_inode_set_modification_time(parent->inode, (uint32_t) now);
+	 * parent->dirty = true;
+	 */
+	
+	/*
+	 * TODO: Update timestamp for inode.
+	 *
+	 * ext4_inode_set_change_inode_time(child_inode_ref->inode,
+	 *     (uint32_t) now);
+	 */
+	
+	ext4_inode_set_links_count(child_inode_ref->inode, lnk_count);
+	child_inode_ref->dirty = true;
+	
+	return EOK;
+}
+
+/** Check if specified node has children.
+ *
+ * For files is response allways false and check is executed only for directories.
+ *
+ * @param has_children Output value for response
+ * @param fn           Node to check
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_has_children(bool *has_children, fs_node_t *fn)
+{
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	ext4_filesystem_t *fs = enode->instance->filesystem;
+	
+	/* Check if node is directory */
+	if (!ext4_inode_is_type(fs->superblock, enode->inode_ref->inode,
+	    EXT4_INODE_MODE_DIRECTORY)) {
+		*has_children = false;
+		return EOK;
+	}
+	
+	ext4_directory_iterator_t it;
+	int rc = ext4_directory_iterator_init(&it, enode->inode_ref, 0);
+	if (rc != EOK)
+		return rc;
+	
+	/* Find a non-empty directory entry */
+	bool found = false;
+	while (it.current != NULL) {
+		if (it.current->inode != 0) {
+			uint16_t name_size =
+			    ext4_directory_entry_ll_get_name_length(fs->superblock,
+			    it.current);
+			if (!ext4fs_is_dots(it.current->name, name_size)) {
+				found = true;
+				break;
+			}
+		}
+		
+		rc = ext4_directory_iterator_next(&it);
+		if (rc != EOK) {
+			ext4_directory_iterator_fini(&it);
+			return rc;
+		}
+	}
+	
+	rc = ext4_directory_iterator_fini(&it);
+	if (rc != EOK)
+		return rc;
+	
+	*has_children = found;
+	
+	return EOK;
+}
+
+/** Unpack index number from node.
+ *
+ * @param fn Node to load index from
+ *
+ * @return Index number of i-node
+ *
+ */
+fs_index_t ext4fs_index_get(fs_node_t *fn)
+{
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	return enode->inode_ref->index;
+}
+
+/** Get real size of file / directory.
+ *
+ * @param fn Node to get size of
+ *
+ * @return Real size of node
+ *
+ */
+aoff64_t ext4fs_size_get(fs_node_t *fn)
+{
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	ext4_superblock_t *sb = enode->instance->filesystem->superblock;
+	return ext4_inode_get_size(sb, enode->inode_ref->inode);
+}
+
+/** Get number of links to specified node.
+ *
+ * @param fn Node to get links to
+ *
+ * @return Number of links
+ *
+ */
+unsigned ext4fs_lnkcnt_get(fs_node_t *fn)
+{
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	uint32_t lnkcnt = ext4_inode_get_links_count(enode->inode_ref->inode);
+	
+	if (ext4fs_is_directory(fn)) {
+		if (lnkcnt > 1)
+			return 1;
+		else
+			return 0;
+	}
+	
+	/* For regular files return real links count */
+	return lnkcnt;
+}
+
+/** Check if node is directory.
+ *
+ * @param fn Node to check
+ *
+ * @return Result of check
+ *
+ */
+bool ext4fs_is_directory(fs_node_t *fn)
+{
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	ext4_superblock_t *sb = enode->instance->filesystem->superblock;
+	
+	return ext4_inode_is_type(sb, enode->inode_ref->inode,
+	    EXT4_INODE_MODE_DIRECTORY);
+}
+
+/** Check if node is regular file.
+ *
+ * @param fn Node to check
+ *
+ * @return Result of check
+ *
+ */
+bool ext4fs_is_file(fs_node_t *fn)
+{
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	ext4_superblock_t *sb = enode->instance->filesystem->superblock;
+	
+	return ext4_inode_is_type(sb, enode->inode_ref->inode,
+	    EXT4_INODE_MODE_FILE);
+}
+
+/** Extract device identifier from node.
+ *
+ * @param node Node to extract id from
+ *
+ * @return id of device, where is the filesystem
+ *
+ */
+service_id_t ext4fs_service_get(fs_node_t *fn)
+{
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	return enode->instance->service_id;
+}
+
+/*
+ * libfs operations.
+ */
+libfs_ops_t ext4fs_libfs_ops = {
+	.root_get = ext4fs_root_get,
+	.match = ext4fs_match,
+	.node_get = ext4fs_node_get,
+	.node_open = ext4fs_node_open,
+	.node_put = ext4fs_node_put,
+	.create = ext4fs_create_node,
+	.destroy = ext4fs_destroy_node,
+	.link = ext4fs_link,
+	.unlink = ext4fs_unlink,
+	.has_children = ext4fs_has_children,
+	.index_get = ext4fs_index_get,
+	.size_get = ext4fs_size_get,
+	.lnkcnt_get = ext4fs_lnkcnt_get,
+	.is_directory = ext4fs_is_directory,
+	.is_file = ext4fs_is_file,
+	.service_get = ext4fs_service_get
+};
+
+/*
+ * VFS operations.
+ */
+
+/** Mount operation.
+ *
+ * Try to mount specified filesystem from device.
+ *
+ * @param service_id Identifier of device
+ * @param opts       Mount options
+ * @param index      Output value - index of root node
+ * @param size       Output value - size of root node
+ * @param lnkcnt     Output value - link count of root node
+ *
+ * @return Error code
+ *
+ */
+static int ext4fs_mounted(service_id_t service_id, const char *opts,
+    fs_index_t *index, aoff64_t *size, unsigned *lnkcnt)
+{
+	/* Allocate libext4 filesystem structure */
+	ext4_filesystem_t *fs = (ext4_filesystem_t *)
+	    malloc(sizeof(ext4_filesystem_t));
+	if (fs == NULL)
+		return ENOMEM;
+	
+	/* Allocate instance structure */
+	ext4fs_instance_t *inst = (ext4fs_instance_t *)
+	    malloc(sizeof(ext4fs_instance_t));
+	if (inst == NULL) {
+		free(fs);
+		return ENOMEM;
+	}
+	
+	enum cache_mode cmode;
+	if (str_cmp(opts, "wtcache") == 0)
+		cmode = CACHE_MODE_WT;
+	else
+		cmode = CACHE_MODE_WB;
+	
+	/* Initialize the filesystem */
+	int rc = ext4_filesystem_init(fs, service_id, cmode);
+	if (rc != EOK) {
+		free(fs);
+		free(inst);
+		return rc;
+	}
+	
+	/* Do some sanity checking */
+	rc = ext4_filesystem_check_sanity(fs);
+	if (rc != EOK) {
+		ext4_filesystem_fini(fs);
+		free(fs);
+		free(inst);
+		return rc;
+	}
+	
+	/* Check flags */
+	bool read_only;
+	rc = ext4_filesystem_check_features(fs, &read_only);
+	if (rc != EOK) {
+		ext4_filesystem_fini(fs);
+		free(fs);
+		free(inst);
+		return rc;
+	}
+	
+	/* Initialize instance */
+	link_initialize(&inst->link);
+	inst->service_id = service_id;
+	inst->filesystem = fs;
+	inst->open_nodes_count = 0;
+	
+	/* Read root node */
+	fs_node_t *root_node;
+	rc = ext4fs_node_get_core(&root_node, inst, EXT4_INODE_ROOT_INDEX);
+	if (rc != EOK) {
+		ext4_filesystem_fini(fs);
+		free(fs);
+		free(inst);
+		return rc;
+	}
+	
+	/* Add instance to the list */
+	fibril_mutex_lock(&instance_list_mutex);
+	list_append(&inst->link, &instance_list);
+	fibril_mutex_unlock(&instance_list_mutex);
+	
+	ext4fs_node_t *enode = EXT4FS_NODE(root_node);
+	
+	*index = EXT4_INODE_ROOT_INDEX;
+	*size = ext4_inode_get_size(fs->superblock, enode->inode_ref->inode);
+	*lnkcnt = 1;
+	
+	ext4fs_node_put(root_node);
+	
+	return EOK;
+}
+
+/** Unmount operation.
+ *
+ * Correctly release the filesystem.
+ *
+ * @param service_id Device to be unmounted
+ *
+ * @return Error code
+ *
+ */
+static int ext4fs_unmounted(service_id_t service_id)
+{
+	ext4fs_instance_t *inst;
+	int rc = ext4fs_instance_get(service_id, &inst);
+	if (rc != EOK)
+		return rc;
+	
+	fibril_mutex_lock(&open_nodes_lock);
+	
+	if (inst->open_nodes_count != 0) {
+		fibril_mutex_unlock(&open_nodes_lock);
+		return EBUSY;
+	}
+	
+	/* Remove the instance from the list */
+	fibril_mutex_lock(&instance_list_mutex);
+	list_remove(&inst->link);
+	fibril_mutex_unlock(&instance_list_mutex);
+	
+	fibril_mutex_unlock(&open_nodes_lock);
+	
+	return ext4_filesystem_fini(inst->filesystem);
+}
+
+/** Read bytes from node.
+ *
+ * @param service_id Device to read data from
+ * @param index      Number of node to read from
+ * @param pos        Position where the read should be started
+ * @param rbytes     Output value, where the real size was returned
+ *
+ * @return Error code
+ *
+ */
+static int ext4fs_read(service_id_t service_id, fs_index_t index, aoff64_t pos,
+    size_t *rbytes)
+{
+	/*
+	 * Receive the read request.
+	 */
+	ipc_callid_t callid;
+	size_t size;
+	if (!async_data_read_receive(&callid, &size)) {
+		async_answer_0(callid, EINVAL);
+		return EINVAL;
+	}
+	
+	ext4fs_instance_t *inst;
+	int rc = ext4fs_instance_get(service_id, &inst);
+	if (rc != EOK) {
+		async_answer_0(callid, rc);
+		return rc;
+	}
+	
+	/* Load i-node */
+	ext4_inode_ref_t *inode_ref;
+	rc = ext4_filesystem_get_inode_ref(inst->filesystem, index, &inode_ref);
+	if (rc != EOK) {
+		async_answer_0(callid, rc);
+		return rc;
+	}
+	
+	/* Read from i-node by type */
+	if (ext4_inode_is_type(inst->filesystem->superblock, inode_ref->inode,
+	    EXT4_INODE_MODE_FILE)) {
+		rc = ext4fs_read_file(callid, pos, size, inst, inode_ref,
+		    rbytes);
+	} else if (ext4_inode_is_type(inst->filesystem->superblock,
+	    inode_ref->inode, EXT4_INODE_MODE_DIRECTORY)) {
+		rc = ext4fs_read_directory(callid, pos, size, inst, inode_ref,
+		    rbytes);
+	} else {
+		/* Other inode types not supported */
+		async_answer_0(callid, ENOTSUP);
+		rc = ENOTSUP;
+	}
+	
+	ext4_filesystem_put_inode_ref(inode_ref);
+	
+	return rc;
+}
+
+/** Check if filename is dot or dotdot (reserved names).
+ *
+ * @param name      Name to check
+ * @param name_size Length of string name
+ *
+ * @return Result of the check
+ *
+ */
+bool ext4fs_is_dots(const uint8_t *name, size_t name_size)
+{
+	if ((name_size == 1) && (name[0] == '.'))
+		return true;
+	
+	if ((name_size == 2) && (name[0] == '.') && (name[1] == '.'))
+		return true;
+	
+	return false;
+}
+
+/** Read data from directory.
+ *
+ * @param callid    IPC id of call (for communication)
+ * @param pos       Position to start reading from
+ * @param size      How many bytes to read
+ * @param inst      Filesystem instance
+ * @param inode_ref Node to read data from
+ * @param rbytes    Output value to return real number of bytes was read
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_read_directory(ipc_callid_t callid, aoff64_t pos, size_t size,
+    ext4fs_instance_t *inst, ext4_inode_ref_t *inode_ref, size_t *rbytes)
+{
+	ext4_directory_iterator_t it;
+	int rc = ext4_directory_iterator_init(&it, inode_ref, pos);
+	if (rc != EOK) {
+		async_answer_0(callid, rc);
+		return rc;
+	}
+	
+	/*
+	 * Find next interesting directory entry.
+	 * We want to skip . and .. entries
+	 * as these are not used in HelenOS
+	 */
+	bool found = false;
+	while (it.current != NULL) {
+		if (it.current->inode == 0)
+			goto skip;
+		
+		uint16_t name_size = ext4_directory_entry_ll_get_name_length(
+		    inst->filesystem->superblock, it.current);
+		
+		/* Skip . and .. */
+		if (ext4fs_is_dots(it.current->name, name_size))
+			goto skip;
+		
+		/*
+		 * The on-disk entry does not contain \0 at the end
+		 * end of entry name, so we copy it to new buffer
+		 * and add the \0 at the end
+		 */
+		uint8_t *buf = malloc(name_size + 1);
+		if (buf == NULL) {
+			ext4_directory_iterator_fini(&it);
+			async_answer_0(callid, ENOMEM);
+			return ENOMEM;
+		}
+		
+		memcpy(buf, &it.current->name, name_size);
+		*(buf + name_size) = 0;
+		found = true;
+		
+		(void) async_data_read_finalize(callid, buf, name_size + 1);
+		free(buf);
+		break;
+		
+skip:
+		rc = ext4_directory_iterator_next(&it);
+		if (rc != EOK) {
+			ext4_directory_iterator_fini(&it);
+			async_answer_0(callid, rc);
+			return rc;
+		}
+	}
+	
+	uint64_t next;
+	if (found) {
+		rc = ext4_directory_iterator_next(&it);
+		if (rc != EOK)
+			return rc;
+		
+		next = it.current_offset;
+	}
+	
+	rc = ext4_directory_iterator_fini(&it);
+	if (rc != EOK)
+		return rc;
+	
+	/* Prepare return values */
+	if (found) {
+		*rbytes = next - pos;
+		return EOK;
+	} else {
+		async_answer_0(callid, ENOENT);
+		return ENOENT;
+	}
+}
+
+/** Read data from file.
+ *
+ * @param callid    IPC id of call (for communication)
+ * @param pos       Position to start reading from
+ * @param size      How many bytes to read
+ * @param inst      Filesystem instance
+ * @param inode_ref Node to read data from
+ * @param rbytes    Output value to return real number of bytes was read
+ *
+ * @return Error code
+ *
+ */
+int ext4fs_read_file(ipc_callid_t callid, aoff64_t pos, size_t size,
+    ext4fs_instance_t *inst, ext4_inode_ref_t *inode_ref, size_t *rbytes)
+{
+	ext4_superblock_t *sb = inst->filesystem->superblock;
+	uint64_t file_size = ext4_inode_get_size(sb, inode_ref->inode);
+	
+	if (pos >= file_size) {
+		/* Read 0 bytes successfully */
+		async_data_read_finalize(callid, NULL, 0);
+		*rbytes = 0;
+		return EOK;
+	}
+	
+	/* For now, we only read data from one block at a time */
+	uint32_t block_size = ext4_superblock_get_block_size(sb);
+	aoff64_t file_block = pos / block_size;
+	uint32_t offset_in_block = pos % block_size;
+	uint32_t bytes = min(block_size - offset_in_block, size);
+	
+	/* Handle end of file */
+	if (pos + bytes > file_size)
+		bytes = file_size - pos;
+	
+	/* Get the real block number */
+	uint32_t fs_block;
+	int rc = ext4_filesystem_get_inode_data_block_index(inode_ref,
+	    file_block, &fs_block);
+	if (rc != EOK) {
+		async_answer_0(callid, rc);
+		return rc;
+	}
+	
+	/*
+	 * Check for sparse file.
+	 * If ext4_filesystem_get_inode_data_block_index returned
+	 * fs_block == 0, it means that the given block is not allocated for the
+	 * file and we need to return a buffer of zeros
+	 */
+	uint8_t *buffer;
+	if (fs_block == 0) {
+		buffer = malloc(bytes);
+		if (buffer == NULL) {
+			async_answer_0(callid, ENOMEM);
+			return ENOMEM;
+		}
+		
+		memset(buffer, 0, bytes);
+		
+		async_data_read_finalize(callid, buffer, bytes);
+		*rbytes = bytes;
+		
+		free(buffer);
+		return EOK;
+	}
+	
+	/* Usual case - we need to read a block from device */
+	block_t *block;
+	rc = block_get(&block, inst->service_id, fs_block, BLOCK_FLAGS_NONE);
+	if (rc != EOK) {
+		async_answer_0(callid, rc);
+		return rc;
+	}
+	
+	assert(offset_in_block + bytes <= block_size);
+	async_data_read_finalize(callid, block->data + offset_in_block, bytes);
+	
+	rc = block_put(block);
+	if (rc != EOK)
+		return rc;
+	
+	*rbytes = bytes;
+	return EOK;
+}
+
+/** Write bytes to file
+ *
+ * @param service_id Device identifier
+ * @param index      I-node number of file
+ * @param pos        Position in file to start reading from
+ * @param wbytes     Output value - real number of written bytes
+ * @param nsize      Output value - new size of i-node
+ *
+ * @return Error code
+ *
+ */
+static int ext4fs_write(service_id_t service_id, fs_index_t index, aoff64_t pos,
+    size_t *wbytes, aoff64_t *nsize)
+{
+	fs_node_t *fn;
+	int rc = ext4fs_node_get(&fn, service_id, index);
+	if (rc != EOK)
+		return rc;
+	
+	ipc_callid_t callid;
+	size_t len;
+	if (!async_data_write_receive(&callid, &len)) {
+		ext4fs_node_put(fn);
+		async_answer_0(callid, EINVAL);
+		return EINVAL;
+	}
+	
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	ext4_filesystem_t *fs = enode->instance->filesystem;
+	
+	uint32_t block_size = ext4_superblock_get_block_size(fs->superblock);
+	
+	/* Prevent writing to more than one block */
+	uint32_t bytes = min(len, block_size - (pos % block_size));
+	
+	int flags = BLOCK_FLAGS_NONE;
+	if (bytes == block_size)
+		flags = BLOCK_FLAGS_NOREAD;
+	
+	uint32_t iblock =  pos / block_size;
+	uint32_t fblock;
+	
+	/* Load inode */
+	ext4_inode_ref_t *inode_ref = enode->inode_ref;
+	rc = ext4_filesystem_get_inode_data_block_index(inode_ref, iblock,
+	    &fblock);
+	if (rc != EOK) {
+		ext4fs_node_put(fn);
+		async_answer_0(callid, rc);
+		return rc;
+	}
+	
+	/* Check for sparse file */
+	if (fblock == 0) {
+		if ((ext4_superblock_has_feature_incompatible(fs->superblock,
+		    EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
+		    (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
+			uint32_t last_iblock =
+			    ext4_inode_get_size(fs->superblock, inode_ref->inode) /
+			    block_size;
+			
+			while (last_iblock < iblock) {
+				rc = ext4_extent_append_block(inode_ref, &last_iblock,
+				    &fblock, true);
+				if (rc != EOK) {
+					ext4fs_node_put(fn);
+					async_answer_0(callid, rc);
+					return rc;
+				}
+			}
+			
+			rc = ext4_extent_append_block(inode_ref, &last_iblock,
+			    &fblock, false);
+			if (rc != EOK) {
+				ext4fs_node_put(fn);
+				async_answer_0(callid, rc);
+				return rc;
+			}
+		} else {
+			rc = ext4_balloc_alloc_block(inode_ref, &fblock);
+			if (rc != EOK) {
+				ext4fs_node_put(fn);
+				async_answer_0(callid, rc);
+				return rc;
+			}
+			
+			rc = ext4_filesystem_set_inode_data_block_index(inode_ref,
+			    iblock, fblock);
+			if (rc != EOK) {
+				ext4_balloc_free_block(inode_ref, fblock);
+				ext4fs_node_put(fn);
+				async_answer_0(callid, rc);
+				return rc;
+			}
+		}
+		
+		flags = BLOCK_FLAGS_NOREAD;
+		inode_ref->dirty = true;
+	}
+	
+	/* Load target block */
+	block_t *write_block;
+	rc = block_get(&write_block, service_id, fblock, flags);
+	if (rc != EOK) {
+		ext4fs_node_put(fn);
+		async_answer_0(callid, rc);
+		return rc;
+	}
+	
+	if (flags == BLOCK_FLAGS_NOREAD)
+		memset(write_block->data, 0, block_size);
+	
+	rc = async_data_write_finalize(callid, write_block->data +
+	    (pos % block_size), bytes);
+	if (rc != EOK) {
+		ext4fs_node_put(fn);
+		return rc;
+	}
+	
+	write_block->dirty = true;
+	
+	rc = block_put(write_block);
+	if (rc != EOK) {
+		ext4fs_node_put(fn);
+		return rc;
+	}
+	
+	/* Do some counting */
+	uint32_t old_inode_size = ext4_inode_get_size(fs->superblock,
+	    inode_ref->inode);
+	if (pos + bytes > old_inode_size) {
+		ext4_inode_set_size(inode_ref->inode, pos + bytes);
+		inode_ref->dirty = true;
+	}
+	
+	*nsize = ext4_inode_get_size(fs->superblock, inode_ref->inode);
+	*wbytes = bytes;
+	
+	return ext4fs_node_put(fn);
+}
+
+/** Truncate file.
+ *
+ * Only the direction to shorter file is supported.
+ *
+ * @param service_id Device identifier
+ * @param index      Index if node to truncated
+ * @param new_size   New size of file
+ *
+ * @return Error code
+ *
+ */
+static int ext4fs_truncate(service_id_t service_id, fs_index_t index,
+    aoff64_t new_size)
+{
+	fs_node_t *fn;
+	int rc = ext4fs_node_get(&fn, service_id, index);
+	if (rc != EOK)
+		return rc;
+	
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	ext4_inode_ref_t *inode_ref = enode->inode_ref;
+	
+	rc = ext4_filesystem_truncate_inode(inode_ref, new_size);
+	ext4fs_node_put(fn);
+	
+	return rc;
+}
+
+/** Close file.
+ *
+ * @param service_id Device identifier
+ * @param index      I-node number
+ *
+ * @return Error code
+ *
+ */
+static int ext4fs_close(service_id_t service_id, fs_index_t index)
+{
+	return EOK;
+}
+
+/** Destroy node specified by index.
+ *
+ * @param service_id Device identifier
+ * @param index      I-node to destroy
+ *
+ * @return Error code
+ *
+ */
+static int ext4fs_destroy(service_id_t service_id, fs_index_t index)
+{
+	fs_node_t *fn;
+	int rc = ext4fs_node_get(&fn, service_id, index);
+	if (rc != EOK)
+		return rc;
+	
+	/* Destroy the inode */
+	return ext4fs_destroy_node(fn);
+}
+
+/** Enforce inode synchronization (write) to device.
+ *
+ * @param service_id Device identifier
+ * @param index      I-node number.
+ *
+ */
+static int ext4fs_sync(service_id_t service_id, fs_index_t index)
+{
+	fs_node_t *fn;
+	int rc = ext4fs_node_get(&fn, service_id, index);
+	if (rc != EOK)
+		return rc;
+	
+	ext4fs_node_t *enode = EXT4FS_NODE(fn);
+	enode->inode_ref->dirty = true;
+	
+	return ext4fs_node_put(fn);
+}
+
+/** VFS operations
+ *
+ */
+vfs_out_ops_t ext4fs_ops = {
+	.mounted = ext4fs_mounted,
+	.unmounted = ext4fs_unmounted,
+	.read = ext4fs_read,
+	.write = ext4fs_write,
+	.truncate = ext4fs_truncate,
+	.close = ext4fs_close,
+	.destroy = ext4fs_destroy,
+	.sync = ext4fs_sync
+};
+
+/**
+ * @}
+ */
Index: uspace/srv/hid/console/console.c
===================================================================
--- uspace/srv/hid/console/console.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/srv/hid/console/console.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -617,5 +617,5 @@
 	
 	size_t pos = 0;
-
+	
 	/*
 	 * Read input from keyboard and copy it to the buffer.
@@ -628,15 +628,17 @@
 			buf[pos] = cons->char_remains[0];
 			pos++;
+			
 			/* Unshift the array. */
-			for (size_t i = 1; i < cons->char_remains_len; i++) {
+			for (size_t i = 1; i < cons->char_remains_len; i++)
 				cons->char_remains[i - 1] = cons->char_remains[i];
-			}
+			
 			cons->char_remains_len--;
 		}
+		
 		/* Still not enough? Then get another key from the queue. */
 		if (pos < size) {
 			link_t *link = prodcons_consume(&cons->input_pc);
 			kbd_event_t *event = list_get_instance(link, kbd_event_t, link);
-
+			
 			/* Accept key presses of printable chars only. */
 			if ((event->type == KEY_PRESS) && (event->c != 0)) {
@@ -645,5 +647,5 @@
 				cons->char_remains_len = str_size(cons->char_remains);
 			}
-
+			
 			free(event);
 		}
Index: uspace/srv/hid/input/port/ns16550.c
===================================================================
--- uspace/srv/hid/input/port/ns16550.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/srv/hid/input/port/ns16550.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -84,5 +84,5 @@
 	},
 	{
-		.cmd = CMD_BTEST,
+		.cmd = CMD_AND,
 		.value = LSR_DATA_READY,
 		.srcarg = 1,
Index: uspace/srv/hid/input/port/pl050.c
===================================================================
--- uspace/srv/hid/input/port/pl050.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/srv/hid/input/port/pl050.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -80,5 +80,5 @@
 	},
 	{
-		.cmd = CMD_BTEST,
+		.cmd = CMD_AND,
 		.value = PL050_STAT_RXFULL,
 		.srcarg = 1,
Index: uspace/srv/hw/bus/cuda_adb/cuda_adb.c
===================================================================
--- uspace/srv/hw/bus/cuda_adb/cuda_adb.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/srv/hw/bus/cuda_adb/cuda_adb.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -116,9 +116,9 @@
 	{
 		.cmd = CMD_PIO_READ_8,
-		.addr = NULL,	/* will be patched in run-time */
+		.addr = NULL,
 		.dstarg = 1
 	},
 	{
-		.cmd = CMD_BTEST,
+		.cmd = CMD_AND,
 		.value = SR_INT,
 		.srcarg = 1,
Index: uspace/srv/loader/Makefile
===================================================================
--- uspace/srv/loader/Makefile	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/srv/loader/Makefile	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -44,5 +44,5 @@
 GENERIC_SOURCES = \
 	main.c \
-	interp.s
+	interp.S
 
 SOURCES = \
Index: uspace/srv/loader/interp.S
===================================================================
--- uspace/srv/loader/interp.S	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
+++ uspace/srv/loader/interp.S	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -0,0 +1,21 @@
+#
+# Provide a string to be included in a special DT_INTERP header, even though
+# this is a statically-linked executable. This will mark the binary as
+# the program loader.
+#
+
+#if ((defined(UARCH_abs32le)) && (defined(COMPILER_gcc_cross)) \
+    && (defined(CROSS_TARGET_arm32)))
+	#define ATSIGN(arg)  % ## arg
+#endif
+
+#ifdef UARCH_arm32
+	#define ATSIGN(arg)  % ## arg
+#endif
+
+#ifndef ATSIGN
+	#define ATSIGN(arg)  @ ## arg
+#endif
+
+.section .interp, "a", ATSIGN(progbits)
+	.string "kernel"
Index: pace/srv/loader/interp.s
===================================================================
--- uspace/srv/loader/interp.s	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ 	(revision )
@@ -1,7 +1,0 @@
-#
-# Provide a string to be included in a special DT_INTERP header, even though
-# this is a statically-linked executable. This will mark the binary as
-# the program loader.
-#
-.section .interp , ""
-	.string "kernel"
Index: uspace/srv/net/tcp/sock.c
===================================================================
--- uspace/srv/net/tcp/sock.c	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ uspace/srv/net/tcp/sock.c	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -779,4 +779,9 @@
 	}
 
+	/* Grab recv_buffer_lock because of CV wait in tcp_sock_recv_fibril() */
+	fibril_mutex_lock(&socket->recv_buffer_lock);
+	socket->sock_core = NULL;
+	fibril_mutex_unlock(&socket->recv_buffer_lock);
+
 	rc = socket_destroy(NULL, socket_id, &client->sockets, &gsock,
 	    tcp_free_sock_data);
@@ -839,8 +844,9 @@
 	log_msg(LVL_DEBUG, "tcp_sock_recv_fibril()");
 
+	fibril_mutex_lock(&sock->recv_buffer_lock);
+
 	while (true) {
 		log_msg(LVL_DEBUG, "call tcp_uc_receive()");
-		fibril_mutex_lock(&sock->recv_buffer_lock);
-		while (sock->recv_buffer_used != 0)
+		while (sock->recv_buffer_used != 0 && sock->sock_core != NULL)
 			fibril_condvar_wait(&sock->recv_buffer_cv,
 			    &sock->recv_buffer_lock);
@@ -852,6 +858,6 @@
 			sock->recv_error = trc;
 			fibril_condvar_broadcast(&sock->recv_buffer_cv);
-			fibril_mutex_unlock(&sock->recv_buffer_lock);
-			tcp_sock_notify_data(sock->sock_core);
+			if (sock->sock_core != NULL)
+				tcp_sock_notify_data(sock->sock_core);
 			break;
 		}
@@ -861,7 +867,9 @@
 		sock->recv_buffer_used = data_len;
 		fibril_condvar_broadcast(&sock->recv_buffer_cv);
-		fibril_mutex_unlock(&sock->recv_buffer_lock);
-		tcp_sock_notify_data(sock->sock_core);
-	}
+		if (sock->sock_core != NULL)
+			tcp_sock_notify_data(sock->sock_core);
+	}
+
+	fibril_mutex_unlock(&sock->recv_buffer_lock);
 
 	tcp_uc_delete(sock->conn);
Index: version
===================================================================
--- version	(revision f4a8734aba1f1f8923661a4d49e442f2eeb00e06)
+++ version	(revision 72cf06404efaa285aa890f576aa2963586dcc7ef)
@@ -36,6 +36,6 @@
 
 VERSION = 0
-PATCHLEVEL = 4
-SUBLEVEL = 3
+PATCHLEVEL = 5
+SUBLEVEL = 0
 
 ifdef EXTRAVERSION
@@ -45,4 +45,4 @@
 endif
 
-NAME = Sashimi
+NAME = Fajtl
 COPYRIGHT = Copyright (c) 2001-2012 HelenOS project
