Index: uspace/lib/c/arch/mips32/include/atomic.h
===================================================================
--- uspace/lib/c/arch/mips32/include/atomic.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/c/arch/mips32/include/atomic.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -70,5 +70,4 @@
 		"	sc %0, %1\n"
 		"	beq %0, %4, 1b\n"	/* if the atomic operation failed, try again */
-		/*	nop	*/		/* nop is inserted automatically by compiler */
 		"	nop\n"
 		: "=&r" (tmp),
Index: uspace/lib/c/generic/adt/measured_strings.c
===================================================================
--- uspace/lib/c/generic/adt/measured_strings.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/c/generic/adt/measured_strings.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -74,5 +74,5 @@
 	new->length = length;
 	new->value = ((uint8_t *) new) + sizeof(measured_string_t);
-	// append terminating zero explicitly - to be safe
+	/* Append terminating zero explicitly - to be safe */
 	memcpy(new->value, string, new->length);
 	new->value[new->length] = '\0';
Index: uspace/lib/c/generic/async.c
===================================================================
--- uspace/lib/c/generic/async.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/c/generic/async.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -1586,12 +1586,14 @@
  * @param dst     Address of the beginning of the destination buffer.
  * @param size    Size of the destination buffer.
+ * @param flags   Flags to control the data transfer.
  *
  * @return Zero on success or a negative error code from errno.h.
  *
  */
-int async_data_read_start(int phoneid, void *dst, size_t size)
-{
-	return async_req_2_0(phoneid, IPC_M_DATA_READ, (sysarg_t) dst,
-	    (sysarg_t) size);
+int
+async_data_read_start_generic(int phoneid, void *dst, size_t size, int flags)
+{
+	return async_req_3_0(phoneid, IPC_M_DATA_READ, (sysarg_t) dst,
+	    (sysarg_t) size, (sysarg_t) flags);
 }
 
@@ -1683,12 +1685,15 @@
  * @param src     Address of the beginning of the source buffer.
  * @param size    Size of the source buffer.
+ * @param flags   Flags to control the data transfer.
  *
  * @return Zero on success or a negative error code from errno.h.
  *
  */
-int async_data_write_start(int phoneid, const void *src, size_t size)
-{
-	return async_req_2_0(phoneid, IPC_M_DATA_WRITE, (sysarg_t) src,
-	    (sysarg_t) size);
+int
+async_data_write_start_generic(int phoneid, const void *src, size_t size,
+    int flags)
+{
+	return async_req_3_0(phoneid, IPC_M_DATA_WRITE, (sysarg_t) src,
+	    (sysarg_t) size, (sysarg_t) flags);
 }
 
Index: uspace/lib/c/generic/vfs/vfs.c
===================================================================
--- uspace/lib/c/generic/vfs/vfs.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/c/generic/vfs/vfs.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -378,5 +378,6 @@
 	
 	req = async_send_1(vfs_phone, VFS_IN_READ, fildes, &answer);
-	rc = async_data_read_start(vfs_phone, (void *)buf, nbyte);
+	rc = async_data_read_start_generic(vfs_phone, (void *) buf, nbyte,
+	    IPC_XF_RESTRICT);
 	if (rc != EOK) {
 		vfs_exchange_end(vfs_phone);
@@ -407,5 +408,6 @@
 	
 	req = async_send_1(vfs_phone, VFS_IN_WRITE, fildes, &answer);
-	rc = async_data_write_start(vfs_phone, (void *)buf, nbyte);
+	rc = async_data_write_start_generic(vfs_phone, (void *) buf, nbyte,
+	    IPC_XF_RESTRICT);
 	if (rc != EOK) {
 		vfs_exchange_end(vfs_phone);
Index: uspace/lib/c/include/async.h
===================================================================
--- uspace/lib/c/include/async.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/c/include/async.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -341,5 +341,8 @@
 
 extern aid_t async_data_read(int, void *, size_t, ipc_call_t *);
-extern int async_data_read_start(int, void *, size_t);
+#define async_data_read_start(p, buf, len) \
+	async_data_read_start_generic((p), (buf), (len), IPC_XF_NONE)
+
+extern int async_data_read_start_generic(int, void *, size_t, int);
 extern bool async_data_read_receive(ipc_callid_t *, size_t *);
 extern int async_data_read_finalize(ipc_callid_t, const void *, size_t);
@@ -380,5 +383,8 @@
 	    (arg4), (answer))
 
-extern int async_data_write_start(int, const void *, size_t);
+#define async_data_write_start(p, buf, len) \
+	async_data_write_start_generic((p), (buf), (len), IPC_XF_NONE)
+
+extern int async_data_write_start_generic(int, const void *, size_t, int);
 extern bool async_data_write_receive(ipc_callid_t *, size_t *);
 extern int async_data_write_finalize(ipc_callid_t, void *, size_t);
Index: uspace/lib/c/include/ipc/dev_iface.h
===================================================================
--- uspace/lib/c/include/ipc/dev_iface.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/c/include/ipc/dev_iface.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -45,4 +45,6 @@
 	/** Interface provided by USB host controller. */
 	USBHC_DEV_IFACE,
+	/** Interface provided by USB HID devices. */
+	USBHID_DEV_IFACE,
 
 	DEV_IFACE_MAX
Index: uspace/lib/drv/generic/dev_iface.c
===================================================================
--- uspace/lib/drv/generic/dev_iface.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/drv/generic/dev_iface.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -43,4 +43,5 @@
 #include "remote_usb.h"
 #include "remote_usbhc.h"
+#include "remote_usbhid.h"
 #include "remote_pci.h"
 
@@ -51,5 +52,6 @@
 		&remote_pci_iface,
 		&remote_usb_iface,
-		&remote_usbhc_iface
+		&remote_usbhc_iface,
+		&remote_usbhid_iface
 	}
 };
Index: uspace/lib/drv/generic/driver.c
===================================================================
--- uspace/lib/drv/generic/driver.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/drv/generic/driver.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -47,4 +47,5 @@
 #include <stdlib.h>
 #include <str.h>
+#include <str_error.h>
 #include <ctype.h>
 #include <errno.h>
@@ -402,5 +403,5 @@
 			    get_remote_method(rem_iface, iface_method_idx);
 			if (iface_method_ptr == NULL) {
-				// the interface has not such method
+				/* The interface has not such method */
 				printf("%s: driver_connection_gen error - "
 				    "invalid interface method.", driver->name);
@@ -655,4 +656,6 @@
 int ddf_driver_main(driver_t *drv)
 {
+	int rc;
+
 	/*
 	 * Remember the driver structure - driver_ops will be called by generic
@@ -668,9 +671,21 @@
 	
 	/*
-	 * Register driver by device manager with generic handler for incoming
-	 * connections.
+	 * Register driver with device manager using generic handler for
+	 * incoming connections.
 	 */
-	devman_driver_register(driver->name, driver_connection);
-	
+	rc = devman_driver_register(driver->name, driver_connection);
+	if (rc != EOK) {
+		printf("Error: Failed to register driver with device manager "
+		    "(%s).\n", (rc == EEXISTS) ? "driver already started" :
+		    str_error(rc));
+		
+		return 1;
+	}
+	
+	/* Return success from the task since server has started. */
+	rc = task_retval(0);
+	if (rc != EOK)
+		return 1;
+
 	async_manager();
 	
Index: uspace/lib/drv/generic/remote_usbhc.c
===================================================================
--- uspace/lib/drv/generic/remote_usbhc.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/drv/generic/remote_usbhc.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -50,6 +50,4 @@
 static void remote_usbhc_control_write(ddf_fun_t *, void *, ipc_callid_t, ipc_call_t *);
 static void remote_usbhc_control_read(ddf_fun_t *, void *, ipc_callid_t, ipc_call_t *);
-static void remote_usbhc_reserve_default_address(ddf_fun_t *, void *, ipc_callid_t, ipc_call_t *);
-static void remote_usbhc_release_default_address(ddf_fun_t *, void *, ipc_callid_t, ipc_call_t *);
 static void remote_usbhc_request_address(ddf_fun_t *, void *, ipc_callid_t, ipc_call_t *);
 static void remote_usbhc_bind_address(ddf_fun_t *, void *, ipc_callid_t, ipc_call_t *);
@@ -61,7 +59,4 @@
 /** Remote USB host controller interface operations. */
 static remote_iface_func_ptr_t remote_usbhc_iface_ops [] = {
-	remote_usbhc_reserve_default_address,
-	remote_usbhc_release_default_address,
-
 	remote_usbhc_request_address,
 	remote_usbhc_bind_address,
@@ -129,36 +124,4 @@
 }
 
-void remote_usbhc_reserve_default_address(ddf_fun_t *fun, void *iface,
-    ipc_callid_t callid, ipc_call_t *call)
-{
-	usbhc_iface_t *usb_iface = (usbhc_iface_t *) iface;
-
-	if (!usb_iface->reserve_default_address) {
-		async_answer_0(callid, ENOTSUP);
-		return;
-	}
-	
-	usb_speed_t speed = DEV_IPC_GET_ARG1(*call);
-	
-	int rc = usb_iface->reserve_default_address(fun, speed);
-
-	async_answer_0(callid, rc);
-}
-
-void remote_usbhc_release_default_address(ddf_fun_t *fun, void *iface,
-    ipc_callid_t callid, ipc_call_t *call)
-{
-	usbhc_iface_t *usb_iface = (usbhc_iface_t *) iface;
-
-	if (!usb_iface->release_default_address) {
-		async_answer_0(callid, ENOTSUP);
-		return;
-	}
-
-	int rc = usb_iface->release_default_address(fun);
-
-	async_answer_0(callid, rc);
-}
-
 void remote_usbhc_request_address(ddf_fun_t *fun, void *iface,
     ipc_callid_t callid, ipc_call_t *call)
@@ -270,5 +233,4 @@
 	}
 
-	size_t max_packet_size = DEV_IPC_GET_ARG3(*call);
 	usb_target_t target = {
 		.address = DEV_IPC_GET_ARG1(*call),
@@ -300,5 +262,5 @@
 	trans->size = len;
 
-	rc = transfer_func(fun, target, max_packet_size,
+	rc = transfer_func(fun, target,
 	    buffer, len,
 	    callback_out, trans);
@@ -326,5 +288,4 @@
 	}
 
-	size_t max_packet_size = DEV_IPC_GET_ARG3(*call);
 	usb_target_t target = {
 		.address = DEV_IPC_GET_ARG1(*call),
@@ -348,5 +309,5 @@
 	trans->size = len;
 
-	int rc = transfer_func(fun, target, max_packet_size,
+	int rc = transfer_func(fun, target,
 	    trans->buffer, len,
 	    callback_in, trans);
@@ -414,5 +375,4 @@
 	};
 	size_t data_buffer_len = DEV_IPC_GET_ARG3(*call);
-	size_t max_packet_size = DEV_IPC_GET_ARG4(*call);
 
 	int rc;
@@ -450,5 +410,5 @@
 	trans->size = data_buffer_len;
 
-	rc = usb_iface->control_write(fun, target, max_packet_size,
+	rc = usb_iface->control_write(fun, target,
 	    setup_packet, setup_packet_len,
 	    data_buffer, data_buffer_len,
@@ -477,5 +437,4 @@
 		.endpoint = DEV_IPC_GET_ARG2(*call)
 	};
-	size_t max_packet_size = DEV_IPC_GET_ARG3(*call);
 
 	int rc;
@@ -515,5 +474,5 @@
 	}
 
-	rc = usb_iface->control_read(fun, target, max_packet_size,
+	rc = usb_iface->control_read(fun, target,
 	    setup_packet, setup_packet_len,
 	    trans->buffer, trans->size,
@@ -537,21 +496,32 @@
 	}
 
-#define INIT_FROM_HIGH_DATA(type, var, arg_no) \
-	type var = (type) DEV_IPC_GET_ARG##arg_no(*call) / 256
-#define INIT_FROM_LOW_DATA(type, var, arg_no) \
-	type var = (type) DEV_IPC_GET_ARG##arg_no(*call) % 256
-
-	INIT_FROM_HIGH_DATA(usb_address_t, address, 1);
-	INIT_FROM_LOW_DATA(usb_endpoint_t, endpoint, 1);
-	INIT_FROM_HIGH_DATA(usb_transfer_type_t, transfer_type, 2);
-	INIT_FROM_LOW_DATA(usb_direction_t, direction, 2);
-
-#undef INIT_FROM_HIGH_DATA
-#undef INIT_FROM_LOW_DATA
-
-	size_t max_packet_size = (size_t) DEV_IPC_GET_ARG3(*call);
-	unsigned int interval  = (unsigned int) DEV_IPC_GET_ARG4(*call);
-
-	int rc = usb_iface->register_endpoint(fun, address, endpoint,
+#define _INIT_FROM_HIGH_DATA2(type, var, arg_no) \
+	type var = (type) DEV_IPC_GET_ARG##arg_no(*call) / (1 << 16)
+#define _INIT_FROM_LOW_DATA2(type, var, arg_no) \
+	type var = (type) DEV_IPC_GET_ARG##arg_no(*call) % (1 << 16)
+#define _INIT_FROM_HIGH_DATA3(type, var, arg_no) \
+	type var = (type) DEV_IPC_GET_ARG##arg_no(*call) / (1 << 16)
+#define _INIT_FROM_MIDDLE_DATA3(type, var, arg_no) \
+	type var = (type) (DEV_IPC_GET_ARG##arg_no(*call) / (1 << 8)) % (1 << 8)
+#define _INIT_FROM_LOW_DATA3(type, var, arg_no) \
+	type var = (type) DEV_IPC_GET_ARG##arg_no(*call) % (1 << 8)
+
+	_INIT_FROM_HIGH_DATA2(usb_address_t, address, 1);
+	_INIT_FROM_LOW_DATA2(usb_endpoint_t, endpoint, 1);
+
+	_INIT_FROM_HIGH_DATA3(usb_speed_t, speed, 2);
+	_INIT_FROM_MIDDLE_DATA3(usb_transfer_type_t, transfer_type, 2);
+	_INIT_FROM_LOW_DATA3(usb_direction_t, direction, 2);
+
+	_INIT_FROM_HIGH_DATA2(size_t, max_packet_size, 3);
+	_INIT_FROM_LOW_DATA2(unsigned int, interval, 3);
+
+#undef _INIT_FROM_HIGH_DATA2
+#undef _INIT_FROM_LOW_DATA2
+#undef _INIT_FROM_HIGH_DATA3
+#undef _INIT_FROM_MIDDLE_DATA3
+#undef _INIT_FROM_LOW_DATA3
+
+	int rc = usb_iface->register_endpoint(fun, address, speed, endpoint,
 	    transfer_type, direction, max_packet_size, interval);
 
Index: uspace/lib/drv/generic/remote_usbhid.c
===================================================================
--- uspace/lib/drv/generic/remote_usbhid.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
+++ uspace/lib/drv/generic/remote_usbhid.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -0,0 +1,144 @@
+/*
+ * 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 libdrv
+ * @{
+ */
+/** @file
+ */
+
+#include <async.h>
+#include <errno.h>
+#include <assert.h>
+
+#include "usbhid_iface.h"
+#include "ddf/driver.h"
+
+static void remote_usbhid_get_event_length(ddf_fun_t *, void *, ipc_callid_t, ipc_call_t *);
+static void remote_usbhid_get_event(ddf_fun_t *, void *, ipc_callid_t, ipc_call_t *);
+// static void remote_usbhid_(ddf_fun_t *, void *, ipc_callid_t, ipc_call_t *);
+
+/** Remote USB HID interface operations. */
+static remote_iface_func_ptr_t remote_usbhid_iface_ops [] = {
+	remote_usbhid_get_event_length,
+	remote_usbhid_get_event
+};
+
+/** Remote USB HID interface structure.
+ */
+remote_iface_t remote_usbhid_iface = {
+	.method_count = sizeof(remote_usbhid_iface_ops) /
+	    sizeof(remote_usbhid_iface_ops[0]),
+	.methods = remote_usbhid_iface_ops
+};
+
+usbhc_iface_t *usb_iface = (usbhc_iface_t *) iface;
+
+
+void remote_usbhid_get_event_length(ddf_fun_t *fun, void *iface,
+    ipc_callid_t callid, ipc_call_t *call)
+{
+	usbhid_iface_t *hid_iface = (usbhid_iface_t *) iface;
+
+	if (!hid_iface->get_event_length) {
+		async_answer_0(callid, ENOTSUP);
+		return;
+	}
+
+	int len = hid_iface->get_event_length(fun);
+	if (len == 0) {
+		len = EEMPTY;
+	}
+	if (len < 0) {
+		async_answer_0(callid, len);
+	} else {
+		async_answer_1(callid, EOK, len);
+	}
+}
+
+void remote_usbhid_get_event(ddf_fun_t *fun, void *iface,
+    ipc_callid_t callid, ipc_call_t *call)
+{
+	usbhid_iface_t *hid_iface = (usbhid_iface_t *) iface;
+
+	if (!hid_iface->get_event) {
+		async_answer_0(callid, ENOTSUP);
+		return;
+	}
+
+	unsigned int flags = DEV_IPC_GET_ARG1(*call);
+
+	size_t len;
+	ipc_callid_t data_callid;
+	if (!async_data_read_receive(&data_callid, &len)) {
+		async_answer_0(callid, EPARTY);
+		return;
+	}
+	/* Check that length is even number. Truncate otherwise. */
+	if ((len % 2) == 1) {
+		len--;
+	}
+	if (len == 0) {
+		async_answer_0(data_callid, EINVAL);
+		async_answer_0(callid, EINVAL);
+	}
+
+	int rc;
+
+	size_t items = len / 2;
+	uint16_t *usage_pages_and_usages = malloc(sizeof(uint16_t) * len);
+	if (usage_pages_and_usages == NULL) {
+		async_answer_0(data_callid, ENOMEM);
+		async_answer_0(callid, ENOMEM);
+	}
+
+	size_t act_items;
+	int rc = hid_iface->get_event(fun, usage_pages_and_usages,
+	    usage_pages_and_usages + items, items, &act_items, flags);
+	if (rc != EOK) {
+		free(usage_pages_and_usages);
+		async_answer_0(data_callid, rc);
+		async_answer_0(callid, rc);
+	}
+	if (act_items >= items) {
+		/* This shall not happen. */
+		// FIXME: how about an assert here?
+		act_items = items;
+	}
+
+	async_data_read_finalize(data_callid, usage_pages_and_usages,
+	    act_items * 2 * sizeof(uint16_t));
+
+	free(usage_pages_and_usages);
+
+	async_answer_0(callid, EOK);
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/drv/include/remote_usbhid.h
===================================================================
--- uspace/lib/drv/include/remote_usbhid.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
+++ uspace/lib/drv/include/remote_usbhid.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+/** @addtogroup libdrv
+ * @{
+ */
+/** @file
+ */
+
+#ifndef LIBDRV_REMOTE_USBHID_H_
+#define LIBDRV_REMOTE_USBHID_H_
+
+remote_iface_t remote_usbhid_iface;
+
+#endif
+
+/**
+ * @}
+ */
Index: uspace/lib/drv/include/usbhc_iface.h
===================================================================
--- uspace/lib/drv/include/usbhc_iface.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/drv/include/usbhc_iface.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -66,5 +66,4 @@
  *   - argument #1 is target address
  *   - argument #2 is target endpoint
- *   - argument #3 is max packet size of the endpoint
  * - this call is immediately followed by IPC data read (async version)
  * - the call is not answered until the device returns some data (or until
@@ -85,19 +84,4 @@
  */
 typedef enum {
-	/** Reserve usage of default address.
-	 * This call informs the host controller that the caller will be
-	 * using default USB address. It is duty of the HC driver to ensure
-	 * that only single entity will have it reserved.
-	 * The address is returned via IPC_M_USBHC_RELEASE_DEFAULT_ADDRESS.
-	 * The caller can start using the address after receiving EOK
-	 * answer.
-	 */
-	IPC_M_USBHC_RESERVE_DEFAULT_ADDRESS,
-
-	/** Release usage of default address.
-	 * @see IPC_M_USBHC_RESERVE_DEFAULT_ADDRESS
-	 */
-	IPC_M_USBHC_RELEASE_DEFAULT_ADDRESS,
-
 	/** Asks for address assignment by host controller.
 	 * Answer:
@@ -169,9 +153,12 @@
 	/** Register endpoint attributes at host controller.
 	 * This is used to reserve portion of USB bandwidth.
+	 * When speed is invalid, speed of the device is used.
 	 * Parameters:
-	 * - USB address + endpoint number (ADDR * 256 + EP)
-	 * - transfer type + direction (TYPE * 256 + DIR)
-	 * - maximum packet size
-	 * - interval (in milliseconds)
+	 * - USB address + endpoint number
+	 *   - packed as ADDR << 16 + EP
+	 * - speed + transfer type + direction
+	 *   - packed as ( SPEED << 8 + TYPE ) << 8 + DIR
+	 * - maximum packet size + interval (in milliseconds)
+	 *   - packed as MPS << 16 + INT
 	 * Answer:
 	 * - EOK - reservation successful
@@ -202,5 +189,5 @@
 
 /** Out transfer processing function prototype. */
-typedef int (*usbhc_iface_transfer_out_t)(ddf_fun_t *, usb_target_t, size_t,
+typedef int (*usbhc_iface_transfer_out_t)(ddf_fun_t *, usb_target_t,
     void *, size_t,
     usbhc_iface_transfer_out_callback_t, void *);
@@ -210,5 +197,5 @@
 
 /** In transfer processing function prototype. */
-typedef int (*usbhc_iface_transfer_in_t)(ddf_fun_t *, usb_target_t, size_t,
+typedef int (*usbhc_iface_transfer_in_t)(ddf_fun_t *, usb_target_t,
     void *, size_t,
     usbhc_iface_transfer_in_callback_t, void *);
@@ -222,5 +209,6 @@
 	int (*release_address)(ddf_fun_t *, usb_address_t);
 
-	int (*register_endpoint)(ddf_fun_t *, usb_address_t, usb_endpoint_t,
+	int (*register_endpoint)(ddf_fun_t *,
+	    usb_address_t, usb_speed_t, usb_endpoint_t,
 	    usb_transfer_type_t, usb_direction_t, size_t, unsigned int);
 	int (*unregister_endpoint)(ddf_fun_t *, usb_address_t, usb_endpoint_t,
@@ -234,10 +222,8 @@
 
 	int (*control_write)(ddf_fun_t *, usb_target_t,
-	    size_t,
 	    void *, size_t, void *, size_t,
 	    usbhc_iface_transfer_out_callback_t, void *);
 
 	int (*control_read)(ddf_fun_t *, usb_target_t,
-	    size_t,
 	    void *, size_t, void *, size_t,
 	    usbhc_iface_transfer_in_callback_t, void *);
Index: uspace/lib/drv/include/usbhid_iface.h
===================================================================
--- uspace/lib/drv/include/usbhid_iface.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
+++ uspace/lib/drv/include/usbhid_iface.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2010 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 libdrv
+ * @{
+ */
+/** @file
+ * USB HID interface definition.
+ */
+
+#ifndef LIBDRV_USBHID_IFACE_H_
+#define LIBDRV_USBHID_IFACE_H_
+
+#include "ddf/driver.h"
+#include <usb/usb.h>
+
+/** IPC methods for USB HID device interface. */
+typedef enum {
+	/** Get number of events reported in single burst.
+	 * Parameters: none
+	 * Answer:
+	 * - EOK (expected always as long as device support USB HID interface)
+	 * Parameters of the answer:
+	 * - number of items
+	 */
+	IPC_M_USBHID_GET_EVENT_LENGTH,
+	/** Get single event from the HID device.
+	 * The word single refers to set of individual events that were
+	 * available at particular point in time.
+	 * Parameters:
+	 * - flags
+	 * The call is followed by data read expecting two concatenated
+	 * arrays.
+	 * Answer:
+	 * - EOK - events returned
+	 * - EAGAIN - no event ready (only in non-blocking mode)
+	 *
+	 * It is okay if the client requests less data. Extra data must
+	 * be truncated by the driver.
+	 */
+	IPC_M_USBHID_GET_EVENT
+} usbhid_iface_funcs_t;
+
+/** USB HID interface flag - return immediately if no data are available. */
+#define USBHID_IFACE_FLAG_NON_BLOCKING (1 << 0)
+
+/** USB HID device communication interface. */
+typedef struct {
+	/** Get number of items in the event.
+	 *
+	 * @param[in] fun DDF function answering the request.
+	 * @return Number of events or error code.
+	 */
+	int (*get_event_length)(ddf_fun_t *fun);
+
+	/** Get single event from the HID device.
+	 *
+	 * @param[in] fun DDF function answering the request.
+	 * @param[out] usage_page Array of usage pages and usages.
+	 * @param[out] usage Array of data (1:1 with @p usage).
+	 * @param[in] size Size of @p usage and @p data arrays.
+	 * @param[out] act_size Actual number of returned events.
+	 * @param[in] flags Flags (see USBHID_IFACE_FLAG_*).
+	 * @return Error code.
+	 */
+	int (*get_event)(ddf_fun_t *fun,
+	    uint16_t *usage_page, uint16_t *usage, size_t size, size_t *act_size,
+	    unsigned int flags);
+} usbhid_iface_t;
+
+
+#endif
+/**
+ * @}
+ */
Index: uspace/lib/net/generic/generic.c
===================================================================
--- uspace/lib/net/generic/generic.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/net/generic/generic.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -106,5 +106,5 @@
 		return EBADMEM;
 
-	// request the address
+	/* Request the address */
 	message_id = async_send_1(phone, (sysarg_t) message,
 	    (sysarg_t) device_id, NULL);
@@ -112,7 +112,7 @@
 	async_wait_for(message_id, &result);
 
-	// if not successful
+	/* If not successful */
 	if ((string == EOK) && (result != EOK)) {
-		// clear the data
+		/* Clear the data */
 		free(*address);
 		free(*data);
@@ -242,5 +242,5 @@
 		return EBADMEM;
 
-	// request the translation
+	/* Request the translation */
 	message_id = async_send_3(phone, (sysarg_t) message,
 	    (sysarg_t) device_id, (sysarg_t) count, (sysarg_t) service, NULL);
@@ -249,7 +249,7 @@
 	async_wait_for(message_id, &result);
 
-	// if not successful
+	/* If not successful */
 	if ((string == EOK) && (result != EOK)) {
-		// clear the data
+		/* Clear the data */
 		free(*translation);
 		free(*data);
Index: uspace/lib/net/generic/net_checksum.c
===================================================================
--- uspace/lib/net/generic/net_checksum.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/net/generic/net_checksum.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -52,5 +52,5 @@
 uint16_t compact_checksum(uint32_t sum)
 {
-	// shorten to the 16 bits
+	/* Shorten to the 16 bits */
 	while (sum >> 16)
 		sum = (sum & 0xffff) + (sum >> 16);
@@ -72,9 +72,9 @@
 	size_t index;
 
-	// sum all the 16 bit fields
+	/* Sum all the 16 bit fields */
 	for (index = 0; index + 1 < length; index += 2)
 		seed += (data[index] << 8) + data[index + 1];
 
-	// last odd byte with zero padding
+	/* Last odd byte with zero padding */
 	if (index + 1 == length)
 		seed += data[index] << 8;
@@ -94,39 +94,39 @@
 	size_t index;
 
-	// process full bytes
+	/* Process full bytes */
 	while (length >= 8) {
-		// add the data
+		/* Add the data */
 		seed ^= (*data) << 24;
 		
-		// for each added bit
+		/* For each added bit */
 		for (index = 0; index < 8; ++index) {
-			// if the first bit is set
+			/* If the first bit is set */
 			if (seed & 0x80000000) {
-				// shift and divide the checksum
+				/* Shift and divide the checksum */
 				seed = (seed << 1) ^ ((uint32_t) CRC_DIVIDER_BE);
 			} else {
-				// shift otherwise
+				/* Shift otherwise */
 				seed <<= 1;
 			}
 		}
 		
-		// move to the next byte
+		/* Move to the next byte */
 		++data;
 		length -= 8;
 	}
 
-	// process the odd bits
+	/* Process the odd bits */
 	if (length > 0) {
-		// add the data with zero padding
+		/* Add the data with zero padding */
 		seed ^= ((*data) & (0xff << (8 - length))) << 24;
 		
-		// for each added bit
+		/* For each added bit */
 		for (index = 0; index < length; ++index) {
-			// if the first bit is set
+			/* If the first bit is set */
 			if (seed & 0x80000000) {
-				// shift and divide the checksum
+				/* Shift and divide the checksum */
 				seed = (seed << 1) ^ ((uint32_t) CRC_DIVIDER_BE);
 			} else {
-				// shift otherwise
+				/* Shift otherwise */
 				seed <<= 1;
 			}
@@ -148,38 +148,38 @@
 	size_t index;
 
-	// process full bytes
+	/* Process full bytes */
 	while (length >= 8) {
-		// add the data
+		/* Add the data */
 		seed ^= (*data);
 		
-		// for each added bit
+		/* For each added bit */
 		for (index = 0; index < 8; ++index) {
-			// if the last bit is set
+			/* If the last bit is set */
 			if (seed & 1) {
-				// shift and divide the checksum
+				/* Shift and divide the checksum */
 				seed = (seed >> 1) ^ ((uint32_t) CRC_DIVIDER_LE);
 			} else {
-				// shift otherwise
+				/* Shift otherwise */
 				seed >>= 1;
 			}
 		}
 		
-		// move to the next byte
+		/* Move to the next byte */
 		++data;
 		length -= 8;
 	}
 
-	// process the odd bits
+	/* Process the odd bits */
 	if (length > 0) {
-		// add the data with zero padding
+		/* Add the data with zero padding */
 		seed ^= (*data) >> (8 - length);
 		
 		for (index = 0; index < length; ++index) {
-			// if the last bit is set
+			/* If the last bit is set */
 			if (seed & 1) {
-				// shift and divide the checksum
+				/* Shift and divide the checksum */
 				seed = (seed >> 1) ^ ((uint32_t) CRC_DIVIDER_LE);
 			} else {
-				// shift otherwise
+				/* Shift otherwise */
 				seed >>= 1;
 			}
@@ -198,5 +198,5 @@
 uint16_t flip_checksum(uint16_t checksum)
 {
-	// flip, zero is returned as 0xFFFF (not flipped)
+	/* Flip, zero is returned as 0xFFFF (not flipped) */
 	checksum = ~checksum;
 	return checksum ? checksum : IP_CHECKSUM_ZERO;
@@ -216,5 +216,5 @@
 uint16_t ip_checksum(uint8_t *data, size_t length)
 {
-	// compute, compact and flip the data checksum
+	/* Compute, compact and flip the data checksum */
 	return flip_checksum(compact_checksum(compute_checksum(0, data,
 	    length)));
Index: uspace/lib/net/generic/packet_client.c
===================================================================
--- uspace/lib/net/generic/packet_client.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/net/generic/packet_client.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -267,5 +267,5 @@
 		return NULL;
 
-	// get a new packet
+	/* Get a new packet */
 	copy = packet_get_4_remote(phone, PACKET_DATA_LENGTH(packet),
 	    PACKET_MAX_ADDRESS_LENGTH(packet), packet->max_prefix,
@@ -274,10 +274,10 @@
 		return NULL;
 
-	// get addresses
+	/* Get addresses */
 	addrlen = packet_get_addr(packet, &src, &dest);
-	// copy data
+	/* Copy data */
 	if ((packet_copy_data(copy, packet_get_data(packet),
 	    PACKET_DATA_LENGTH(packet)) == EOK) &&
-	    // copy addresses if present
+	    /* Copy addresses if present */
 	    ((addrlen <= 0) ||
 	    (packet_set_addr(copy, src, dest, addrlen) == EOK))) {
Index: uspace/lib/net/il/ip_client.c
===================================================================
--- uspace/lib/net/il/ip_client.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/net/il/ip_client.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -124,5 +124,6 @@
 
 	// TODO IPv6
-/*	case AF_INET6:
+#if 0
+	case AF_INET6:
 		if (addrlen != sizeof(struct sockaddr_in6))
 			return EINVAL;
@@ -130,5 +131,5 @@
 		address_in6 = (struct sockaddr_in6 *) addr;
 		return EOK;
-*/
+#endif
 
 	default:
@@ -159,6 +160,8 @@
 	size_t padding;
 
-	// compute the padding if IP options are set
-	// multiple of 4 bytes
+	/*
+	 * Compute the padding if IP options are set
+	 * multiple of 4 bytes
+	 */
 	padding =  ipopt_length % 4;
 	if (padding) {
@@ -167,14 +170,14 @@
 	}
 
-	// prefix the header
+	/* Prefix the header */
 	data = (uint8_t *) packet_prefix(packet, sizeof(ip_header_t) + padding);
 	if (!data)
 		return ENOMEM;
 
-	// add the padding
+	/* Add the padding */
 	while (padding--)
 		data[sizeof(ip_header_t) + padding] = IPOPT_NOOP;
 
-	// set the header
+	/* Set the header */
 	header = (ip_header_t *) data;
 	header->header_length = IP_COMPUTE_HEADER_LENGTH(sizeof(ip_header_t) +
Index: uspace/lib/net/tl/icmp_client.c
===================================================================
--- uspace/lib/net/tl/icmp_client.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/net/tl/icmp_client.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -81,5 +81,5 @@
 		*mtu = header->un.frag.mtu;
 
-	// remove debug dump
+	/* Remove debug dump */
 #ifdef CONFIG_DEBUG
 	printf("ICMP error %d (%d) in packet %d\n", header->type, header->code,
Index: uspace/lib/net/tl/socket_core.c
===================================================================
--- uspace/lib/net/tl/socket_core.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/net/tl/socket_core.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -91,11 +91,11 @@
 	int packet_id;
 
-	// if bound
+	/* If bound */
 	if (socket->port) {
-		// release the port
+		/* Release the port */
 		socket_port_release(global_sockets, socket);
 	}
 	
-	// release all received packets
+	/* Release all received packets */
 	while ((packet_id = dyn_fifo_pop(&socket->received)) >= 0)
 		pq_release_remote(packet_phone, packet_id);
@@ -166,5 +166,5 @@
 	int rc;
 
-	// create a wrapper
+	/* Create a wrapper */
 	socket_ref = malloc(sizeof(*socket_ref));
 	if (!socket_ref)
@@ -172,5 +172,5 @@
 
 	*socket_ref = socket;
-	// add the wrapper
+	/* Add the wrapper */
 	rc = socket_port_map_add(&socket_port->map, key, key_length,
 	    socket_ref);
@@ -206,5 +206,5 @@
 	int rc;
 
-	// create a wrapper
+	/* Create a wrapper */
 	socket_port = malloc(sizeof(*socket_port));
 	if (!socket_port)
@@ -221,5 +221,5 @@
 		goto fail;
 	
-	// register the incomming port
+	/* Register the incoming port */
 	rc = socket_ports_add(global_sockets, port, socket_port);
 	if (rc < 0)
@@ -277,25 +277,25 @@
 		
 		address_in = (struct sockaddr_in *) addr;
-		// find the socket
+		/* Find the socket */
 		socket = socket_cores_find(local_sockets, socket_id);
 		if (!socket)
 			return ENOTSOCK;
 		
-		// bind a free port?
+		/* Bind a free port? */
 		if (address_in->sin_port <= 0)
 			return socket_bind_free_port(global_sockets, socket,
 			     free_ports_start, free_ports_end, last_used_port);
 		
-		// try to find the port
+		/* Try to find the port */
 		socket_port = socket_ports_find(global_sockets,
 		    ntohs(address_in->sin_port));
 		if (socket_port) {
-			// already used
+			/* Already used */
 			return EADDRINUSE;
 		}
 		
-		// if bound
+		/* If bound */
 		if (socket->port) {
-			// release the port
+			/* Release the port */
 			socket_port_release(global_sockets, socket);
 		}
@@ -333,5 +333,5 @@
 	int index;
 
-	// from the last used one
+	/* From the last used one */
 	index = last_used_port;
 	
@@ -339,18 +339,18 @@
 		++index;
 		
-		// til the range end
+		/* Till the range end */
 		if (index >= free_ports_end) {
-			// start from the range beginning
+			/* Start from the range beginning */
 			index = free_ports_start - 1;
 			do {
 				++index;
-				// til the last used one
+				/* Till the last used one */
 				if (index >= last_used_port) {
-					// none found
+					/* None found */
 					return ENOTCONN;
 				}
 			} while (socket_ports_find(global_sockets, index));
 			
-			// found, break immediately
+			/* Found, break immediately */
 			break;
 		}
@@ -376,5 +376,7 @@
 
 	count = 0;
-//	socket_id = socket_globals.last_id;
+#if 0
+	socket_id = socket_globals.last_id;
+#endif
 	do {
 		if (count < SOCKET_ID_TRIES) {
@@ -384,12 +386,14 @@
 			socket_id = 1;
 			++count;
-		// only this branch for last_id
+		/* Only this branch for last_id */
 		} else {
 			if (socket_id < INT_MAX) {
 				++ socket_id;
-/*			} else if(socket_globals.last_id) {
-*				socket_globals.last_id = 0;
-*				socket_id = 1;
-*/			} else {
+#if 0
+			} else if(socket_globals.last_id) {
+				socket_globals.last_id = 0;
+				socket_id = 1;
+#endif
+			} else {
 				return ELIMIT;
 			}
@@ -425,5 +429,5 @@
 		return EINVAL;
 	
-	// store the socket
+	/* Store the socket */
 	if (*socket_id <= 0) {
 		positive = (*socket_id == 0);
@@ -441,5 +445,5 @@
 		return ENOMEM;
 	
-	// initialize
+	/* Initialize */
 	socket->phone = app_phone;
 	socket->port = -1;
@@ -493,10 +497,10 @@
 	int accepted_id;
 
-	// find the socket
+	/* Find the socket */
 	socket = socket_cores_find(local_sockets, socket_id);
 	if (!socket)
 		return ENOTSOCK;
 	
-	// destroy all accepted sockets
+	/* Destroy all accepted sockets */
 	while ((accepted_id = dyn_fifo_pop(&socket->accepted)) >= 0)
 		socket_destroy(packet_phone, accepted_id, local_sockets,
@@ -535,13 +539,13 @@
 	next_packet = pq_next(packet);
 	if (!next_packet) {
-		// write all if only one fragment
+		/* Write all if only one fragment */
 		rc = data_reply(packet_get_data(packet),
 		    packet_get_data_length(packet));
 		if (rc != EOK)
 			return rc;
-		// store the total length
+		/* Store the total length */
 		*length = packet_get_data_length(packet);
 	} else {
-		// count the packet fragments
+		/* Count the packet fragments */
 		fragments = 1;
 		next_packet = pq_next(packet);
@@ -549,5 +553,5 @@
 			++fragments;
 		
-		// compute and store the fragment lengths
+		/* Compute and store the fragment lengths */
 		lengths = (size_t *) malloc(sizeof(size_t) * fragments +
 		    sizeof(size_t));
@@ -565,5 +569,5 @@
 		}
 		
-		// write the fragment lengths
+		/* Write the fragment lengths */
 		rc = data_reply(lengths, sizeof(int) * (fragments + 1));
 		if (rc != EOK) {
@@ -573,5 +577,5 @@
 		next_packet = packet;
 		
-		// write the fragments
+		/* Write the fragments */
 		for (index = 0; index < fragments; ++index) {
 			rc = data_reply(packet_get_data(next_packet),
@@ -584,5 +588,5 @@
 		}
 		
-		// store the total length
+		/* Store the total length */
 		*length = lengths[fragments];
 		free(lengths);
@@ -636,8 +640,8 @@
 		return;
 	
-	// find ports
+	/* Find ports */
 	socket_port = socket_ports_find(global_sockets, socket->port);
 	if (socket_port) {
-		// find the socket
+		/* Find the socket */
 		socket_ref = socket_port_map_find(&socket_port->map,
 		    socket->key, socket->key_length);
@@ -646,13 +650,13 @@
 			--socket_port->count;
 			
-			// release if empty
+			/* Release if empty */
 			if (socket_port->count <= 0) {
-				// destroy the map
+				/* Destroy the map */
 				socket_port_map_destroy(&socket_port->map, free);
-				// release the port
+				/* Release the port */
 				socket_ports_exclude(global_sockets,
 				    socket->port, free);
 			} else {
-				// remove
+				/* Remove */
 				socket_port_map_exclude(&socket_port->map,
 				    socket->key, socket->key_length, free);
@@ -685,10 +689,10 @@
 	int rc;
 
-	// find ports
+	/* Find ports */
 	socket_port = socket_ports_find(global_sockets, port);
 	if (!socket_port)
 		return ENOENT;
 	
-	// add the socket
+	/* Add the socket */
 	rc = socket_port_add_core(socket_port, socket, key, key_length);
 	if (rc != EOK)
Index: uspace/lib/net/tl/tl_common.c
===================================================================
--- uspace/lib/net/tl/tl_common.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/net/tl/tl_common.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -255,5 +255,5 @@
 	int length;
 
-	// detach the first packet and release the others
+	/* Detach the first packet and release the others */
 	next = pq_detach(packet);
 	if (next)
@@ -262,6 +262,8 @@
 	length = packet_get_addr(packet, &src, NULL);
 	if ((length > 0) && (!error) && (icmp_phone >= 0) &&
-	    // set both addresses to the source one (avoids the source address
-	    // deletion before setting the destination one)
+	    /*
+	     * Set both addresses to the source one (avoids the source address
+	     * deletion before setting the destination one)
+	     */
 	    (packet_set_addr(packet, src, src, (size_t) length) == EOK)) {
 		return EOK;
@@ -299,9 +301,9 @@
 		return EINVAL;
 
-	// get the data length
+	/* Get the data length */
 	if (!async_data_write_receive(&callid, &length))
 		return EINVAL;
 
-	// get a new packet
+	/* Get a new packet */
 	*packet = packet_get_4_remote(packet_phone, length, dimension->addr_len,
 	    prefix + dimension->prefix, dimension->suffix);
@@ -309,5 +311,5 @@
 		return ENOMEM;
 
-	// allocate space in the packet
+	/* Allocate space in the packet */
 	data = packet_suffix(*packet, length);
 	if (!data) {
@@ -316,5 +318,5 @@
 	}
 
-	// read the data into the packet
+	/* Read the data into the packet */
 	rc = async_data_write_finalize(callid, data, length);
 	if (rc != EOK) {
@@ -323,5 +325,5 @@
 	}
 	
-	// set the packet destination address
+	/* Set the packet destination address */
 	rc = packet_set_addr(*packet, NULL, (uint8_t *) addr, addrlen);
 	if (rc != EOK) {
Index: uspace/lib/packet/generic/packet_server.c
===================================================================
--- uspace/lib/packet/generic/packet_server.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/packet/generic/packet_server.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -112,9 +112,9 @@
     size_t max_content, size_t max_suffix)
 {
-	// clear the packet content
+	/* Clear the packet content */
 	bzero(((void *) packet) + sizeof(packet_t),
 	    packet->length - sizeof(packet_t));
 	
-	// clear the packet header
+	/* Clear the packet header */
 	packet->order = 0;
 	packet->metric = 0;
@@ -151,5 +151,5 @@
 	assert(fibril_mutex_is_locked(&ps_globals.lock));
 
-	// already locked
+	/* Already locked */
 	packet = (packet_t *) mmap(NULL, length, PROTO_READ | PROTO_WRITE,
 	    MAP_SHARED | MAP_ANONYMOUS, 0, 0);
Index: uspace/lib/softint/generic/multiplication.c
===================================================================
--- uspace/lib/softint/generic/multiplication.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/softint/generic/multiplication.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -109,5 +109,5 @@
 	 * result does not fit in signed one */
 	if (SOFTINT_CHECK_OF && ((t2 < t1) || (t2 & (1ull << 63)))) {
-		// error, overflow
+		/* Error, overflow */
 		return (neg ? INT64_MIN : INT64_MAX);
 	}
Index: uspace/lib/usb/Makefile
===================================================================
--- uspace/lib/usb/Makefile	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/Makefile	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -34,4 +34,5 @@
 SOURCES = \
 	src/addrkeep.c \
+	src/altiface.c \
 	src/class.c \
 	src/ddfiface.c \
@@ -41,6 +42,8 @@
 	src/dp.c \
 	src/dump.c \
+	src/hidiface.c \
 	src/hidparser.c \
 	src/hub.c \
+	src/pipepriv.c \
 	src/pipes.c \
 	src/pipesinit.c \
Index: uspace/lib/usb/include/usb/classes/hid/iface.h
===================================================================
--- uspace/lib/usb/include/usb/classes/hid/iface.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
+++ uspace/lib/usb/include/usb/classes/hid/iface.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+/** @addtogroup libusb
+ * @{
+ */
+/** @file
+ * Client functions for accessing USB HID interface.
+ */
+#ifndef LIBUSB_CLASSES_HID_IFACE_H_
+#define LIBUSB_CLASSES_HID_IFACE_H_
+
+#include <sys/types.h>
+
+int usbhid_dev_get_event_length(int);
+int usbhid_dev_get_event(int, uint16_t *, uint16_t *, size_t, size_t *,
+    unsigned int);
+
+#endif
+/**
+ * @}
+ */
Index: uspace/lib/usb/include/usb/classes/hidparser.h
===================================================================
--- uspace/lib/usb/include/usb/classes/hidparser.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/classes/hidparser.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -317,4 +317,5 @@
 usb_hid_report_path_t *usb_hid_report_path_clone(usb_hid_report_path_t *usage_path);
 
+usb_hid_report_field_t *usb_hid_report_get_sibling(usb_hid_report_t *report, usb_hid_report_field_t *field, usb_hid_report_path_t *path, int flags, usb_hid_report_type_t type);
 
 /*
Index: uspace/lib/usb/include/usb/classes/hub.h
===================================================================
--- uspace/lib/usb/include/usb/classes/hub.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/classes/hub.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -43,4 +43,6 @@
  */
 typedef enum {
+	USB_HUB_FEATURE_HUB_LOCAL_POWER = 0,
+	USB_HUB_FEATURE_HUB_OVER_CURRENT = 1,
 	USB_HUB_FEATURE_C_HUB_LOCAL_POWER = 0,
 	USB_HUB_FEATURE_C_HUB_OVER_CURRENT = 1,
@@ -59,4 +61,5 @@
 	/* USB_HUB_FEATURE_ = , */
 } usb_hub_class_feature_t;
+
 
 /** Header of standard hub descriptor without the "variadic" part. */
@@ -149,5 +152,5 @@
             maximum of 255 ports).
      */
-    uint8_t * devices_removable;
+    uint8_t devices_removable[32];
 
     /**
Index: uspace/lib/usb/include/usb/classes/massstor.h
===================================================================
--- uspace/lib/usb/include/usb/classes/massstor.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
+++ uspace/lib/usb/include/usb/classes/massstor.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+
+/** @addtogroup libusb
+ * @{
+ */
+/** @file
+ * USB mass storage related functions and constants.
+ */
+#ifndef LIBUSB_CLASS_MASSSTOR_H_
+#define LIBUSB_CLASS_MASSSTOR_H_
+
+#include <sys/types.h>
+
+/** USB mass storage subclasses. */
+typedef enum {
+	USB_MASSSTOR_SUBCLASS_RBC = 0x01,
+	/** Also known as MMC-5. */
+	USB_MASSSTOR_SUBCLASS_ATAPI = 0x02,
+	USB_MASSSTOR_SUBCLASS_UFI = 0x04,
+	USB_MASSSTOR_SUBCLASS_SCSI = 0x06,
+	USB_MASSSTOR_SUBCLASS_LSDFS = 0x07,
+	USB_MASSSTOR_SUBCLASS_IEEE1667 = 0x08,
+	USB_MASSSTOR_SUBCLASS_VENDOR = 0xFF
+} usb_massstor_subclass_t;
+
+/** USB mass storage interface protocols. */
+typedef enum {
+	/** CBI transport with command completion interrupt. */
+	USB_MASSSTOR_PROTOCOL_CBI_CC = 0x00,
+	/** CBI transport with no command completion interrupt. */
+	USB_MASSSTOR_PROTOCOL_CBI = 0x01,
+	/** Bulk only transport. */
+	USB_MASSSTOR_PROTOCOL_BBB = 0x50,
+	/** USB attached SCSI. */
+	USB_MASSSTOR_PROTOCOL_UAS = 0x62,
+	USB_MASSSTOR_PROTOCOL_VENDOR = 0xFF
+} usb_massstor_protocol_t;
+
+#endif
+/**
+ * @}
+ */
Index: uspace/lib/usb/include/usb/devdrv.h
===================================================================
--- uspace/lib/usb/include/usb/devdrv.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/devdrv.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -162,10 +162,14 @@
     usb_endpoint_description_t **);
 
-typedef bool (*usb_polling_callback_t)(usb_device_t *,
-    uint8_t *, size_t, void *);
-typedef void (*usb_polling_terminted_callback_t)(usb_device_t *, bool, void *);
+int usb_device_retrieve_descriptors(usb_pipe_t *, usb_device_descriptors_t *);
+int usb_device_create_pipes(ddf_dev_t *, usb_device_connection_t *,
+    usb_endpoint_description_t **, uint8_t *, size_t, int, int,
+    usb_endpoint_mapping_t **, size_t *);
+int usb_device_destroy_pipes(ddf_dev_t *, usb_endpoint_mapping_t *, size_t);
+int usb_device_create(ddf_dev_t *, usb_endpoint_description_t **, usb_device_t **, const char **);
 
-int usb_device_auto_poll(usb_device_t *, size_t,
-    usb_polling_callback_t, size_t, usb_polling_terminted_callback_t, void *);
+size_t usb_interface_count_alternates(uint8_t *, size_t, uint8_t);
+int usb_alternate_interfaces_create(uint8_t *, size_t, int,
+    usb_alternate_interfaces_t **);
 
 #endif
Index: uspace/lib/usb/include/usb/devpoll.h
===================================================================
--- uspace/lib/usb/include/usb/devpoll.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
+++ uspace/lib/usb/include/usb/devpoll.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -0,0 +1,99 @@
+/*
+ * 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.
+ */
+
+/** @addtogroup libusb
+ * @{
+ */
+/** @file
+ * USB device polling functions.
+ */
+#ifndef LIBUSB_DEVPOLL_H_
+#define LIBUSB_DEVPOLL_H_
+
+#include <usb/devdrv.h>
+#include <time.h>
+
+typedef struct {
+	/** Level of debugging messages from auto polling.
+	 * 0 - nothing
+	 * 1 - inform about errors and polling start/end
+	 * 2 - also dump every retrieved buffer
+	 */
+	int debug;
+	/** Maximum number of consecutive errors before polling termination. */
+	size_t max_failures;
+	/** Delay between poll requests in milliseconds.
+	 * Set to negative value to use value from endpoint descriptor.
+	 */
+	int delay;
+	/** Whether to automatically try to clear the HALT feature after
+	 * the endpoint stalls.
+	 */
+	bool auto_clear_halt;
+	/** Callback when data arrives.
+	 *
+	 * @param dev Device that was polled.
+	 * @param data Data buffer (in USB endianness).
+	 * @param data_size Size of the @p data buffer in bytes.
+	 * @param arg Custom argument.
+	 * @return Whether to continue in polling.
+	 */
+	bool (*on_data)(usb_device_t *dev, uint8_t *data, size_t data_size,
+	    void *arg);
+	/** Callback when polling is terminated.
+	 *
+	 * @param dev Device where the polling was terminated.
+	 * @param due_to_errors Whether polling stopped due to several failures.
+	 * @param arg Custom argument.
+	 */
+	void (*on_polling_end)(usb_device_t *dev, bool due_to_errors,
+	    void *arg);
+	/** Callback when error occurs.
+	 *
+	 * @param dev Device where error occurred.
+	 * @param err_code Error code (as returned from usb_pipe_read).
+	 * @param arg Custom argument.
+	 * @return Whether to continue in polling.
+	 */
+	bool (*on_error)(usb_device_t *dev, int err_code, void *arg);
+} usb_device_auto_polling_t;
+
+int usb_device_auto_polling(usb_device_t *, size_t, usb_device_auto_polling_t *,
+    size_t, void *);
+
+typedef bool (*usb_polling_callback_t)(usb_device_t *,
+    uint8_t *, size_t, void *);
+typedef void (*usb_polling_terminted_callback_t)(usb_device_t *, bool, void *);
+
+int usb_device_auto_poll(usb_device_t *, size_t,
+    usb_polling_callback_t, size_t, usb_polling_terminted_callback_t, void *);
+
+#endif
+/**
+ * @}
+ */
Index: uspace/lib/usb/include/usb/host/batch.h
===================================================================
--- uspace/lib/usb/include/usb/host/batch.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/host/batch.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -43,34 +43,27 @@
 typedef struct usb_transfer_batch usb_transfer_batch_t;
 struct usb_transfer_batch {
+	endpoint_t *ep;
 	link_t link;
-	usb_target_t target;
-	usb_transfer_type_t transfer_type;
-	usb_speed_t speed;
-	usb_direction_t direction;
 	usbhc_iface_transfer_in_callback_t callback_in;
 	usbhc_iface_transfer_out_callback_t callback_out;
+	void *arg;
 	char *buffer;
-	char *transport_buffer;
+	char *data_buffer;
 	size_t buffer_size;
 	char *setup_buffer;
 	size_t setup_size;
-	size_t max_packet_size;
 	size_t transfered_size;
 	void (*next_step)(usb_transfer_batch_t *);
 	int error;
 	ddf_fun_t *fun;
-	void *arg;
-	endpoint_t *ep;
 	void *private_data;
+	void (*private_data_dtor)(void *p_data);
 };
 
 void usb_transfer_batch_init(
     usb_transfer_batch_t *instance,
-    usb_target_t target,
-    usb_transfer_type_t transfer_type,
-    usb_speed_t speed,
-    size_t max_packet_size,
+    endpoint_t *ep,
     char *buffer,
-    char *transport_buffer,
+    char *data_buffer,
     size_t buffer_size,
     char *setup_buffer,
@@ -80,7 +73,20 @@
     void *arg,
     ddf_fun_t *fun,
-		endpoint_t *ep,
-    void *private_data
+    void *private_data,
+    void (*private_data_dtor)(void *p_data)
 );
+
+void usb_transfer_batch_call_in_and_dispose(usb_transfer_batch_t *instance);
+void usb_transfer_batch_call_out_and_dispose(usb_transfer_batch_t *instance);
+void usb_transfer_batch_finish(usb_transfer_batch_t *instance);
+void usb_transfer_batch_dispose(usb_transfer_batch_t *instance);
+
+static inline void usb_transfer_batch_finish_error(
+    usb_transfer_batch_t *instance, int error)
+{
+	assert(instance);
+	instance->error = error;
+	usb_transfer_batch_finish(instance);
+}
 
 static inline usb_transfer_batch_t *usb_transfer_batch_from_link(link_t *l)
@@ -90,8 +96,4 @@
 }
 
-void usb_transfer_batch_call_in(usb_transfer_batch_t *instance);
-void usb_transfer_batch_call_out(usb_transfer_batch_t *instance);
-void usb_transfer_batch_finish(usb_transfer_batch_t *instance, int error);
-
 #endif
 /**
Index: uspace/lib/usb/include/usb/host/device_keeper.h
===================================================================
--- uspace/lib/usb/include/usb/host/device_keeper.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/host/device_keeper.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -54,6 +54,4 @@
 	usb_speed_t speed;
 	bool occupied;
-	link_t endpoints;
-	uint16_t control_used;
 	devman_handle_t handle;
 };
@@ -65,20 +63,8 @@
 	struct usb_device_info devices[USB_ADDRESS_COUNT];
 	fibril_mutex_t guard;
-	fibril_condvar_t change;
 	usb_address_t last_address;
 } usb_device_keeper_t;
 
 void usb_device_keeper_init(usb_device_keeper_t *instance);
-
-void usb_device_keeper_add_ep(
-    usb_device_keeper_t *instance, usb_address_t address, endpoint_t *ep);
-
-void usb_device_keeper_reserve_default_address(
-    usb_device_keeper_t *instance, usb_speed_t speed);
-
-void usb_device_keeper_release_default_address(usb_device_keeper_t *instance);
-
-void usb_device_keeper_reset_if_need(usb_device_keeper_t *instance,
-    usb_target_t target, const uint8_t *setup_data);
 
 usb_address_t device_keeper_get_free_address(usb_device_keeper_t *instance,
@@ -96,11 +82,4 @@
 usb_speed_t usb_device_keeper_get_speed(usb_device_keeper_t *instance,
     usb_address_t address);
-
-void usb_device_keeper_use_control(usb_device_keeper_t *instance,
-    usb_target_t target);
-
-void usb_device_keeper_release_control(usb_device_keeper_t *instance,
-    usb_target_t target);
-
 #endif
 /**
Index: uspace/lib/usb/include/usb/host/endpoint.h
===================================================================
--- uspace/lib/usb/include/usb/host/endpoint.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/host/endpoint.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -39,4 +39,6 @@
 #include <bool.h>
 #include <adt/list.h>
+#include <fibril_synch.h>
+
 #include <usb/usb.h>
 
@@ -48,7 +50,13 @@
 	usb_speed_t speed;
 	size_t max_packet_size;
-	bool active;
 	unsigned toggle:1;
-	link_t same_device_eps;
+	fibril_mutex_t guard;
+	fibril_condvar_t avail;
+	volatile bool active;
+	struct {
+		void *data;
+		int (*toggle_get)(void *);
+		void (*toggle_set)(void *, int);
+	} hc_data;
 } endpoint_t;
 
@@ -59,12 +67,18 @@
 void endpoint_destroy(endpoint_t *instance);
 
+void endpoint_set_hc_data(endpoint_t *instance,
+    void *data, int (*toggle_get)(void *), void (*toggle_set)(void *, int));
+
+void endpoint_clear_hc_data(endpoint_t *instance);
+
+void endpoint_use(endpoint_t *instance);
+
+void endpoint_release(endpoint_t *instance);
+
 int endpoint_toggle_get(endpoint_t *instance);
 
 void endpoint_toggle_set(endpoint_t *instance, int toggle);
 
-void endpoint_toggle_reset(link_t *ep);
-
-void endpoint_toggle_reset_filtered(link_t *ep, usb_endpoint_t epn);
-
+void endpoint_toggle_reset_filtered(endpoint_t *instance, usb_target_t target);
 #endif
 /**
Index: uspace/lib/usb/include/usb/host/usb_endpoint_manager.h
===================================================================
--- uspace/lib/usb/include/usb/host/usb_endpoint_manager.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/host/usb_endpoint_manager.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -66,9 +66,4 @@
     endpoint_t *ep, size_t data_size);
 
-int usb_endpoint_manager_register_ep_wait(usb_endpoint_manager_t *instance,
-    usb_address_t address, usb_endpoint_t ep, usb_direction_t direction,
-    void *data, void (*data_remove_callback)(void* data, void* arg), void *arg,
-    size_t bw);
-
 int usb_endpoint_manager_unregister_ep(usb_endpoint_manager_t *instance,
     usb_address_t address, usb_endpoint_t ep, usb_direction_t direction);
@@ -78,4 +73,30 @@
     size_t *bw);
 
+void usb_endpoint_manager_reset_if_need(
+    usb_endpoint_manager_t *instance, usb_target_t target, const uint8_t *data);
+
+static inline int usb_endpoint_manager_add_ep(usb_endpoint_manager_t *instance,
+    usb_address_t address, usb_endpoint_t endpoint, usb_direction_t direction,
+    usb_transfer_type_t type, usb_speed_t speed, size_t max_packet_size,
+    size_t data_size)
+{
+	endpoint_t *ep = malloc(sizeof(endpoint_t));
+	if (ep == NULL)
+		return ENOMEM;
+
+	int ret = endpoint_init(ep, address, endpoint, direction, type, speed,
+	    max_packet_size);
+	if (ret != EOK) {
+		free(ep);
+		return ret;
+	}
+
+	ret = usb_endpoint_manager_register_ep(instance, ep, data_size);
+	if (ret != EOK) {
+		endpoint_destroy(ep);
+		return ret;
+	}
+	return EOK;
+}
 #endif
 /**
Index: uspace/lib/usb/include/usb/hub.h
===================================================================
--- uspace/lib/usb/include/usb/hub.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/hub.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -59,7 +59,4 @@
 } usb_hc_attached_device_t;
 
-int usb_hc_reserve_default_address(usb_hc_connection_t *, usb_speed_t);
-int usb_hc_release_default_address(usb_hc_connection_t *);
-
 usb_address_t usb_hc_request_address(usb_hc_connection_t *, usb_speed_t);
 int usb_hc_register_device(usb_hc_connection_t *,
Index: uspace/lib/usb/include/usb/pipes.h
===================================================================
--- uspace/lib/usb/include/usb/pipes.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/pipes.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -42,4 +42,5 @@
 #include <ipc/devman.h>
 #include <ddf/driver.h>
+#include <fibril_synch.h>
 
 /** Abstraction of a physical connection to the device.
@@ -59,6 +60,14 @@
  * This endpoint must be bound with existing usb_device_connection_t
  * (i.e. the wire to send data over).
+ *
+ * Locking order: if you want to lock both mutexes
+ * (@c guard and @c hc_phone_mutex), lock @c guard first.
+ * It is not necessary to lock @c guard if you want to lock @c hc_phone_mutex
+ * only.
  */
 typedef struct {
+	/** Guard of the whole pipe. */
+	fibril_mutex_t guard;
+
 	/** The connection used for sending the data. */
 	usb_device_connection_t *wire;
@@ -78,6 +87,21 @@
 	/** Phone to the host controller.
 	 * Negative when no session is active.
+	 * It is an error to access this member without @c hc_phone_mutex
+	 * being locked.
+	 * If call over the phone is to be made, it must be preceeded by
+	 * call to pipe_add_ref() [internal libusb function].
 	 */
 	int hc_phone;
+
+	/** Guard for serialization of requests over the phone. */
+	fibril_mutex_t hc_phone_mutex;
+
+	/** Number of active transfers over the pipe. */
+	int refcount;
+
+	/** Whether to automatically reset halt on the endpoint.
+	 * Valid only for control endpoint zero.
+	 */
+	bool auto_reset_halt;
 } usb_pipe_t;
 
@@ -134,4 +158,6 @@
 int usb_pipe_initialize_from_configuration(usb_endpoint_mapping_t *,
     size_t, uint8_t *, size_t, usb_device_connection_t *);
+int usb_pipe_register_with_speed(usb_pipe_t *, usb_speed_t,
+    unsigned int, usb_hc_connection_t *);
 int usb_pipe_register(usb_pipe_t *, unsigned int, usb_hc_connection_t *);
 int usb_pipe_unregister(usb_pipe_t *, usb_hc_connection_t *);
@@ -140,4 +166,7 @@
 int usb_pipe_end_session(usb_pipe_t *);
 bool usb_pipe_is_session_started(usb_pipe_t *);
+
+int usb_pipe_start_long_transfer(usb_pipe_t *);
+void usb_pipe_end_long_transfer(usb_pipe_t *);
 
 int usb_pipe_read(usb_pipe_t *, void *, size_t, size_t *);
Index: uspace/lib/usb/include/usb/request.h
===================================================================
--- uspace/lib/usb/include/usb/request.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/request.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -50,4 +50,10 @@
 /** USB endpoint status - endpoint is halted (stalled). */
 #define USB_ENDPOINT_STATUS_HALTED ((uint16_t)(1 << 0))
+
+/** USB feature selector - endpoint halt (stall). */
+#define USB_FEATURE_SELECTOR_ENDPOINT_HALT (0)
+
+/** USB feature selector - device remote wake-up. */
+#define USB_FEATURE_SELECTOR_REMOTE_WAKEUP (1)
 
 /** Standard device request. */
@@ -135,4 +141,6 @@
     char **);
 
+int usb_request_clear_endpoint_halt(usb_pipe_t *, uint16_t);
+
 #endif
 /**
Index: uspace/lib/usb/include/usb/usb.h
===================================================================
--- uspace/lib/usb/include/usb/usb.h	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/include/usb/usb.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -77,5 +77,7 @@
 	USB_SPEED_FULL,
 	/** USB 2.0 high speed (480Mbits/s). */
-	USB_SPEED_HIGH
+	USB_SPEED_HIGH,
+	/** Psuedo-speed serving as a boundary. */
+	USB_SPEED_MAX
 } usb_speed_t;
 
Index: uspace/lib/usb/src/altiface.c
===================================================================
--- uspace/lib/usb/src/altiface.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
+++ uspace/lib/usb/src/altiface.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -0,0 +1,181 @@
+/*
+ * 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.
+ */
+
+/** @addtogroup libusb
+ * @{
+ */
+/** @file
+ * Handling alternate interface settings.
+ */
+#include <usb/devdrv.h>
+#include <usb/request.h>
+#include <usb/debug.h>
+#include <usb/dp.h>
+#include <errno.h>
+#include <str_error.h>
+#include <assert.h>
+
+/** Count number of alternate settings of a interface.
+ *
+ * @param config_descr Full configuration descriptor.
+ * @param config_descr_size Size of @p config_descr in bytes.
+ * @param interface_no Interface number.
+ * @return Number of alternate interfaces for @p interface_no interface.
+ */
+size_t usb_interface_count_alternates(uint8_t *config_descr,
+    size_t config_descr_size, uint8_t interface_no)
+{
+	assert(config_descr != NULL);
+	assert(config_descr_size > 0);
+
+	usb_dp_parser_t dp_parser = {
+		.nesting = usb_dp_standard_descriptor_nesting
+	};
+	usb_dp_parser_data_t dp_data = {
+		.data = config_descr,
+		.size = config_descr_size,
+		.arg = NULL
+	};
+
+	size_t alternate_count = 0;
+
+	uint8_t *iface_ptr = usb_dp_get_nested_descriptor(&dp_parser,
+	    &dp_data, config_descr);
+	while (iface_ptr != NULL) {
+		usb_standard_interface_descriptor_t *iface
+		    = (usb_standard_interface_descriptor_t *) iface_ptr;
+		if (iface->descriptor_type == USB_DESCTYPE_INTERFACE) {
+			if (iface->interface_number == interface_no) {
+				alternate_count++;
+			}
+		}
+		iface_ptr = usb_dp_get_sibling_descriptor(&dp_parser, &dp_data,
+		    config_descr, iface_ptr);
+	}
+
+	return alternate_count;
+}
+
+/** Create alternate interface representation structure.
+ *
+ * @param[in] config_descr Configuration descriptor.
+ * @param[in] config_descr_size Size of configuration descriptor.
+ * @param[in] interface_number Interface number.
+ * @param[out] alternates_ptr Where to store pointer to allocated structure.
+ * @return Error code.
+ */
+int usb_alternate_interfaces_create(uint8_t *config_descr,
+    size_t config_descr_size, int interface_number,
+    usb_alternate_interfaces_t **alternates_ptr)
+{
+	assert(alternates_ptr != NULL);
+	assert(config_descr != NULL);
+	assert(config_descr_size > 0);
+
+	if (interface_number < 0) {
+		alternates_ptr = NULL;
+		return EOK;
+	}
+
+	usb_alternate_interfaces_t *alternates
+	    = malloc(sizeof(usb_alternate_interfaces_t));
+
+	if (alternates == NULL) {
+		return ENOMEM;
+	}
+
+	alternates->alternative_count
+	    = usb_interface_count_alternates(config_descr, config_descr_size,
+	    interface_number);
+
+	if (alternates->alternative_count == 0) {
+		free(alternates);
+		return ENOENT;
+	}
+
+	alternates->alternatives = malloc(alternates->alternative_count
+	    * sizeof(usb_alternate_interface_descriptors_t));
+	if (alternates->alternatives == NULL) {
+		free(alternates);
+		return ENOMEM;
+	}
+
+	alternates->current = 0;
+
+	usb_dp_parser_t dp_parser = {
+		.nesting = usb_dp_standard_descriptor_nesting
+	};
+	usb_dp_parser_data_t dp_data = {
+		.data = config_descr,
+		.size = config_descr_size,
+		.arg = NULL
+	};
+
+	usb_alternate_interface_descriptors_t *cur_alt_iface
+	    = &alternates->alternatives[0];
+
+	uint8_t *iface_ptr = usb_dp_get_nested_descriptor(&dp_parser,
+	    &dp_data, dp_data.data);
+	while (iface_ptr != NULL) {
+		usb_standard_interface_descriptor_t *iface
+		    = (usb_standard_interface_descriptor_t *) iface_ptr;
+		if ((iface->descriptor_type != USB_DESCTYPE_INTERFACE)
+		    || (iface->interface_number != interface_number)) {
+			iface_ptr = usb_dp_get_sibling_descriptor(&dp_parser,
+			    &dp_data,
+			    dp_data.data, iface_ptr);
+			continue;
+		}
+
+		cur_alt_iface->interface = iface;
+		cur_alt_iface->nested_descriptors = iface_ptr + sizeof(*iface);
+
+		/* Find next interface to count size of nested descriptors. */
+		iface_ptr = usb_dp_get_sibling_descriptor(&dp_parser, &dp_data,
+		    dp_data.data, iface_ptr);
+		if (iface_ptr == NULL) {
+			uint8_t *next = dp_data.data + dp_data.size;
+			cur_alt_iface->nested_descriptors_size
+			    = next - cur_alt_iface->nested_descriptors;
+		} else {
+			cur_alt_iface->nested_descriptors_size
+			    = iface_ptr - cur_alt_iface->nested_descriptors;
+		}
+
+		cur_alt_iface++;
+	}
+
+	*alternates_ptr = alternates;
+
+	return EOK;
+}
+
+
+/**
+ * @}
+ */
Index: uspace/lib/usb/src/devdrv.c
===================================================================
--- uspace/lib/usb/src/devdrv.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/devdrv.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -72,14 +72,4 @@
 }
 
-/** Log out of memory error on given device.
- *
- * @param dev Device causing the trouble.
- */
-static void usb_log_oom(ddf_dev_t *dev)
-{
-	usb_log_error("Out of memory when adding device `%s'.\n",
-	    dev->name);
-}
-
 /** Count number of pipes the driver expects.
  *
@@ -108,300 +98,26 @@
  */
 static int initialize_other_pipes(usb_endpoint_description_t **endpoints,
-    usb_device_t *dev)
-{
-	int rc;
-
-	size_t pipe_count = count_other_pipes(endpoints);
-	if (pipe_count == 0) {
+    usb_device_t *dev, int alternate_setting)
+{
+	if (endpoints == NULL) {
+		dev->pipes = NULL;
+		dev->pipes_count = 0;
 		return EOK;
 	}
 
-	dev->pipes = malloc(sizeof(usb_endpoint_mapping_t) * pipe_count);
-	if (dev->pipes == NULL) {
-		usb_log_oom(dev->ddf_dev);
-		return ENOMEM;
-	}
-
-	size_t i;
-
-	/* Initialize to NULL first for rollback purposes. */
-	for (i = 0; i < pipe_count; i++) {
-		dev->pipes[i].pipe = NULL;
-	}
-
-	for (i = 0; i < pipe_count; i++) {
-		dev->pipes[i].pipe = malloc(sizeof(usb_pipe_t));
-		if (dev->pipes[i].pipe == NULL) {
-			usb_log_oom(dev->ddf_dev);
-			rc = ENOMEM;
-			goto rollback;
-		}
-
-		dev->pipes[i].description = endpoints[i];
-		dev->pipes[i].interface_no = dev->interface_no;
-		dev->pipes[i].interface_setting = 0;
-	}
-
-	rc = usb_pipe_initialize_from_configuration(dev->pipes, pipe_count,
+	usb_endpoint_mapping_t *pipes;
+	size_t pipes_count;
+
+	int rc = usb_device_create_pipes(dev->ddf_dev, &dev->wire, endpoints,
 	    dev->descriptors.configuration, dev->descriptors.configuration_size,
-	    &dev->wire);
-	if (rc != EOK) {
-		usb_log_error("Failed initializing USB endpoints: %s.\n",
-		    str_error(rc));
-		goto rollback;
-	}
-
-	/* Register the endpoints. */
-	usb_hc_connection_t hc_conn;
-	rc = usb_hc_connection_initialize_from_device(&hc_conn, dev->ddf_dev);
-	if (rc != EOK) {
-		usb_log_error(
-		    "Failed initializing connection to host controller: %s.\n",
-		    str_error(rc));
-		goto rollback;
-	}
-	rc = usb_hc_connection_open(&hc_conn);
-	if (rc != EOK) {
-		usb_log_error("Failed to connect to host controller: %s.\n",
-		    str_error(rc));
-		goto rollback;
-	}
-	for (i = 0; i < pipe_count; i++) {
-		if (dev->pipes[i].present) {
-			rc = usb_pipe_register(dev->pipes[i].pipe,
-			    dev->pipes[i].descriptor->poll_interval,
-			    &hc_conn);
-			/* Ignore error when operation not supported by HC. */
-			if ((rc != EOK) && (rc != ENOTSUP)) {
-				/* FIXME: what shall we do? */
-				dev->pipes[i].present = false;
-				free(dev->pipes[i].pipe);
-				dev->pipes[i].pipe = NULL;
-			}
-		}
-	}
-	/* Ignoring errors here. */
-	usb_hc_connection_close(&hc_conn);
-
-	dev->pipes_count = pipe_count;
-
-	return EOK;
-
-rollback:
-	for (i = 0; i < pipe_count; i++) {
-		if (dev->pipes[i].pipe != NULL) {
-			free(dev->pipes[i].pipe);
-		}
-	}
-	free(dev->pipes);
-
-	return rc;
-}
-
-/** Initialize all endpoint pipes.
- *
- * @param drv The driver.
- * @param dev The device to be initialized.
- * @return Error code.
- */
-static int initialize_pipes(usb_device_t *dev)
-{
-	int rc;
-
-	rc = usb_device_connection_initialize_from_device(&dev->wire,
-	    dev->ddf_dev);
-	if (rc != EOK) {
-		usb_log_error(
-		    "Failed initializing connection on device `%s'. %s.\n",
-		    dev->ddf_dev->name, str_error(rc));
-		return rc;
-	}
-
-	rc = usb_pipe_initialize_default_control(&dev->ctrl_pipe,
-	    &dev->wire);
-	if (rc != EOK) {
-		usb_log_error("Failed to initialize default control pipe " \
-		    "on device `%s': %s.\n",
-		    dev->ddf_dev->name, str_error(rc));
-		return rc;
-	}
-
-	rc = usb_pipe_probe_default_control(&dev->ctrl_pipe);
-	if (rc != EOK) {
-		usb_log_error(
-		    "Probing default control pipe on device `%s' failed: %s.\n",
-		    dev->ddf_dev->name, str_error(rc));
-		return rc;
-	}
-
-	/* Get our interface. */
-	dev->interface_no = usb_device_get_assigned_interface(dev->ddf_dev);
-
-	/*
-	 * For further actions, we need open session on default control pipe.
-	 */
-	rc = usb_pipe_start_session(&dev->ctrl_pipe);
-	if (rc != EOK) {
-		usb_log_error("Failed to start an IPC session: %s.\n",
-		    str_error(rc));
-		return rc;
-	}
-
-	/* Get the device descriptor. */
-	rc = usb_request_get_device_descriptor(&dev->ctrl_pipe,
-	    &dev->descriptors.device);
-	if (rc != EOK) {
-		usb_log_error("Failed to retrieve device descriptor: %s.\n",
-		    str_error(rc));
-		return rc;
-	}
-
-	/* Get the full configuration descriptor. */
-	rc = usb_request_get_full_configuration_descriptor_alloc(
-	    &dev->ctrl_pipe, 0, (void **) &dev->descriptors.configuration,
-	    &dev->descriptors.configuration_size);
-	if (rc != EOK) {
-		usb_log_error("Failed retrieving configuration descriptor: %s. %s\n",
-		    dev->ddf_dev->name, str_error(rc));
-		return rc;
-	}
-
-	if (driver->endpoints != NULL) {
-		rc = initialize_other_pipes(driver->endpoints, dev);
-	}
-
-	/* No checking here. */
-	usb_pipe_end_session(&dev->ctrl_pipe);
-
-	/* Rollback actions. */
-	if (rc != EOK) {
-		if (dev->descriptors.configuration != NULL) {
-			free(dev->descriptors.configuration);
-		}
-	}
-
-	return rc;
-}
-
-/** Count number of alternate settings of a interface.
- *
- * @param config_descr Full configuration descriptor.
- * @param config_descr_size Size of @p config_descr in bytes.
- * @param interface_no Interface number.
- * @return Number of alternate interfaces for @p interface_no interface.
- */
-static size_t count_alternate_interfaces(uint8_t *config_descr,
-    size_t config_descr_size, int interface_no)
-{
-	assert(config_descr != NULL);
-	usb_dp_parser_t dp_parser = {
-		.nesting = usb_dp_standard_descriptor_nesting
-	};
-	usb_dp_parser_data_t dp_data = {
-		.data = config_descr,
-		.size = config_descr_size,
-		.arg = NULL
-	};
-
-	size_t alternate_count = 0;
-
-	uint8_t *iface_ptr = usb_dp_get_nested_descriptor(&dp_parser,
-	    &dp_data, config_descr);
-	while (iface_ptr != NULL) {
-		usb_standard_interface_descriptor_t *iface
-		    = (usb_standard_interface_descriptor_t *) iface_ptr;
-		if (iface->descriptor_type == USB_DESCTYPE_INTERFACE) {
-			if (iface->interface_number == interface_no) {
-				alternate_count++;
-			}
-		}
-		iface_ptr = usb_dp_get_sibling_descriptor(&dp_parser, &dp_data,
-		    config_descr, iface_ptr);
-	}
-
-	return alternate_count;
-}
-
-/** Initialize structures related to alternate interfaces.
- *
- * @param dev Device where alternate settings shall be initialized.
- * @return Error code.
- */
-static int initialize_alternate_interfaces(usb_device_t *dev)
-{
-	if (dev->interface_no < 0) {
-		dev->alternate_interfaces = NULL;
-		return EOK;
-	}
-
-	usb_alternate_interfaces_t *alternates
-	    = malloc(sizeof(usb_alternate_interfaces_t));
-
-	if (alternates == NULL) {
-		return ENOMEM;
-	}
-
-	alternates->alternative_count
-	    = count_alternate_interfaces(dev->descriptors.configuration,
-	    dev->descriptors.configuration_size, dev->interface_no);
-
-	if (alternates->alternative_count == 0) {
-		free(alternates);
-		return ENOENT;
-	}
-
-	alternates->alternatives = malloc(alternates->alternative_count
-	    * sizeof(usb_alternate_interface_descriptors_t));
-	if (alternates->alternatives == NULL) {
-		free(alternates);
-		return ENOMEM;
-	}
-
-	alternates->current = 0;
-
-	usb_dp_parser_t dp_parser = {
-		.nesting = usb_dp_standard_descriptor_nesting
-	};
-	usb_dp_parser_data_t dp_data = {
-		.data = dev->descriptors.configuration,
-		.size = dev->descriptors.configuration_size,
-		.arg = NULL
-	};
-
-	usb_alternate_interface_descriptors_t *cur_alt_iface
-	    = &alternates->alternatives[0];
-
-	uint8_t *iface_ptr = usb_dp_get_nested_descriptor(&dp_parser,
-	    &dp_data, dp_data.data);
-	while (iface_ptr != NULL) {
-		usb_standard_interface_descriptor_t *iface
-		    = (usb_standard_interface_descriptor_t *) iface_ptr;
-		if ((iface->descriptor_type != USB_DESCTYPE_INTERFACE)
-		    || (iface->interface_number != dev->interface_no)) {
-			iface_ptr = usb_dp_get_sibling_descriptor(&dp_parser,
-			    &dp_data,
-			    dp_data.data, iface_ptr);
-			continue;
-		}
-
-		cur_alt_iface->interface = iface;
-		cur_alt_iface->nested_descriptors = iface_ptr + sizeof(*iface);
-
-		/* Find next interface to count size of nested descriptors. */
-		iface_ptr = usb_dp_get_sibling_descriptor(&dp_parser, &dp_data,
-		    dp_data.data, iface_ptr);
-		if (iface_ptr == NULL) {
-			uint8_t *next = dp_data.data + dp_data.size;
-			cur_alt_iface->nested_descriptors_size
-			    = next - cur_alt_iface->nested_descriptors;
-		} else {
-			cur_alt_iface->nested_descriptors_size
-			    = iface_ptr - cur_alt_iface->nested_descriptors;
-		}
-
-		cur_alt_iface++;
-	}
-
-	dev->alternate_interfaces = alternates;
+	    dev->interface_no, alternate_setting,
+	    &pipes, &pipes_count);
+
+	if (rc != EOK) {
+		return rc;
+	}
+
+	dev->pipes = pipes;
+	dev->pipes_count = pipes_count;
 
 	return EOK;
@@ -423,27 +139,12 @@
 	int rc;
 
-	usb_device_t *dev = malloc(sizeof(usb_device_t));
-	if (dev == NULL) {
-		usb_log_error("Out of memory when adding device `%s'.\n",
-		    gen_dev->name);
-		return ENOMEM;
-	}
-
-
-	dev->ddf_dev = gen_dev;
-	dev->ddf_dev->driver_data = dev;
-	dev->driver_data = NULL;
-	dev->descriptors.configuration = NULL;
-
-	dev->pipes_count = 0;
-	dev->pipes = NULL;
-
-	rc = initialize_pipes(dev);
-	if (rc != EOK) {
-		free(dev);
-		return rc;
-	}
-
-	(void) initialize_alternate_interfaces(dev);
+	usb_device_t *dev = NULL;
+	const char *err_msg = NULL;
+	rc = usb_device_create(gen_dev, driver->endpoints, &dev, &err_msg);
+	if (rc != EOK) {
+		usb_log_error("USB device `%s' creation failed (%s): %s.\n",
+		    gen_dev->name, err_msg, str_error(rc));
+		return rc;
+	}
 
 	return driver->ops->add_device(dev);
@@ -457,36 +158,10 @@
 static int destroy_current_pipes(usb_device_t *dev)
 {
-	size_t i;
-	int rc;
-
-	/* TODO: this shall be done under some device mutex. */
-
-	/* First check that no session is opened. */
-	for (i = 0; i < dev->pipes_count; i++) {
-		if (usb_pipe_is_session_started(dev->pipes[i].pipe)) {
-			return EBUSY;
-		}
-	}
-
-	/* Prepare connection to HC. */
-	usb_hc_connection_t hc_conn;
-	rc = usb_hc_connection_initialize_from_device(&hc_conn, dev->ddf_dev);
-	if (rc != EOK) {
-		return rc;
-	}
-	rc = usb_hc_connection_open(&hc_conn);
-	if (rc != EOK) {
-		return rc;
-	}
-
-	/* Destroy the pipes. */
-	for (i = 0; i < dev->pipes_count; i++) {
-		usb_pipe_unregister(dev->pipes[i].pipe, &hc_conn);
-		free(dev->pipes[i].pipe);
-	}
-
-	usb_hc_connection_close(&hc_conn);
-
-	free(dev->pipes);
+	int rc = usb_device_destroy_pipes(dev->ddf_dev,
+	    dev->pipes, dev->pipes_count);
+	if (rc != EOK) {
+		return rc;
+	}
+
 	dev->pipes = NULL;
 	dev->pipes_count = 0;
@@ -505,4 +180,11 @@
  * with usb_pipe_initialize_from_configuration().
  *
+ * @warning This is a wrapper function that does several operations that
+ * can fail and that cannot be rollbacked easily. That means that a failure
+ * during the SET_INTERFACE request would result in having a device with
+ * no pipes at all (except the default control one). That is because the old
+ * pipes needs to be unregistered at HC first and the new ones could not
+ * be created.
+ *
  * @param dev USB device.
  * @param alternate_setting Alternate setting to choose.
@@ -519,6 +201,4 @@
 	int rc;
 
-	/* TODO: more transactional behavior. */
-
 	/* Destroy existing pipes. */
 	rc = destroy_current_pipes(dev);
@@ -535,7 +215,323 @@
 
 	/* Create new pipes. */
-	rc = initialize_other_pipes(endpoints, dev);
+	rc = initialize_other_pipes(endpoints, dev, (int) alternate_setting);
 
 	return rc;
+}
+
+/** Retrieve basic descriptors from the device.
+ *
+ * @param[in] ctrl_pipe Control endpoint pipe.
+ * @param[out] descriptors Where to store the descriptors.
+ * @return Error code.
+ */
+int usb_device_retrieve_descriptors(usb_pipe_t *ctrl_pipe,
+    usb_device_descriptors_t *descriptors)
+{
+	assert(descriptors != NULL);
+
+	descriptors->configuration = NULL;
+
+	int rc;
+
+	/* It is worth to start a long transfer. */
+	rc = usb_pipe_start_long_transfer(ctrl_pipe);
+	if (rc != EOK) {
+		return rc;
+	}
+
+	/* Get the device descriptor. */
+	rc = usb_request_get_device_descriptor(ctrl_pipe, &descriptors->device);
+	if (rc != EOK) {
+		goto leave;
+	}
+
+	/* Get the full configuration descriptor. */
+	rc = usb_request_get_full_configuration_descriptor_alloc(
+	    ctrl_pipe, 0, (void **) &descriptors->configuration,
+	    &descriptors->configuration_size);
+
+leave:
+	usb_pipe_end_long_transfer(ctrl_pipe);
+
+	return rc;
+}
+
+/** Create pipes for a device.
+ *
+ * This is more or less a wrapper that does following actions:
+ * - allocate and initialize pipes
+ * - map endpoints to the pipes based on the descriptions
+ * - registers endpoints with the host controller
+ *
+ * @param[in] dev Generic DDF device backing the USB one.
+ * @param[in] wire Initialized backing connection to the host controller.
+ * @param[in] endpoints Endpoints description, NULL terminated.
+ * @param[in] config_descr Configuration descriptor of active configuration.
+ * @param[in] config_descr_size Size of @p config_descr in bytes.
+ * @param[in] interface_no Interface to map from.
+ * @param[in] interface_setting Interface setting (default is usually 0).
+ * @param[out] pipes_ptr Where to store array of created pipes
+ *	(not NULL terminated).
+ * @param[out] pipes_count_ptr Where to store number of pipes
+ *	(set to if you wish to ignore the count).
+ * @return Error code.
+ */
+int usb_device_create_pipes(ddf_dev_t *dev, usb_device_connection_t *wire,
+    usb_endpoint_description_t **endpoints,
+    uint8_t *config_descr, size_t config_descr_size,
+    int interface_no, int interface_setting,
+    usb_endpoint_mapping_t **pipes_ptr, size_t *pipes_count_ptr)
+{
+	assert(dev != NULL);
+	assert(wire != NULL);
+	assert(endpoints != NULL);
+	assert(config_descr != NULL);
+	assert(config_descr_size > 0);
+	assert(pipes_ptr != NULL);
+
+	size_t i;
+	int rc;
+
+	size_t pipe_count = count_other_pipes(endpoints);
+	if (pipe_count == 0) {
+		*pipes_ptr = NULL;
+		return EOK;
+	}
+
+	usb_endpoint_mapping_t *pipes
+	    = malloc(sizeof(usb_endpoint_mapping_t) * pipe_count);
+	if (pipes == NULL) {
+		return ENOMEM;
+	}
+
+	/* Initialize to NULL to allow smooth rollback. */
+	for (i = 0; i < pipe_count; i++) {
+		pipes[i].pipe = NULL;
+	}
+
+	/* Now allocate and fully initialize. */
+	for (i = 0; i < pipe_count; i++) {
+		pipes[i].pipe = malloc(sizeof(usb_pipe_t));
+		if (pipes[i].pipe == NULL) {
+			rc = ENOMEM;
+			goto rollback_free_only;
+		}
+		pipes[i].description = endpoints[i];
+		pipes[i].interface_no = interface_no;
+		pipes[i].interface_setting = interface_setting;
+	}
+
+	/* Find the mapping from configuration descriptor. */
+	rc = usb_pipe_initialize_from_configuration(pipes, pipe_count,
+	    config_descr, config_descr_size, wire);
+	if (rc != EOK) {
+		goto rollback_free_only;
+	}
+
+	/* Register the endpoints with HC. */
+	usb_hc_connection_t hc_conn;
+	rc = usb_hc_connection_initialize_from_device(&hc_conn, dev);
+	if (rc != EOK) {
+		goto rollback_free_only;
+	}
+
+	rc = usb_hc_connection_open(&hc_conn);
+	if (rc != EOK) {
+		goto rollback_free_only;
+	}
+
+	for (i = 0; i < pipe_count; i++) {
+		if (pipes[i].present) {
+			rc = usb_pipe_register(pipes[i].pipe,
+			    pipes[i].descriptor->poll_interval, &hc_conn);
+			if (rc != EOK) {
+				goto rollback_unregister_endpoints;
+			}
+		}
+	}
+
+	usb_hc_connection_close(&hc_conn);
+
+	*pipes_ptr = pipes;
+	if (pipes_count_ptr != NULL) {
+		*pipes_count_ptr = pipe_count;
+	}
+
+	return EOK;
+
+	/*
+	 * Jump here if something went wrong after endpoints have
+	 * been registered.
+	 * This is also the target when the registration of
+	 * endpoints fails.
+	 */
+rollback_unregister_endpoints:
+	for (i = 0; i < pipe_count; i++) {
+		if (pipes[i].present) {
+			usb_pipe_unregister(pipes[i].pipe, &hc_conn);
+		}
+	}
+
+	usb_hc_connection_close(&hc_conn);
+
+	/*
+	 * Jump here if something went wrong before some actual communication
+	 * with HC. Then the only thing that needs to be done is to free
+	 * allocated memory.
+	 */
+rollback_free_only:
+	for (i = 0; i < pipe_count; i++) {
+		if (pipes[i].pipe != NULL) {
+			free(pipes[i].pipe);
+		}
+	}
+	free(pipes);
+
+	return rc;
+}
+
+/** Destroy pipes previously created by usb_device_create_pipes.
+ *
+ * @param[in] dev Generic DDF device backing the USB one.
+ * @param[in] pipes Endpoint mapping to be destroyed.
+ * @param[in] pipes_count Number of endpoints.
+ */
+int usb_device_destroy_pipes(ddf_dev_t *dev,
+    usb_endpoint_mapping_t *pipes, size_t pipes_count)
+{
+	assert(dev != NULL);
+	assert(((pipes != NULL) && (pipes_count > 0))
+	    || ((pipes == NULL) && (pipes_count == 0)));
+
+	if (pipes_count == 0) {
+		return EOK;
+	}
+
+	int rc;
+
+	/* Prepare connection to HC to allow endpoint unregistering. */
+	usb_hc_connection_t hc_conn;
+	rc = usb_hc_connection_initialize_from_device(&hc_conn, dev);
+	if (rc != EOK) {
+		return rc;
+	}
+	rc = usb_hc_connection_open(&hc_conn);
+	if (rc != EOK) {
+		return rc;
+	}
+
+	/* Destroy the pipes. */
+	size_t i;
+	for (i = 0; i < pipes_count; i++) {
+		usb_pipe_unregister(pipes[i].pipe, &hc_conn);
+		free(pipes[i].pipe);
+	}
+
+	usb_hc_connection_close(&hc_conn);
+
+	free(pipes);
+
+	return EOK;
+}
+
+/** Initialize control pipe in a device.
+ *
+ * @param dev USB device in question.
+ * @param errmsg Where to store error context.
+ * @return
+ */
+static int init_wire_and_ctrl_pipe(usb_device_t *dev, const char **errmsg)
+{
+	int rc;
+
+	rc = usb_device_connection_initialize_from_device(&dev->wire,
+	    dev->ddf_dev);
+	if (rc != EOK) {
+		*errmsg = "device connection initialization";
+		return rc;
+	}
+
+	rc = usb_pipe_initialize_default_control(&dev->ctrl_pipe,
+	    &dev->wire);
+	if (rc != EOK) {
+		*errmsg = "default control pipe initialization";
+		return rc;
+	}
+
+	return EOK;
+}
+
+
+/** Create new instance of USB device.
+ *
+ * @param[in] ddf_dev Generic DDF device backing the USB one.
+ * @param[in] endpoints NULL terminated array of endpoints (NULL for none).
+ * @param[out] dev_ptr Where to store pointer to the new device.
+ * @param[out] errstr_ptr Where to store description of context
+ *	(in case error occurs).
+ * @return Error code.
+ */
+int usb_device_create(ddf_dev_t *ddf_dev,
+    usb_endpoint_description_t **endpoints,
+    usb_device_t **dev_ptr, const char **errstr_ptr)
+{
+	assert(dev_ptr != NULL);
+	assert(ddf_dev != NULL);
+
+	int rc;
+
+	usb_device_t *dev = malloc(sizeof(usb_device_t));
+	if (dev == NULL) {
+		*errstr_ptr = "structure allocation";
+		return ENOMEM;
+	}
+
+	// FIXME: proper deallocation in case of errors
+
+	dev->ddf_dev = ddf_dev;
+	dev->driver_data = NULL;
+	dev->descriptors.configuration = NULL;
+	dev->alternate_interfaces = NULL;
+
+	dev->pipes_count = 0;
+	dev->pipes = NULL;
+
+	/* Initialize backing wire and control pipe. */
+	rc = init_wire_and_ctrl_pipe(dev, errstr_ptr);
+	if (rc != EOK) {
+		return rc;
+	}
+
+	/* Get our interface. */
+	dev->interface_no = usb_device_get_assigned_interface(dev->ddf_dev);
+
+	/* Retrieve standard descriptors. */
+	rc = usb_device_retrieve_descriptors(&dev->ctrl_pipe,
+	    &dev->descriptors);
+	if (rc != EOK) {
+		*errstr_ptr = "descriptor retrieval";
+		return rc;
+	}
+
+	/* Create alternate interfaces. */
+	rc = usb_alternate_interfaces_create(dev->descriptors.configuration,
+	    dev->descriptors.configuration_size, dev->interface_no,
+	    &dev->alternate_interfaces);
+	if (rc != EOK) {
+		/* We will try to silently ignore this. */
+		dev->alternate_interfaces = NULL;
+	}
+
+	rc = initialize_other_pipes(endpoints, dev, 0);
+	if (rc != EOK) {
+		*errstr_ptr = "pipes initialization";
+		return rc;
+	}
+
+	*errstr_ptr = NULL;
+	*dev_ptr = dev;
+
+	return EOK;
 }
 
Index: uspace/lib/usb/src/devpoll.c
===================================================================
--- uspace/lib/usb/src/devpoll.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/devpoll.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -33,7 +33,8 @@
  * USB device driver framework - automatic interrupt polling.
  */
-#include <usb/devdrv.h>
+#include <usb/devpoll.h>
 #include <usb/request.h>
 #include <usb/debug.h>
+#include <usb/classes/classes.h>
 #include <errno.h>
 #include <str_error.h>
@@ -45,8 +46,14 @@
 /** Data needed for polling. */
 typedef struct {
+	int debug;
+	size_t max_failures;
+	useconds_t delay;
+	bool auto_clear_halt;
+	bool (*on_data)(usb_device_t *, uint8_t *, size_t, void *);
+	void (*on_polling_end)(usb_device_t *, bool, void *);
+	bool (*on_error)(usb_device_t *, int, void *);
+
 	usb_device_t *dev;
 	size_t pipe_index;
-	usb_polling_callback_t callback;
-	usb_polling_terminted_callback_t terminated_callback;
 	size_t request_size;
 	uint8_t *buffer;
@@ -54,4 +61,5 @@
 } polling_data_t;
 
+
 /** Polling fibril.
  *
@@ -66,14 +74,22 @@
 	usb_pipe_t *pipe
 	    = polling_data->dev->pipes[polling_data->pipe_index].pipe;
+	
+	if (polling_data->debug > 0) {
+		usb_endpoint_mapping_t *mapping
+		    = &polling_data->dev->pipes[polling_data->pipe_index];
+		usb_log_debug("Poll0x%x: started polling of `%s' - " \
+		    "interface %d (%s,%d,%d), %zuB/%zu.\n",
+		    polling_data,
+		    polling_data->dev->ddf_dev->name,
+		    (int) mapping->interface->interface_number,
+		    usb_str_class(mapping->interface->interface_class),
+		    (int) mapping->interface->interface_subclass,
+		    (int) mapping->interface->interface_protocol,
+		    polling_data->request_size, pipe->max_packet_size);
+	}
 
 	size_t failed_attempts = 0;
-	while (failed_attempts < MAX_FAILED_ATTEMPTS) {
+	while (failed_attempts <= polling_data->max_failures) {
 		int rc;
-
-		rc = usb_pipe_start_session(pipe);
-		if (rc != EOK) {
-			failed_attempts++;
-			continue;
-		}
 
 		size_t actual_size;
@@ -81,8 +97,40 @@
 		    polling_data->request_size, &actual_size);
 
-		/* Quit the session regardless of errors. */
-		usb_pipe_end_session(pipe);
+		if (polling_data->debug > 1) {
+			if (rc == EOK) {
+				usb_log_debug(
+				    "Poll0x%x: received: '%s' (%zuB).\n",
+				    polling_data,
+				    usb_debug_str_buffer(polling_data->buffer,
+				        actual_size, 16),
+				    actual_size);
+			} else {
+				usb_log_debug(
+				    "Poll0x%x: polling failed: %s.\n",
+				    polling_data, str_error(rc));
+			}
+		}
+
+		/* If the pipe stalled, we can try to reset the stall. */
+		if ((rc == ESTALL) && (polling_data->auto_clear_halt)) {
+			/*
+			 * We ignore error here as this is usually a futile
+			 * attempt anyway.
+			 */
+			usb_request_clear_endpoint_halt(
+			    &polling_data->dev->ctrl_pipe,
+			    pipe->endpoint_no);
+		}
 
 		if (rc != EOK) {
+			if (polling_data->on_error != NULL) {
+				bool cont = polling_data->on_error(
+				    polling_data->dev, rc,
+				    polling_data->custom_arg);
+				if (!cont) {
+					failed_attempts
+					    = polling_data->max_failures;
+				}
+			}
 			failed_attempts++;
 			continue;
@@ -90,5 +138,5 @@
 
 		/* We have the data, execute the callback now. */
-		bool carry_on = polling_data->callback(polling_data->dev,
+		bool carry_on = polling_data->on_data(polling_data->dev,
 		    polling_data->buffer, actual_size,
 		    polling_data->custom_arg);
@@ -101,15 +149,26 @@
 		/* Reset as something might be only a temporary problem. */
 		failed_attempts = 0;
-	}
-
-	if (failed_attempts > 0) {
-		usb_log_error(
-		    "Polling of device `%s' terminated: recurring failures.\n",
-		    polling_data->dev->ddf_dev->name);
-	}
-
-	if (polling_data->terminated_callback != NULL) {
-		polling_data->terminated_callback(polling_data->dev,
+
+		/* Take a rest before next request. */
+		async_usleep(polling_data->delay);
+	}
+
+	if (polling_data->on_polling_end != NULL) {
+		polling_data->on_polling_end(polling_data->dev,
 		    failed_attempts > 0, polling_data->custom_arg);
+	}
+
+	if (polling_data->debug > 0) {
+		if (failed_attempts > 0) {
+			usb_log_error(
+			    "Polling of device `%s' terminated: %s.\n",
+			    polling_data->dev->ddf_dev->name,
+			    "recurring failures");
+		} else {
+			usb_log_debug(
+			    "Polling of device `%s' terminated by user.\n",
+			    polling_data->dev->ddf_dev->name
+			);
+		}
 	}
 
@@ -154,4 +213,61 @@
 	}
 
+	usb_device_auto_polling_t *auto_polling
+	    = malloc(sizeof(usb_device_auto_polling_t));
+	if (auto_polling == NULL) {
+		return ENOMEM;
+	}
+
+	auto_polling->debug = 1;
+	auto_polling->auto_clear_halt = true;
+	auto_polling->delay = 0;
+	auto_polling->max_failures = MAX_FAILED_ATTEMPTS;
+	auto_polling->on_data = callback;
+	auto_polling->on_polling_end = terminated_callback;
+	auto_polling->on_error = NULL;
+
+	int rc = usb_device_auto_polling(dev, pipe_index, auto_polling,
+	   request_size, arg);
+
+	free(auto_polling);
+
+	return rc;
+}
+
+/** Start automatic device polling over interrupt in pipe.
+ *
+ * The polling settings is copied thus it is okay to destroy the structure
+ * after this function returns.
+ *
+ * @warning There is no guarantee when the request to the device
+ * will be sent for the first time (it is possible that this
+ * first request would be executed prior to return from this function).
+ *
+ * @param dev Device to be periodically polled.
+ * @param pipe_index Index of the endpoint pipe used for polling.
+ * @param polling Polling settings.
+ * @param request_size How many bytes to ask for in each request.
+ * @param arg Custom argument (passed as is to the callbacks).
+ * @return Error code.
+ * @retval EOK New fibril polling the device was already started.
+ */
+int usb_device_auto_polling(usb_device_t *dev, size_t pipe_index,
+    usb_device_auto_polling_t *polling,
+    size_t request_size, void *arg)
+{
+	if (dev == NULL) {
+		return EBADMEM;
+	}
+	if (pipe_index >= dev->pipes_count) {
+		return EINVAL;
+	}
+	if ((dev->pipes[pipe_index].pipe->transfer_type != USB_TRANSFER_INTERRUPT)
+	    || (dev->pipes[pipe_index].pipe->direction != USB_DIRECTION_IN)) {
+		return EINVAL;
+	}
+	if ((polling == NULL) || (polling->on_data == NULL)) {
+		return EBADMEM;
+	}
+
 	polling_data_t *polling_data = malloc(sizeof(polling_data_t));
 	if (polling_data == NULL) {
@@ -159,16 +275,28 @@
 	}
 
-	/* Allocate now to prevent immediate failure in the polling fibril. */
-	polling_data->buffer = malloc(request_size);
+	/* Fill-in the data. */
+	polling_data->buffer = malloc(sizeof(request_size));
 	if (polling_data->buffer == NULL) {
 		free(polling_data);
 		return ENOMEM;
 	}
+	polling_data->request_size = request_size;
 	polling_data->dev = dev;
 	polling_data->pipe_index = pipe_index;
-	polling_data->callback = callback;
-	polling_data->terminated_callback = terminated_callback;
-	polling_data->request_size = request_size;
 	polling_data->custom_arg = arg;
+
+	polling_data->debug = polling->debug;
+	polling_data->max_failures = polling->max_failures;
+	if (polling->delay >= 0) {
+		polling_data->delay = (useconds_t) polling->delay;
+	} else {
+		polling_data->delay = (useconds_t) dev->pipes[pipe_index]
+		    .descriptor->poll_interval;
+	}
+	polling_data->auto_clear_halt = polling->auto_clear_halt;
+
+	polling_data->on_data = polling->on_data;
+	polling_data->on_polling_end = polling->on_polling_end;
+	polling_data->on_error = polling->on_error;
 
 	fid_t fibril = fibril_create(polling_fibril, polling_data);
@@ -176,10 +304,9 @@
 		free(polling_data->buffer);
 		free(polling_data);
-		/* FIXME: better error code. */
 		return ENOMEM;
 	}
 	fibril_add_ready(fibril);
 
-	/* The allocated buffer etc. will be freed by the fibril. */
+	/* Fibril launched. That fibril will free the allocated data. */
 
 	return EOK;
Index: uspace/lib/usb/src/hidiface.c
===================================================================
--- uspace/lib/usb/src/hidiface.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
+++ uspace/lib/usb/src/hidiface.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -0,0 +1,146 @@
+/*
+ * 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.
+ */
+
+/** @addtogroup libusb
+ * @{
+ */
+/** @file
+ * Client functions for accessing USB HID interface (implementation).
+ */
+#include <dev_iface.h>
+#include <usbhid_iface.h>
+#include <usb/classes/hid/iface.h>
+#include <errno.h>
+#include <str_error.h>
+#include <async.h>
+#include <assert.h>
+
+/** Ask for event array length.
+ *
+ * @param dev_phone Opened phone to DDF device providing USB HID interface.
+ * @return Number of usages returned or negative error code.
+ */
+int usbhid_dev_get_event_length(int dev_phone)
+{
+	if (dev_phone < 0) {
+		return EINVAL;
+	}
+
+	sysarg_t len;
+	int rc = async_req_1_1(dev_phone, DEV_IFACE_ID(USBHID_DEV_IFACE),
+	    IPC_M_USBHID_GET_EVENT_LENGTH, &len);
+	if (rc == EOK) {
+		return (int) len;
+	} else {
+		return rc;
+	}
+}
+
+/** Request for next event from HID device.
+ *
+ * @param[in] dev_phone Opened phone to DDF device providing USB HID interface.
+ * @param[out] usage_pages Where to store usage pages.
+ * @param[out] usages Where to store usages (actual data).
+ * @param[in] usage_count Length of @p usage_pages and @p usages buffer
+ *	(in items, not bytes).
+ * @param[out] actual_usage_count Number of usages actually returned by the
+ *	device driver.
+ * @param[in] flags Flags (see USBHID_IFACE_FLAG_*).
+ * @return Error code.
+ */
+int usbhid_dev_get_event(int dev_phone, uint16_t *usage_pages, uint16_t *usages,
+    size_t usage_count, size_t *actual_usage_count, unsigned int flags)
+{
+	if (dev_phone < 0) {
+		return EINVAL;
+	}
+	if ((usage_pages == NULL) || (usages == NULL)) {
+		return ENOMEM;
+	}
+	if (usage_count == 0) {
+		return EINVAL;
+	}
+
+	size_t buffer_size = sizeof(uint16_t) * usage_count * 2;
+	uint16_t *buffer = malloc(buffer_size);
+	if (buffer == NULL) {
+		return ENOMEM;
+	}
+
+	aid_t opening_request = async_send_2(dev_phone,
+	    DEV_IFACE_ID(USBHID_DEV_IFACE), IPC_M_USBHID_GET_EVENT,
+	    flags, NULL);
+	if (opening_request == 0) {
+		free(buffer);
+		return ENOMEM;
+	}
+
+	ipc_call_t data_request_call;
+	aid_t data_request = async_data_read(dev_phone, buffer, buffer_size,
+	    &data_request_call);
+	if (data_request == 0) {
+		async_wait_for(opening_request, NULL);
+		free(buffer);
+		return ENOMEM;
+	}
+
+	sysarg_t data_request_rc;
+	sysarg_t opening_request_rc;
+	async_wait_for(data_request, &data_request_rc);
+	async_wait_for(opening_request, &opening_request_rc);
+
+	if (data_request_rc != EOK) {
+		/* Prefer return code of the opening request. */
+		if (opening_request_rc != EOK) {
+			return (int) opening_request_rc;
+		} else {
+			return (int) data_request_rc;
+		}
+	}
+
+	if (opening_request_rc != EOK) {
+		return (int) opening_request_rc;
+	}
+
+	size_t actual_size = IPC_GET_ARG2(data_request_call);
+	size_t items = actual_size / 2;
+
+	/* Copy the individual items. */
+	memcpy(usage_pages, buffer, items * sizeof(uint16_t));
+	memcpy(usages, buffer + items, items * sizeof(uint16_t));
+
+	if (actual_usage_count != NULL) {
+		*actual_usage_count = items;
+	}
+
+	return EOK;
+}
+
+/**
+ * @}
+ */
Index: uspace/lib/usb/src/hidparser.c
===================================================================
--- uspace/lib/usb/src/hidparser.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/hidparser.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -877,5 +877,4 @@
 
 	offset = item->offset + (j * item->size);
-	
 	// FIXME
 	if((size_t)(offset/8) != (size_t)((offset+item->size-1)/8)) {
@@ -1352,9 +1351,11 @@
 
 		field = list_get_instance(field_it, usb_hid_report_field_t, link);
-		usb_hid_report_path_append_item (field->collection_path, field->usage_page, field->usage);
-		if(usb_hid_report_compare_usage_path (field->collection_path, path, flags) == EOK) {
-			ret++;
-		}
-		usb_hid_report_remove_last_item (field->collection_path);
+		if(USB_HID_ITEM_FLAG_CONSTANT(field->item_flags) == 0){
+			usb_hid_report_path_append_item (field->collection_path, field->usage_page, field->usage);
+			if(usb_hid_report_compare_usage_path (field->collection_path, path, flags) == EOK) {
+				ret++;
+			}
+			usb_hid_report_remove_last_item (field->collection_path);
+		}
 		
 		field_it = field_it->next;
@@ -1536,24 +1537,4 @@
 
 /**
- * Clones given report item structure and returns the new one
- *
- * @param item Report item structure to clone
- * @return Clonned item
- */
-usb_hid_report_item_t *usb_hid_report_item_clone(const usb_hid_report_item_t *item)
-{
-	usb_hid_report_item_t *new_report_item;
-	
-	if(!(new_report_item = malloc(sizeof(usb_hid_report_item_t)))) {
-		return NULL;
-	}					
-	memcpy(new_report_item,item, sizeof(usb_hid_report_item_t));
-	link_initialize(&(new_report_item->link));
-
-	return new_report_item;
-}
-
-
-/**
  *
  *
@@ -1604,4 +1585,55 @@
 }
 
+
+usb_hid_report_item_t *usb_hid_report_item_clone(const usb_hid_report_item_t *item)
+{
+	usb_hid_report_item_t *new_report_item;
+	
+	if(!(new_report_item = malloc(sizeof(usb_hid_report_item_t)))) {
+		return NULL;
+	}					
+	memcpy(new_report_item,item, sizeof(usb_hid_report_item_t));
+	link_initialize(&(new_report_item->link));
+
+	return new_report_item;
+}
+
+
+usb_hid_report_field_t *usb_hid_report_get_sibling(usb_hid_report_t *report, 
+							usb_hid_report_field_t *field, 
+                            usb_hid_report_path_t *path, int flags, 
+                            usb_hid_report_type_t type)
+{
+	usb_hid_report_description_t *report_des = usb_hid_report_find_description (report, path->report_id, type);
+	link_t *field_it;
+	
+	if(report_des == NULL){
+		return NULL;
+	}
+
+	if(field == NULL){
+		// vezmu prvni co mathuje podle path!!
+		field_it = report_des->report_items.next;
+	}
+	else {
+		field_it = field->link.next;
+	}
+
+	while(field_it != &report_des->report_items) {
+		field = list_get_instance(field_it, usb_hid_report_field_t, link);
+			
+		usb_hid_report_path_append_item (field->collection_path, field->usage_page, field->usage);
+		if(usb_hid_report_compare_usage_path (field->collection_path, path, flags) == EOK){
+			usb_hid_report_remove_last_item (field->collection_path);
+			usb_log_debug("....OK\n");
+			return field;
+		}
+		usb_hid_report_remove_last_item (field->collection_path);
+
+		field_it = field_it->next;
+	}
+
+	return NULL;
+}
 /**
  * @}
Index: uspace/lib/usb/src/hidreport.c
===================================================================
--- uspace/lib/usb/src/hidreport.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/hidreport.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -80,4 +80,5 @@
 		d = usb_dp_get_sibling_descriptor(&parser, &parser_data, 
 		    dev->descriptors.configuration, d);
+		++i;
 	}
 	
@@ -118,14 +119,4 @@
 	uint16_t length =  hid_desc->report_desc_info.length;
 	size_t actual_size = 0;
-	
-	/*
-	 * Start session for the control transfer.
-	 */
-	int sess_rc = usb_pipe_start_session(&dev->ctrl_pipe);
-	if (sess_rc != EOK) {
-		usb_log_warning("Failed to start a session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
-	}
 
 	/*
@@ -161,16 +152,4 @@
 		    "%u)\n", actual_size, length);
 		return EINVAL;
-	}
-	
-	/*
-	 * End session for the control transfer.
-	 */
-	sess_rc = usb_pipe_end_session(&dev->ctrl_pipe);
-	if (sess_rc != EOK) {
-		usb_log_warning("Failed to end a session: %s.\n",
-		    str_error(sess_rc));
-		free(*report_desc);
-		*report_desc = NULL;
-		return sess_rc;
 	}
 	
Index: uspace/lib/usb/src/hidreq.c
===================================================================
--- uspace/lib/usb/src/hidreq.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/hidreq.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -56,7 +56,5 @@
  * @retval EOK if successful.
  * @retval EINVAL if no HID device is given.
- * @return Other value inherited from one of functions 
- *         usb_pipe_start_session(), usb_pipe_end_session(),
- *         usb_control_request_set().
+ * @return Other value inherited from function usb_control_request_set().
  */
 int usbhid_req_set_report(usb_pipe_t *ctrl_pipe, int iface_no,
@@ -79,12 +77,5 @@
 	 */
 	
-	int rc, sess_rc;
-	
-	sess_rc = usb_pipe_start_session(ctrl_pipe);
-	if (sess_rc != EOK) {
-		usb_log_warning("Failed to start a session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
-	}
+	int rc;
 	
 	uint16_t value = 0;
@@ -97,16 +88,8 @@
 	    USB_HIDREQ_SET_REPORT, value, iface_no, buffer, buf_size);
 
-	sess_rc = usb_pipe_end_session(ctrl_pipe);
-
-	if (rc != EOK) {
-		usb_log_warning("Error sending output report to the keyboard: "
-		    "%s.\n", str_error(rc));
-		return rc;
-	}
-
-	if (sess_rc != EOK) {
-		usb_log_warning("Error closing session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
+	if (rc != EOK) {
+		usb_log_warning("Error sending output report to the keyboard: "
+		    "%s.\n", str_error(rc));
+		return rc;
 	}
 	
@@ -123,7 +106,5 @@
  * @retval EOK if successful.
  * @retval EINVAL if no HID device is given.
- * @return Other value inherited from one of functions 
- *         usb_pipe_start_session(), usb_pipe_end_session(),
- *         usb_control_request_set().
+ * @return Other value inherited from function usb_control_request_set().
  */
 int usbhid_req_set_protocol(usb_pipe_t *ctrl_pipe, int iface_no,
@@ -146,12 +127,5 @@
 	 */
 	
-	int rc, sess_rc;
-	
-	sess_rc = usb_pipe_start_session(ctrl_pipe);
-	if (sess_rc != EOK) {
-		usb_log_warning("Failed to start a session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
-	}
+	int rc;
 
 	usb_log_debug("Sending Set_Protocol request to the device ("
@@ -162,16 +136,8 @@
 	    USB_HIDREQ_SET_PROTOCOL, protocol, iface_no, NULL, 0);
 
-	sess_rc = usb_pipe_end_session(ctrl_pipe);
-
-	if (rc != EOK) {
-		usb_log_warning("Error sending output report to the keyboard: "
-		    "%s.\n", str_error(rc));
-		return rc;
-	}
-
-	if (sess_rc != EOK) {
-		usb_log_warning("Error closing session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
+	if (rc != EOK) {
+		usb_log_warning("Error sending output report to the keyboard: "
+		    "%s.\n", str_error(rc));
+		return rc;
 	}
 	
@@ -189,7 +155,5 @@
  * @retval EOK if successful.
  * @retval EINVAL if no HID device is given.
- * @return Other value inherited from one of functions 
- *         usb_pipe_start_session(), usb_pipe_end_session(),
- *         usb_control_request_set().
+ * @return Other value inherited from function usb_control_request_set().
  */
 int usbhid_req_set_idle(usb_pipe_t *ctrl_pipe, int iface_no, uint8_t duration)
@@ -211,12 +175,5 @@
 	 */
 	
-	int rc, sess_rc;
-	
-	sess_rc = usb_pipe_start_session(ctrl_pipe);
-	if (sess_rc != EOK) {
-		usb_log_warning("Failed to start a session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
-	}
+	int rc;
 
 	usb_log_debug("Sending Set_Idle request to the device ("
@@ -229,16 +186,8 @@
 	    USB_HIDREQ_SET_IDLE, value, iface_no, NULL, 0);
 
-	sess_rc = usb_pipe_end_session(ctrl_pipe);
-
-	if (rc != EOK) {
-		usb_log_warning("Error sending output report to the keyboard: "
-		    "%s.\n", str_error(rc));
-		return rc;
-	}
-
-	if (sess_rc != EOK) {
-		usb_log_warning("Error closing session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
+	if (rc != EOK) {
+		usb_log_warning("Error sending output report to the keyboard: "
+		    "%s.\n", str_error(rc));
+		return rc;
 	}
 	
@@ -259,7 +208,5 @@
  * @retval EOK if successful.
  * @retval EINVAL if no HID device is given.
- * @return Other value inherited from one of functions 
- *         usb_pipe_start_session(), usb_pipe_end_session(),
- *         usb_control_request_set().
+ * @return Other value inherited from function usb_control_request_set().
  */
 int usbhid_req_get_report(usb_pipe_t *ctrl_pipe, int iface_no, 
@@ -283,12 +230,5 @@
 	 */
 	
-	int rc, sess_rc;
-	
-	sess_rc = usb_pipe_start_session(ctrl_pipe);
-	if (sess_rc != EOK) {
-		usb_log_warning("Failed to start a session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
-	}
+	int rc;
 
 	uint16_t value = 0;
@@ -302,16 +242,8 @@
 	    actual_size);
 
-	sess_rc = usb_pipe_end_session(ctrl_pipe);
-
-	if (rc != EOK) {
-		usb_log_warning("Error sending output report to the keyboard: "
-		    "%s.\n", str_error(rc));
-		return rc;
-	}
-
-	if (sess_rc != EOK) {
-		usb_log_warning("Error closing session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
+	if (rc != EOK) {
+		usb_log_warning("Error sending output report to the keyboard: "
+		    "%s.\n", str_error(rc));
+		return rc;
 	}
 	
@@ -328,7 +260,5 @@
  * @retval EOK if successful.
  * @retval EINVAL if no HID device is given.
- * @return Other value inherited from one of functions 
- *         usb_pipe_start_session(), usb_pipe_end_session(),
- *         usb_control_request_set().
+ * @return Other value inherited from function usb_control_request_set().
  */
 int usbhid_req_get_protocol(usb_pipe_t *ctrl_pipe, int iface_no, 
@@ -351,12 +281,5 @@
 	 */
 	
-	int rc, sess_rc;
-	
-	sess_rc = usb_pipe_start_session(ctrl_pipe);
-	if (sess_rc != EOK) {
-		usb_log_warning("Failed to start a session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
-	}
+	int rc;	
 
 	usb_log_debug("Sending Get_Protocol request to the device ("
@@ -370,16 +293,8 @@
 	    USB_HIDREQ_GET_PROTOCOL, 0, iface_no, buffer, 1, &actual_size);
 
-	sess_rc = usb_pipe_end_session(ctrl_pipe);
-
-	if (rc != EOK) {
-		usb_log_warning("Error sending output report to the keyboard: "
-		    "%s.\n", str_error(rc));
-		return rc;
-	}
-
-	if (sess_rc != EOK) {
-		usb_log_warning("Error closing session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
+	if (rc != EOK) {
+		usb_log_warning("Error sending output report to the keyboard: "
+		    "%s.\n", str_error(rc));
+		return rc;
 	}
 	
@@ -427,12 +342,5 @@
 	 */
 	
-	int rc, sess_rc;
-	
-	sess_rc = usb_pipe_start_session(ctrl_pipe);
-	if (sess_rc != EOK) {
-		usb_log_warning("Failed to start a session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
-	}
+	int rc;
 
 	usb_log_debug("Sending Get_Idle request to the device ("
@@ -448,16 +356,8 @@
 	    &actual_size);
 
-	sess_rc = usb_pipe_end_session(ctrl_pipe);
-
-	if (rc != EOK) {
-		usb_log_warning("Error sending output report to the keyboard: "
-		    "%s.\n", str_error(rc));
-		return rc;
-	}
-
-	if (sess_rc != EOK) {
-		usb_log_warning("Error closing session: %s.\n",
-		    str_error(sess_rc));
-		return sess_rc;
+	if (rc != EOK) {
+		usb_log_warning("Error sending output report to the keyboard: "
+		    "%s.\n", str_error(rc));
+		return rc;
 	}
 	
Index: uspace/lib/usb/src/host/batch.c
===================================================================
--- uspace/lib/usb/src/host/batch.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/host/batch.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -39,12 +39,12 @@
 #include <usb/host/batch.h>
 
+void usb_transfer_batch_call_in(usb_transfer_batch_t *instance);
+void usb_transfer_batch_call_out(usb_transfer_batch_t *instance);
+
 void usb_transfer_batch_init(
     usb_transfer_batch_t *instance,
-    usb_target_t target,
-    usb_transfer_type_t transfer_type,
-    usb_speed_t speed,
-    size_t max_packet_size,
+    endpoint_t *ep,
     char *buffer,
-    char *transport_buffer,
+    char *data_buffer,
     size_t buffer_size,
     char *setup_buffer,
@@ -54,29 +54,48 @@
     void *arg,
     ddf_fun_t *fun,
-		endpoint_t *ep,
-    void *private_data
+    void *private_data,
+    void (*private_data_dtor)(void *p_data)
     )
 {
 	assert(instance);
 	link_initialize(&instance->link);
-	instance->target = target;
-	instance->transfer_type = transfer_type;
-	instance->speed = speed;
-	instance->direction = USB_DIRECTION_BOTH;
+	instance->ep = ep;
 	instance->callback_in = func_in;
 	instance->callback_out = func_out;
 	instance->arg = arg;
 	instance->buffer = buffer;
-	instance->transport_buffer = transport_buffer;
+	instance->data_buffer = data_buffer;
 	instance->buffer_size = buffer_size;
 	instance->setup_buffer = setup_buffer;
 	instance->setup_size = setup_size;
-	instance->max_packet_size = max_packet_size;
 	instance->fun = fun;
 	instance->private_data = private_data;
+	instance->private_data_dtor = private_data_dtor;
 	instance->transfered_size = 0;
 	instance->next_step = NULL;
 	instance->error = EOK;
-	instance->ep = ep;
+	endpoint_use(instance->ep);
+}
+/*----------------------------------------------------------------------------*/
+/** Helper function, calls callback and correctly destroys batch structure.
+ *
+ * @param[in] instance Batch structure to use.
+ */
+void usb_transfer_batch_call_in_and_dispose(usb_transfer_batch_t *instance)
+{
+	assert(instance);
+	usb_transfer_batch_call_in(instance);
+	usb_transfer_batch_dispose(instance);
+}
+/*----------------------------------------------------------------------------*/
+/** Helper function calls callback and correctly destroys batch structure.
+ *
+ * @param[in] instance Batch structure to use.
+ */
+void usb_transfer_batch_call_out_and_dispose(usb_transfer_batch_t *instance)
+{
+	assert(instance);
+	usb_transfer_batch_call_out(instance);
+	usb_transfer_batch_dispose(instance);
 }
 /*----------------------------------------------------------------------------*/
@@ -86,8 +105,9 @@
  *
  */
-void usb_transfer_batch_finish(usb_transfer_batch_t *instance, int error)
+void usb_transfer_batch_finish(usb_transfer_batch_t *instance)
 {
 	assert(instance);
-	instance->error = error;
+	assert(instance->ep);
+	endpoint_release(instance->ep);
 	instance->next_step(instance);
 }
@@ -103,16 +123,14 @@
 	assert(instance);
 	assert(instance->callback_in);
+	assert(instance->ep);
 
 	/* We are data in, we need data */
-	memcpy(instance->buffer, instance->transport_buffer,
-	    instance->buffer_size);
+	memcpy(instance->buffer, instance->data_buffer, instance->buffer_size);
 
 	usb_log_debug("Batch %p done (T%d.%d, %s %s in, %zuB): %s (%d).\n",
-	    instance,
-	    instance->target.address, instance->target.endpoint,
-	    usb_str_speed(instance->speed),
-	    usb_str_transfer_type_short(instance->transfer_type),
-	    instance->transfered_size,
-	    str_error(instance->error), instance->error);
+	    instance, instance->ep->address, instance->ep->endpoint,
+	    usb_str_speed(instance->ep->speed),
+	    usb_str_transfer_type_short(instance->ep->transfer_type),
+	    instance->transfered_size, str_error(instance->error), instance->error);
 
 	instance->callback_in(instance->fun, instance->error,
@@ -130,8 +148,7 @@
 
 	usb_log_debug("Batch %p done (T%d.%d, %s %s out): %s (%d).\n",
-	    instance,
-	    instance->target.address, instance->target.endpoint,
-	    usb_str_speed(instance->speed),
-	    usb_str_transfer_type_short(instance->transfer_type),
+	    instance, instance->ep->address, instance->ep->endpoint,
+	    usb_str_speed(instance->ep->speed),
+	    usb_str_transfer_type_short(instance->ep->transfer_type),
 	    str_error(instance->error), instance->error);
 
@@ -139,4 +156,19 @@
 	    instance->error, instance->arg);
 }
+/*----------------------------------------------------------------------------*/
+/** Correctly dispose all used data structures.
+ *
+ * @param[in] instance Batch structure to use.
+ */
+void usb_transfer_batch_dispose(usb_transfer_batch_t *instance)
+{
+	assert(instance);
+	usb_log_debug("Batch(%p) disposing.\n", instance);
+	if (instance->private_data) {
+		assert(instance->private_data_dtor);
+		instance->private_data_dtor(instance->private_data);
+	}
+	free(instance);
+}
 /**
  * @}
Index: uspace/lib/usb/src/host/device_keeper.c
===================================================================
--- uspace/lib/usb/src/host/device_keeper.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/host/device_keeper.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -48,113 +48,15 @@
 {
 	assert(instance);
-	fibril_mutex_initialize(&instance->guard);
-	fibril_condvar_initialize(&instance->change);
-	instance->last_address = 0;
 	unsigned i = 0;
 	for (; i < USB_ADDRESS_COUNT; ++i) {
 		instance->devices[i].occupied = false;
-		instance->devices[i].control_used = 0;
 		instance->devices[i].handle = 0;
-		list_initialize(&instance->devices[i].endpoints);
+		instance->devices[i].speed = USB_SPEED_MAX;
 	}
-}
-/*----------------------------------------------------------------------------*/
-void usb_device_keeper_add_ep(
-    usb_device_keeper_t *instance, usb_address_t address, endpoint_t *ep)
-{
-	assert(instance);
-	fibril_mutex_lock(&instance->guard);
-	assert(instance->devices[address].occupied);
-	list_append(&ep->same_device_eps, &instance->devices[address].endpoints);
-	fibril_mutex_unlock(&instance->guard);
-}
-/*----------------------------------------------------------------------------*/
-/** Attempt to obtain address 0, blocks.
- *
- * @param[in] instance Device keeper structure to use.
- * @param[in] speed Speed of the device requesting default address.
- */
-void usb_device_keeper_reserve_default_address(
-    usb_device_keeper_t *instance, usb_speed_t speed)
-{
-	assert(instance);
-	fibril_mutex_lock(&instance->guard);
-	while (instance->devices[USB_ADDRESS_DEFAULT].occupied) {
-		fibril_condvar_wait(&instance->change, &instance->guard);
-	}
-	instance->devices[USB_ADDRESS_DEFAULT].occupied = true;
-	instance->devices[USB_ADDRESS_DEFAULT].speed = speed;
-	fibril_mutex_unlock(&instance->guard);
-}
-/*----------------------------------------------------------------------------*/
-/** Attempt to obtain address 0, blocks.
- *
- * @param[in] instance Device keeper structure to use.
- * @param[in] speed Speed of the device requesting default address.
- */
-void usb_device_keeper_release_default_address(usb_device_keeper_t *instance)
-{
-	assert(instance);
-	fibril_mutex_lock(&instance->guard);
-	instance->devices[USB_ADDRESS_DEFAULT].occupied = false;
-	fibril_mutex_unlock(&instance->guard);
-	fibril_condvar_signal(&instance->change);
-}
-/*----------------------------------------------------------------------------*/
-/** Check setup packet data for signs of toggle reset.
- *
- * @param[in] instance Device keeper structure to use.
- * @param[in] target Device to receive setup packet.
- * @param[in] data Setup packet data.
- *
- * Really ugly one.
- */
-void usb_device_keeper_reset_if_need(
-    usb_device_keeper_t *instance, usb_target_t target, const uint8_t *data)
-{
-	assert(instance);
-	fibril_mutex_lock(&instance->guard);
-	if (target.endpoint > 15 || target.endpoint < 0
-	    || target.address >= USB_ADDRESS_COUNT || target.address < 0
-	    || !instance->devices[target.address].occupied) {
-		fibril_mutex_unlock(&instance->guard);
-		usb_log_error("Invalid data when checking for toggle reset.\n");
-		return;
-	}
-
-	switch (data[1])
-	{
-	case 0x01: /*clear feature*/
-		/* recipient is endpoint, value is zero (ENDPOINT_STALL) */
-		if (((data[0] & 0xf) == 1) && ((data[2] | data[3]) == 0)) {
-			link_t *current =
-			    instance->devices[target.address].endpoints.next;
-			while (current !=
-			   &instance->devices[target.address].endpoints)
-			{
-			/* endpoint number is < 16, thus first byte is enough */
-				endpoint_toggle_reset_filtered(
-				    current, data[4]);
-				current = current->next;
-			}
-		}
-	break;
-
-	case 0x9: /* set configuration */
-	case 0x11: /* set interface */
-		/* target must be device */
-		if ((data[0] & 0xf) == 0) {
-			link_t *current =
-			    instance->devices[target.address].endpoints.next;
-			while (current !=
-			   &instance->devices[target.address].endpoints)
-			{
-				endpoint_toggle_reset(current);
-				current = current->next;
-			}
-		}
-	break;
-	}
-	fibril_mutex_unlock(&instance->guard);
+	// TODO: is this hack enough?
+	// (it is needed to allow smooth registration at default address)
+	instance->devices[0].occupied = true;
+	instance->last_address = 0;
+	fibril_mutex_initialize(&instance->guard);
 }
 /*----------------------------------------------------------------------------*/
@@ -184,7 +86,9 @@
 	assert(new_address != USB_ADDRESS_DEFAULT);
 	assert(instance->devices[new_address].occupied == false);
+
 	instance->devices[new_address].occupied = true;
 	instance->devices[new_address].speed = speed;
 	instance->last_address = new_address;
+
 	fibril_mutex_unlock(&instance->guard);
 	return new_address;
@@ -202,7 +106,9 @@
 	assert(instance);
 	fibril_mutex_lock(&instance->guard);
+
 	assert(address > 0);
 	assert(address <= USB11_ADDRESS_MAX);
 	assert(instance->devices[address].occupied);
+
 	instance->devices[address].handle = handle;
 	fibril_mutex_unlock(&instance->guard);
@@ -223,4 +129,5 @@
 	fibril_mutex_lock(&instance->guard);
 	assert(instance->devices[address].occupied);
+
 	instance->devices[address].occupied = false;
 	fibril_mutex_unlock(&instance->guard);
@@ -241,4 +148,5 @@
 	while (address <= USB11_ADDRESS_MAX) {
 		if (instance->devices[address].handle == handle) {
+			assert(instance->devices[address].occupied);
 			fibril_mutex_unlock(&instance->guard);
 			return address;
@@ -262,30 +170,6 @@
 	assert(address >= 0);
 	assert(address <= USB11_ADDRESS_MAX);
+
 	return instance->devices[address].speed;
-}
-/*----------------------------------------------------------------------------*/
-void usb_device_keeper_use_control(
-    usb_device_keeper_t *instance, usb_target_t target)
-{
-	assert(instance);
-	const uint16_t ep = 1 << target.endpoint;
-	fibril_mutex_lock(&instance->guard);
-	while (instance->devices[target.address].control_used & ep) {
-		fibril_condvar_wait(&instance->change, &instance->guard);
-	}
-	instance->devices[target.address].control_used |= ep;
-	fibril_mutex_unlock(&instance->guard);
-}
-/*----------------------------------------------------------------------------*/
-void usb_device_keeper_release_control(
-    usb_device_keeper_t *instance, usb_target_t target)
-{
-	assert(instance);
-	const uint16_t ep = 1 << target.endpoint;
-	fibril_mutex_lock(&instance->guard);
-	assert((instance->devices[target.address].control_used & ep) != 0);
-	instance->devices[target.address].control_used &= ~ep;
-	fibril_mutex_unlock(&instance->guard);
-	fibril_condvar_signal(&instance->change);
 }
 /**
Index: uspace/lib/usb/src/host/endpoint.c
===================================================================
--- uspace/lib/usb/src/host/endpoint.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/host/endpoint.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -34,4 +34,5 @@
  */
 
+#include <assert.h>
 #include <errno.h>
 #include <usb/host/endpoint.h>
@@ -49,5 +50,8 @@
 	instance->max_packet_size = max_packet_size;
 	instance->toggle = 0;
-	link_initialize(&instance->same_device_eps);
+	instance->active = false;
+	fibril_mutex_initialize(&instance->guard);
+	fibril_condvar_initialize(&instance->avail);
+	endpoint_clear_hc_data(instance);
 	return EOK;
 }
@@ -56,6 +60,42 @@
 {
 	assert(instance);
-	list_remove(&instance->same_device_eps);
+	assert(!instance->active);
 	free(instance);
+}
+/*----------------------------------------------------------------------------*/
+void endpoint_set_hc_data(endpoint_t *instance,
+    void *data, int (*toggle_get)(void *), void (*toggle_set)(void *, int))
+{
+	assert(instance);
+	instance->hc_data.data = data;
+	instance->hc_data.toggle_get = toggle_get;
+	instance->hc_data.toggle_set = toggle_set;
+}
+/*----------------------------------------------------------------------------*/
+void endpoint_clear_hc_data(endpoint_t *instance)
+{
+	assert(instance);
+	instance->hc_data.data = NULL;
+	instance->hc_data.toggle_get = NULL;
+	instance->hc_data.toggle_set = NULL;
+}
+/*----------------------------------------------------------------------------*/
+void endpoint_use(endpoint_t *instance)
+{
+	assert(instance);
+	fibril_mutex_lock(&instance->guard);
+	while (instance->active)
+		fibril_condvar_wait(&instance->avail, &instance->guard);
+	instance->active = true;
+	fibril_mutex_unlock(&instance->guard);
+}
+/*----------------------------------------------------------------------------*/
+void endpoint_release(endpoint_t *instance)
+{
+	assert(instance);
+	fibril_mutex_lock(&instance->guard);
+	instance->active = false;
+	fibril_mutex_unlock(&instance->guard);
+	fibril_condvar_signal(&instance->avail);
 }
 /*----------------------------------------------------------------------------*/
@@ -63,4 +103,7 @@
 {
 	assert(instance);
+	if (instance->hc_data.toggle_get)
+		instance->toggle =
+		    instance->hc_data.toggle_get(instance->hc_data.data);
 	return (int)instance->toggle;
 }
@@ -70,22 +113,15 @@
 	assert(instance);
 	assert(toggle == 0 || toggle == 1);
+	if (instance->hc_data.toggle_set)
+		instance->hc_data.toggle_set(instance->hc_data.data, toggle);
 	instance->toggle = toggle;
 }
 /*----------------------------------------------------------------------------*/
-void endpoint_toggle_reset(link_t *ep)
+void endpoint_toggle_reset_filtered(endpoint_t *instance, usb_target_t target)
 {
-	endpoint_t *instance =
-	    list_get_instance(ep, endpoint_t, same_device_eps);
 	assert(instance);
-	instance->toggle = 0;
-}
-/*----------------------------------------------------------------------------*/
-void endpoint_toggle_reset_filtered(link_t *ep, usb_endpoint_t epn)
-{
-	endpoint_t *instance =
-	    list_get_instance(ep, endpoint_t, same_device_eps);
-	assert(instance);
-	if (instance->endpoint == epn)
-		instance->toggle = 0;
+	if (instance->address == target.address &&
+	    (instance->endpoint == target.endpoint || target.endpoint == 0))
+		endpoint_toggle_set(instance, 0);
 }
 /**
Index: uspace/lib/usb/src/host/usb_endpoint_manager.c
===================================================================
--- uspace/lib/usb/src/host/usb_endpoint_manager.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/host/usb_endpoint_manager.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -31,4 +31,5 @@
 #include <errno.h>
 
+#include <usb/debug.h>
 #include <usb/host/usb_endpoint_manager.h>
 
@@ -80,4 +81,12 @@
 	endpoint_destroy(node->ep);
 	free(node);
+}
+/*----------------------------------------------------------------------------*/
+static void node_toggle_reset_filtered(link_t *item, void *arg)
+{
+	assert(item);
+	node_t *node = hash_table_get_instance(item, node_t, link);
+	usb_target_t *target = arg;
+	endpoint_toggle_reset_filtered(node->ep, *target);
 }
 /*----------------------------------------------------------------------------*/
@@ -202,4 +211,7 @@
 
 	node_t *node = hash_table_get_instance(item, node_t, link);
+	if (node->ep->active)
+		return EBUSY;
+
 	instance->free_bw += node->bw;
 	hash_table_remove(&instance->ep_table, key, MAX_KEYS);
@@ -230,2 +242,50 @@
 	return node->ep;
 }
+/*----------------------------------------------------------------------------*/
+/** Check setup packet data for signs of toggle reset.
+ *
+ * @param[in] instance Device keeper structure to use.
+ * @param[in] target Device to receive setup packet.
+ * @param[in] data Setup packet data.
+ *
+ * Really ugly one.
+ */
+void usb_endpoint_manager_reset_if_need(
+    usb_endpoint_manager_t *instance, usb_target_t target, const uint8_t *data)
+{
+	assert(instance);
+	if (target.endpoint > 15 || target.endpoint < 0
+	    || target.address >= USB11_ADDRESS_MAX || target.address < 0) {
+		usb_log_error("Invalid data when checking for toggle reset.\n");
+		return;
+	}
+
+	switch (data[1])
+	{
+	case 0x01: /*clear feature*/
+		/* recipient is endpoint, value is zero (ENDPOINT_STALL) */
+		if (((data[0] & 0xf) == 1) && ((data[2] | data[3]) == 0)) {
+			/* endpoint number is < 16, thus first byte is enough */
+			usb_target_t reset_target =
+			    { .address = target.address, data[4] };
+			fibril_mutex_lock(&instance->guard);
+			hash_table_apply(&instance->ep_table,
+			    node_toggle_reset_filtered, &reset_target);
+			fibril_mutex_unlock(&instance->guard);
+		}
+	break;
+
+	case 0x9: /* set configuration */
+	case 0x11: /* set interface */
+		/* target must be device */
+		if ((data[0] & 0xf) == 0) {
+			usb_target_t reset_target =
+			    { .address = target.address, 0 };
+			fibril_mutex_lock(&instance->guard);
+			hash_table_apply(&instance->ep_table,
+			    node_toggle_reset_filtered, &reset_target);
+			fibril_mutex_unlock(&instance->guard);
+		}
+	break;
+	}
+}
Index: uspace/lib/usb/src/hub.c
===================================================================
--- uspace/lib/usb/src/hub.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/hub.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -40,4 +40,10 @@
 #include <errno.h>
 #include <assert.h>
+#include <usb/debug.h>
+
+/** How much time to wait between attempts to register endpoint 0:0.
+ * The value is based on typical value for port reset + some overhead.
+ */
+#define ENDPOINT_0_0_REGISTER_ATTEMPT_DELAY_USEC (1000 * (10 + 2))
 
 /** Check that HC connection is alright.
@@ -53,35 +59,4 @@
 	} while (false)
 
-
-/** Tell host controller to reserve default address.
- *
- * @param connection Opened connection to host controller.
- * @param speed Speed of the device that will respond on the default address.
- * @return Error code.
- */
-int usb_hc_reserve_default_address(usb_hc_connection_t *connection,
-    usb_speed_t speed)
-{
-	CHECK_CONNECTION(connection);
-
-	return async_req_2_0(connection->hc_phone,
-	    DEV_IFACE_ID(USBHC_DEV_IFACE),
-	    IPC_M_USBHC_RESERVE_DEFAULT_ADDRESS, speed);
-}
-
-/** Tell host controller to release default address.
- *
- * @param connection Opened connection to host controller.
- * @return Error code.
- */
-int usb_hc_release_default_address(usb_hc_connection_t *connection)
-{
-	CHECK_CONNECTION(connection);
-
-	return async_req_1_0(connection->hc_phone,
-	    DEV_IFACE_ID(USBHC_DEV_IFACE),
-	    IPC_M_USBHC_RELEASE_DEFAULT_ADDRESS);
-}
-
 /** Ask host controller for free address assignment.
  *
@@ -178,6 +153,11 @@
  * error codes than those listed as return codes by this function itself).
  *
+ * The @p connection representing connection with host controller does not
+ * need to be started.
+ * This function duplicates the connection to allow simultaneous calls of
+ * this function (i.e. from different fibrils).
+ *
  * @param[in] parent Parent device (i.e. the hub device).
- * @param[in] connection Opened connection to host controller.
+ * @param[in] connection Connection to host controller.
  * @param[in] dev_speed New device speed.
  * @param[in] enable_port Function for enabling signaling through the port the
@@ -206,43 +186,40 @@
     ddf_dev_ops_t *dev_ops, void *new_dev_data, ddf_fun_t **new_fun)
 {
-	CHECK_CONNECTION(connection);
+	assert(connection != NULL);
+	// FIXME: this is awful, we are accessing directly the structure.
+	usb_hc_connection_t hc_conn = {
+		.hc_handle = connection->hc_handle,
+		.hc_phone = -1
+	};
+
+	int rc;
+
+	rc = usb_hc_connection_open(&hc_conn);
+	if (rc != EOK) {
+		return rc;
+	}
+
 
 	/*
 	 * Request new address.
 	 */
-	usb_address_t dev_addr = usb_hc_request_address(connection, dev_speed);
+	usb_address_t dev_addr = usb_hc_request_address(&hc_conn, dev_speed);
 	if (dev_addr < 0) {
+		usb_hc_connection_close(&hc_conn);
 		return EADDRNOTAVAIL;
 	}
 
-	int rc;
-
-	/*
-	 * Reserve the default address.
-	 */
-	rc = usb_hc_reserve_default_address(connection, dev_speed);
-	if (rc != EOK) {
-		rc = EBUSY;
-		goto leave_release_free_address;
-	}
-
-	/*
-	 * Enable the port (i.e. allow signaling through this port).
-	 */
-	rc = enable_port(port_no, arg);
-	if (rc != EOK) {
-		goto leave_release_default_address;
-	}
-
-	/*
-	 * Change the address from default to the free one.
-	 * We need to create a new control pipe for that.
+	/*
+	 * We will not register control pipe on default address.
+	 * The registration might fail. That means that someone else already
+	 * registered that endpoint. We will simply wait and try again.
+	 * (Someone else already wants to add a new device.)
 	 */
 	usb_device_connection_t dev_conn;
 	rc = usb_device_connection_initialize_on_default_address(&dev_conn,
-	    connection);
+	    &hc_conn);
 	if (rc != EOK) {
 		rc = ENOTCONN;
-		goto leave_release_default_address;
+		goto leave_release_free_address;
 	}
 
@@ -252,54 +229,50 @@
 	if (rc != EOK) {
 		rc = ENOTCONN;
+		goto leave_release_free_address;
+	}
+
+	do {
+		rc = usb_pipe_register_with_speed(&ctrl_pipe, dev_speed, 0,
+		    &hc_conn);
+		if (rc != EOK) {
+			/* Do not overheat the CPU ;-). */
+			async_usleep(ENDPOINT_0_0_REGISTER_ATTEMPT_DELAY_USEC);
+		}
+	} while (rc != EOK);
+
+	/*
+	 * Endpoint is registered. We can enable the port and change
+	 * device address.
+	 */
+	rc = enable_port(port_no, arg);
+	if (rc != EOK) {
 		goto leave_release_default_address;
 	}
 
-	/* Before sending any traffic, we need to register this
-	 * endpoint.
-	 */
-	rc = usb_pipe_register(&ctrl_pipe, 0, connection);
-	if (rc != EOK) {
-		rc = EREFUSED;
+	rc = usb_pipe_probe_default_control(&ctrl_pipe);
+	if (rc != EOK) {
+		rc = ESTALL;
 		goto leave_release_default_address;
 	}
-	rc = usb_pipe_probe_default_control(&ctrl_pipe);
-	if (rc != EOK) {
-		rc = ENOTCONN;
+
+	rc = usb_request_set_address(&ctrl_pipe, dev_addr);
+	if (rc != EOK) {
+		rc = ESTALL;
 		goto leave_release_default_address;
 	}
 
-	rc = usb_pipe_start_session(&ctrl_pipe);
-	if (rc != EOK) {
-		rc = ENOTCONN;
-		goto leave_unregister_endpoint;
-	}
-
-	rc = usb_request_set_address(&ctrl_pipe, dev_addr);
-	if (rc != EOK) {
-		rc = ESTALL;
-		goto leave_stop_session;
-	}
-
-	usb_pipe_end_session(&ctrl_pipe);
-
-	/*
-	 * Register the control endpoint for the new device.
-	 */
-	rc = usb_pipe_register(&ctrl_pipe, 0, connection);
-	if (rc != EOK) {
-		rc = EREFUSED;
-		goto leave_unregister_endpoint;
-	}
-
-	/*
-	 * Release the original endpoint.
-	 */
-	unregister_control_endpoint_on_default_address(connection);
-
-	/*
-	 * Once the address is changed, we can return the default address.
-	 */
-	usb_hc_release_default_address(connection);
-
+	/*
+	 * Address changed. We can release the original endpoint, thus
+	 * allowing other to access the default address.
+	 */
+	unregister_control_endpoint_on_default_address(&hc_conn);
+
+	/*
+	 * Time to register the new endpoint.
+	 */
+	rc = usb_pipe_register(&ctrl_pipe, 0, &hc_conn);
+	if (rc != EOK) {
+		goto leave_release_free_address;
+	}
 
 	/*
@@ -316,6 +289,4 @@
 	}
 
-
-
 	/*
 	 * And now inform the host controller about the handle.
@@ -325,5 +296,5 @@
 		.handle = child_handle
 	};
-	rc = usb_hc_register_device(connection, &new_device);
+	rc = usb_hc_register_device(&hc_conn, &new_device);
 	if (rc != EOK) {
 		rc = EDESTADDRREQ;
@@ -349,16 +320,11 @@
 	 * Completely ignoring errors here.
 	 */
-
-leave_stop_session:
-	usb_pipe_end_session(&ctrl_pipe);
-
-leave_unregister_endpoint:
-	usb_pipe_unregister(&ctrl_pipe, connection);
-
 leave_release_default_address:
-	usb_hc_release_default_address(connection);
+	usb_pipe_unregister(&ctrl_pipe, &hc_conn);
 
 leave_release_free_address:
-	usb_hc_unregister_device(connection, dev_addr);
+	usb_hc_unregister_device(&hc_conn, dev_addr);
+
+	usb_hc_connection_close(&hc_conn);
 
 	return rc;
Index: uspace/lib/usb/src/pipepriv.c
===================================================================
--- uspace/lib/usb/src/pipepriv.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
+++ uspace/lib/usb/src/pipepriv.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -0,0 +1,129 @@
+/*
+ * 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.
+ */
+
+/** @addtogroup libusb
+ * @{
+ */
+/** @file
+ * Library internal functions on USB pipes (implementation).
+ */
+#include "pipepriv.h"
+#include <devman.h>
+#include <errno.h>
+#include <assert.h>
+
+/** Ensure exclusive access to the IPC phone of given pipe.
+ *
+ * @param pipe Pipe to be exclusively accessed.
+ */
+void pipe_start_transaction(usb_pipe_t *pipe)
+{
+	fibril_mutex_lock(&pipe->hc_phone_mutex);
+}
+
+/** Terminate exclusive access to the IPC phone of given pipe.
+ *
+ * @param pipe Pipe to be released from exclusive usage.
+ */
+void pipe_end_transaction(usb_pipe_t *pipe)
+{
+	fibril_mutex_unlock(&pipe->hc_phone_mutex);
+}
+
+/** Ensure exclusive access to the pipe as a whole.
+ *
+ * @param pipe Pipe to be exclusively accessed.
+ */
+void pipe_acquire(usb_pipe_t *pipe)
+{
+	fibril_mutex_lock(&pipe->guard);
+}
+
+/** Terminate exclusive access to the pipe as a whole.
+ *
+ * @param pipe Pipe to be released from exclusive usage.
+ */
+void pipe_release(usb_pipe_t *pipe)
+{
+	fibril_mutex_unlock(&pipe->guard);
+}
+
+/** Add reference of active transfers over the pipe.
+ *
+ * @param pipe The USB pipe.
+ * @return Error code.
+ * @retval EOK Currently always.
+ */
+int pipe_add_ref(usb_pipe_t *pipe)
+{
+another_try:
+	pipe_acquire(pipe);
+
+	if (pipe->refcount == 0) {
+		/* Need to open the phone by ourselves. */
+		int phone = devman_device_connect(pipe->wire->hc_handle, 0);
+		if (phone < 0) {
+			// TODO: treat some error as non-recoverable
+			// and return error from here
+			pipe_release(pipe);
+			goto another_try;
+		}
+		/*
+		 * No locking is needed, refcount is zero and whole pipe
+		 * mutex is locked.
+		 */
+		pipe->hc_phone = phone;
+	}
+	pipe->refcount++;
+
+	pipe_release(pipe);
+
+	return EOK;
+}
+
+/** Drop active transfer reference on the pipe.
+ *
+ * @param pipe The USB pipe.
+ */
+void pipe_drop_ref(usb_pipe_t *pipe)
+{
+	pipe_acquire(pipe);
+	assert(pipe->refcount > 0);
+	pipe->refcount--;
+	if (pipe->refcount == 0) {
+		/* We were the last users, let's hang-up. */
+		async_hangup(pipe->hc_phone);
+		pipe->hc_phone = -1;
+	}
+	pipe_release(pipe);
+}
+
+
+/**
+ * @}
+ */
Index: uspace/lib/usb/src/pipepriv.h
===================================================================
--- uspace/lib/usb/src/pipepriv.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
+++ uspace/lib/usb/src/pipepriv.h	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+
+/** @addtogroup libusb
+ * @{
+ */
+/** @file
+ * Library internal functions on USB pipes.
+ */
+#ifndef LIBUSB_PIPEPRIV_H_
+#define LIBUSB_PIPEPRIV_H_
+
+#include <usb/pipes.h>
+
+void pipe_acquire(usb_pipe_t *);
+void pipe_release(usb_pipe_t *);
+
+void pipe_start_transaction(usb_pipe_t *);
+void pipe_end_transaction(usb_pipe_t *);
+
+int pipe_add_ref(usb_pipe_t *);
+void pipe_drop_ref(usb_pipe_t *);
+
+
+#endif
+/**
+ * @}
+ */
Index: uspace/lib/usb/src/pipes.c
===================================================================
--- uspace/lib/usb/src/pipes.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/pipes.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -41,4 +41,5 @@
 #include <errno.h>
 #include <assert.h>
+#include "pipepriv.h"
 
 #define IPC_AGAIN_DELAY (1000 * 2) /* 2ms */
@@ -241,4 +242,7 @@
  * necessary.
  *
+ * @deprecated
+ * Obsoleted with introduction of usb_pipe_start_long_transfer
+ *
  * @param pipe Endpoint pipe to start the session on.
  * @return Error code.
@@ -246,17 +250,5 @@
 int usb_pipe_start_session(usb_pipe_t *pipe)
 {
-	assert(pipe);
-
-	if (usb_pipe_is_session_started(pipe)) {
-		return EBUSY;
-	}
-
-	int phone = devman_device_connect(pipe->wire->hc_handle, 0);
-	if (phone < 0) {
-		return phone;
-	}
-
-	pipe->hc_phone = phone;
-
+	usb_log_warning("usb_pipe_start_session() was deprecated.\n");
 	return EOK;
 }
@@ -265,4 +257,7 @@
 /** Ends a session on the endpoint pipe.
  *
+ * @deprecated
+ * Obsoleted with introduction of usb_pipe_end_long_transfer
+ *
  * @see usb_pipe_start_session
  *
@@ -272,17 +267,5 @@
 int usb_pipe_end_session(usb_pipe_t *pipe)
 {
-	assert(pipe);
-
-	if (!usb_pipe_is_session_started(pipe)) {
-		return ENOENT;
-	}
-
-	int rc = async_hangup(pipe->hc_phone);
-	if (rc != EOK) {
-		return rc;
-	}
-
-	pipe->hc_phone = -1;
-
+	usb_log_warning("usb_pipe_end_session() was deprecated.\n");
 	return EOK;
 }
@@ -298,5 +281,34 @@
 bool usb_pipe_is_session_started(usb_pipe_t *pipe)
 {
-	return (pipe->hc_phone >= 0);
+	pipe_acquire(pipe);
+	bool started = pipe->refcount > 0;
+	pipe_release(pipe);
+	return started;
+}
+
+/** Prepare pipe for a long transfer.
+ *
+ * By a long transfer is mean transfer consisting of several
+ * requests to the HC.
+ * Calling such function is optional and it has positive effect of
+ * improved performance because IPC session is initiated only once.
+ *
+ * @param pipe Pipe over which the transfer will happen.
+ * @return Error code.
+ */
+int usb_pipe_start_long_transfer(usb_pipe_t *pipe)
+{
+	return pipe_add_ref(pipe);
+}
+
+/** Terminate a long transfer on a pipe.
+ *
+ * @see usb_pipe_start_long_transfer
+ *
+ * @param pipe Pipe where to end the long transfer.
+ */
+void usb_pipe_end_long_transfer(usb_pipe_t *pipe)
+{
+	pipe_drop_ref(pipe);
 }
 
Index: uspace/lib/usb/src/pipesinit.c
===================================================================
--- uspace/lib/usb/src/pipesinit.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/pipesinit.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -356,10 +356,14 @@
 	assert(connection);
 
+	fibril_mutex_initialize(&pipe->guard);
 	pipe->wire = connection;
 	pipe->hc_phone = -1;
+	fibril_mutex_initialize(&pipe->hc_phone_mutex);
 	pipe->endpoint_no = endpoint_no;
 	pipe->transfer_type = transfer_type;
 	pipe->max_packet_size = max_packet_size;
 	pipe->direction = direction;
+	pipe->refcount = 0;
+	pipe->auto_reset_halt = false;
 
 	return EOK;
@@ -382,4 +386,6 @@
 	    0, USB_TRANSFER_CONTROL, CTRL_PIPE_MIN_PACKET_SIZE,
 	    USB_DIRECTION_BOTH);
+
+	pipe->auto_reset_halt = true;
 
 	return rc;
@@ -413,10 +419,5 @@
 	int rc;
 
-	TRY_LOOP(failed_attempts) {
-		rc = usb_pipe_start_session(pipe);
-		if (rc == EOK) {
-			break;
-		}
-	}
+	rc = usb_pipe_start_long_transfer(pipe);
 	if (rc != EOK) {
 		return rc;
@@ -439,5 +440,5 @@
 		}
 	}
-	usb_pipe_end_session(pipe);
+	usb_pipe_end_long_transfer(pipe);
 	if (rc != EOK) {
 		return rc;
@@ -461,4 +462,25 @@
     usb_hc_connection_t *hc_connection)
 {
+	return usb_pipe_register_with_speed(pipe, USB_SPEED_MAX + 1,
+	    interval, hc_connection);
+}
+
+/** Register endpoint with a speed at the host controller.
+ *
+ * You will rarely need to use this function because it is needed only
+ * if the registered endpoint is of address 0 and there is no other way
+ * to tell speed of the device at address 0.
+ *
+ * @param pipe Pipe to be registered.
+ * @param speed Speed of the device
+ *	(invalid speed means use previously specified one).
+ * @param interval Polling interval.
+ * @param hc_connection Connection to the host controller (must be opened).
+ * @return Error code.
+ */
+int usb_pipe_register_with_speed(usb_pipe_t *pipe, usb_speed_t speed,
+    unsigned int interval,
+    usb_hc_connection_t *hc_connection)
+{
 	assert(pipe);
 	assert(hc_connection);
@@ -468,13 +490,15 @@
 	}
 
-#define _PACK(high, low) ((high) * 256 + (low))
-
-	return async_req_5_0(hc_connection->hc_phone,
+#define _PACK2(high, low) (((high) << 16) + (low))
+#define _PACK3(high, middle, low) (((((high) << 8) + (middle)) << 8) + (low))
+
+	return async_req_4_0(hc_connection->hc_phone,
 	    DEV_IFACE_ID(USBHC_DEV_IFACE), IPC_M_USBHC_REGISTER_ENDPOINT,
-	    _PACK(pipe->wire->address, pipe->endpoint_no),
-	    _PACK(pipe->transfer_type, pipe->direction),
-	    pipe->max_packet_size, interval);
-
-#undef _PACK
+	    _PACK2(pipe->wire->address, pipe->endpoint_no),
+	    _PACK3(speed, pipe->transfer_type, pipe->direction),
+	    _PACK2(pipe->max_packet_size, interval));
+
+#undef _PACK2
+#undef _PACK3
 }
 
Index: uspace/lib/usb/src/pipesio.c
===================================================================
--- uspace/lib/usb/src/pipesio.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/pipesio.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -49,4 +49,6 @@
 #include <assert.h>
 #include <usbhc_iface.h>
+#include <usb/request.h>
+#include "pipepriv.h"
 
 /** Request an in transfer, no checking of input parameters.
@@ -78,13 +80,16 @@
 	}
 
+	/* Ensure serialization over the phone. */
+	pipe_start_transaction(pipe);
+
 	/*
 	 * Make call identifying target USB device and type of transfer.
 	 */
-	aid_t opening_request = async_send_4(pipe->hc_phone,
+	aid_t opening_request = async_send_3(pipe->hc_phone,
 	    DEV_IFACE_ID(USBHC_DEV_IFACE), ipc_method,
 	    pipe->wire->address, pipe->endpoint_no,
-	    pipe->max_packet_size,
 	    NULL);
 	if (opening_request == 0) {
+		pipe_end_transaction(pipe);
 		return ENOMEM;
 	}
@@ -96,4 +101,10 @@
 	aid_t data_request = async_data_read(pipe->hc_phone, buffer, size,
 	    &data_request_call);
+
+	/*
+	 * Since now on, someone else might access the backing phone
+	 * without breaking the transfer IPC protocol.
+	 */
+	pipe_end_transaction(pipe);
 
 	if (data_request == 0) {
@@ -146,13 +157,9 @@
 
 	if (buffer == NULL) {
-			return EINVAL;
+		return EINVAL;
 	}
 
 	if (size == 0) {
 		return EINVAL;
-	}
-
-	if (!usb_pipe_is_session_started(pipe)) {
-		return EBADF;
 	}
 
@@ -165,8 +172,17 @@
 	}
 
+	int rc;
+	rc = pipe_add_ref(pipe);
+	if (rc != EOK) {
+		return rc;
+	}
+
+
 	size_t act_size = 0;
-	int rc;
 
 	rc = usb_pipe_read_no_checks(pipe, buffer, size, &act_size);
+
+	pipe_drop_ref(pipe);
+
 	if (rc != EOK) {
 		return rc;
@@ -210,13 +226,16 @@
 	}
 
+	/* Ensure serialization over the phone. */
+	pipe_start_transaction(pipe);
+
 	/*
 	 * Make call identifying target USB device and type of transfer.
 	 */
-	aid_t opening_request = async_send_4(pipe->hc_phone,
+	aid_t opening_request = async_send_3(pipe->hc_phone,
 	    DEV_IFACE_ID(USBHC_DEV_IFACE), ipc_method,
 	    pipe->wire->address, pipe->endpoint_no,
-	    pipe->max_packet_size,
 	    NULL);
 	if (opening_request == 0) {
+		pipe_end_transaction(pipe);
 		return ENOMEM;
 	}
@@ -226,4 +245,11 @@
 	 */
 	int rc = async_data_write_start(pipe->hc_phone, buffer, size);
+
+	/*
+	 * Since now on, someone else might access the backing phone
+	 * without breaking the transfer IPC protocol.
+	 */
+	pipe_end_transaction(pipe);
+
 	if (rc != EOK) {
 		async_wait_for(opening_request, NULL);
@@ -260,8 +286,4 @@
 	}
 
-	if (!usb_pipe_is_session_started(pipe)) {
-		return EBADF;
-	}
-
 	if (pipe->direction != USB_DIRECTION_OUT) {
 		return EBADF;
@@ -272,7 +294,35 @@
 	}
 
-	int rc = usb_pipe_write_no_check(pipe, buffer, size);
+	int rc;
+
+	rc = pipe_add_ref(pipe);
+	if (rc != EOK) {
+		return rc;
+	}
+
+	rc = usb_pipe_write_no_check(pipe, buffer, size);
+
+	pipe_drop_ref(pipe);
 
 	return rc;
+}
+
+/** Try to clear endpoint halt of default control pipe.
+ *
+ * @param pipe Pipe for control endpoint zero.
+ */
+static void clear_self_endpoint_halt(usb_pipe_t *pipe)
+{
+	assert(pipe != NULL);
+
+	if (!pipe->auto_reset_halt || (pipe->endpoint_no != 0)) {
+		return;
+	}
+
+
+	/* Prevent indefinite recursion. */
+	pipe->auto_reset_halt = false;
+	usb_request_clear_endpoint_halt(pipe, 0);
+	pipe->auto_reset_halt = true;
 }
 
@@ -293,11 +343,13 @@
     void *data_buffer, size_t data_buffer_size, size_t *data_transfered_size)
 {
+	/* Ensure serialization over the phone. */
+	pipe_start_transaction(pipe);
+
 	/*
 	 * Make call identifying target USB device and control transfer type.
 	 */
-	aid_t opening_request = async_send_4(pipe->hc_phone,
+	aid_t opening_request = async_send_3(pipe->hc_phone,
 	    DEV_IFACE_ID(USBHC_DEV_IFACE), IPC_M_USBHC_CONTROL_READ,
 	    pipe->wire->address, pipe->endpoint_no,
-	    pipe->max_packet_size,
 	    NULL);
 	if (opening_request == 0) {
@@ -311,4 +363,5 @@
 	    setup_buffer, setup_buffer_size);
 	if (rc != EOK) {
+		pipe_end_transaction(pipe);
 		async_wait_for(opening_request, NULL);
 		return rc;
@@ -322,4 +375,12 @@
 	    data_buffer, data_buffer_size,
 	    &data_request_call);
+
+	/*
+	 * Since now on, someone else might access the backing phone
+	 * without breaking the transfer IPC protocol.
+	 */
+	pipe_end_transaction(pipe);
+
+
 	if (data_request == 0) {
 		async_wait_for(opening_request, NULL);
@@ -379,8 +440,4 @@
 	}
 
-	if (!usb_pipe_is_session_started(pipe)) {
-		return EBADF;
-	}
-
 	if ((pipe->direction != USB_DIRECTION_BOTH)
 	    || (pipe->transfer_type != USB_TRANSFER_CONTROL)) {
@@ -388,8 +445,21 @@
 	}
 
+	int rc;
+
+	rc = pipe_add_ref(pipe);
+	if (rc != EOK) {
+		return rc;
+	}
+
 	size_t act_size = 0;
-	int rc = usb_pipe_control_read_no_check(pipe,
+	rc = usb_pipe_control_read_no_check(pipe,
 	    setup_buffer, setup_buffer_size,
 	    data_buffer, data_buffer_size, &act_size);
+
+	if (rc == ESTALL) {
+		clear_self_endpoint_halt(pipe);
+	}
+
+	pipe_drop_ref(pipe);
 
 	if (rc != EOK) {
@@ -418,14 +488,17 @@
     void *data_buffer, size_t data_buffer_size)
 {
+	/* Ensure serialization over the phone. */
+	pipe_start_transaction(pipe);
+
 	/*
 	 * Make call identifying target USB device and control transfer type.
 	 */
-	aid_t opening_request = async_send_5(pipe->hc_phone,
+	aid_t opening_request = async_send_4(pipe->hc_phone,
 	    DEV_IFACE_ID(USBHC_DEV_IFACE), IPC_M_USBHC_CONTROL_WRITE,
 	    pipe->wire->address, pipe->endpoint_no,
 	    data_buffer_size,
-	    pipe->max_packet_size,
 	    NULL);
 	if (opening_request == 0) {
+		pipe_end_transaction(pipe);
 		return ENOMEM;
 	}
@@ -437,4 +510,5 @@
 	    setup_buffer, setup_buffer_size);
 	if (rc != EOK) {
+		pipe_end_transaction(pipe);
 		async_wait_for(opening_request, NULL);
 		return rc;
@@ -447,8 +521,15 @@
 		rc = async_data_write_start(pipe->hc_phone,
 		    data_buffer, data_buffer_size);
+
+		/* All data sent, pipe can be released. */
+		pipe_end_transaction(pipe);
+
 		if (rc != EOK) {
 			async_wait_for(opening_request, NULL);
 			return rc;
 		}
+	} else {
+		/* No data to send, we can release the pipe for others. */
+		pipe_end_transaction(pipe);
 	}
 
@@ -491,8 +572,4 @@
 	}
 
-	if (!usb_pipe_is_session_started(pipe)) {
-		return EBADF;
-	}
-
 	if ((pipe->direction != USB_DIRECTION_BOTH)
 	    || (pipe->transfer_type != USB_TRANSFER_CONTROL)) {
@@ -500,6 +577,19 @@
 	}
 
-	int rc = usb_pipe_control_write_no_check(pipe,
+	int rc;
+
+	rc = pipe_add_ref(pipe);
+	if (rc != EOK) {
+		return rc;
+	}
+
+	rc = usb_pipe_control_write_no_check(pipe,
 	    setup_buffer, setup_buffer_size, data_buffer, data_buffer_size);
+
+	if (rc == ESTALL) {
+		clear_self_endpoint_halt(pipe);
+	}
+
+	pipe_drop_ref(pipe);
 
 	return rc;
Index: uspace/lib/usb/src/recognise.c
===================================================================
--- uspace/lib/usb/src/recognise.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/recognise.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -404,15 +404,5 @@
 	child->driver_data = dev_data;
 
-	rc = usb_pipe_start_session(&ctrl_pipe);
-	if (rc != EOK) {
-		goto failure;
-	}
-
 	rc = usb_device_create_match_ids(&ctrl_pipe, &child->match_ids);
-	if (rc != EOK) {
-		goto failure;
-	}
-
-	rc = usb_pipe_end_session(&ctrl_pipe);
 	if (rc != EOK) {
 		goto failure;
Index: uspace/lib/usb/src/request.c
===================================================================
--- uspace/lib/usb/src/request.c	(revision ef354b6778a2049a1546b354af20cf92410bf74c)
+++ uspace/lib/usb/src/request.c	(revision e50cd7f06f4f69de26916ce998bb262dbcd8bec0)
@@ -871,4 +871,18 @@
 }
 
+/** Clear halt bit of an endpoint pipe (after pipe stall).
+ *
+ * @param pipe Control pipe.
+ * @param ep_index Endpoint index (in native endianness).
+ * @return Error code.
+ */
+int usb_request_clear_endpoint_halt(usb_pipe_t *pipe, uint16_t ep_index)
+{
+	return usb_request_clear_feature(pipe,
+	    USB_REQUEST_TYPE_STANDARD, USB_REQUEST_RECIPIENT_ENDPOINT,
+	    uint16_host2usb(USB_FEATURE_SELECTOR_ENDPOINT_HALT),
+	    uint16_host2usb(ep_index));
+}
+
 /**
  * @}
