Linux swiotlb技术解析

概述


swiotlb技术是一种纯软件的地址映射技术,主要为寻址能力受限的DMA提供软件上的地址映射,听起来比较玄乎,实际上其原理非常简单。我们下面先来谈一下该技术提出的背景。
我们假设一个64位系统,其内存的基地址是0x80000000,内存大小是4G,则内存的物理地址范围是0x80000000-0x180000000,同时该系统中某个外设的DMA只能按32 bits地址寻址,即寻址范围为0-0xffffffff,如果恰好非给该外设DMA的内存地址超过了这个范围,该外设DMA实际无法使用该地址。那么怎么办呢?此时swiotlb就登上了舞台!
swiotlb维护了一块低地址的buffer,该buffer的大小可以由bootloader通过swiotlb参数传递给内核,也可以使用默认值,默认值是64M。
如果给DMA分配的物理地址(这里记做phyaddr1)超过了其寻址能力,那么swiotlb技术将从其buffer中分配同样大小的一块空间,给DMA使用,其物理地址记做phyaddr2,swiotlb会维护phyaddr1和phyaddr2的映射关系。
这里有两个问题比较关键:
第一个问题是:如何确保swiotlb维护的buffer在低地址呢?
这个问题很好回答,只要尽可能早地分配该buffer就可以了,只要分配的足够早,想要哪一块buffer还不是一句话的事!在ARM64平台上在函数mem_init的一开始,就调用swiotlb_init做swiotlb的初始化,swiotlb_init中就会分配所需要的buffer。
第二个问题是:一般来说先分配page,然后映射其物理地址(这里我们暂时认为是物理地址,其实是DMA地址),如果在映射物理地址的时候发现物理地址超过DMA的寻址能力,就会偷偷从buffer中申请一块等大小的内存,来替换掉原来内存地址,给DMA使用。但是此时物理page和DMA实际使用的物理地址不一致,也就是说DMA看到内存和CPU看到的内存实际上是两块内存,这两块内存没有任何关系。
以上分析除了最后一句之外,全部是正确的。这两个内存是有关系的,他们的关系就是swiotlb维护了一张io_tlb_orig_addr表,这张表维护了原始物理地址和swiotlb分配物理地址之间的映射关系。当DMA将数据写入swiotlb分配的物理地址后,一般会以中断的方式通知CPU,CPU在查看DMA写到内存的数据之前,需要先做一个sync,该sync操作就会触发swiotlb将数据拷贝到原始物理地址处,这样就保证了CPU能够看到正确的数据,不过显而易见,这种方法效率非常低下。

代码分析


swiotlb初始化

mem_init->swiotlb_init
void  __init
swiotlb_init(int verbose)
{
	size_t default_size = IO_TLB_DEFAULT_SIZE;
	unsigned char *vstart;
	unsigned long bytes;

	if (!io_tlb_nslabs) {
		io_tlb_nslabs = (default_size >> IO_TLB_SHIFT);
		io_tlb_nslabs = ALIGN(io_tlb_nslabs, IO_TLB_SEGSIZE);
	}

	bytes = io_tlb_nslabs << IO_TLB_SHIFT;

	/* Get IO TLB memory from the low pages */
	vstart = memblock_virt_alloc_low_nopanic(PAGE_ALIGN(bytes), PAGE_SIZE);
	if (vstart && !swiotlb_init_with_tbl(vstart, io_tlb_nslabs, verbose))
		return;

	if (io_tlb_start)
		memblock_free_early(io_tlb_start,
				    PAGE_ALIGN(io_tlb_nslabs << IO_TLB_SHIFT));
	pr_warn("Cannot allocate SWIOTLB buffer");
	no_iotlb_memory = true;
}
  • 这里一个slab是2K,io_tlb_nslabs表示有多少个slab,也即buffer是多大,默认buffer size是IO_TLB_DEFAULT_SIZE,即64M,也可以由bootloader通过swiotlb参数设置io_tlb_nslabs,io_tlb_nslabs会换算成buffer size。
  • memblock_virt_alloc_low_nopanic用于从低地址物理页分配内存空间。
  • swiotlb_init_with_tbl进一步初始化
mem_init->swiotlb_init->swiotlb_init_with_tbl
int __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose)
{
	void *v_overflow_buffer;
	unsigned long i, bytes;

	bytes = nslabs << IO_TLB_SHIFT;

	io_tlb_nslabs = nslabs;
	io_tlb_start = __pa(tlb);
	io_tlb_end = io_tlb_start + bytes;

	/*
	 * Get the overflow emergency buffer
	 */
	v_overflow_buffer = memblock_virt_alloc_low_nopanic(
						PAGE_ALIGN(io_tlb_overflow),
						PAGE_SIZE);
	if (!v_overflow_buffer)
		return -ENOMEM;

	io_tlb_overflow_buffer = __pa(v_overflow_buffer);

	/*
	 * Allocate and initialize the free list array.  This array is used
	 * to find contiguous free memory regions of size up to IO_TLB_SEGSIZE
	 * between io_tlb_start and io_tlb_end.
	 */
	io_tlb_list = memblock_virt_alloc(
				PAGE_ALIGN(io_tlb_nslabs * sizeof(int)),
				PAGE_SIZE);
	io_tlb_orig_addr = memblock_virt_alloc(
				PAGE_ALIGN(io_tlb_nslabs * sizeof(phys_addr_t)),
				PAGE_SIZE);
	for (i = 0; i < io_tlb_nslabs; i++) {
		io_tlb_list[i] = IO_TLB_SEGSIZE - OFFSET(i, IO_TLB_SEGSIZE);
		io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
	}
	io_tlb_index = 0;

	if (verbose)
		swiotlb_print_info();

	return 0;
}
  • io_tlb_start和io_tlb_end记录swiotlb buffer的物理地址范围。
  • io_tlb_nslabs用于记录swiotlb总共有多少个slab。
  • io_tlb_overflow_buffer指向一块32K的内存,这块内存也是从低物理页分配的,这块内存是在swiotlb buffer溢出时备用的。
  • io_tlb_list这张表非常有意思,它表示从该slab开始,有多少个连续的slab是可用的。最大只允许分配连续IO_TLB_SEGSIZE(128)个slab,即64K Bytes。io_tlb_list[0]=128,表示从第一个slab开始,有连续128个slabs可用,io_tlb_list[1]=127,表示从第二个slab开始,有连续127个slabs可用,依次类推,我们会发现设置的可用的slab的数量远远大于实际的slab数量,其实这里初始化设置的是最大可能的值。比如从第一个slab开始分配了10个slabs之后,会同时将io_tlb_list[0]-io_tlb_list[9]设置为0,表示第一个到第十个slab不能用。
  • io_tlb_orig_addr记录原始物理地址与slab index的映射关系。

物理页映射

dma_map_page->__swiotlb_map_page->swiotlb_map_page
dma_addr_t swiotlb_map_page(struct device *dev, struct page *page,
			    unsigned long offset, size_t size,
			    enum dma_data_direction dir,
			    unsigned long attrs)
{
	phys_addr_t map, phys = page_to_phys(page) + offset;
	dma_addr_t dev_addr = phys_to_dma(dev, phys);

	BUG_ON(dir == DMA_NONE);
	/*
	 * If the address happens to be in the device's DMA window,
	 * we can safely return the device addr and not worry about bounce
	 * buffering it.
	 */
	if (dma_capable(dev, dev_addr, size) && swiotlb_force != SWIOTLB_FORCE)
		return dev_addr;

	trace_swiotlb_bounced(dev, dev_addr, size, swiotlb_force);

	/* Oh well, have to allocate and map a bounce buffer. */
	map = map_single(dev, phys, size, dir);
	if (map == SWIOTLB_MAP_ERROR) {
		swiotlb_full(dev, size, dir, 1);
		return phys_to_dma(dev, io_tlb_overflow_buffer);
	}

	dev_addr = phys_to_dma(dev, map);

	/* Ensure that the address returned is DMA'ble */
	if (!dma_capable(dev, dev_addr, size)) {
		swiotlb_tbl_unmap_single(dev, map, size, dir);
		return phys_to_dma(dev, io_tlb_overflow_buffer);
	}

	return dev_addr;
}
  • 首先根据页号获取物理地址,进而获得DMA地址,这里我们认为物理地址和DMA地址是一致的。
  • 判断DMA的寻址能力是否能够覆盖上一步得到的物理地址,如果能的话,直接返回物理地址,否则采用swiotlb机制分配内存。
  • 调用map_single采用swiotlb机制分配内存
  • 判断调用swiotlb机制分配的内存物理地址是否在DMA寻址能力范围内,如果在的话直接返回,否则没办法,直接返回备用地址吧,能不能满足要求只能听天由命了。
dma_map_page->__swiotlb_map_page->swiotlb_map_page->map_single->swiotlb_tbl_map_single
phys_addr_t swiotlb_tbl_map_single(struct device *hwdev,
				   dma_addr_t tbl_dma_addr,
				   phys_addr_t orig_addr, size_t size,
				   enum dma_data_direction dir)
{
	unsigned long flags;
	phys_addr_t tlb_addr;
	unsigned int nslots, stride, index, wrap;
	int i;
	unsigned long mask;
	unsigned long offset_slots;
	unsigned long max_slots;

	if (no_iotlb_memory)
		panic("Can not allocate SWIOTLB buffer earlier and can't now provide you with the DMA bounce buffer");

	mask = dma_get_seg_boundary(hwdev);

	tbl_dma_addr &= mask;

	offset_slots = ALIGN(tbl_dma_addr, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;

	/*
 	 * Carefully handle integer overflow which can occur when mask == ~0UL.
 	 */
	max_slots = mask + 1
		    ? ALIGN(mask + 1, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT
		    : 1UL << (BITS_PER_LONG - IO_TLB_SHIFT);

	/*
	 * For mappings greater than a page, we limit the stride (and
	 * hence alignment) to a page size.
	 */
	nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
	if (size > PAGE_SIZE)
		stride = (1 << (PAGE_SHIFT - IO_TLB_SHIFT));
	else
		stride = 1;

	BUG_ON(!nslots);

	/*
	 * Find suitable number of IO TLB entries size that will fit this
	 * request and allocate a buffer from that IO TLB pool.
	 */
	spin_lock_irqsave(&io_tlb_lock, flags);
	index = ALIGN(io_tlb_index, stride);
	if (index >= io_tlb_nslabs)
		index = 0;
	wrap = index;

	do {
		while (iommu_is_span_boundary(index, nslots, offset_slots,
					      max_slots)) {
			index += stride;
			if (index >= io_tlb_nslabs)
				index = 0;
			if (index == wrap)
				goto not_found;
		}

		/*
		 * If we find a slot that indicates we have 'nslots' number of
		 * contiguous buffers, we allocate the buffers from that slot
		 * and mark the entries as '0' indicating unavailable.
		 */
		if (io_tlb_list[index] >= nslots) {
			int count = 0;

			for (i = index; i < (int) (index + nslots); i++)
				io_tlb_list[i] = 0;
			for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE - 1) && io_tlb_list[i]; i--)
				io_tlb_list[i] = ++count;
			tlb_addr = io_tlb_start + (index << IO_TLB_SHIFT);

			/*
			 * Update the indices to avoid searching in the next
			 * round.
			 */
			io_tlb_index = ((index + nslots) < io_tlb_nslabs
					? (index + nslots) : 0);

			goto found;
		}
		index += stride;
		if (index >= io_tlb_nslabs)
			index = 0;
	} while (index != wrap);

not_found:
	spin_unlock_irqrestore(&io_tlb_lock, flags);
	if (printk_ratelimit())
		dev_warn(hwdev, "swiotlb buffer is full (sz: %zd bytes)\n", size);
	return SWIOTLB_MAP_ERROR;
found:
	spin_unlock_irqrestore(&io_tlb_lock, flags);

	/*
	 * Save away the mapping from the original address to the DMA address.
	 * This is needed when we sync the memory.  Then we sync the buffer if
	 * needed.
	 */
	for (i = 0; i < nslots; i++)
		io_tlb_orig_addr[index+i] = orig_addr + (i << IO_TLB_SHIFT);
	if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL)
		swiotlb_bounce(orig_addr, tlb_addr, size, DMA_TO_DEVICE);

	return tlb_addr;
}
  • 计算需要map的空间则算成多少个slab,记做nslots。
  • 先查找能够连续分配nslots个slab的起始slab,记做index,找之后更新io_tlb_list,io_tlb_list[index]-io_tlb_list[index+nslots]设置为0,表示这些slab不可用了。同时更新io_tlb_orig_addr,它记录每个slab所对应的原来的物理地址,这里是以slab number为索引记录的。
  • 如果DMA针对该内存的操作方式是将数据从内存拷贝到Device,则此时还需要将数据从原始物理地址对应的内存拷贝到新的物理地址对应的内存。

数据同步

如果通过swiotlb分配的内存给DMA用于将数据从Device拷贝到内存,则DMA将数据拷贝到内存后,需要通知CPU,CPU在访问数据前需要先调用sync函数,sync主要用于将数据从swiotlb buffer拷贝到原始物理地址处。

dma_sync_single_range_for_cpu->__swiotlb_sync_single_for_cpu->swiotlb_sync_single_for_cpu->swiotlb_sync_single->swiotlb_tbl_sync_single
void swiotlb_tbl_sync_single(struct device *hwdev, phys_addr_t tlb_addr,
			     size_t size, enum dma_data_direction dir,
			     enum dma_sync_target target)
{
	int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
	phys_addr_t orig_addr = io_tlb_orig_addr[index];

	if (orig_addr == INVALID_PHYS_ADDR)
		return;
	orig_addr += (unsigned long)tlb_addr & ((1 << IO_TLB_SHIFT) - 1);

	switch (target) {
	case SYNC_FOR_CPU:
		if (likely(dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL))
			swiotlb_bounce(orig_addr, tlb_addr,
				       size, DMA_FROM_DEVICE);
		else
			BUG_ON(dir != DMA_TO_DEVICE);
		break;
	case SYNC_FOR_DEVICE:
		if (likely(dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
			swiotlb_bounce(orig_addr, tlb_addr,
				       size, DMA_TO_DEVICE);
		else
			BUG_ON(dir != DMA_FROM_DEVICE);
		break;
	default:
		BUG();
	}
}
  • 如果是SYNC_FOR_CPU,调用swiotlb_bounce将数据从swiotlb buffer拷贝到原始物理地址处。
  • 如果是SYNC_FOR_DEVICE,调用swiotlb_bounce将数据从原始物理地址处拷贝到swiotlb buffer。上面我们提到dma_map_page的时候会判断申请的内存类型,如果是DMA_TO_DEVICE,则将数据从原始物理地址拷贝到swiotlb buffer。但是mapping的时候数据不一定是有效的,或者说mapping后,数据可能还会修改,数据修改后,需要调用dma_sync_single_range_for_device函数,这个函数最终也会调用到swiotlb_tbl_sync_single。

解除DMA映射

dma_unmap_page->__swiotlb_unmap_page->swiotlb_unmap_page->unmap_single->swiotlb_tbl_unmap_single
void swiotlb_tbl_unmap_single(struct device *hwdev, phys_addr_t tlb_addr,
			      size_t size, enum dma_data_direction dir)
{
	unsigned long flags;
	int i, count, nslots = ALIGN(size, 1 << IO_TLB_SHIFT) >> IO_TLB_SHIFT;
	int index = (tlb_addr - io_tlb_start) >> IO_TLB_SHIFT;
	phys_addr_t orig_addr = io_tlb_orig_addr[index];

	/*
	 * First, sync the memory before unmapping the entry
	 */
	if (orig_addr != INVALID_PHYS_ADDR &&
	    ((dir == DMA_FROM_DEVICE) || (dir == DMA_BIDIRECTIONAL)))
		swiotlb_bounce(orig_addr, tlb_addr, size, DMA_FROM_DEVICE);

	/*
	 * Return the buffer to the free list by setting the corresponding
	 * entries to indicate the number of contiguous entries available.
	 * While returning the entries to the free list, we merge the entries
	 * with slots below and above the pool being returned.
	 */
	spin_lock_irqsave(&io_tlb_lock, flags);
	{
		count = ((index + nslots) < ALIGN(index + 1, IO_TLB_SEGSIZE) ?
			 io_tlb_list[index + nslots] : 0);
		/*
		 * Step 1: return the slots to the free list, merging the
		 * slots with superceeding slots
		 */
		for (i = index + nslots - 1; i >= index; i--) {
			io_tlb_list[i] = ++count;
			io_tlb_orig_addr[i] = INVALID_PHYS_ADDR;
		}
		/*
		 * Step 2: merge the returned slots with the preceding slots,
		 * if available (non zero)
		 */
		for (i = index - 1; (OFFSET(i, IO_TLB_SEGSIZE) != IO_TLB_SEGSIZE -1) && io_tlb_list[i]; i--)
			io_tlb_list[i] = ++count;
	}
	spin_unlock_irqrestore(&io_tlb_lock, flags);
}

该函数会更新io_tlb_list和io_tlb_orig_addr以释放之前分配的slabs,这里我们不再祥诉。
这里我们需要注意的是,如果之前分配的内存的类型是DMA_FROM_DEVICE,这里会调用swiotlb_bounce函数将数据从swiotlb buffer拷贝到原始物理地址处。在使用上我们需要非常注意当调用dma_unmap_page的时候,一定要保证CPU没有在使用该page的数据,因为dma_unmap_page会用DMA送过来的原始数据覆盖最新的数据。举一个网卡的例子,通过swiotlb分配了一块DMA_FROM_DEVICE的内存,当有报文到来的时候,网卡的DMA会将报文送到swiotlb buffer,之后通过中断告知CPU有报文到来,CPU会先调用dma_sync_single_range_for_cpu函数,将数据从swiotlb buffer拷贝到原始物理地址处,然后将报文交给上层协议栈来处理,上层协议栈处理报文的时候会涉及对报文编辑,如果在协议栈处理报文的过程中调用dma_unmap_page,会导致原始报文覆盖编辑过的报文,进而引发错误。

你可能感兴趣的:(Linux,DMA技术杂谈)