Skip to contentSkip to conversation

Intel IOMMU Support

PATCH In review [email protected] 8 participants 63 messages Jun 6, 2007 – Jun 13, 2007

Subsystems (5)
Documentation ACPI PCI Library code +1 more subsystems
lore
Share & tools
lore
#0 lore raw

cover Intel IOMMU Support

Sorry for the resend as my previous posting did not make it to several people.

Hi,
We are pleased to announce the revised version of
the Intel IOMMU driver. This driver incorporates several feedback received from Anid Kleen, David Miller and several others.

Most notable changes from previous postings (apart from general code cleanup) are

1) Replaced linear linked list with RB tree to manage IOVA's.

2) IOVA address is now being allocated from the cards MAX DMA address capability or DMA32bit limit which ever is lower. This allowed us to get rid of having to preserve certain address range when multiple cards of different DMA address capabilities share the same domain.

3)Implements generic pre-allocated pools a.k.a. resource pool to allocate memory for IOVA's and for vt-d page tables. This resource pools grows automagically in the background (work queued to keventd) based on the demand.

4) Did some tuning in terms of locking for iova allocation and freeing.

5) Changed command line options for isa and gfx workaround to CONFIG options, so that when we have all the components adhere to PCI-DMA api's we can easily yank this workarounds.

With all the above changes, the performance greatly improved and the results showed that performance with IOMMU was comparable to without IOMMU configured.

Once again, thanks for providing valuable feedback, please apply this set of patches to MM if you have no further objectios.

Cheers,
-Anil Keshavamurthy
e-mail: [email protected]
Open Source Technology Center
Intel Corp.

#1 lore raw

PATCH 1/10 DMAR detection and parsing logic

This patch adds support for early detection and parsing of DMAR's reported to OS via ACPI tables.

---
 arch/x86_64/Kconfig   |   11 +
 drivers/pci/Makefile  |    3 
 drivers/pci/dmar.c    |  318 ++++++++++++++++++++++++++++++++++++++++++++++++++
 include/acpi/actbl1.h |   27 +++-
 include/linux/dmar.h  |   52 ++++++++
 5 files changed, 404 insertions(+), 7 deletions(-)
arch/x86_64/Kconfig +11 -0
Index: linux-2.6.22-rc3/arch/x86_64/Kconfig
===================================================================
@@ -716,6 +716,17 @@
 	bool "Support mmconfig PCI config space access"
 	depends on PCI && ACPI
 
+config DMAR
+	bool "Support for DMA Remapping Devices (EXPERIMENTAL)"
+	depends on PCI_MSI && ACPI && EXPERIMENTAL
+	default y
+	help
+	  DMA remapping(DMAR) devices support enables independent address
+	  translations for Direct Memory Access(DMA) from Devices.
+	  These DMA remapping devices are reported via ACPI tables
+	  and includes pci device scope covered by these DMA
+	  remapping device.
+
 source "drivers/pci/pcie/Kconfig"
 
 source "drivers/pci/Kconfig"
drivers/pci/Makefile +3 -0
Index: linux-2.6.22-rc3/drivers/pci/Makefile
===================================================================
@@ -20,6 +20,9 @@
 # Build the Hypertransport interrupt support
 obj-$(CONFIG_HT_IRQ) += htirq.o
 
+# Build Intel IOMMU support
+obj-$(CONFIG_DMAR) += dmar.o
+
 #
 # Some architectures use the generic PCI setup functions
 #
drivers/pci/dmar.c new file +318 -0

318 lines not on this page · raw message

include/acpi/actbl1.h +20 -7
Index: linux-2.6.22-rc3/include/acpi/actbl1.h
===================================================================
@@ -257,7 +257,8 @@
 struct acpi_table_dmar {
 	struct acpi_table_header header;	/* Common ACPI table header */
 	u8 width;		/* Host Address Width */
-	u8 reserved[11];
+	u8 flags;
+	u8 reserved[10];
 };
 
 /* DMAR subtable header */
@@ -265,8 +266,6 @@
 struct acpi_dmar_header {
 	u16 type;
 	u16 length;
-	u8 flags;
-	u8 reserved[3];
 };
 
 /* Values for subtable type in struct acpi_dmar_header */
@@ -274,13 +273,15 @@
 enum acpi_dmar_type {
 	ACPI_DMAR_TYPE_HARDWARE_UNIT = 0,
 	ACPI_DMAR_TYPE_RESERVED_MEMORY = 1,
-	ACPI_DMAR_TYPE_RESERVED = 2	/* 2 and greater are reserved */
+	ACPI_DMAR_TYPE_ATSR = 2,
+	ACPI_DMAR_TYPE_RESERVED = 3	/* 3 and greater are reserved */
 };
 
 struct acpi_dmar_device_scope {
 	u8 entry_type;
 	u8 length;
-	u8 segment;
+	u16 reserved;
+	u8 enumeration_id;
 	u8 bus;
 };
 
@@ -290,7 +291,14 @@
 	ACPI_DMAR_SCOPE_TYPE_NOT_USED = 0,
 	ACPI_DMAR_SCOPE_TYPE_ENDPOINT = 1,
 	ACPI_DMAR_SCOPE_TYPE_BRIDGE = 2,
-	ACPI_DMAR_SCOPE_TYPE_RESERVED = 3	/* 3 and greater are reserved */
+	ACPI_DMAR_SCOPE_TYPE_IOAPIC = 3,
+	ACPI_DMAR_SCOPE_TYPE_HPET = 4,
+	ACPI_DMAR_SCOPE_TYPE_RESERVED = 5	/* 5 and greater are reserved */
+};
+
+struct acpi_dmar_pci_path {
+	u8 dev;
+	u8 fn;
 };
 
 /*
@@ -301,6 +309,9 @@
 
 struct acpi_dmar_hardware_unit {
 	struct acpi_dmar_header header;
+	u8 flags;
+	u8 reserved;
+	u16 segment;
 	u64 address;		/* Register Base Address */
 };
 
@@ -312,7 +323,9 @@
 
 struct acpi_dmar_reserved_memory {
 	struct acpi_dmar_header header;
-	u64 address;		/* 4_k aligned base address */
+	u16 reserved;
+	u16 segment;
+	u64 base_address;		/* 4_k aligned base address */
 	u64 end_address;	/* 4_k aligned limit address */
 };
 
include/linux/dmar.h new file +52 -0

52 lines not on this page · raw message

#2 lore raw

PATCH 2/10 Library routine for pre-allocat pool handling

In reply to [email protected]
---
 include/linux/respool.h |   43 +++++++++
 lib/Makefile            |    1 
 lib/respool.c           |  222 ++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 266 insertions(+)
include/linux/respool.h new file +43 -0
Index: linux-2.6.22-rc3/include/linux/respool.h
===================================================================
@@ -0,0 +1,43 @@
+/*
+ * respool.c - library routines for handling generic pre-allocated pool of objects
+ *
+ * Copyright (c) 2006, Intel Corporation.
+ *
+ * This file is released under the GPLv2.
+ *
+ * Copyright (C) 2006 Anil S Keshavamurthy <[email protected]>
+ *
+ */
+
+#ifndef _RESPOOL_H_
+#define _RESPOOL_H_
+
+#include <linux/types.h>
+#include <linux/kernel.h>
+#include <linux/slab.h>
+#include <linux/workqueue.h>
+
+typedef void *(*rpool_alloc_t)(unsigned int, gfp_t);
+typedef void (*rpool_free_t)(void *, unsigned int);
+
+struct resource_pool {
+	struct work_struct work;
+	spinlock_t	pool_lock;	/* pool lock to walk the pool_head */
+	struct list_head pool_head;	/* pool objects list head	*/
+	unsigned int	min_count;	/* min count to maintain	*/
+	unsigned int	grow_count;	/* grow by count when time to grow */
+	unsigned int	curr_count;	/* count of current free objects */
+	unsigned int	alloc_size;	/* objects size			*/
+	rpool_alloc_t 	alloc_mem;	/* pool mem alloc function pointer */
+	rpool_free_t 	free_mem;	/* pool mem free function pointer */
+};
+
+void *get_resource_pool_obj(struct resource_pool *ppool);
+void put_resource_pool_obj(void * vaddr, struct resource_pool *ppool);
+void destroy_resource_pool(struct resource_pool *ppool);
+int init_resource_pool(struct resource_pool *res,
+	unsigned int min_count, unsigned int alloc_size,
+	unsigned int grow_count, rpool_alloc_t alloc_fn,
+	rpool_free_t free_fn);
+
+#endif
lib/Makefile +1 -0
Index: linux-2.6.22-rc3/lib/Makefile
===================================================================
@@ -58,6 +58,7 @@
 obj-$(CONFIG_AUDIT_GENERIC) += audit.o
 
 obj-$(CONFIG_SWIOTLB) += swiotlb.o
+obj-$(CONFIG_DMAR) += respool.o
 obj-$(CONFIG_FAULT_INJECTION) += fault-inject.o
 
 lib-$(CONFIG_GENERIC_BUG) += bug.o
lib/respool.c new file +222 -0

222 lines not on this page · raw message

maintainer
#3 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 1 line · On Wed, 06 Jun 2007 11:57:00 -0700 [email protected] wrote:

That was a terse changelog.

Obvious question: how does this differ from mempools, and would it be better to fill in any gaps in mempool functionality instead of implementing something similar-looking?

The changelog very much should describe all this, as well as explaining what the dynamic behaviour of this new thing is, and what applications are envisaged, what problems it solves, etc, etc.

lib/respool.c

Quoted 2 lines
lib/respool.c new file +0 -0

There are a number of coding-style glitches in here, but scripts/checkpatch.pl catches most of them. Please run it, and fix.

Quoted 49 lines
lib/respool.c new file +48 -0
@@ -0,0 +1,222 @@
+/*
+ * respool.c - library routines for handling generic pre-allocated pool of objects
+ *
+ * Copyright (c) 2006, Intel Corporation.
+ *
+ * This file is released under the GPLv2.
+ *
+ * Copyright (C) 2006 Anil S Keshavamurthy <[email protected]>
+ */
+
+#include <linux/respool.h>
+
+/**
+ * get_resource_pool_obj - gets an object from the pool
+ * @ppool - resource pool in question
+ * This function gets an object from the pool and
+ * if the pool count drops below min_count, this
+ * function schedules work to grow the pool. If
+ * no elements are fount in the pool then this function
+ * tries to get memory from kernel.
+ */
+void * get_resource_pool_obj(struct resource_pool *ppool)
+{
+	unsigned long	flags;
+	struct list_head *plist;
+	bool queue_work = 0;
+
+	spin_lock_irqsave(&ppool->pool_lock, flags);
+	if (!list_empty(&ppool->pool_head)) {
+		plist = ppool->pool_head.next;
+		list_del(plist);
+		ppool->curr_count--;
+	} else {
+		/*Making sure that curr_count is 0 when list is empty */
+		plist = NULL;
+		BUG_ON(ppool->curr_count != 0);
+	}
+
+	/* Check if pool needs to grow */
+	if (ppool->curr_count <= ppool->min_count)
+		queue_work = 1;
+	spin_unlock_irqrestore(&ppool->pool_lock, flags);
+
+	if (queue_work)
+		schedule_work(&ppool->work); /* queue work to grow the pool */
+
+
+	if (plist) {

lib/respool.c line 58

Quoted 10 lines
lib/respool.c new file +10 -0
+		memset(plist, 0, ppool->alloc_size); /* Zero out memory */
+		return plist;
+	}
+
+	/* Out of luck, try to get memory from kernel */
+	plist = (struct list_head *)ppool->alloc_mem(ppool->alloc_size,
+			GFP_ATOMIC);
+
+	return plist;
+}

A function like this should take a gfp_t from the caller, and pass it on.

Quoted 11 lines
lib/respool.c new file +11 -0
+/**
+ * put_resource_pool_obj - puts an object back to the pool
+ * @vaddr - object's address
+ * @ppool - resource pool in question.
+ * This function puts an object back to the pool.
+ */
+void put_resource_pool_obj(void * vaddr, struct resource_pool *ppool)
+{
+	unsigned long	flags;
+	struct list_head *plist = (struct list_head *)vaddr;
+	bool queue_work = 0;

lib/respool.c line 80

Quoted 10 lines
lib/respool.c new file +10 -0
+
+	BUG_ON(!vaddr);
+	BUG_ON(!ppool);
+
+	spin_lock_irqsave(&ppool->pool_lock, flags);
+	list_add(plist, &ppool->pool_head);
+	ppool->curr_count++;
+	if (ppool->curr_count > (ppool->min_count +
+		ppool->grow_count * 2))
+		queue_work = 1;

Some of the indenting is a bit funny-looking in here.

Quoted 6 lines
lib/respool.c new file +6 -0
+	spin_unlock_irqrestore(&ppool->pool_lock, flags);
+
+	if (queue_work)
+		schedule_work(&ppool->work); /* queue work to shrink the pool */
+}
+

lib/respool.c line 96

Quoted 10 lines
lib/respool.c new file +10 -0
+void
+__grow_resource_pool(struct resource_pool *ppool,
+	unsigned int grow_count)
+{
+	unsigned long	flags;
+	struct list_head *plist;
+
+	while(grow_count) {
+		plist = (struct list_head *)ppool->alloc_mem(ppool->alloc_size,
+			GFP_KERNEL);

resource_pool.alloc_mem() already returns void *, so there is never a need to cast its return value.

Quoted 12 lines
lib/respool.c new file +12 -0
+		if (!plist)
+			break;
+
+		/* Add the element to the list */
+		spin_lock_irqsave(&ppool->pool_lock, flags);
+		list_add(plist, &ppool->pool_head);
+		ppool->curr_count++;
+		spin_unlock_irqrestore(&ppool->pool_lock, flags);
+		grow_count--;
+	}
+}
+
#4 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 10 lines · Andrew Morton
Quoted 1 line · On Wed, 06 Jun 2007 11:57:00 -0700 [email protected] wrote:

That was a terse changelog.

Obvious question: how does this differ from mempools, and would it be better to fill in any gaps in mempool functionality instead of implementing something similar-looking?

Very good question. Mempool pre-allocates the elements
to the required minimum count size during its initilization time. However when mempool_alloc() is called it tries to obtain the element from OS and if that fails then it looks for the element in its pool. If there are no elements in its pool and if the gpf_t flags says it can wait then it waits untill someone puts the element back to pool, else if gpf_t flag say it can;t wait then it returns NULL. In other words, mempool acts as *emergency* pool, i.e only if the OS fails to allocate the required memory, then the pool object is used.

In the IOMMU case, we need exactly opposite of what mempool provides, i.e we always want to look for the element in the pool and if the pool has no element then go to OS as a worst case. This resource pool library routines do the same. Again, this resource pools grows and shrinks automatically to maintain the minimum pool elements in the background. I am not sure whether this totally opposite functionality of mempools and resource pools can be merged.

In fact the very first version of this IOMMU patch used mempools and the performance was worse because mempool did not help as IOMMU did a very frequent alloc and free of pool objects and every call to alloc/free used to go to os. Andi Kleen, noticied and told us that mempool usage for IOMMU is wrong and hence we came up with resource pool concept.

Quoted 4 lines

The changelog very much should describe all this, as well as explaining what the dynamic behaviour of this new thing is, and what applications are envisaged, what problems it solves, etc, etc.

I can gladly update the changelog if the resource pool concept is approved. I will fix all the below minor comments.

I envision that this might be useful for all vendor's (IBM, AMD, Intel, etc) IOMMU driver and for any kernel component which does lots of dynamic alloc/free an object of same size.

thanks,
Anil

maintainer
#5 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 23 lines · Anil S
Quoted 10 lines · Andrew Morton
Quoted 1 line · On Wed, 06 Jun 2007 11:57:00 -0700 [email protected] wrote:

That was a terse changelog.

Obvious question: how does this differ from mempools, and would it be better to fill in any gaps in mempool functionality instead of implementing something similar-looking?

Very good question. Mempool pre-allocates the elements
to the required minimum count size during its initilization time. However when mempool_alloc() is called it tries to obtain the element from OS and if that fails then it looks for the element in its pool. If there are no elements in its pool and if the gpf_t flags says it can wait then it waits untill someone puts the element back to pool, else if gpf_t flag say it can;t wait then it returns NULL. In other words, mempool acts as *emergency* pool, i.e only if the OS fails to allocate the required memory, then the pool object is used.

Quoted 8 lines

In the IOMMU case, we need exactly opposite of what mempool provides, i.e we always want to look for the element in the pool and if the pool has no element then go to OS as a worst case. This resource pool library routines do the same. Again, this resource pools grows and shrinks automatically to maintain the minimum pool elements in the background. I am not sure whether this totally opposite functionality of mempools and resource pools can be merged.

Confused.

If resource pools are not designed to provide extra robustness via an emergency pool, then what _are_ they designed for? (Boy this is a hard way to write a changelog!)

Quoted 6 lines

In fact the very first version of this IOMMU patch used mempools and the performance was worse because mempool did not help as IOMMU did a very frequent alloc and free of pool objects and every call to alloc/free used to go to os. Andi Kleen, noticied and told us that mempool usage for IOMMU is wrong and hence we came up with resource pool concept.

You _seem_ to be saying that the resource pools are there purely for alloc/free performance reasons. If so, I'd be skeptical: slab is pretty darned fast.

Quoted 11 lines
Quoted 4 lines

The changelog very much should describe all this, as well as explaining what the dynamic behaviour of this new thing is, and what applications are envisaged, what problems it solves, etc, etc.

I can gladly update the changelog if the resource pool concept is approved. I will fix all the below minor comments.

I envision that this might be useful for all vendor's (IBM, AMD, Intel, etc) IOMMU driver and for any kernel component which does lots of dynamic alloc/free an object of same size.

That's what kmem_cache_alloc() is for?!?!

#6 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 35 lines · Andrew Morton
Quoted 23 lines · Anil S
Quoted 10 lines · Andrew Morton
Quoted 1 line · On Wed, 06 Jun 2007 11:57:00 -0700 [email protected] wrote:

That was a terse changelog.

Obvious question: how does this differ from mempools, and would it be better to fill in any gaps in mempool functionality instead of implementing something similar-looking?

Very good question. Mempool pre-allocates the elements
to the required minimum count size during its initilization time. However when mempool_alloc() is called it tries to obtain the element from OS and if that fails then it looks for the element in its pool. If there are no elements in its pool and if the gpf_t flags says it can wait then it waits untill someone puts the element back to pool, else if gpf_t flag say it can;t wait then it returns NULL. In other words, mempool acts as *emergency* pool, i.e only if the OS fails to allocate the required memory, then the pool object is used.

Quoted 8 lines

In the IOMMU case, we need exactly opposite of what mempool provides, i.e we always want to look for the element in the pool and if the pool has no element then go to OS as a worst case. This resource pool library routines do the same. Again, this resource pools grows and shrinks automatically to maintain the minimum pool elements in the background. I am not sure whether this totally opposite functionality of mempools and resource pools can be merged.

Quoted 5 lines

Confused.

If resource pools are not designed to provide extra robustness via an emergency pool, then what _are_ they designed for? (Boy this is a hard way to write a changelog!)

The resource pool indeed provide extra robustness, the initial pool size will be equal to min_count + grow_count. If the pool object count goes below min_count, then pool grows in the background while serving as emergency pool with min_count of objects in it. If we run out of emergency pool objects before the pool grow in the background, then we go to OS for allocation.

Similary, if the pool objects grows above the max threshold, the objects are freed to OS in the background thread maintaining the pool objects close to min_count + grow_count size.

Quoted 11 lines
Quoted 7 lines

In fact the very first version of this IOMMU patch used mempools and the performance was worse because mempool did not help as IOMMU did a very frequent alloc and free of pool objects and every call to alloc/free used to go to os. Andi Kleen, noticied and told us that mempool usage for IOMMU is wrong and hence we came up with resource pool concept.

You _seem_ to be saying that the resource pools are there purely for alloc/free performance reasons. If so, I'd be skeptical: slab is pretty darned fast.

We need several objects of size say( 4 * sizeof(u64)) and reuse them in dma map/unmap api calls for managing io virtual allocation address that this driver has dished out. Hence having pool of objects where we put the element in the linked list and and get it from the linked list is pretty fast compared to slab.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

The changelog very much should describe all this, as well as explaining what the dynamic behaviour of this new thing is, and what applications are envisaged, what problems it solves, etc, etc.

Quoted 8 lines
Quoted 6 lines

I can gladly update the changelog if the resource pool concept is approved. I will fix all the below minor comments.

I envision that this might be useful for all vendor's (IBM, AMD, Intel, etc) IOMMU driver and for any kernel component which does lots of dynamic alloc/free an object of same size.

That's what kmem_cache_alloc() is for?!?!

We had this kmem_cache_alloc() with mempool concept earlier and Andi suggest to come up with something pre-allocated pool.
Andi, Can you chime in please.

-Anil

#7 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 9 lines · Anil S

The resource pool indeed provide extra robustness, the initial pool size will be equal to min_count + grow_count. If the pool object count goes below min_count, then pool grows in the background while serving as emergency pool with min_count of objects in it. If we run out of emergency pool objects before the pool grow in the background, then we go to OS for allocation.

Similary, if the pool objects grows above the max threshold, the objects are freed to OS in the background thread maintaining the pool objects close to min_count + grow_count size.

slab already has this and it has additional functionalities like reaping over time, when there is no activity...

Quoted 5 lines

We need several objects of size say( 4 * sizeof(u64)) and reuse them in dma map/unmap api calls for managing io virtual allocation address that this driver has dished out. Hence having pool of objects where we put the element in the linked list and and get it from the linked list is pretty fast compared to slab.

Not sure how is this fast compared to slab. Atleast slab is lockless in the fast case..

Quoted 3 lines

We had this kmem_cache_alloc() with mempool concept earlier and Andi suggest to come up with something pre-allocated pool.
Andi, Can you chime in please.

In the initial patches, only for iova we were using slabs + mempool. But for others like pgtable_mempool, we were using simple mempools.

Even slabs + mempool is not same as just usng slab.. slab is lockless for the fast case.

thanks,
suresh

maintainer
#8 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Keshavamurthy, Anil S
Quoted 42 lines · Anil S
Quoted 35 lines · Andrew Morton
Quoted 23 lines · Anil S
Quoted 10 lines · Andrew Morton
Quoted 1 line · On Wed, 06 Jun 2007 11:57:00 -0700 [email protected] wrote:

That was a terse changelog.

Obvious question: how does this differ from mempools, and would it be better to fill in any gaps in mempool functionality instead of implementing something similar-looking?

Very good question. Mempool pre-allocates the elements
to the required minimum count size during its initilization time. However when mempool_alloc() is called it tries to obtain the element from OS and if that fails then it looks for the element in its pool. If there are no elements in its pool and if the gpf_t flags says it can wait then it waits untill someone puts the element back to pool, else if gpf_t flag say it can;t wait then it returns NULL. In other words, mempool acts as *emergency* pool, i.e only if the OS fails to allocate the required memory, then the pool object is used.

Quoted 8 lines

In the IOMMU case, we need exactly opposite of what mempool provides, i.e we always want to look for the element in the pool and if the pool has no element then go to OS as a worst case. This resource pool library routines do the same. Again, this resource pools grows and shrinks automatically to maintain the minimum pool elements in the background. I am not sure whether this totally opposite functionality of mempools and resource pools can be merged.

Quoted 5 lines

Confused.

If resource pools are not designed to provide extra robustness via an emergency pool, then what _are_ they designed for? (Boy this is a hard way to write a changelog!)

Quoted 5 lines

The resource pool indeed provide extra robustness, the initial pool size will be equal to min_count + grow_count. If the pool object count goes below min_count, then pool grows in the background while serving as emergency pool with min_count of objects in it. If we run out of emergency pool objects before the pool grow in the background, then we go to OS for allocation.

This wholly duplicates kswapd functionality.

Quoted 3 lines

Similary, if the pool objects grows above the max threshold, the objects are freed to OS in the background thread maintaining the pool objects close to min_count + grow_count size.

That problem was _introduced_ by resource-pools, so yes, it also needs to be solved there.

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines

In fact the very first version of this IOMMU patch used mempools and the performance was worse because mempool did not help as IOMMU did a very frequent alloc and free of pool objects and every call to alloc/free used to go to os. Andi Kleen, noticied and told us that mempool usage for IOMMU is wrong and hence we came up with resource pool concept.

Quoted 8 lines
Quoted 3 lines

You _seem_ to be saying that the resource pools are there purely for alloc/free performance reasons. If so, I'd be skeptical: slab is pretty darned fast.

We need several objects of size say( 4 * sizeof(u64)) and reuse them in dma map/unmap api calls for managing io virtual allocation address that this driver has dished out. Hence having pool of objects where we put the element in the linked list and and get it from the linked list is pretty fast compared to slab.

slab is fast (and IO is slow!). Do you have benchmark results?

Quoted 17 lines
Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

The changelog very much should describe all this, as well as explaining what the dynamic behaviour of this new thing is, and what applications are envisaged, what problems it solves, etc, etc.

Quoted 8 lines
Quoted 6 lines

I can gladly update the changelog if the resource pool concept is approved. I will fix all the below minor comments.

I envision that this might be useful for all vendor's (IBM, AMD, Intel, etc) IOMMU driver and for any kernel component which does lots of dynamic alloc/free an object of same size.

That's what kmem_cache_alloc() is for?!?!

We had this kmem_cache_alloc() with mempool concept earlier and Andi suggest to come up with something pre-allocated pool.
Andi, Can you chime in please.

#9 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Keshavamurthy, Anil S
Quoted 8 lines · Anil S
Quoted 3 lines

You _seem_ to be saying that the resource pools are there purely for alloc/free performance reasons. If so, I'd be skeptical: slab is pretty darned fast.

We need several objects of size say( 4 * sizeof(u64)) and reuse them in dma map/unmap api calls for managing io virtual allocation address that this driver has dished out. Hence having pool of objects where we put the element in the linked list and and get it from the linked list is pretty fast compared to slab.

SLUB also manages objects using a linked list. Is there a real performance difference?

#10 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 5 lines · Christoph Lameter
Quoted 3 lines · Anil S
Quoted 3 lines

You _seem_ to be saying that the resource pools are there purely for alloc/free performance reasons. If so, I'd be skeptical: slab is pretty darned fast.

Quoted 8 lines
Quoted 5 lines

We need several objects of size say( 4 * sizeof(u64)) and reuse them in dma map/unmap api calls for managing io virtual allocation address that this driver has dished out. Hence having pool of objects where we put the element in the linked list and and get it from the linked list is pretty fast compared to slab.

SLUB also manages objects using a linked list. Is there a real performance difference?

Sorry, I have not tried using SLUB, I will surely check this out.

-Anil

#11 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Andrew Morton

Am Fr 08.06.2007 21:01 schrieb Andrew Morton
<[email protected]>:

Quoted 41 lines
Quoted 27 lines · Anil S
Quoted 6 lines · Andrew Morton
Quoted 2 lines · On Wed, 06 Jun 2007 11:57:00 -0700 [email protected] wrote:

Signed-off-by: Anil S Keshavamurthy
<[email protected]>

Quoted 6 lines

That was a terse changelog.

Obvious question: how does this differ from mempools, and would it be
better to fill in any gaps in mempool functionality instead of implementing something similar-looking?

Very good question. Mempool pre-allocates the elements
to the required minimum count size during its initilization time. However when mempool_alloc() is called it tries to obtain the element from OS and if that fails then it looks for the element in its pool. If there are no elements in its pool and if the gpf_t flags says it can wait then it waits untill someone puts the element back to pool, else if gpf_t flag say it can;t wait then it returns NULL.
In other words, mempool acts as *emergency* pool, i.e only if the OS fails
to allocate the required memory, then the pool object is used.

Quoted 10 lines

In the IOMMU case, we need exactly opposite of what mempool provides,
i.e we always want to look for the element in the pool and if the pool
has no element then go to OS as a worst case. This resource pool library routines do the same. Again, this resource pools grows and shrinks automatically to maintain the minimum pool elements in the background. I am not sure whether this totally opposite functionality of mempools and resource pools can be merged.

Quoted 6 lines

Confused.

If resource pools are not designed to provide extra robustness via an emergency pool, then what _are_ they designed for? (Boy this is a hard way
to write a changelog!)

mempools are designed to manage a limited resource pool by sleeping if necessary until someone else frees a resource. It's basically similar how to main VM works with a sleeping allocation, just in a "private user group"

In the IOMMU case sleeping is not allowed because pci_map_* typically happens inside spinlocks.  But the IOMMU code might need to allocate new page tables and other datastructures in there.

This means mempools don't work for those (the previous version had non sensical
constructs like GFP_ATOMIC mempool calls)

 I haven't looked at Anil's code, but I suspect the only really robust way to handle this case is to always preallocate everything. But I'm not sure
why that would need new library functions; it should be just some simple lists that could be open coded.

If it needs to fall back to the OS for any non pre allocation then it will
likely be flakey under high load. Now that might be ok in some cases -- apparently block layer is much better at handling this than it used to be and networking has to handle it anyways, but it might be still a unpleasant surprise for many drivers. One generic problem is that there are no upcalls when such resources become avaialable again so the upper layers would need to poll to know when to resubmit a request.

It's a pretty messy problem unfortunately.

One relatively easy way out would be to just preallocate a static aperture fully and always map into it. Not sure how much memory that would need -- when it's too large it might take a lot of memory for page tables always and when it's too small it might overflow under high load.

Quoted 1 line

That's what kmem_cache_alloc() is for?!?!

Tradtionally that was not allowed in block layer path. Not sure it is fully obsolete with the recent dirty tracking work, probably not.

Besides it would need to be GFP_ATOMIC and the default atomic pools are not that big.

-Andi

maintainer
#12 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 7 lines · On Fri, 8 Jun 2007 22:43:10 +0200 (CEST) Andreas Kleen <[email protected]> wrote:
Quoted 1 line

That's what kmem_cache_alloc() is for?!?!

Tradtionally that was not allowed in block layer path. Not sure it is fully obsolete with the recent dirty tracking work, probably not.

Besides it would need to be GFP_ATOMIC and the default atomic pools are not that big.

That in itself is a problem. What do we have to do to be able to make these allocations use the *much* stronger GFP_NOIO?

We could perhaps talk to Christoph about arranging for each slabcache to have an optional private reserve page pool. But fixing the GFP_ATOMIC would be better.

#13 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 5 lines · Andrew Morton

On Fri, 8 Jun 2007 22:43:10 +0200 (CEST)

Quoted 2 lines · Andreas Kleen
Quoted 1 line

That's what kmem_cache_alloc() is for?!?!

Quoted 8 lines
Quoted 5 lines

Tradtionally that was not allowed in block layer path. Not sure it is fully obsolete with the recent dirty tracking work, probably not.

Besides it would need to be GFP_ATOMIC and the default atomic pools are not that big.

That in itself is a problem. What do we have to do to be able to make these allocations use the *much* stronger GFP_NOIO?

That still sleeps.

Allow networking and block drivers (and other device drivers) to map SGs without holding spinlocks.

Would be major work. I've been asking for it for years
because it would also avoid other nasty problem, like the panic-on-overflow issues with swiotlb/AMD GART iommu -- it could just block for free space instead.

-Andi

#14 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Andreas Kleen
Quoted 64 lines · Andreas Kleen

Am Fr 08.06.2007 21:01 schrieb Andrew Morton
<[email protected]>:

Quoted 41 lines
Quoted 27 lines · Anil S
Quoted 6 lines · Andrew Morton
Quoted 2 lines · On Wed, 06 Jun 2007 11:57:00 -0700 [email protected] wrote:

Signed-off-by: Anil S Keshavamurthy
<[email protected]>

Quoted 6 lines

That was a terse changelog.

Obvious question: how does this differ from mempools, and would it be
better to fill in any gaps in mempool functionality instead of implementing something similar-looking?

Very good question. Mempool pre-allocates the elements
to the required minimum count size during its initilization time. However when mempool_alloc() is called it tries to obtain the element from OS and if that fails then it looks for the element in its pool. If there are no elements in its pool and if the gpf_t flags says it can wait then it waits untill someone puts the element back to pool, else if gpf_t flag say it can;t wait then it returns NULL.
In other words, mempool acts as *emergency* pool, i.e only if the OS fails
to allocate the required memory, then the pool object is used.

Quoted 10 lines

In the IOMMU case, we need exactly opposite of what mempool provides,
i.e we always want to look for the element in the pool and if the pool
has no element then go to OS as a worst case. This resource pool library routines do the same. Again, this resource pools grows and shrinks automatically to maintain the minimum pool elements in the background. I am not sure whether this totally opposite functionality of mempools and resource pools can be merged.

Quoted 6 lines

Confused.

If resource pools are not designed to provide extra robustness via an emergency pool, then what _are_ they designed for? (Boy this is a hard way
to write a changelog!)

mempools are designed to manage a limited resource pool by sleeping if necessary until someone else frees a resource. It's basically similar how to main VM works with a sleeping allocation, just in a "private user group"

In the IOMMU case sleeping is not allowed because pci_map_* typically happens inside spinlocks.  But the IOMMU code might need to allocate new page tables and other datastructures in there.

This means mempools don't work for those (the previous version had non sensical
constructs like GFP_ATOMIC mempool calls)

Quoted 5 lines

 I haven't looked at Anil's code, but I suspect the only really robust way to handle this case is to always preallocate everything. But I'm not sure
why that would need new library functions; it should be just some simple lists that could be open coded.

Since it is practically impossible to predicit how much to preallocate, we have a min_count+grow_count of object allocated and we always use from this pool. If the object count goes below certain low threshold(which acts as emergency pool from this point), the pool grows by allocating and adding the newly allocated object into the pool in the
worker (keventd) thread.
Again, once the IO pressure is over, the PCI driver
does the unmap calls and we put back the objects back to preallocate pools. The smartness is builtin to the pool as the elements are put back to the pool it detects that the pool count is greater then the threshold and it automagically queues the work to free the objects and bring back the pre-allocated object count back to minimum threshold.
Thus this preallocated pool grow and shrinks based on the demand, while acting as both pre-allocated pools and as emergency pool.

Currently I have made this as a libray functions, if that is not correct, we can pull this and make it part of the Intel IOMMU driver itself. Please do let me know your suggestions.

Quoted 11 lines

If it needs to fall back to the OS for any non pre allocation then it will
likely be flakey under high load. Now that might be ok in some cases -- apparently block layer is much better at handling this than it used to be and networking has to handle it anyways, but it might be still a unpleasant surprise for many drivers. One generic problem is that there are no upcalls when such resources become avaialable again so the upper layers would need to poll to know when to resubmit a request.

Quoted 1 line

It's a pretty messy problem unfortunately.

I agree, worst case if the element is not available in the pool we need to fall back to the OS and if OS fails then it is tough luck.

Quoted 6 lines

One relatively easy way out would be to just preallocate a static aperture fully and always map into it. Not sure how much memory that would need -- when it's too large it might take a lot of memory for page tables always and when it's too small it might overflow under high load.

Yup, and since we need to use the same driver from desktop to servers, preallocation count for servers many not be suitable for desktops.

Quoted 10 lines
Quoted 2 lines

That's what kmem_cache_alloc() is for?!?!

Tradtionally that was not allowed in block layer path. Not sure it is fully obsolete with the recent dirty tracking work, probably not.

Besides it would need to be GFP_ATOMIC and the default atomic pools are not that big.

-Andi

maintainer
#15 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 10 lines · Anil S
Quoted 9 lines

This means mempools don't work for those (the previous version had non sensical
constructs like GFP_ATOMIC mempool calls)

__I haven't looked at Anil's code, but I suspect the only really robust way to handle this case is to always preallocate everything. But I'm not sure
why that would need new library functions; it should be just some simple lists that could be open coded.

Quoted 6 lines

Since it is practically impossible to predicit how much to preallocate, we have a min_count+grow_count of object allocated and we always use from this pool. If the object count goes below certain low threshold(which acts as emergency pool from this point), the pool grows by allocating and adding the newly allocated object into the pool in the
worker (keventd) thread.

Asking keventd to do this might be problematic: there may be code in various dark corners of device drivers which also depend upon keventd services for IO completion, in which case there might be obscure deadlocks, dunno. otoh, keventd already surely does GFP_KERNEL allocations...

But still, the whole thing seems pointless: kswapd is already doing all of this, replenishing the page reserves. So why not use that?

Quoted 9 lines

Again, once the IO pressure is over, the PCI driver
does the unmap calls and we put back the objects back to preallocate pools. The smartness is builtin to the pool as the elements are put back to the pool it detects that the pool count is greater then the threshold and it automagically queues the work to free the objects and bring back the pre-allocated object count back to minimum threshold.
Thus this preallocated pool grow and shrinks based on the demand, while acting as both pre-allocated pools and as emergency pool.

Quoted 3 lines

Currently I have made this as a libray functions, if that is not correct, we can pull this and make it part of the Intel IOMMU driver itself. Please do let me know your suggestions.

I'd say just remove the whole thing and use kmem_cache_alloc().

Put much effort into removing the GFP_ATOMIC and using GFP_NOIO instead:
there's your problem right there.

If for some reason you really can't do that (and a requirement for allocation-in-interrupt is the only valid reason, really) and if you indeed can demonstrate memory allocation failures with certain workloads then let's take a look at that. As I said, attaching a reserve pool to your slab cache might be a suitable approach. But none of these things are
magic: if memory allcoation failures or deadlocks or livelocks are demonstrable with the reserves absent, then they'll also be possible with the reserves present.

Unless you use mempools, and can sleep.

#16 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 5 lines · Andrew Morton

Put much effort into removing the GFP_ATOMIC and using GFP_NOIO instead:
there's your problem right there.

If for some reason you really can't do that (and a requirement for allocation-in-interrupt is the only valid reason, really)

and that's the case here; IO gets submitted from IRQ handlers (both network and block).......

#17 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Andrew Morton
Quoted 1 line · Andrew Morton

I'd say just remove the whole thing and use kmem_cache_alloc().

We will try that.

Quoted 2 lines

Put much effort into removing the GFP_ATOMIC and using GFP_NOIO instead:
there's your problem right there.

As these are called from interrupt handlers, we can't use GFP_NOIO.

Quoted 5 lines

If for some reason you really can't do that (and a requirement for allocation-in-interrupt is the only valid reason, really) and if you indeed can demonstrate memory allocation failures with certain workloads then let's take a look at that. As I said, attaching a reserve pool to your slab cache might be a suitable approach. But none of these things are

I agree. We are better off with enhancing slab infrastructure for this, if needed.

Quoted 5 lines

magic: if memory allcoation failures or deadlocks or livelocks are demonstrable with the reserves absent, then they'll also be possible with the reserves present.

Unless you use mempools, and can sleep.

#18 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 8 lines · Suresh B
Quoted 5 lines

If for some reason you really can't do that (and a requirement for allocation-in-interrupt is the only valid reason, really) and if you indeed can demonstrate memory allocation failures with certain workloads then let's take a look at that. As I said, attaching a reserve pool to your slab cache might be a suitable approach. But none of these things are

I agree. We are better off with enhancing slab infrastructure for this, if needed.

The slab allocators already use the page allocators atomic reserves if called with GFP_ATOMIC.

#19 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Andreas Kleen
Quoted 4 lines · Andreas Kleen
Quoted 1 line

That's what kmem_cache_alloc() is for?!?!

Tradtionally that was not allowed in block layer path. Not sure it is fully obsolete with the recent dirty tracking work, probably not.

Why was it not allowed? Because interrupts are disabled?

Quoted 2 lines

Besides it would need to be GFP_ATOMIC and the default atomic pools are not that big.

Those could be increased. I think Mel has them already increased in mm.

#20 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 7 lines · Christoph Lameter
Quoted 4 lines · Andreas Kleen
Quoted 1 line

That's what kmem_cache_alloc() is for?!?!

Tradtionally that was not allowed in block layer path. Not sure it is fully obsolete with the recent dirty tracking work, probably not.

Why was it not allowed? Because interrupts are disabled?

Allocating memory during page out under low memory could lead to deadlocks. That is because Linux used to make no attempt to limit dirty pages for anonymous mappings and then you could end up with most of your memory dirty and not enough memory cleanable for page out and then when page out needs more memory you could be dead.

[yes that implies that mmap over NFS was always broken]

Now there is a anon dirty limit since a few releases, but I'm not fully convinced it solves the problem completely.

Quoted 4 lines
Quoted 2 lines

Besides it would need to be GFP_ATOMIC and the default atomic pools are not that big.

Those could be increased. I think Mel has them already increased in mm.

That would be lots of wasted memory. I already got >100 MB free on my workstation under steady caching state. Already far too much imho.

-Andi

#21 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 10 lines · Andi Kleen
Quoted 1 line

Why was it not allowed? Because interrupts are disabled?

Allocating memory during page out under low memory could lead to deadlocks. That is because Linux used to make no attempt to limit dirty pages for anonymous mappings and then you could end up with most of your memory dirty and not enough memory cleanable for page out and then when page out needs more memory you could be dead.

[yes that implies that mmap over NFS was always broken]

Right. We got that fixed in 2.6.19.

Quoted 2 lines

Now there is a anon dirty limit since a few releases, but I'm not fully convinced it solves the problem completely.

A gut feeling or is there more?

#22 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 5 lines
Quoted 3 lines

Now there is a anon dirty limit since a few releases, but I'm not fully convinced it solves the problem completely.

A gut feeling or is there more?

Lots of other subsystem can allocate a lot of memory
and they usually don't cooperate and have similar dirty limit concepts. So you could run out of usable memory anyways and then have a similar issue.

For example a flood of network packets could always steal your GFP_ATOMIC pools very quickly in the background (gigabit or 10gig can transfer a lot of data very quickly)

Also iirc try_to_free_pages() is not completely fair and might fail under extreme load for some requesters.

Not requiring memory allocation for any IO would be certainly safer.

Anyways, it's a theoretic question because you can't sleep in there anyways unless something drastic changes in the driver interfaces.

-Andi

#23 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 17 lines · Andi Kleen
Quoted 5 lines
Quoted 3 lines

Now there is a anon dirty limit since a few releases, but I'm not fully convinced it solves the problem completely.

A gut feeling or is there more?

Lots of other subsystem can allocate a lot of memory
and they usually don't cooperate and have similar dirty limit concepts. So you could run out of usable memory anyways and then have a similar issue.

For example a flood of network packets could always steal your GFP_ATOMIC pools very quickly in the background (gigabit or 10gig can transfer a lot of data very quickly) >
Also iirc try_to_free_pages() is not completely fair and might fail under extreme load for some requesters.

Quoted 4 lines

Not requiring memory allocation for any IO would be certainly safer.

Anyways, it's a theoretic question because you can't sleep in there anyways unless something drastic changes in the driver interfaces.

Agree, that the ideal thing would be to make such changes in the driver interfaces where in dma_map_{singe|sg} API's are not called in the interrupt context and/or spinlock held, there by IOMMU drivers are free to block when memory is not available. This seems to be a noble goal invloving huge changes and testing beyond the scope of the current IOMMU driver. I guess it would be ideal if this gets discussed and resolved at kernel summit.

Assuming that we may have to live with the above limitations for a while, what is the best way to allocate memory in the dma_map_{single|sg} API's for the IOMMU drivers? (these memory are required to setup internal IOMMU pagetables etc.)

In the first implementation of ours, we had used mempools api's to allocate memory and we were told that mempools with GFP_ATOMIC is useless and hence in the second implementation we came up with resource pools ( which is preallocate pools) and again as I understand the argument is why create another when we have slab allocation which is similar to this resource pools.

Hence, can I assume that the conclusion of this
discussion is to use kmem_cache_alloc() functions
to allocate memory in dma_map_{single|sg} API's?

Again, if dma_map_{single|sg} API's fails due to failure to allocate memory, the only thing that can be done is to panic as this is what few of the other IOMMU implementation is doing today.

Please advice.

Thanks,
Anil

maintainer
#24 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 6 lines · Anil S

In the first implementation of ours, we had used mempools api's to allocate memory and we were told that mempools with GFP_ATOMIC is useless and hence in the second implementation we came up with resource pools ( which is preallocate pools) and again as I understand the argument is why create another when we have slab allocation which is similar to this resource pools.

Odd. mempool with GFP_ATOMIC is basically equivalent to your resource-pools, isn't it?: we'll try the slab allocator and if that failed, fall back to the reserves.

It's missing the recharge-from-a-kernel-thread functionality but that can be added easily enough if it's useful. It's slightly abusive of the mempool philosophy, but it's probably better to do that than to create a new and very-similar thing.

Quoted 8 lines

Hence, can I assume that the conclusion of this
discussion is to use kmem_cache_alloc() functions
to allocate memory in dma_map_{single|sg} API's?

Again, if dma_map_{single|sg} API's fails due to failure to allocate memory, the only thing that can be done is to panic as this is what few of the other IOMMU implementation is doing today.

If the only option is to panic then something's busted. If it's network IO then there should be a way of dropping the frame. If it's disk IO then we should report the failure and cause an IO error.

#25 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 9 lines · Andrew Morton
Quoted 5 lines

Again, if dma_map_{single|sg} API's fails due to failure to allocate memory, the only thing that can be done is to panic as this is what few of the other IOMMU implementation is doing today.

If the only option is to panic then something's busted. If it's network IO then there should be a way of dropping the frame. If it's disk IO then we should report the failure and cause an IO error.

Just looking at the code.. appears that quite a few popular ones (or should say most) dont even look at the dma_addr_t returned to check for failure.

Thats going to be another major cleanup work.

#26 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Andrew Morton
Quoted 5 lines

If the only option is to panic then something's busted. If it's network IO then there should be a way of dropping the frame. If it's disk IO then we should report the failure and cause an IO error.

An block IO error is basically catastrophic for the system too. There isn't really a concept of "temporary IO error that will resolve itself" concept in Unix.

There are still lots of users of pci_map_single() that don't check the return
value unfortunately. That is mostly in old drivers; it is generally
picked on in reviews now. But then there is no guarantee that these rarely used likely untested error handling paths actually work.

The alternative is writing out random junk which is somewhat risky.

We fixed over time all the pci_map_sg()s at least to do the checks correctly.

When I wrote the IOMMU code originally this wasn't the case and it destroyed several file systems of test systems due to IOMMU leaks in drivers (writing junk over the super block when the IOMMU is full doesn't make mount happy after the next reboot)

Because of these experiences I'm more inclined towards the panic option, although x86-64 defaults to not panic these days.

It would be really much better if sleeping was allowed, but it is hard.

-Andi

#27 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 6 lines · Andi Kleen
Quoted 3 lines

If the only option is to panic then something's busted. If it's network IO then there should be a way of dropping the frame. If it's disk IO then we should report the failure and cause an IO error.

An block IO error is basically catastrophic for the system too. There isn't really a concept of "temporary IO error that will resolve itself" concept in Unix.

In Unix? You mean the block layer cannot handle a I/O error? Not too familiar with it but from what I can tell an I/O operation can be aborted in the request function.

Quoted 4 lines

There are still lots of users of pci_map_single() that don't check the return
value unfortunately. That is mostly in old drivers; it is generally
picked on in reviews now. But then there is no guarantee that these rarely used likely untested error handling paths actually work.

Then we need to review the code and clean these up.

#28 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Andrew Morton
Quoted 10 lines · Andrew Morton
Quoted 6 lines · Anil S

In the first implementation of ours, we had used mempools api's to allocate memory and we were told that mempools with GFP_ATOMIC is useless and hence in the second implementation we came up with resource pools ( which is preallocate pools) and again as I understand the argument is why create another when we have slab allocation which is similar to this resource pools.

Quoted 3 lines

Odd. mempool with GFP_ATOMIC is basically equivalent to your resource-pools, isn't it?: we'll try the slab allocator and if that failed, fall back to the reserves.

slab allocators don;t reserve the memory, in other words this memory can be consumed by VM under memory pressure which we don;t want in IOMMU case.

Nope,they both are exactly opposite.
mempool with GFP_ATOMIC, first tries to get memory from OS and if that fails, it looks for the object in the pool and returns.

Where as resource pool is exactly opposite of mempool, where each time it looks for an object in the pool and if it exist then we return that object else we try to get the memory for OS while scheduling the work to grow the pool objects. In fact, the work is schedule to grow the pool when the low threshold point is hit.

Hence, I still feel resource pool implementation is best choice for IOMMU.

-Anil

maintainer
#29 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 23 lines · Anil S
Quoted 10 lines · Andrew Morton
Quoted 6 lines · Anil S

In the first implementation of ours, we had used mempools api's to allocate memory and we were told that mempools with GFP_ATOMIC is useless and hence in the second implementation we came up with resource pools ( which is preallocate pools) and again as I understand the argument is why create another when we have slab allocation which is similar to this resource pools.

Quoted 3 lines

Odd. mempool with GFP_ATOMIC is basically equivalent to your resource-pools, isn't it?: we'll try the slab allocator and if that failed, fall back to the reserves.

slab allocators don;t reserve the memory, in other words this memory can be consumed by VM under memory pressure which we don;t want in IOMMU case.

Nope,they both are exactly opposite.
mempool with GFP_ATOMIC, first tries to get memory from OS and if that fails, it looks for the object in the pool and returns.

Quoted 5 lines

Where as resource pool is exactly opposite of mempool, where each time it looks for an object in the pool and if it exist then we return that object else we try to get the memory for OS while scheduling the work to grow the pool objects. In fact, the work is schedule to grow the pool when the low threshold point is hit.

I realise all that. But I'd have thought that the mempool approach is actually better: use the page allocator and only deplete your reserve pool when the page allocator fails.

The refill-the-pool-in-the-background feature sounds pretty worthless to me. On a uniprocessor machine (for example), the kernel thread may not get scheduled for tens of milliseconds (easily), which is far, far more than is needed for that reserve pool to become fully consumed.

#30 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 6 lines · Andrew Morton
Quoted 2 lines

Where as resource pool is exactly opposite of mempool, where each time it looks for an object in the pool and if it exist then we return that object else we try to get the memory for OS while scheduling the work to grow the pool objects. In fact, the work is schedule to grow the pool when the low threshold point is hit.

I realise all that. But I'd have thought that the mempool approach is actually better: use the page allocator and only deplete your reserve pool when the page allocator fails.

the problem with that is that if anything downstream from the iommu layer ALSO needs memory, we've now eaten up the last free page and things go splat.

in terms of deadlock avoidance... I wonder if we need something similar to the swap token; once a process dips into the emergency pool, it becomes the only one that gets to use this pool, so that it's entire chain of allocations will succeed, rather than each process only getting halfway through...

But yeah it's minute details and you can argue either way is the right approach.

You can even argue for the old highmem.c approach; go into half the pool before going to the VM, then to kmalloc() and if that fails dip into the second half of the pool.

#31 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 2 lines · Arjan van de Ven

the problem with that is that if anything downstream from the iommu layer ALSO needs memory, we've now eaten up the last free page and things go splat.

Hmmm... We need something like a reservation system right? Higher levels in a atomic context could register their future needs. Then we can avoid overallocating in the iommu layer.

maintainer
#32 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Arjan van de Ven
Quoted 7 lines · On Mon, 11 Jun 2007 18:10:40 -0700 Arjan van de Ven <[email protected]>…
Quoted 6 lines · Andrew Morton
Quoted 5 lines

Where as resource pool is exactly opposite of mempool, where each time it looks for an object in the pool and if it exist then we return that object else we try to get the memory for OS while scheduling the work to grow the pool objects. In fact, the work is schedule to grow the pool when the low threshold point is hit.

Quoted 7 lines
Quoted 3 lines

I realise all that. But I'd have thought that the mempool approach is actually better: use the page allocator and only deplete your reserve pool when the page allocator fails.

the problem with that is that if anything downstream from the iommu layer ALSO needs memory, we've now eaten up the last free page and things go splat.

If that happens, we still have the mempool reserve to fall back to.

I don't see why it is better to consume the reserves before going to the page allocator instead of holding them, err, in reserve.

#33 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 11 lines · Andrew Morton
Quoted 7 lines · On Mon, 11 Jun 2007 18:10:40 -0700 Arjan van de Ven <[email protected]>…
Quoted 5 lines · Andrew Morton
Quoted 2 lines

Where as resource pool is exactly opposite of mempool, where each time it looks for an object in the pool and if it exist then we return that object else we try to get the memory for OS while scheduling the work to grow the pool objects. In fact, the work is schedule to grow the pool when the low threshold point is hit.

I realise all that. But I'd have thought that the mempool approach is actually better: use the page allocator and only deplete your reserve pool when the page allocator fails.

the problem with that is that if anything downstream from the iommu layer ALSO needs memory, we've now eaten up the last free page and things go splat.

If that happens, we still have the mempool reserve to fall back to.

we do, except that we just ate the memory the downstream code would use and get ... so THAT can't get any.

#34 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 14 lines · Arjan van de Ven
Quoted 13 lines · Andrew Morton
Quoted 10 lines · On Mon, 11 Jun 2007 18:10:40 -0700 Arjan van de Ven <[email protected]>…
Quoted 9 lines · Andrew Morton
Quoted 5 lines

Where as resource pool is exactly opposite of mempool, where each time it looks for an object in the pool and if it exist then we return that object else we try to get the memory for OS while scheduling the work to grow the pool objects. In fact, the work is schedule to grow the pool when the low threshold point is hit.

I realise all that. But I'd have thought that the mempool approach is actually better: use the page allocator and only deplete your reserve pool
when the page allocator fails.

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

the problem with that is that if anything downstream from the iommu layer ALSO needs memory, we've now eaten up the last free page and things go splat.

If that happens, we still have the mempool reserve to fall back to.

we do, except that we just ate the memory the downstream code would use and get ... so THAT can't get any.

Then this problem can happen, irrespective of the changes we are reviewing in this patch set. Is n't it?

thanks,
suresh

#35 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Arjan van de Ven
Quoted 14 lines · Arjan van de Ven
Quoted 13 lines · Andrew Morton
Quoted 10 lines · On Mon, 11 Jun 2007 18:10:40 -0700 Arjan van de Ven <[email protected]>…
Quoted 9 lines · Andrew Morton
Quoted 5 lines

Where as resource pool is exactly opposite of mempool, where each time it looks for an object in the pool and if it exist then we return that object else we try to get the memory for OS while scheduling the work to grow the pool objects. In fact, the work is schedule to grow the pool when the low threshold point is hit.

I realise all that. But I'd have thought that the mempool approach is actually better: use the page allocator and only deplete your reserve pool
when the page allocator fails.

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

the problem with that is that if anything downstream from the iommu layer ALSO needs memory, we've now eaten up the last free page and things go splat.

If that happens, we still have the mempool reserve to fall back to.

we do, except that we just ate the memory the downstream code would use and get ... so THAT can't get any.

Then the downstream ought to be using a mempool?

Signature · 1 line
Mathematics is the supreme nostalgia of our time.
#36 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 19 lines · On Wednesday 13 June 2007 20:40:11 Matt Mackall wrote:
Quoted 18 lines · Arjan van de Ven
Quoted 17 lines · Andrew Morton
Quoted 13 lines · On Mon, 11 Jun 2007 18:10:40 -0700 Arjan van de Ven <[email protected]>…
Quoted 9 lines · Andrew Morton
Quoted 5 lines

Where as resource pool is exactly opposite of mempool, where each time it looks for an object in the pool and if it exist then we return that object else we try to get the memory for OS while scheduling the work to grow the pool objects. In fact, the work is schedule to grow the pool when the low threshold point is hit.

I realise all that. But I'd have thought that the mempool approach is actually better: use the page allocator and only deplete your reserve pool
when the page allocator fails.

the problem with that is that if anything downstream from the iommu layer ALSO needs memory, we've now eaten up the last free page and things go splat.

Quoted 6 lines
Quoted 4 lines
Quoted 1 line

If that happens, we still have the mempool reserve to fall back to.

we do, except that we just ate the memory the downstream code would use and get ... so THAT can't get any.

Then the downstream ought to be using a mempool?

Normally there shouldn't be a downstream. PCI IO tends to be not stacked, but at the edges (unless you're talking hypervisors with virtual devices but those definitely have separate memory pools). And the drivers I'm familiar with tend to first grab whatever resources they need and then map the DMA mappings.

-Andi

#37 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Keshavamurthy, Anil S
Quoted 3 lines · Anil S

slab allocators don;t reserve the memory, in other words this memory can be consumed by VM under memory pressure which we don;t want in IOMMU case.

So mempools....

Quoted 3 lines

Nope,they both are exactly opposite.
mempool with GFP_ATOMIC, first tries to get memory from OS and if that fails, it looks for the object in the pool and returns.

How does the difference matter? In both cases you get the memory you want.

Quoted 5 lines

Where as resource pool is exactly opposite of mempool, where each time it looks for an object in the pool and if it exist then we return that object else we try to get the memory for OS while scheduling the work to grow the pool objects. In fact, the work is schedule to grow the pool when the low threshold point is hit.

Grow the mempool when the low level point is hit? Or equip mempools with the functionality that you want?

#38 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Keshavamurthy, Anil S
Quoted 3 lines · Anil S

Hence, can I assume that the conclusion of this discussion is to use kmem_cache_alloc() functions to allocate memory in dma_map_{single|sg} API's?

Use the page allocator for page size allocations. If you need to have specially aligned memory in less than page sized chunks then use kmem_cache_alloc with a specially configured slab.

Quoted 5 lines

Again, if dma_map_{single|sg} API's fails due to failure to allocate memory, the only thing that can be done is to panic as this is what few of the other IOMMU implementation is doing today.

Why does it have to be so severe? The I/O operation fails right?

#39 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 10 lines · Christoph Lameter
Quoted 3 lines · Anil S

Hence, can I assume that the conclusion of this discussion is to use kmem_cache_alloc() functions to allocate memory in dma_map_{single|sg} API's?

Use the page allocator for page size allocations. If you need to have specially aligned memory in less than page sized chunks then use kmem_cache_alloc with a specially configured slab.

Okay, will do this change and get back to the list.

Quoted 7 lines
Quoted 5 lines

Again, if dma_map_{single|sg} API's fails due to failure to allocate memory, the only thing that can be done is to panic as this is what few of the other IOMMU implementation is doing today.

Why does it have to be so severe? The I/O operation fails right?

Not sure. Also most of the callers today don;t check for failures.

-Anil

#40 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Keshavamurthy, Anil S
Quoted 2 lines

Please advice.

I think the short term only safe option would be to fully preallocate an aperture. If it is too small you can try GFP_ATOMIC but it would be just
a unreliable fallback. For safety you could perhaps have some kernel thread that tries to enlarge it in the background depending on current
use. That would be not 100% guaranteed to keep up with load,
but would at least keep up if the system is not too busy.

That is basically what your resource pools do, but they seem to be unnecessarily convoluted for the task :- after all you could just preallocate the page tables and rewrite/flush them without having some kind of allocator inbetween, can't you?

If you make the start value large enough (256+MB?) that might reasonably work. How much memory in page tables would that take? Or perhaps scale it with available memory or available devices.

In theory it could also be precomputed from the block/network device queue lengths etc.; the trouble is just such checks would need to be added to all kinds of other odd subsystems that manage devices too. That would be much more work.

Some investigation how to do sleeping block/network submit would be also interesting (e.g. replace the spinlocks there with mutexes and see how much it affects performance). For networking you would need to keep at least a non sleeping path though because packets can be legally submitted from interrupt context. If it works out then sleeping interfaces to the IOMMU code could be added.

-Andi

#41 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 10 lines · Andi Kleen
Quoted 2 lines

Please advice.

I think the short term only safe option would be to fully preallocate an aperture. If it is too small you can try GFP_ATOMIC but it would be just
a unreliable fallback. For safety you could perhaps have some kernel thread that tries to enlarge it in the background depending on current
use. That would be not 100% guaranteed to keep up with load,
but would at least keep up if the system is not too busy.

Quoted 4 lines

That is basically what your resource pools do, but they seem to be unnecessarily convoluted for the task :- after all you could just preallocate the page tables and rewrite/flush them without having some kind of allocator inbetween, can't you?

Nope, it is not convoluted for the task. If you see carefully how the IO virtual address is obtained, I am basically reusing the the previous translated virutal address once it is freed instead of going for continious IO virtural address. Because of this reuse of IO virtual address, these address tend to map to the same PAGE tables and hence the memory for page tables itself does not grow unless there is that much IO going on in the System where all entries in the page tables are full(which means that much IO is in flight).

The only defect I see in the current resource pool is that I am queuing the work on Keventd to grow the pool which could be a problem as many other subsystem in the kernel depends on keventd and as Anderew pointed out we could dead lock. If we have a separate worker thread to grow the pool then the deadlock issues is taken care.

I would still love to get my current resource pool (just fix the keventd to separate thread to grow the pool) implementations to get into linus kernrl compared to kmem_cache_alloc implementation as I don;t see any benifit in moving to kmem_cache_alloc. But if people want I can provide kmem_cache_alloc implementation too just for comparisions. But this does not solve the fundamental problem that we have today.

So ideally for IOMMU's we should have some preallocated buffers and if the buffers reach certain min_threshould the pool should grow in the background and all of these features is in resource pool implementation. Since we did not see any problems, can we atleat try this resource pool implementation in the linux MM kernels? If it is too bad, then I will change to kmem_cache_alloc() version. If this testing is OKAY, then I will refresh my patch for the coding styles etc and resubmit with resource pool implementation. Andrew??

Quoted 4 lines

If you make the start value large enough (256+MB?) that might reasonably work. How much memory in page tables would that take? Or perhaps scale it with available memory or available devices.

What you are suggesting is to prealloacate and setup the page tables at the begining. But this would waste lot of memory because we don't know ahead of time how large the page table setup should be and in future our hardware can support 64K domains where each domain can dish out independent address from its start to end address range. And pre-setup of tables for all of the 64K domains is not feasible.

Quoted 11 lines

In theory it could also be precomputed from the block/network device queue lengths etc.; the trouble is just such checks would need to be added to all kinds of other odd subsystems that manage devices too. That would be much more work.

Some investigation how to do sleeping block/network submit would be also interesting (e.g. replace the spinlocks there with mutexes and see how much it affects performance). For networking you would need to keep at least a non sleeping path though because packets can be legally submitted from interrupt context. If it works out then sleeping interfaces to the IOMMU code could be added.

Yup, these investigations needs to happen and sooner the better for all and for general linux community.

Quoted 2 lines

-Andi

#42 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Andi Kleen
Quoted 10 lines · Andi Kleen
Quoted 2 lines

Please advice.

I think the short term only safe option would be to fully preallocate an aperture. If it is too small you can try GFP_ATOMIC but it would be just
a unreliable fallback. For safety you could perhaps have some kernel thread that tries to enlarge it in the background depending on current
use. That would be not 100% guaranteed to keep up with load,
but would at least keep up if the system is not too busy.

Quoted 4 lines

That is basically what your resource pools do, but they seem to be unnecessarily convoluted for the task :- after all you could just preallocate the page tables and rewrite/flush them without having some kind of allocator inbetween, can't you?

Each iommu has multiple domains, where each domain represents an address space. PCIexpress endpoints can be located on its own domain for addr protection reasons, and also have its own tag for iotlb cache.

each addr space can be either a 3 or 4 level. So it would be hard to predict how much to setup ahead of time for each domain/device.

Its not a simple single level table with a small window like the gart case.

Just keeping a pool of page sized pages its easy to respond and use where its really necessary without having to lock pages down without knowing real demand.

The addr space is plenty, so growing on demand is the best use of memory available.

Quoted 16 lines

If you make the start value large enough (256+MB?) that might reasonably work. How much memory in page tables would that take? Or perhaps scale it with available memory or available devices.

In theory it could also be precomputed from the block/network device queue lengths etc.; the trouble is just such checks would need to be added to all kinds of other odd subsystems that manage devices too. That would be much more work.

Some investigation how to do sleeping block/network submit would be also interesting (e.g. replace the spinlocks there with mutexes and see how much it affects performance). For networking you would need to keep at least a non sleeping path though because packets can be legally submitted from interrupt context. If it works out then sleeping interfaces to the IOMMU code could be added.

-Andi

#43 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

In reply to Keshavamurthy, Anil S
Quoted 8 lines · Anil S

In the IOMMU case, we need exactly opposite of what mempool provides, i.e we always want to look for the element in the pool and if the pool has no element then go to OS as a worst case. This resource pool library routines do the same. Again, this resource pools grows and shrinks automatically to maintain the minimum pool elements in the background. I am not sure whether this totally opposite functionality of mempools and resource pools can be merged.

What functionality are you missing in the page allocator? It seems that is does what you want?

#44 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 11 lines · Christoph Lameter
Quoted 8 lines · Anil S

In the IOMMU case, we need exactly opposite of what mempool provides, i.e we always want to look for the element in the pool and if the pool has no element then go to OS as a worst case. This resource pool library routines do the same. Again, this resource pools grows and shrinks automatically to maintain the minimum pool elements in the background. I am not sure whether this totally opposite functionality of mempools and resource pools can be merged.

Quoted 2 lines

What functionality are you missing in the page allocator? It seems that is does what you want?

Humm..I basically want to allocate memory during interrupt context and expect not to fail. I know this is a hard requirement :)
I want to be able to reserve certain amount of memory specifically for IOMMU purpose.

-Anil

#45 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 4 lines · Anil S
Quoted 2 lines

What functionality are you missing in the page allocator? It seems that is does what you want?

Humm..I basically want to allocate memory during interrupt context and expect not to fail. I know this is a hard requirement :)

The page allocator can do that for you. The reserves are configurable. Not failing is a thing unseen in the computer world.

Quoted 2 lines

I want to be able to reserve certain amount of memory specifically for IOMMU purpose.

That is of course a problem unless you allocate memory beforehand. Mempool?

#46 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 6 lines · Christoph Lameter
Quoted 2 lines · Anil S
Quoted 1 line

What functionality are you missing in the page allocator? It seems that is does what you want?

Humm..I basically want to allocate memory during interrupt context and expect not to fail. I know this is a hard requirement :)

The page allocator can do that for you. The reserves are configurable. Not failing is a thing unseen in the computer world.

but the page allocator reserve is shared.. and you will need this one EXACTLY when the shared pool is getting low... it's not an uncorrelated thing!

#47 lore raw

Re: [Intel-IOMMU 02/10] Library routine for pre-allocat pool handling

Quoted 5 lines · Arjan van de Ven
Quoted 4 lines · Christoph Lameter
Quoted 2 lines · Anil S
Quoted 2 lines

What functionality are you missing in the page allocator? It seems that is does what you want?

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Humm..I basically want to allocate memory during interrupt context and expect not to fail. I know this is a hard requirement :)

The page allocator can do that for you. The reserves are configurable. Not failing is a thing unseen in the computer world.

but the page allocator reserve is shared.. and you will need this one EXACTLY when the shared pool is getting low... it's not an uncorrelated thing!

I think what needs to be done first is to define under what conditions the allocation should not fail. There is certainly no way to have GFP_ATOMIC allocation that never fail. After all memory is limited and at some point we need to reclaim memory.

#48 lore raw

PATCH 3/10 PCI generic helper function

In reply to [email protected]

When devices are under a p2p bridge, upstream
transactions get replaced by the device id of the bridge as it owns the PCIE transaction. Hence its necessary to setup translations on behalf of the bridge as well. Due to this limitation all devices under a p2p share the same domain in a DMAR.

We just cache the type of device, if its a native PCIe device or not for later use.

---
 drivers/pci/pci.h    |    1 +
 drivers/pci/probe.c  |   14 ++++++++++++++
 drivers/pci/search.c |   30 ++++++++++++++++++++++++++++++
 include/linux/pci.h  |    2 ++
 4 files changed, 47 insertions(+)
drivers/pci/pci.h +1 -0
Index: linux-2.6.22-rc3/drivers/pci/pci.h
===================================================================
@@ -92,3 +92,4 @@
 	return NULL;
 }
 
+struct pci_dev *pci_find_upstream_pcie_bridge(struct pci_dev *pdev);
drivers/pci/probe.c +14 -0
Index: linux-2.6.22-rc3/drivers/pci/probe.c
===================================================================
@@ -803,6 +803,19 @@
 	kfree(pci_dev);
 }
 
+static void set_pcie_port_type(struct pci_dev *pdev)
+{
+	int pos;
+	u16 reg16;
+
+	pos = pci_find_capability(pdev, PCI_CAP_ID_EXP);
+	if (!pos)
+		return;
+	pdev->is_pcie = 1;
+	pci_read_config_word(pdev, pos + PCI_EXP_FLAGS, &reg16);
+	pdev->pcie_type = (reg16 & PCI_EXP_FLAGS_TYPE) >> 4;
+}
+
 /**
  * pci_cfg_space_size - get the configuration space size of the PCI device.
  * @dev: PCI device
@@ -917,6 +930,7 @@
 	dev->device = (l >> 16) & 0xffff;
 	dev->cfg_size = pci_cfg_space_size(dev);
 	dev->error_state = pci_channel_io_normal;
+	set_pcie_port_type(dev);
 
 	/* Assume 32-bit PCI; let 64-bit PCI cards (which are far rarer)
 	   set this higher, assuming the system even supports it.  */
drivers/pci/search.c +30 -0
Index: linux-2.6.22-rc3/drivers/pci/search.c
===================================================================
@@ -14,6 +14,36 @@
 #include "pci.h"
 
 DECLARE_RWSEM(pci_bus_sem);
+/*
+ * find the upstream PCIE-to-PCI bridge of a PCI device
+ * if the device is PCIE, return NULL
+ * if the device isn't connected to a PCIE bridge (that is its parent is a
+ * legacy PCI bridge and the bridge is directly connected to bus 0), return its
+ * parent
+ */
+struct pci_dev *
+pci_find_upstream_pcie_bridge(struct pci_dev *pdev)
+{
+	struct pci_dev *tmp = NULL;
+
+	if (pdev->is_pcie)
+		return NULL;
+	while (1) {
+		if (!pdev->bus->self)
+			break;
+		pdev = pdev->bus->self;
+		/* a p2p bridge */
+		if (!pdev->is_pcie) {
+			tmp = pdev;
+			continue;
+		}
+		/* PCI device should connect to a PCIE bridge */
+		BUG_ON(pdev->pcie_type != PCI_EXP_TYPE_PCI_BRIDGE);
+		return pdev;
+	}
+
+	return tmp;
+}
 
 static struct pci_bus *pci_do_find_bus(struct pci_bus *bus, unsigned char busnr)
 {
include/linux/pci.h +2 -0
Index: linux-2.6.22-rc3/include/linux/pci.h
===================================================================
@@ -139,6 +139,7 @@
 	unsigned short	subsystem_device;
 	unsigned int	class;		/* 3 bytes: (base,sub,prog-if) */
 	u8		hdr_type;	/* PCI header type (`multi' flag masked out) */
+	u8		pcie_type;	/* PCI-E device/port type */
 	u8		rom_base_reg;	/* which config register controls the ROM */
 	u8		pin;  		/* which interrupt pin this device uses */
 
@@ -181,6 +182,7 @@
 	unsigned int 	msi_enabled:1;
 	unsigned int	msix_enabled:1;
 	unsigned int	is_managed:1;
+	unsigned int	is_pcie:1;
 	atomic_t	enable_cnt;	/* pci_enable_device has been called */
 
 	u32		saved_config_space[16]; /* config space saved at suspend time */
#49 lore raw

PATCH 4/10 clflush_cache_range now takes size param

In reply to [email protected]

Introduce the size param for clflush_cache_range().

---
 arch/x86_64/mm/pageattr.c       |    6 +++---
 include/asm-x86_64/cacheflush.h |    1 +
 2 files changed, 4 insertions(+), 3 deletions(-)
arch/x86_64/mm/pageattr.c +3 -3
Index: linux-2.6.22-rc3/arch/x86_64/mm/pageattr.c
===================================================================
@@ -61,10 +61,10 @@
 	return base;
 } 
 
-static void cache_flush_page(void *adr)
+void clflush_cache_range(void *adr, int size)
 {
 	int i;
-	for (i = 0; i < PAGE_SIZE; i += boot_cpu_data.x86_clflush_size)
+	for (i = 0; i < size; i += boot_cpu_data.x86_clflush_size)
 		asm volatile("clflush (%0)" :: "r" (adr + i));
 }
 
@@ -80,7 +80,7 @@
 	list_for_each_entry(pg, l, lru) {
 		void *adr = page_address(pg);
 		if (cpu_has_clflush)
-			cache_flush_page(adr);
+ 			clflush_cache_range(adr, PAGE_SIZE);
 	}
 	__flush_tlb_all();
 }
include/asm-x86_64/cacheflush.h +1 -0
Index: linux-2.6.22-rc3/include/asm-x86_64/cacheflush.h
===================================================================
@@ -27,6 +27,7 @@
 void global_flush_tlb(void); 
 int change_page_attr(struct page *page, int numpages, pgprot_t prot);
 int change_page_attr_addr(unsigned long addr, int numpages, pgprot_t prot);
+void clflush_cache_range(void *addr, int size);
 
 #ifdef CONFIG_DEBUG_RODATA
 void mark_rodata_ro(void);
#50 lore raw

PATCH 5/10 IOVA allocation and management routines

In reply to [email protected]

This code implements a generic IOVA allocation and
management. As per Dave's suggestion we are now allocating IO virtual address from Higher DMA limit address rather than lower end address and this eliminated the need to preserve the IO virtual address for multiple devices sharing the same domain virtual address.

Also this code uses red black trees to store the allocated and reserved iova nodes. This showed a good performance improvements over previous linear linked list.

---
 drivers/pci/iova.c |  344 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 drivers/pci/iova.h |   57 ++++++++
 2 files changed, 401 insertions(+)
drivers/pci/iova.c new file +344 -0
Index: linux-2.6.22-rc3/drivers/pci/iova.c
===================================================================
@@ -0,0 +1,344 @@
+/*
+ * Copyright (c) 2006, Intel Corporation.
+ *
+ * This file is released under the GPLv2.
+ *
+ * Copyright (C) 2006 Anil S Keshavamurthy <[email protected]>
+ */
+
+#include "iova.h"
+
+void
+init_iova_domain(struct iova_domain *iovad)
+{
+	spin_lock_init(&iovad->iova_alloc_lock);
+	spin_lock_init(&iovad->iova_rbtree_lock);
+	iovad->rbroot = RB_ROOT;
+	iovad->cached32_node = NULL;
+
+}
+
+static struct rb_node *
+__get_cached_rbnode(struct iova_domain *iovad, unsigned long *limit_pfn)
+{
+	if ((*limit_pfn != DMA_32BIT_PFN) ||
+		(iovad->cached32_node == NULL))
+		return rb_last(&iovad->rbroot);
+	else {
+		struct rb_node *prev_node = rb_prev(iovad->cached32_node);
+		struct iova *curr_iova =
+			container_of(iovad->cached32_node, struct iova, node);
+		*limit_pfn = curr_iova->pfn_lo - 1;
+		return prev_node;
+	}
+}
+
+static inline void
+__cached_rbnode_insert_update(struct iova_domain *iovad,
+	unsigned long limit_pfn, struct iova *new)
+{
+	if (limit_pfn != DMA_32BIT_PFN)
+		return;
+	iovad->cached32_node = &new->node;
+}
+
+static inline void
+__cached_rbnode_delete_update(struct iova_domain *iovad, struct iova *free)
+{
+	struct iova *cached_iova;
+	struct rb_node *curr;
+
+	if (!iovad->cached32_node)
+		return;
+	curr = iovad->cached32_node;
+	cached_iova = container_of(curr, struct iova, node);
+
+	if (free->pfn_lo >= cached_iova->pfn_lo)
+		iovad->cached32_node = rb_next(&free->node);
+}
+
+static inline int __alloc_iova_range(struct iova_domain *iovad,
+	unsigned long size, unsigned long limit_pfn, struct iova *new)
+{
+	struct rb_node *curr = NULL;
+	unsigned long flags;
+	unsigned long saved_pfn;
+
+	/* Walk the tree backwards */
+	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
+	saved_pfn = limit_pfn;
+	curr = __get_cached_rbnode(iovad, &limit_pfn);
+	while (curr) {
+		struct iova *curr_iova = container_of(curr, struct iova, node);
+		if (limit_pfn < curr_iova->pfn_lo)
+			goto move_left;
+		if (limit_pfn < curr_iova->pfn_hi)
+			goto adjust_limit_pfn;
+		if ((curr_iova->pfn_hi + size) <= limit_pfn)
+			break;	/* found a free slot */
+adjust_limit_pfn:
+		limit_pfn = curr_iova->pfn_lo - 1;
+move_left:
+		curr = rb_prev(curr);
+	}
+
+	if ((!curr) && !(IOVA_START_PFN + size <= limit_pfn)) {
+		spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
+		return -ENOMEM;
+	}
+	new->pfn_hi = limit_pfn;
+	new->pfn_lo = limit_pfn - size + 1;
+
+	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
+	return 0;
+}
+
+static void
+iova_insert_rbtree(struct rb_root *root, struct iova *iova)
+{
+	struct rb_node **new = &(root->rb_node), *parent = NULL;
+	/* Figure out where to put new node */
+	while (*new) {
+		struct iova *this = container_of(*new, struct iova, node);
+		parent = *new;
+
+		if (iova->pfn_lo < this->pfn_lo)
+			new = &((*new)->rb_left);
+		else if (iova->pfn_lo > this->pfn_lo)
+			new = &((*new)->rb_right);
+		else
+			BUG(); /* this should not happen */
+	}
+	/* Add new node and rebalance tree. */
+	rb_link_node(&iova->node, parent, new);
+	rb_insert_color(&iova->node, root);
+}
+
+/**
+ * alloc_iova - allocates an iova
+ * @iovad - iova domain in question
+ * @size - size of page frames to allocate
+ * @limit_pfn - max limit address
+ * This function allocates an iova in the range limit_pfn to IOVA_START_PFN
+ * looking from limit_pfn instead from IOVA_START_PFN.
+ */
+
+struct iova *
+alloc_iova(struct iova_domain *iovad, unsigned long size, unsigned long limit_pfn)
+{
+	unsigned long flags,flags1;
+	struct iova *new_iova;
+	int ret;
+
+	new_iova = alloc_iova_mem();
+	if (!new_iova)
+		return NULL;
+
+	spin_lock_irqsave(&iovad->iova_alloc_lock, flags1);
+	ret = __alloc_iova_range(iovad, size, limit_pfn, new_iova);
+
+	if (ret) {
+		spin_unlock_irqrestore(&iovad->iova_alloc_lock, flags1);
+		free_iova_mem(new_iova);
+		return NULL;
+	}
+
+	/* Insert the new_iova into domain rbtree by holding writer lock */
+	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
+	iova_insert_rbtree(&iovad->rbroot, new_iova);
+	__cached_rbnode_insert_update(iovad, limit_pfn, new_iova);
+	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
+
+	spin_unlock_irqrestore(&iovad->iova_alloc_lock, flags1);
+
+	return new_iova;
+}
+
+/**
+ * find_iova - find's an iova for a given pfn
+ * @iovad - iova domain in question.
+ * pfn - page frame number
+ * This function finds and returns an iova belonging to the
+ * given doamin which matches the given pfn.
+ */
+struct iova *find_iova(struct iova_domain *iovad, unsigned long pfn)
+{
+	unsigned long flags;
+	struct rb_node *node;
+
+	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
+	node = iovad->rbroot.rb_node;
+	while (node) {
+		struct iova *iova = container_of(node, struct iova, node);
+
+		/* If pfn falls within iova's range, return iova */
+		if ((pfn >= iova->pfn_lo) && (pfn <= iova->pfn_hi)) {
+			spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
+			return iova;
+		}
+
+		if (pfn < iova->pfn_lo)
+			node = node->rb_left;
+		else if (pfn > iova->pfn_lo)
+			node = node->rb_right;
+	}
+
+	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
+	return NULL;
+}
+
+/**
+ * __free_iova - frees the given iova
+ * @iovad: iova domain in question.
+ * @iova: iova in question.
+ * Frees the given iova belonging to the giving domain
+ */
+void
+__free_iova(struct iova_domain *iovad, struct iova *iova)
+{
+	unsigned long flags;
+
+	if (iova) {
+		spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
+		__cached_rbnode_delete_update(iovad, iova);
+		rb_erase(&iova->node, &iovad->rbroot);
+		spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
+		free_iova_mem(iova);
+	}
+}
+/**
+ * free_iova - finds and frees the iova for a given pfn
+ * @iovad: - iova domain in question.
+ * @pfn: - pfn that is allocated previously
+ * This functions finds an iova for a given pfn and then
+ * frees the iova from that domain.
+ */
+
+void
+free_iova(struct iova_domain *iovad, unsigned long pfn)
+{
+	struct iova *iova = find_iova(iovad, pfn);
+	__free_iova(iovad, iova);
+
+}
+
+/**
+ * put_iova_domain - destroys the iova doamin
+ * @iovad: - iova domain in question.
+ * All the iova's in that domain are destroyed.
+ */
+void put_iova_domain(struct iova_domain *iovad)
+{
+	struct rb_node *node;
+	unsigned long flags;
+
+	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
+	while ((node = rb_first(&iovad->rbroot))) {
+		struct iova *iova = container_of(node, struct iova, node);
+		rb_erase(node, &iovad->rbroot);
+		free_iova_mem(iova);
+	}
+	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
+}
+
+static inline int
+__is_range_overlap(struct rb_node *node, unsigned long pfn_lo, unsigned long pfn_hi)
+{
+	struct iova * iova = container_of(node, struct iova, node);
+
+	if ((pfn_lo <= iova->pfn_hi) && (pfn_hi >= iova->pfn_lo))
+		return 1;
+	return 0;
+}
+
+static inline struct iova *
+__insert_new_range(struct iova_domain *iovad, unsigned long pfn_lo, unsigned long pfn_hi)
+{
+	struct iova *iova;
+
+	iova = alloc_iova_mem();
+	if (!iova)
+		return iova;
+
+	iova->pfn_hi = pfn_hi;
+	iova->pfn_lo = pfn_lo;
+	iova_insert_rbtree(&iovad->rbroot,iova);
+	return iova;
+}
+
+static inline void
+__adjust_overlap_range(struct iova *iova, unsigned long *pfn_lo, unsigned long *pfn_hi)
+{
+	if (*pfn_lo < iova->pfn_lo)
+		iova->pfn_lo = *pfn_lo;
+	if (*pfn_hi > iova->pfn_hi)
+		*pfn_lo = iova->pfn_hi + 1;
+}
+
+/**
+ * reserve_iova - reserves an iova in the given range
+ * @iovad: - iova domain pointer
+ * @pfn_lo: - lower page frame address
+ * @pfn_hi:- higher pfn adderss
+ * This function allocates reserves the address range from pfn_lo to pfn_hi so
+ * that this address is not dished out as part of alloc_iova.
+ */
+struct iova *
+reserve_iova(struct iova_domain *iovad, unsigned long pfn_lo, unsigned long pfn_hi)
+{
+	struct rb_node *node;
+	unsigned long flags, flags1;
+	struct iova *iova;
+	unsigned int overlap = 0;
+
+	spin_lock_irqsave(&iovad->iova_alloc_lock, flags);
+	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags1);
+	for (node = rb_first(&iovad->rbroot); node; node = rb_next(node)) {
+		if (__is_range_overlap(node, pfn_lo, pfn_hi)) {
+			iova = container_of(node, struct iova, node);
+			__adjust_overlap_range(iova, &pfn_lo, &pfn_hi);
+			if ((pfn_lo >= iova->pfn_lo) &&
+				(pfn_hi <= iova->pfn_hi))
+				goto finish;
+			overlap = 1;
+
+		} else if (overlap)
+				break;
+	}
+
+	/* We are here either becasue this is the first reserver node
+	 * or need to insert remaining non overlap addr range
+	 */
+	iova = __insert_new_range(iovad, pfn_lo, pfn_hi);
+finish:
+
+	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags1);
+	spin_unlock_irqrestore(&iovad->iova_alloc_lock, flags);
+	return iova;
+}
+
+/**
+ * copy_reserved_iova - copies the reserved between domains
+ * @from: - source doamin from where to copy
+ * @to: - destination domin where to copy
+ * This function copies reserved iova's from one doamin to
+ * other.
+ */
+void
+copy_reserved_iova(struct iova_domain *from, struct iova_domain *to)
+{
+	unsigned long flags, flags1;
+	struct rb_node *node;
+	spin_lock_irqsave(&from->iova_alloc_lock, flags);
+	spin_lock_irqsave(&from->iova_rbtree_lock, flags1);
+	for (node = rb_first(&from->rbroot); node; node = rb_next(node)) {
+		struct iova *iova = container_of(node, struct iova, node);
+		struct iova *new_iova;
+		new_iova = reserve_iova(to, iova->pfn_lo, iova->pfn_hi);
+		if (!new_iova)
+			printk(KERN_ERR "Reserve iova range %lx@%lx failed\n",
+				iova->pfn_lo, iova->pfn_lo);
+	}
+	spin_unlock_irqrestore(&from->iova_rbtree_lock, flags1);
+	spin_unlock_irqrestore(&from->iova_alloc_lock, flags);
+}
drivers/pci/iova.h new file +57 -0

57 lines not on this page · raw message

maintainer
#51 lore raw

Re: [Intel-IOMMU 05/10] IOVA allocation and management routines

Quoted 15 lines · On Wed, 06 Jun 2007 11:57:03 -0700 [email protected] wrote:

This code implements a generic IOVA allocation and
management. As per Dave's suggestion we are now allocating IO virtual address from Higher DMA limit address rather than lower end address and this eliminated the need to preserve the IO virtual address for multiple devices sharing the same domain virtual address.

Also this code uses red black trees to store the allocated and reserved iova nodes. This showed a good performance improvements over previous linear linked list.

...

drivers/pci/iova.c new file +2 -0
+
+/**

drivers/pci/iova.c line 127

Quoted 10 lines
drivers/pci/iova.c new file +10 -0
+ * alloc_iova - allocates an iova
+ * @iovad - iova domain in question
+ * @size - size of page frames to allocate
+ * @limit_pfn - max limit address
+ * This function allocates an iova in the range limit_pfn to IOVA_START_PFN
+ * looking from limit_pfn instead from IOVA_START_PFN.
+ */
+
+struct iova *
+alloc_iova(struct iova_domain *iovad, unsigned long size, unsigned long limit_pfn)

Generally we omit the blank line between the end-of-comment and the function definition.

Quoted 15 lines
drivers/pci/iova.c new file +15 -0
+{
+	unsigned long flags,flags1;
+	struct iova *new_iova;
+	int ret;
+
+	new_iova = alloc_iova_mem();
+	if (!new_iova)
+		return NULL;
+
+	spin_lock_irqsave(&iovad->iova_alloc_lock, flags1);
+	ret = __alloc_iova_range(iovad, size, limit_pfn, new_iova);
+
+	if (ret) {
+		spin_unlock_irqrestore(&iovad->iova_alloc_lock, flags1);
+		free_iova_mem(new_iova);

drivers/pci/iova.c line 152

Quoted 10 lines
drivers/pci/iova.c new file +10 -0
+		return NULL;
+	}
+
+	/* Insert the new_iova into domain rbtree by holding writer lock */
+	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags);
+	iova_insert_rbtree(&iovad->rbroot, new_iova);
+	__cached_rbnode_insert_update(iovad, limit_pfn, new_iova);
+	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags);
+
+	spin_unlock_irqrestore(&iovad->iova_alloc_lock, flags1);

spin_unlock_irqrestore() within spin_unlock_irqrestore() is fairly pointless. You can just use spin_lock()/spin_unlock() for the innermost pair.

drivers/pci/iova.c line 247

Quoted 8 lines
drivers/pci/iova.c new file +5 -0
+	return new_iova;
+}
 
...
 
+__is_range_overlap(struct rb_node *node, unsigned long pfn_lo, unsigned long pfn_hi)
+{
+	struct iova * iova = container_of(node, struct iova, node);

run checkpatch.pl, please.

Quoted 29 lines
drivers/pci/iova.c new file +26 -0
+	if ((pfn_lo <= iova->pfn_hi) && (pfn_hi >= iova->pfn_lo))
+		return 1;
+	return 0;
+}
+
 
...
 
+struct iova *
+reserve_iova(struct iova_domain *iovad, unsigned long pfn_lo, unsigned long pfn_hi)
+{
+	struct rb_node *node;
+	unsigned long flags, flags1;
+	struct iova *iova;
+	unsigned int overlap = 0;
+
+	spin_lock_irqsave(&iovad->iova_alloc_lock, flags);
+	spin_lock_irqsave(&iovad->iova_rbtree_lock, flags1);
+	for (node = rb_first(&iovad->rbroot); node; node = rb_next(node)) {
+		if (__is_range_overlap(node, pfn_lo, pfn_hi)) {
+			iova = container_of(node, struct iova, node);
+			__adjust_overlap_range(iova, &pfn_lo, &pfn_hi);
+			if ((pfn_lo >= iova->pfn_lo) &&
+				(pfn_hi <= iova->pfn_hi))
+				goto finish;
+			overlap = 1;
+
+		} else if (overlap)
+				break;

drivers/pci/iova.c line 316

Quoted 10 lines
drivers/pci/iova.c new file +10 -0
+	}
+
+	/* We are here either becasue this is the first reserver node
+	 * or need to insert remaining non overlap addr range
+	 */
+	iova = __insert_new_range(iovad, pfn_lo, pfn_hi);
+finish:
+
+	spin_unlock_irqrestore(&iovad->iova_rbtree_lock, flags1);
+	spin_unlock_irqrestore(&iovad->iova_alloc_lock, flags);

ditto

Quoted 7 lines
drivers/pci/iova.c new file +7 -0
+	return iova;
+}
+
+/**
+ * copy_reserved_iova - copies the reserved between domains
+ * @from: - source doamin from where to copy
+ * @to: - destination domin where to copy

drivers/pci/iova.c line 333

Quoted 10 lines
drivers/pci/iova.c new file +10 -0
+ * This function copies reserved iova's from one doamin to
+ * other.
+ */
+void
+copy_reserved_iova(struct iova_domain *from, struct iova_domain *to)
+{
+	unsigned long flags, flags1;
+	struct rb_node *node;
+	spin_lock_irqsave(&from->iova_alloc_lock, flags);
+	spin_lock_irqsave(&from->iova_rbtree_lock, flags1);

Add a blank line betwee the end-of-locals and the start-of-statements

drivers/pci/iova.c line 343

Quoted 10 lines
drivers/pci/iova.c new file +10 -0
+	for (node = rb_first(&from->rbroot); node; node = rb_next(node)) {
+		struct iova *iova = container_of(node, struct iova, node);
+		struct iova *new_iova;
+		new_iova = reserve_iova(to, iova->pfn_lo, iova->pfn_hi);
+		if (!new_iova)
+			printk(KERN_ERR "Reserve iova range %lx@%lx failed\n",
+				iova->pfn_lo, iova->pfn_lo);
+	}
+	spin_unlock_irqrestore(&from->iova_rbtree_lock, flags1);
+	spin_unlock_irqrestore(&from->iova_alloc_lock, flags);

ditto

Quoted 18 lines

+}
Index: linux-2.6.22-rc3/drivers/pci/iova.h
===================================================================

drivers/pci/iova.h new file +12 -0
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2006, Intel Corporation.
+ *
+ * This file is released under the GPLv2.
+ *
+ * Copyright (C) 2006 Anil S Keshavamurthy <[email protected]>
+ *
+ */
+
+#ifndef _IOVA_H_
+#define _IOVA_H_
+

drivers/pci/iova.h line 22

Quoted 10 lines
drivers/pci/iova.h new file +10 -0
+#include <linux/types.h>
+#include <linux/kernel.h>
+#include <linux/rbtree.h>
+#include <linux/dma-mapping.h>
+
+
+#define PAGE_SHIFT_4K		(12)
+#define PAGE_SIZE_4K		(1UL << PAGE_SHIFT_4K)
+#define PAGE_MASK_4K		(((u64)-1) << PAGE_SHIFT_4K)
+#define PAGE_ALIGN_4K(addr)	(((addr) + PAGE_SIZE_4K - 1) & PAGE_MASK_4K)

hm. We can't use the architecture's PAGE_SHIFT and friends here?

Quoted 36 lines
drivers/pci/iova.h new file +34 -0
+#define IOVA_START_ADDR		(0x1000)
+#define IOVA_START_PFN		(IOVA_START_ADDR >> PAGE_SHIFT_4K)
+
+#define IOVA_PFN(addr)		((addr) >> PAGE_SHIFT_4K)
+#define DMA_32BIT_PFN	IOVA_PFN(DMA_32BIT_MASK)
+#define DMA_64BIT_PFN	IOVA_PFN(DMA_64BIT_MASK)
+
+/* iova structure */
+struct iova {
+	struct rb_node	node;
+	unsigned long	pfn_hi; /* IOMMU dish out addr hi */
+	unsigned long	pfn_lo; /* IOMMU dish out addr lo */
+};
+
+/* holds all the iova translations for a domain */
+struct iova_domain {
+	spinlock_t	iova_alloc_lock;/* Lock to protect iova  allocation */
+	spinlock_t	iova_rbtree_lock; /* Lock to protect update of rbtree */
+	struct rb_root	rbroot;		/* iova domain rbtree root */
+	struct rb_node	*cached32_node; /* Save last alloced node to optimize alloc */
+};
+
+struct iova *alloc_iova_mem(void);
+void free_iova_mem(struct iova *iova);
+void free_iova(struct iova_domain *iovad, unsigned long pfn);
+void __free_iova(struct iova_domain *iovad, struct iova *iova);
+struct iova * alloc_iova(struct iova_domain *iovad, unsigned long size, unsigned long limit_pfn);
+struct iova * reserve_iova(struct iova_domain *iovad, unsigned long pfn_lo, unsigned long pfn_hi);
+void copy_reserved_iova(struct iova_domain *from, struct iova_domain *to);
+void init_iova_domain(struct iova_domain *iovad);
+struct iova * find_iova(struct iova_domain *iovad, unsigned long pfn);
+void put_iova_domain(struct iova_domain *iovad);
+
+#endif
Signature · 1 line
-- 
#52 lore raw

Re: [Intel-IOMMU 05/10] IOVA allocation and management routines

Quoted 10 lines · Andrew Morton

drivers/pci/iova.h line 22

Quoted 5 lines · On Wed, 06 Jun 2007 11:57:03 -0700 [email protected] wrote:
drivers/pci/iova.h new file +5 -0
+
+#define PAGE_SHIFT_4K		(12)
+#define PAGE_SIZE_4K		(1UL << PAGE_SHIFT_4K)
+#define PAGE_MASK_4K		(((u64)-1) << PAGE_SHIFT_4K)
+#define PAGE_ALIGN_4K(addr)	(((addr) + PAGE_SIZE_4K - 1) & PAGE_MASK_4K)

hm. We can't use the architecture's PAGE_SHIFT and friends here?

I will see how I can get rid of this.

-Anil

#53 lore raw

PATCH 6/10 Intel IOMMU driver

In reply to [email protected]

Actual intel IOMMU driver. Hardware spec can be found at:
http://www.intel.com/technology/virtualization

This driver sets X86_64 'dma_ops', so hook into standard DMA APIs. In this way, PCI driver will get virtual DMA address. This change is transparent to PCI drivers.

---
 Documentation/Intel-IOMMU.txt       |   93 +
 Documentation/kernel-parameters.txt |   10 
 arch/x86_64/kernel/pci-dma.c        |    9 
 drivers/pci/Makefile                |    5 
 drivers/pci/intel-iommu.c           | 1918 ++++++++++++++++++++++++++++++++++++
 drivers/pci/intel-iommu.h           |  296 +++++
 include/linux/dmar.h                |   23 
 7 files changed, 2353 insertions(+), 1 deletion(-)
Documentation/Intel-IOMMU.txt new file +93 -0
Index: linux-2.6.22-rc3/Documentation/Intel-IOMMU.txt
===================================================================
@@ -0,0 +1,93 @@
+Linux IOMMU Support
+===================
+
+The architecture spec can be obtained from the below location.
+
+http://www.intel.com/technology/virtualization/
+
+This guide gives a quick cheat sheet for some basic understanding.
+
+Some Keywords
+
+DMAR - DMA remapping
+DRHD - DMA Engine Reporting Structure
+RMRR - Reserved memory Region Reporting Structure
+ZLR  - Zero length reads from PCI devices
+IOVA - IO Virtual address.
+
+Basic stuff
+-----------
+
+ACPI enumerates and lists the different DMA engines in the platform, and
+device scope relationships between PCI devices and which DMA engine  controls
+them.
+
+What is RMRR?
+-------------
+
+There are some devices the BIOS controls, for e.g USB devices to perform
+PS2 emulation. The regions of memory used for these devices are marked
+reserved in the e820 map. When we turn on DMA translation, DMA to those
+regions will fail. Hence BIOS uses RMRR to specify these regions along with
+devices that need to access these regions. OS is expected to setup
+unity mappings for these regions for these devices to access these regions.
+
+How is IOVA generated?
+---------------------
+
+Well behaved drivers call pci_map_*() calls before sending command to device
+that needs to perform DMA. Once DMA is completed and mapping is no longer
+required, device performs a pci_unmap_*() calls to unmap the region.
+
+The Intel IOMMU driver allocates a virtual address per domain. Each PCIE
+device has its own domain (hence protection). Devices under p2p bridges
+share the virtual address with all devices under the p2p bridge due to
+transaction id aliasing for p2p bridges.
+
+IOVA generation is pretty generic. We used the same technique as vmalloc()
+but these are not global address spaces, but separate for each domain.
+Different DMA engines may support different number of domains.
+
+We also allocate gaurd pages with each mapping, so we can attempt to catch
+any overflow that might happen.
+
+
+Graphics Problems?
+------------------
+If you encounter issues with graphics devices, you can try adding
+option intel_iommu=igfx_off to turn off the integrated graphics engine.
+
+Some exceptions to IOVA
+-----------------------
+Interrupt ranges are not address translated, (0xfee00000 - 0xfeefffff).
+The same is true for peer to peer transactions. Hence we reserve the
+address from PCI MMIO ranges so they are not allocated for IOVA addresses.
+
+Boot Message Sample
+-------------------
+
+Something like this gets printed indicating presence of DMAR tables
+in ACPI.
+
+ACPI: DMAR (v001 A M I  OEMDMAR  0x00000001 MSFT 0x00000097) @ 0x000000007f5b5ef0
+
+When DMAR is being processed and initialized by ACPI, prints DMAR locations
+and any RMRR's processed.
+
+ACPI DMAR:Host address width 36
+ACPI DMAR:DRHD (flags: 0x00000000)base: 0x00000000fed90000
+ACPI DMAR:DRHD (flags: 0x00000000)base: 0x00000000fed91000
+ACPI DMAR:DRHD (flags: 0x00000001)base: 0x00000000fed93000
+ACPI DMAR:RMRR base: 0x00000000000ed000 end: 0x00000000000effff
+ACPI DMAR:RMRR base: 0x000000007f600000 end: 0x000000007fffffff
+
+When DMAR is enabled for use, you will notice..
+
+PCI-DMA: Using DMAR IOMMU
+
+TBD
+----
+
+- For compatibility testing, could use unity map domain for all devices, just
+  provide a 1-1 for all useful memory under a single domain for all devices.
+- API for paravirt ops for abstracting functionlity for VMM folks.
Documentation/kernel-parameters.txt +10 -0
Index: linux-2.6.22-rc3/Documentation/kernel-parameters.txt
===================================================================
@@ -776,6 +776,16 @@
 
 	inttest=	[IA64]
 
+	intel_iommu=	[DMAR] Intel IOMMU driver (DMAR) option
+		off
+			Disable intel iommu driver.
+		igfx_off [Default Off]
+			By default, gfx is mapped as normal device. If a gfx
+			device has a dedicated DMAR unit, the DMAR unit is
+			bypassed by not enabling DMAR with this option. In
+			this case, gfx device will use physical address for
+			DMA.
+
 	io7=		[HW] IO7 for Marvel based alpha systems
 			See comment before marvel_specify_io7 in
 			arch/alpha/kernel/core_marvel.c.
arch/x86_64/kernel/pci-dma.c +9 -0
Index: linux-2.6.22-rc3/arch/x86_64/kernel/pci-dma.c
===================================================================
@@ -7,6 +7,7 @@
 #include <linux/string.h>
 #include <linux/pci.h>
 #include <linux/module.h>
+#include <linux/dmar.h>
 #include <asm/io.h>
 #include <asm/proto.h>
 #include <asm/calgary.h>
@@ -303,6 +304,10 @@
 	detect_calgary();
 #endif
 
+#ifdef CONFIG_DMAR
+	detect_intel_iommu();
+#endif
+
 #ifdef CONFIG_SWIOTLB
 	pci_swiotlb_init();
 #endif
@@ -314,6 +319,10 @@
 	calgary_iommu_init();
 #endif
 
+#ifdef CONFIG_DMAR
+	intel_iommu_init();
+#endif
+
 #ifdef CONFIG_IOMMU
 	gart_iommu_init();
 #endif
drivers/pci/Makefile +4 -1
Index: linux-2.6.22-rc3/drivers/pci/Makefile
===================================================================
@@ -21,7 +21,10 @@
 obj-$(CONFIG_HT_IRQ) += htirq.o
 
 # Build Intel IOMMU support
-obj-$(CONFIG_DMAR) += dmar.o
+obj-$(CONFIG_DMAR) += dmar.o iova.o intel-iommu.o
+
+#Build Intel-IOMMU support
+obj-$(CONFIG_DMAR) += iova.o dmar.o intel-iommu.o
 
 #
 # Some architectures use the generic PCI setup functions
drivers/pci/intel-iommu.c new file +1918 -0

1,918 lines not on this page · raw message

drivers/pci/intel-iommu.h new file +296 -0

296 lines not on this page · raw message

include/linux/dmar.h +23 -0
Index: linux-2.6.22-rc3/include/linux/dmar.h
===================================================================
@@ -23,8 +23,15 @@
 
 #include <linux/acpi.h>
 #include <linux/types.h>
+#include <linux/msi.h>
 
 
+struct intel_iommu;
+
+/* Intel IOMMU detection and initialization functions */
+extern void detect_intel_iommu(void);
+extern int intel_iommu_init(void);
+
 extern int dmar_table_init(void);
 extern int early_dmar_detect(void);
 
@@ -49,4 +56,20 @@
 	int	devices_cnt;		/* target device count */
 };
 
+#define for_each_drhd_unit(drhd) \
+	list_for_each_entry(drhd, &dmar_drhd_units, list)
+#define for_each_rmrr_units(rmrr) \
+	list_for_each_entry(rmrr, &dmar_rmrr_units, list)
+#define begin_for_each_rmrr_device(rmrr, pdev) \
+	for_each_rmrr_units(rmrr) { \
+		int _i; \
+		for (_i = 0; _i < rmrr->devices_cnt; _i++) { \
+			pdev = rmrr->devices[_i]; \
+			/* some BIOS lists non-exist devices in DMAR table */\
+			if (!pdev) \
+				continue;
+#define end_for_each_rmrr_device(rmrr, pdev) \
+		} \
+	}
+
 #endif /* __DMAR_H__ */
maintainer
#54 lore raw

Re: [Intel-IOMMU 06/10] Intel IOMMU driver

Quoted 17 lines · On Wed, 06 Jun 2007 11:57:04 -0700 [email protected] wrote:

Actual intel IOMMU driver. Hardware spec can be found at:
http://www.intel.com/technology/virtualization

This driver sets X86_64 'dma_ops', so hook into standard DMA APIs. In this way, PCI driver will get virtual DMA address. This change is transparent to PCI drivers.

...

arch/x86_64/kernel/pci-dma.c +4 -0
+#ifdef CONFIG_DMAR
+	detect_intel_iommu();
+#endif
+
 #ifdef CONFIG_SWIOTLB
 	pci_swiotlb_init();
 #endif

arch/x86_64/kernel/pci-dma.c line 324

Quoted 6 lines
arch/x86_64/kernel/pci-dma.c +3 -0
@@ -314,6 +319,10 @@
 	calgary_iommu_init();
 #endif
 
+#ifdef CONFIG_DMAR
+	intel_iommu_init();
+#endif

We'd prefer that the header file have suitable #ifndef CONFIG_DMAR stubs, so the ifdefs here become unneeded.

Quoted 16 lines
drivers/pci/intel-iommu.c new file +16 -0
+/* context entry handling */
+static struct context_entry * device_to_context_entry(struct intel_iommu *iommu,
+		u8 bus, u8 devfn)
+{
+	struct root_entry *root;
+	struct context_entry *context;
+	unsigned long phy_addr;
+	unsigned long flags;
+
+	spin_lock_irqsave(&iommu->lock, flags);
+	root = &iommu->root_entry[bus];
+	if (!(context = get_context_addr_from_root(*root))) {
+		context = (struct context_entry *)alloc_pgtable_page();
+		if (!context) {
+			spin_unlock_irqrestore(&iommu->lock, flags);
+			return NULL;

drivers/pci/intel-iommu.c line 170

Quoted 10 lines
drivers/pci/intel-iommu.c new file +10 -0
+		}
+		__iommu_flush_cache(iommu, (void *)context, PAGE_SIZE_4K);
+		phy_addr = virt_to_phys((void *)context);
+		set_root_value(*root, phy_addr);
+		set_root_present(*root);
+		__iommu_flush_cache(iommu, root, sizeof(*root));
+	}
+	spin_unlock_irqrestore(&iommu->lock, flags);
+	return &context[devfn];
+}

checkpatch.pl has lots of fun with this patch.

drivers/pci/intel-iommu.c line 240

Quoted 12 lines
drivers/pci/intel-iommu.c new file +12 -0
+/* page table handling */
+#define LEVEL_STRIDE		(9)
+#define LEVEL_MASK		(((u64)1 << LEVEL_STRIDE) - 1)
+#define agaw_to_level(val) ((val) + 2)
+#define agaw_to_width(val) (30 + val * LEVEL_STRIDE)
+#define width_to_agaw(w)  ((w - 30)/LEVEL_STRIDE)
+#define level_to_offset_bits(l) (12 + (l - 1) * LEVEL_STRIDE)
+#define address_level_offset(addr, level) \
+	((addr >> level_to_offset_bits(level)) & LEVEL_MASK)
+#define level_mask(l) (((u64)(-1)) << level_to_offset_bits(l))
+#define level_size(l) ((u64)1 << level_to_offset_bits(l))
+#define align_to_level(addr, l) ((addr + level_size(l) - 1) & level_mask(l))

static inlines are better than macros - please consider.

If you're going to stick with macros here then you'll find that many of the above macro's arguments are insufficiently parenthesised.

drivers/pci/intel-iommu.c line 411

Quoted 12 lines
drivers/pci/intel-iommu.c new file +12 -0
+#define IOMMU_WAIT_OP(iommu, offset, op, cond, sts) \
+{\
+	unsigned long start_time = jiffies;\
+	while (1) {\
+		sts = op (iommu->reg, offset);\
+		if (cond)\
+			break;\
+		if (time_after(jiffies, start_time + DMAR_OPERATION_TIMEOUT))\
+			panic("DMAR hardware is malfunctional, please disable IOMMU\n");\
+		cpu_relax();\
+	}\
+}

wow, harsh treatment.

"malfunctioning" might parse better here.

drivers/pci/intel-iommu.c line 619

Quoted 13 lines
drivers/pci/intel-iommu.c new file +13 -0
+static int inline get_alignment(u64 base, unsigned int size)
+{
+	int t = 0;
+	u64 end;
+
+	end = base + size - 1;
+	while (base != end) {
+		t++;
+		base >>= 1;
+		end >>= 1;
+	}
+	return t;
+}

What's this (too large to inline) function doing? I suspect we might have helper functions which already do it... If not, perhasp we should.

Quoted 19 lines
drivers/pci/intel-iommu.c new file +19 -0
+static int inline iommu_flush_iotlb_psi(struct intel_iommu *iommu, u16 did,
+	u64 addr, unsigned int pages, int non_present_entry_flush)
+{
+	unsigned int align;
+
+	BUG_ON(addr & (~PAGE_MASK_4K));
+	BUG_ON(pages == 0);
+
+	/* Fallback to domain selective flush if no PSI support */
+	if (!cap_pgsel_inv(iommu->cap))
+		return iommu_flush_iotlb_dsi(iommu, did,
+			non_present_entry_flush);
+
+	/*
+	 * PSI requires page size is 2 ^ x, and the base address is naturally
+	 * aligned to the size
+	 */
+	align = get_alignment(addr >> PAGE_SHIFT_4K, pages);
+	/* Fallback to domain selective flush if size is too big */

drivers/pci/intel-iommu.c line 649

Quoted 10 lines
drivers/pci/intel-iommu.c new file +10 -0
+	if (align > cap_max_amask_val(iommu->cap))
+		return iommu_flush_iotlb_dsi(iommu, did,
+			non_present_entry_flush);
+
+	addr >>= PAGE_SHIFT_4K + align;
+	addr <<= PAGE_SHIFT_4K + align;
+
+	return __iommu_flush_iotlb(iommu, did, addr, align,
+		DMA_TLB_PSI_FLUSH, non_present_entry_flush);
+}

too large for inlining.

drivers/pci/intel-iommu.c line 654

Quoted 4 lines
drivers/pci/intel-iommu.c new file +4 -0
+static int iommu_enable_translation(struct intel_iommu *iommu)
+{
+	u32 sts;
+	unsigned long flag;

we conventionally use "flags" for this.

Quoted 6 lines
drivers/pci/intel-iommu.c new file +6 -0
+	spin_lock_irqsave(&iommu->register_lock, flag);
+	dmar_writel(iommu->reg, DMAR_GCMD_REG, iommu->gcmd|DMA_GCMD_TE);
+
+	/* Make sure hardware complete it */
+	IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG, dmar_readl, (sts & DMA_GSTS_TES), sts);
+

drivers/pci/intel-iommu.c

Quoted 10 lines
drivers/pci/intel-iommu.c new file +6 -0
+	iommu->gcmd |= DMA_GCMD_TE;
+	spin_unlock_irqrestore(&iommu->register_lock, flag);
+	return 0;
+}
 
...
 
 
+#define aligned_size(host_addr, size) \
+	PAGE_ALIGN_4K((host_addr & (~PAGE_MASK_4K)) + size)

insufficiently parenthesized. Consider usign a static inline.

drivers/pci/intel-iommu.c line 1753

Quoted 8 lines
drivers/pci/intel-iommu.c new file +8 -0
+struct dma_mapping_ops intel_dma_ops = {
+	.alloc_coherent = intel_alloc_coherent,
+	.free_coherent = intel_free_coherent,
+	.map_single = intel_map_single,
+	.unmap_single = intel_unmap_single,
+	.map_sg = intel_map_sg,
+	.unmap_sg = intel_unmap_sg,
+};

can it be static?

drivers/pci/intel-iommu.c line 1761

Quoted 7 lines
drivers/pci/intel-iommu.c new file +7 -0
+void *iommu_rpool_alloc(unsigned int size, gfp_t flag)
+{
+	if (size == PAGE_SIZE_4K)
+		return(void *)get_zeroed_page(flag);
+	else
+		return kzalloc(size, flag);
+}

kmalloc(4k) is pretty efficient and (I think) is guaranteed to return a page-aligned address.

iow: can we just use kmalloc here?

Quoted 35 lines
drivers/pci/intel-iommu.c new file +35 -0
+
+static inline int
+iommu_devinfo_pool_init(void)
+{
+	return init_resource_pool(&iommu_devinfo_pool, MIN_DEVINFO_REQ,
+		sizeof(struct device_domain_info),
+		GROW_DEVINFO_REQ, iommu_rpool_alloc,
+		iommu_rpool_free);
+}
+
+static inline int
+iommu_iova_pool_init(void)
+{
+	return init_resource_pool(&iommu_iova_pool, MIN_IOVA_REQ,
+		sizeof(struct iova),
+		GROW_IOVA_REQ, iommu_rpool_alloc, iommu_rpool_free);
+}
+
+static int iommu_init_mempool(void)
+{
+	int ret;
+	ret = iommu_iova_pool_init();
+	if (ret)
+		return ret;
+
+	ret = iommu_pgtable_pool_init();
+	if (ret)
+		goto pgtable_error;
+
+	ret = iommu_domain_pool_init();
+	if (ret)
+		goto domain_error;
+
+	ret = iommu_devinfo_pool_init();
+	if (!ret)

drivers/pci/intel-iommu.c line 1831

Quoted 10 lines
drivers/pci/intel-iommu.c new file +10 -0
+		return ret;
+
+	destroy_resource_pool(&iommu_domain_pool);
+domain_error:
+	destroy_resource_pool(&iommu_pgtable_pool);
+pgtable_error:
+	destroy_resource_pool(&iommu_iova_pool);
+
+	return -ENOMEM;
+}

can be __init

drivers/pci/intel-iommu.c line 1839

Quoted 7 lines
drivers/pci/intel-iommu.c new file +7 -0
+static void iommu_exit_mempool(void)
+{
+	destroy_resource_pool(&iommu_devinfo_pool);
+	destroy_resource_pool(&iommu_domain_pool);
+	destroy_resource_pool(&iommu_pgtable_pool);
+	destroy_resource_pool(&iommu_iova_pool);
+}

ditto (unexpectedly)

Quoted 13 lines
drivers/pci/intel-iommu.c new file +13 -0
+void __init detect_intel_iommu(void)
+{
+	if (swiotlb || no_iommu || iommu_detected || dmar_disabled)
+		return;
+	if (early_dmar_detect()) {
+		iommu_detected = 1;
+	}
+}
+
+static void __init init_no_remapping_devices(void)
+{
+	struct dmar_drhd_unit *drhd;
+

drivers/pci/intel-iommu.c line 1863

Quoted 10 lines
drivers/pci/intel-iommu.c new file +10 -0
+	for_each_drhd_unit(drhd)
+		if (!drhd->include_all) {
+			int i;
+			for (i=0; i < drhd->devices_cnt; i++)
+				if (drhd->devices[i] != NULL)
+					break;
+			/* ignore DMAR unit if no pci devices exist */
+			if (i == drhd->devices_cnt)
+				drhd->ignored = 1;
+		}

looks weird - I'd add the extra braces here.

Quoted 21 lines
drivers/pci/intel-iommu.c new file +21 -0
+	if (dmar_map_gfx)
+		return;
+
+	for_each_drhd_unit(drhd) {
+		int i;
+		if (drhd->ignored || drhd->include_all)
+			continue;
+
+		for (i = 0; i < drhd->devices_cnt; i++)
+			if (drhd->devices[i] && !IS_GFX_DEVICE(drhd->devices[i]))
+				break;
+
+		if (i < drhd->devices_cnt)
+			continue;
+
+		/* bypass IOMMU if it is just for gfx devices */
+		drhd->ignored = 1;
+		for (i = 0; i < drhd->devices_cnt; i++) {
+			if (!drhd->devices[i])
+				continue;
+			drhd->devices[i]->sysdata = DUMMY_DEVICE_DOMAIN_INFO;

drivers/pci/intel-iommu.c

Quoted 10 lines
drivers/pci/intel-iommu.c new file +7 -0
+		}
+	}
+}
+
 
...
 
+#define OFFSET_STRIDE		(9)
+#define dmar_readl(dmar, reg) readl(dmar + reg)
+#define dmar_writel(dmar, reg, val) writel((val), dmar + reg)

Is this pointless obfuscation?

drivers/pci/intel-iommu.h line 62

Quoted 9 lines
drivers/pci/intel-iommu.h new file +9 -0
+#define dmar_readq(dmar, reg) ({ \
+		u32 lo, hi; \
+		lo = dmar_readl(dmar, reg); \
+		hi = dmar_readl(dmar, reg + 4); \
+		(((u64) hi) << 32) + lo; })
+#define dmar_writeq(dmar, reg, val) do {\
+		dmar_writel(dmar, reg, (u32)(val)); \
+		dmar_writel(dmar, reg + 4, (u32)((val) >> 32)); \
+	} while (0)

Do these need to be macros? If not, a regular C function would be better. Not necessarily an inlined one, either.

drivers/pci/intel-iommu.h line 65

Quoted 2 lines
drivers/pci/intel-iommu.h new file +2 -0
+#define VER_MAJOR(v)		(((v) & 0xf0) >> 4)
+#define VER_MINOR(v)		((v) & 0x0f)

We already have several VER_MAJORs defined in the tree, so adding a new one is asking for trouble. Suggest the use of a more specific identifier.

drivers/pci/intel-iommu.h line 184

Quoted 2 lines
drivers/pci/intel-iommu.h new file +2 -0
+#define set_root_value(root, value) \
+	do {(root).val |= ((value) & PAGE_MASK_4K);} while(0)

Methinks that could be written in C too.

Quoted 1 line

+struct domain {

hm, "domain" is a pretty generic term. I think there's a bit of namespace hogging here..

Quoted 24 lines
(quoted diff) +21 -0
+	int	id;			/* domain id */
+	struct intel_iommu *iommu;	/* back pointer to owning iommu */
+
+	struct list_head devices; 	/* all devices' list */
+	struct iova_domain iovad;	/* iova's that belong to this domain */
+
+	struct dma_pte	*pgd;		/* virtual address */
+	spinlock_t	mapping_lock;	/* page table lock */
+	int		gaw;		/* max guest address width */
+	int		agaw;		/* adjusted guest address width, 0 is level 2 30-bit */
+
+#define DOMAIN_FLAG_MULTIPLE_DEVICES 1
+	int		flags;
+};
+
 
...
 
+#define for_each_drhd_unit(drhd) \
+	list_for_each_entry(drhd, &dmar_drhd_units, list)
+#define for_each_rmrr_units(rmrr) \
+	list_for_each_entry(rmrr, &dmar_rmrr_units, list)
+#define begin_for_each_rmrr_device(rmrr, pdev) \
+	for_each_rmrr_units(rmrr) { \

Review

Quoted 10 lines
(quoted diff) +10 -0
+		int _i; \
+		for (_i = 0; _i < rmrr->devices_cnt; _i++) { \
+			pdev = rmrr->devices[_i]; \
+			/* some BIOS lists non-exist devices in DMAR table */\
+			if (!pdev) \
+				continue;
+#define end_for_each_rmrr_device(rmrr, pdev) \
+		} \
+	}
+

Are these used often enough to justify their inclusion?

Would it be possible to implement these as regular C functions which are passed the address of a callback function?

#55 lore raw

Re: [Intel-IOMMU 06/10] Intel IOMMU driver

Quoted 10 lines · Andrew Morton

drivers/pci/intel-iommu.c line 1761

Quoted 7 lines
drivers/pci/intel-iommu.c new file +7 -0
+void *iommu_rpool_alloc(unsigned int size, gfp_t flag)
+{
+	if (size == PAGE_SIZE_4K)
+		return(void *)get_zeroed_page(flag);
+	else
+		return kzalloc(size, flag);
+}

kmalloc(4k) is pretty efficient and (I think) is guaranteed to return a page-aligned address.

Page allocations should be done through the page allocator. 4k allocations benefit from the per cpu caches of the page allocator which makes the use of the page allocator fastest and best for 4k allocs.

kmalloc allocations are not guaranteed to be aligned to 4k boundaries. They usually are but ...

#57 lore raw

PATCH 7/10 Intel iommu cmdline option - forcedac

In reply to [email protected]

Introduce intel_iommu=forcedac commandline option.
This option is helpful to verify the pci device capability of handling physical dma'able address greater than 4G.

---
 Documentation/kernel-parameters.txt |    7 +++++++
 drivers/pci/intel-iommu.c           |    6 +++++-
 2 files changed, 12 insertions(+), 1 deletion(-)
Documentation/kernel-parameters.txt +7 -0
Index: linux-2.6.22-rc3/Documentation/kernel-parameters.txt
===================================================================
@@ -785,6 +785,13 @@
 			bypassed by not enabling DMAR with this option. In
 			this case, gfx device will use physical address for
 			DMA.
+		forcedac
+			With this option iommu will not optimize to look
+			for io virtual address below 32 bit forcing dual
+			address cycle on pci bus for cards supporting greater
+			than 32 bit addressing. The default is to look
+			for translation below 32 bit and if not available
+			then look in the higher range.
 
 	io7=		[HW] IO7 for Marvel based alpha systems
 			See comment before marvel_specify_io7 in
drivers/pci/intel-iommu.c +5 -1
Index: linux-2.6.22-rc3/drivers/pci/intel-iommu.c
===================================================================
@@ -53,6 +53,7 @@
 
 static int dmar_disabled;
 static int __initdata dmar_map_gfx = 1;
+static int dmar_forcedac = 0;
 
 #define DUMMY_DEVICE_DOMAIN_INFO ((struct device_domain_info *)(-1))
 static DEFINE_SPINLOCK(device_domain_lock);
@@ -69,6 +70,9 @@
 		} else if (!strncmp(str, "igfx_off", 8)) {
 			dmar_map_gfx = 0;
 			printk(KERN_INFO"Intel-IOMMU: disable GFX device mapping\n");
+ 		} else if (!strncmp(str, "forcedac", 8)) {
+			printk (KERN_INFO"Intel-IOMMU: Enabling DAC for PCI supporting > 32Bit DMA\n");
+			dmar_forcedac = 1;
 		}
 
 		str += strcspn(str, ",");
@@ -1500,7 +1504,7 @@
 
 	start_addr = IOVA_START_ADDR;
 
-	if (pdev->dma_mask <= DMA_32BIT_MASK) {
+	if ((pdev->dma_mask <= DMA_32BIT_MASK) || (dmar_forcedac)) {
 		iova = iommu_alloc_iova(domain, addr, size, start_addr,
 			pdev->dma_mask);
 	} else  {
maintainer
#58 lore raw

Re: [Intel-IOMMU 07/10] Intel iommu cmdline option - forcedac

Documentation/kernel-parameters.txt line 788

Quoted 7 lines · On Wed, 06 Jun 2007 11:57:05 -0700 [email protected] wrote:
Documentation/kernel-parameters.txt +1 -0
@@ -785,6 +785,13 @@
 			bypassed by not enabling DMAR with this option. In
 			this case, gfx device will use physical address for
 			DMA.
+		forcedac

You want

		forcedac [X86-64]
Quoted 6 lines
Documentation/kernel-parameters.txt +6 -0
+			With this option iommu will not optimize to look
+			for io virtual address below 32 bit forcing dual
+			address cycle on pci bus for cards supporting greater
+			than 32 bit addressing. The default is to look
+			for translation below 32 bit and if not available
+			then look in the higher range.
#59 lore raw

PATCH 8/10 DMAR fault handling support

In reply to [email protected]

MSI interrupt handler registrations and fault handling support
for Intel-IOMMU hadrware.

---
 Documentation/Intel-IOMMU.txt |   17 +++
 arch/x86_64/kernel/io_apic.c  |   59 ++++++++++++
 drivers/pci/intel-iommu.c     |  194 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/dmar.h          |   12 ++
 4 files changed, 281 insertions(+), 1 deletion(-)
Documentation/Intel-IOMMU.txt +17 -0
Index: linux-2.6.22-rc3/Documentation/Intel-IOMMU.txt
===================================================================
@@ -63,6 +63,15 @@
 The same is true for peer to peer transactions. Hence we reserve the
 address from PCI MMIO ranges so they are not allocated for IOVA addresses.
 
+
+Fault reporting
+---------------
+When errors are reported, the DMA engine signals via an interrupt. The fault
+reason and device that caused it with fault reason is printed on console.
+
+See below for sample.
+
+
 Boot Message Sample
 -------------------
 
@@ -85,6 +94,14 @@
 
 PCI-DMA: Using DMAR IOMMU
 
+Fault reporting
+---------------
+
+DMAR:[DMA Write] Request device [00:02.0] fault addr 6df084000
+DMAR:[fault reason 05] PTE Write access is not set
+DMAR:[DMA Write] Request device [00:02.0] fault addr 6df084000
+DMAR:[fault reason 05] PTE Write access is not set
+
 TBD
 ----
 
arch/x86_64/kernel/io_apic.c +58 -1

72 lines not on this page · raw message

drivers/pci/intel-iommu.c +194 -0

206 lines not on this page · raw message

include/linux/dmar.h +12 -0
Index: linux-2.6.22-rc3/include/linux/dmar.h
===================================================================
@@ -28,6 +28,18 @@
 
 struct intel_iommu;
 
+extern char *dmar_get_fault_reason(u8 fault_reason);
+
+/* Can't use the common MSI interrupt functions
+ * since DMAR is not a pci device
+ */
+extern void dmar_msi_unmask(unsigned int irq);
+extern void dmar_msi_mask(unsigned int irq);
+extern void dmar_msi_read(int irq, struct msi_msg *msg);
+extern void dmar_msi_write(int irq, struct msi_msg *msg);
+extern int dmar_set_interrupt(struct intel_iommu *iommu);
+extern int arch_setup_dmar_msi(unsigned int irq);
+
 /* Intel IOMMU detection and initialization functions */
 extern void detect_intel_iommu(void);
 extern int intel_iommu_init(void);
#60 lore raw

PATCH 9/10 Iommu Gfx workaround

In reply to [email protected]

When we fix all the opensource gfx drivers to use the DMA api's, at that time we can yank this config options out.

---
 Documentation/Intel-IOMMU.txt |    5 +++++
 arch/x86_64/Kconfig           |   11 +++++++++++
 arch/x86_64/kernel/e820.c     |   19 +++++++++++++++++++
 drivers/pci/intel-iommu.c     |   32 ++++++++++++++++++++++++++++++++
 4 files changed, 67 insertions(+)
Documentation/Intel-IOMMU.txt +5 -0
Index: linux-2.6.22-rc3/Documentation/Intel-IOMMU.txt
===================================================================
@@ -57,6 +57,11 @@
 If you encounter issues with graphics devices, you can try adding
 option intel_iommu=igfx_off to turn off the integrated graphics engine.
 
+If it happens to be a PCI device included in the INCLUDE_ALL Engine,
+then try enabling CONFIG_DMAR_GFX_WA to setup a 1-1 map. We hear
+graphics drivers may be in process of using DMA api's in the near
+future and at that time this option can be yanked out.
+
 Some exceptions to IOVA
 -----------------------
 Interrupt ranges are not address translated, (0xfee00000 - 0xfeefffff).
arch/x86_64/Kconfig +11 -0
Index: linux-2.6.22-rc3/arch/x86_64/Kconfig
===================================================================
@@ -727,6 +727,17 @@
 	  and includes pci device scope covered by these DMA
 	  remapping device.
 
+config DMAR_GFX_WA
+	bool "Support for Graphics workaround"
+	depends on DMAR
+	default y
+	help
+	 Current Graphics drivers tend to use physical address
+	 for DMA and avoid using DMA api's. Setting this config
+	 option permits the IOMMU driver to set a unity map for
+	 all the OS visible memory. Hence the driver can continue
+	 to use physical addresses for DMA.
+
 source "drivers/pci/pcie/Kconfig"
 
 source "drivers/pci/Kconfig"
arch/x86_64/kernel/e820.c +19 -0
Index: linux-2.6.22-rc3/arch/x86_64/kernel/e820.c
===================================================================
@@ -717,3 +717,22 @@
 	printk(KERN_INFO "Allocating PCI resources starting at %lx (gap: %lx:%lx)\n",
 		pci_mem_start, gapstart, gapsize);
 }
+
+int __init arch_get_ram_range(int slot, u64 *addr, u64 *size)
+{
+	int i;
+
+	if (slot < 0 || slot >= e820.nr_map)
+		return -1;
+	for (i = slot; i < e820.nr_map; i++) {
+		if(e820.map[i].type != E820_RAM)
+			continue;
+		break;
+	}
+	if (i == e820.nr_map || e820.map[i].addr > (max_pfn << PAGE_SHIFT))
+		return -1;
+	*addr = e820.map[i].addr;
+	*size = min_t(u64, e820.map[i].size + e820.map[i].addr,
+		max_pfn << PAGE_SHIFT) - *addr;
+	return i + 1;
+}
drivers/pci/intel-iommu.c +32 -0
Index: linux-2.6.22-rc3/drivers/pci/intel-iommu.c
===================================================================
@@ -1556,6 +1556,34 @@
 		rmrr->end_address + 1);
 }
 
+#ifdef CONFIG_DMAR_GFX_WA
+extern int arch_get_ram_range(int slot, u64 *addr, u64 *size);
+static void __init iommu_prepare_gfx_mapping(void)
+{
+	struct pci_dev *pdev = NULL;
+	u64 base, size;
+	int slot;
+	int ret;
+
+	for_each_pci_dev(pdev) {
+		if (pdev->sysdata == DUMMY_DEVICE_DOMAIN_INFO ||
+				!IS_GFX_DEVICE(pdev))
+			continue;
+		printk(KERN_INFO "IOMMU: gfx device %s 1-1 mapping\n",
+			pci_name(pdev));
+		slot = 0;
+		while ((slot = arch_get_ram_range(slot, &base, &size)) >= 0) {
+			ret = iommu_prepare_identity_map(pdev, base, base + size);
+			if (ret)
+				goto error;
+		}
+		continue;
+error:
+		printk(KERN_ERR "IOMMU: mapping reserved region failed\n");
+	}
+}
+#endif
+
 int __init init_dmars(void)
 {
 	struct dmar_drhd_unit *drhd;
@@ -1611,6 +1639,10 @@
 			printk(KERN_ERR "IOMMU: mapping reserved region failed\n");
 	end_for_each_rmrr_device(rmrr, pdev)
 
+#ifdef CONFIG_DMAR_GFX_WA
+	iommu_prepare_gfx_mapping();
+#endif
+
 	/*
 	 * for each drhd
 	 *   enable fault log
maintainer
#61 lore raw

Re: [Intel-IOMMU 09/10] Iommu Gfx workaround

drivers/pci/intel-iommu.c line 1644

Quoted 3 lines · On Wed, 06 Jun 2007 11:57:07 -0700 [email protected] wrote:
drivers/pci/intel-iommu.c +3 -0
+#ifdef CONFIG_DMAR_GFX_WA
+	iommu_prepare_gfx_mapping();
+#endif

Please do

#ifndef CONFIG_DMAR_GFX_WA
static inline void iommu_prepare_gfx_mapping(void) {
}
#endif

in the head file instead (whole patchset)

#62 lore raw

PATCH 10/10 Iommu floppy workaround

In reply to [email protected]

This config option (DMAR_FLPY_WA) sets up 1:1 mapping for the
floppy device so that the floppy device which does not use DMA api's will continue to work.

---
 arch/x86_64/Kconfig       |   10 ++++++++++
 drivers/pci/intel-iommu.c |   23 +++++++++++++++++++++++
 2 files changed, 33 insertions(+)
arch/x86_64/Kconfig +10 -0
Index: linux-2.6.22-rc3/arch/x86_64/Kconfig
===================================================================
@@ -738,6 +738,16 @@
 	 all the OS visible memory. Hence the driver can continue
 	 to use physical addresses for DMA.
 
+config DMAR_FLPY_WA
+	bool "Support for Floppy disk workaround"
+	depends on DMAR
+	default y
+	help
+	 Floppy disk drivers are know to by pass dma api calls
+	 their by failing to work when IOMMU is enabled. This
+	 work around will setup a 1 to 1 mappings for the first
+	 16M to make floppy(isa device) work.
+
 source "drivers/pci/pcie/Kconfig"
 
 source "drivers/pci/Kconfig"
drivers/pci/intel-iommu.c +23 -0
Index: linux-2.6.22-rc3/drivers/pci/intel-iommu.c
===================================================================
@@ -1584,6 +1584,25 @@
 }
 #endif
 
+#ifdef CONFIG_DMAR_FLPY_WA
+static void iommu_prepare_isa(void)
+{
+	struct pci_dev *pdev = NULL;
+	int ret;
+
+	pdev = pci_get_class (PCI_CLASS_BRIDGE_ISA << 8, NULL);
+	if (!pdev)
+		return;
+
+	printk (KERN_INFO "IOMMU: Prepare 0-16M unity mapping for LPC\n");
+	ret = iommu_prepare_identity_map(pdev, 0, 16*1024*1024);
+
+	if (ret)
+		printk ("IOMMU: Failed to create 0-64M identity map, Floppy might not work\n");
+
+}
+#endif
+
 int __init init_dmars(void)
 {
 	struct dmar_drhd_unit *drhd;
@@ -1643,6 +1662,10 @@
 	iommu_prepare_gfx_mapping();
 #endif
 
+#ifdef CONFIG_DMAR_FLPY_WA
+	iommu_prepare_isa();
+#endif
+
 	/*
 	 * for each drhd
 	 *   enable fault log