1/*
2 * Copyright (C) 2004-2006 Atmel Corporation
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 */
8#include <linux/vmalloc.h>
9#include <linux/module.h>
10#include <linux/io.h>
11
12#include <asm/pgtable.h>
13#include <asm/addrspace.h>
14
15/*
16 * Re-map an arbitrary physical address space into the kernel virtual
17 * address space. Needed when the kernel wants to access physical
18 * memory directly.
19 */
20void __iomem *__ioremap(unsigned long phys_addr, size_t size,
21			unsigned long flags)
22{
23	unsigned long addr;
24	struct vm_struct *area;
25	unsigned long offset, last_addr;
26	pgprot_t prot;
27
28	/*
29	 * Check if we can simply use the P4 segment. This area is
30	 * uncacheable, so if caching/buffering is requested, we can't
31	 * use it.
32	 */
33	if ((phys_addr >= P4SEG) && (flags == 0))
34		return (void __iomem *)phys_addr;
35
36	/* Don't allow wraparound or zero size */
37	last_addr = phys_addr + size - 1;
38	if (!size || last_addr < phys_addr)
39		return NULL;
40
41	if (PHYSADDR(P2SEGADDR(phys_addr)) == phys_addr)
42		return (void __iomem *)P2SEGADDR(phys_addr);
43
44	/* Mappings have to be page-aligned */
45	offset = phys_addr & ~PAGE_MASK;
46	phys_addr &= PAGE_MASK;
47	size = PAGE_ALIGN(last_addr + 1) - phys_addr;
48
49	prot = __pgprot(_PAGE_PRESENT | _PAGE_GLOBAL | _PAGE_RW | _PAGE_DIRTY
50			| _PAGE_ACCESSED | _PAGE_TYPE_SMALL | flags);
51
52	/*
53	 * Ok, go for it..
54	 */
55	area = get_vm_area(size, VM_IOREMAP);
56	if (!area)
57		return NULL;
58	area->phys_addr = phys_addr;
59	addr = (unsigned long )area->addr;
60	if (ioremap_page_range(addr, addr + size, phys_addr, prot)) {
61		vunmap((void *)addr);
62		return NULL;
63	}
64
65	return (void __iomem *)(offset + (char *)addr);
66}
67EXPORT_SYMBOL(__ioremap);
68
69void __iounmap(void __iomem *addr)
70{
71	struct vm_struct *p;
72
73	if ((unsigned long)addr >= P4SEG)
74		return;
75	if (PXSEG(addr) == P2SEG)
76		return;
77
78	p = remove_vm_area((void *)(PAGE_MASK & (unsigned long __force)addr));
79	if (unlikely(!p)) {
80		printk (KERN_ERR "iounmap: bad address %p\n", addr);
81		return;
82	}
83
84	kfree (p);
85}
86EXPORT_SYMBOL(__iounmap);
87