vserver 1.9.5.x5
[linux-2.6.git] / drivers / parisc / ccio-dma.c
1 /*
2 ** ccio-dma.c:
3 **      DMA management routines for first generation cache-coherent machines.
4 **      Program U2/Uturn in "Virtual Mode" and use the I/O MMU.
5 **
6 **      (c) Copyright 2000 Grant Grundler
7 **      (c) Copyright 2000 Ryan Bradetich
8 **      (c) Copyright 2000 Hewlett-Packard Company
9 **
10 ** This program is free software; you can redistribute it and/or modify
11 ** it under the terms of the GNU General Public License as published by
12 ** the Free Software Foundation; either version 2 of the License, or
13 ** (at your option) any later version.
14 **
15 **
16 **  "Real Mode" operation refers to U2/Uturn chip operation.
17 **  U2/Uturn were designed to perform coherency checks w/o using
18 **  the I/O MMU - basically what x86 does.
19 **
20 **  Philipp Rumpf has a "Real Mode" driver for PCX-W machines at:
21 **      CVSROOT=:pserver:anonymous@198.186.203.37:/cvsroot/linux-parisc
22 **      cvs -z3 co linux/arch/parisc/kernel/dma-rm.c
23 **
24 **  I've rewritten his code to work under TPG's tree. See ccio-rm-dma.c.
25 **
26 **  Drawbacks of using Real Mode are:
27 **      o outbound DMA is slower - U2 won't prefetch data (GSC+ XQL signal).
28 **      o Inbound DMA less efficient - U2 can't use DMA_FAST attribute.
29 **      o Ability to do scatter/gather in HW is lost.
30 **      o Doesn't work under PCX-U/U+ machines since they didn't follow
31 **        the coherency design originally worked out. Only PCX-W does.
32 */
33
34 #include <linux/config.h>
35 #include <linux/types.h>
36 #include <linux/init.h>
37 #include <linux/mm.h>
38 #include <linux/spinlock.h>
39 #include <linux/slab.h>
40 #include <linux/string.h>
41 #include <linux/pci.h>
42 #include <linux/reboot.h>
43
44 #include <asm/byteorder.h>
45 #include <asm/cache.h>          /* for L1_CACHE_BYTES */
46 #include <asm/uaccess.h>
47 #include <asm/page.h>
48 #include <asm/dma.h>
49 #include <asm/io.h>
50 #include <asm/hardware.h>       /* for register_module() */
51 #include <asm/parisc-device.h>
52
53 /* 
54 ** Choose "ccio" since that's what HP-UX calls it.
55 ** Make it easier for folks to migrate from one to the other :^)
56 */
57 #define MODULE_NAME "ccio"
58
59 #undef DEBUG_CCIO_RES
60 #undef DEBUG_CCIO_RUN
61 #undef DEBUG_CCIO_INIT
62 #undef DEBUG_CCIO_RUN_SG
63
64 #ifdef CONFIG_PROC_FS
65 /*
66  * CCIO_SEARCH_TIME can help measure how fast the bitmap search is.
67  * impacts performance though - ditch it if you don't use it.
68  */
69 #define CCIO_SEARCH_TIME
70 #undef CCIO_MAP_STATS
71 #else
72 #undef CCIO_SEARCH_TIME
73 #undef CCIO_MAP_STATS
74 #endif
75
76 #include <linux/proc_fs.h>
77 #include <asm/runway.h>         /* for proc_runway_root */
78
79 #ifdef DEBUG_CCIO_INIT
80 #define DBG_INIT(x...)  printk(x)
81 #else
82 #define DBG_INIT(x...)
83 #endif
84
85 #ifdef DEBUG_CCIO_RUN
86 #define DBG_RUN(x...)   printk(x)
87 #else
88 #define DBG_RUN(x...)
89 #endif
90
91 #ifdef DEBUG_CCIO_RES
92 #define DBG_RES(x...)   printk(x)
93 #else
94 #define DBG_RES(x...)
95 #endif
96
97 #ifdef DEBUG_CCIO_RUN_SG
98 #define DBG_RUN_SG(x...) printk(x)
99 #else
100 #define DBG_RUN_SG(x...)
101 #endif
102
103 #define CCIO_INLINE     /* inline */
104 #define WRITE_U32(value, addr) gsc_writel(value, (u32 *)(addr))
105 #define READ_U32(addr) gsc_readl((u32 *)(addr))
106
107 #define U2_IOA_RUNWAY 0x580
108 #define U2_BC_GSC     0x501
109 #define UTURN_IOA_RUNWAY 0x581
110 #define UTURN_BC_GSC     0x502
111
112 #define IOA_NORMAL_MODE      0x00020080 /* IO_CONTROL to turn on CCIO        */
113 #define CMD_TLB_DIRECT_WRITE 35         /* IO_COMMAND for I/O TLB Writes     */
114 #define CMD_TLB_PURGE        33         /* IO_COMMAND to Purge I/O TLB entry */
115
116 struct ioa_registers {
117         /* Runway Supervisory Set */
118         volatile int32_t    unused1[12];
119         volatile uint32_t   io_command;             /* Offset 12 */
120         volatile uint32_t   io_status;              /* Offset 13 */
121         volatile uint32_t   io_control;             /* Offset 14 */
122         volatile int32_t    unused2[1];
123
124         /* Runway Auxiliary Register Set */
125         volatile uint32_t   io_err_resp;            /* Offset  0 */
126         volatile uint32_t   io_err_info;            /* Offset  1 */
127         volatile uint32_t   io_err_req;             /* Offset  2 */
128         volatile uint32_t   io_err_resp_hi;         /* Offset  3 */
129         volatile uint32_t   io_tlb_entry_m;         /* Offset  4 */
130         volatile uint32_t   io_tlb_entry_l;         /* Offset  5 */
131         volatile uint32_t   unused3[1];
132         volatile uint32_t   io_pdir_base;           /* Offset  7 */
133         volatile uint32_t   io_io_low_hv;           /* Offset  8 */
134         volatile uint32_t   io_io_high_hv;          /* Offset  9 */
135         volatile uint32_t   unused4[1];
136         volatile uint32_t   io_chain_id_mask;       /* Offset 11 */
137         volatile uint32_t   unused5[2];
138         volatile uint32_t   io_io_low;              /* Offset 14 */
139         volatile uint32_t   io_io_high;             /* Offset 15 */
140 };
141
142 /*
143 ** IOA Registers
144 ** -------------
145 **
146 ** Runway IO_CONTROL Register (+0x38)
147 ** 
148 ** The Runway IO_CONTROL register controls the forwarding of transactions.
149 **
150 ** | 0  ...  13  |  14 15 | 16 ... 21 | 22 | 23 24 |  25 ... 31 |
151 ** |    HV       |   TLB  |  reserved | HV | mode  |  reserved  |
152 **
153 ** o mode field indicates the address translation of transactions
154 **   forwarded from Runway to GSC+:
155 **       Mode Name     Value        Definition
156 **       Off (default)   0          Opaque to matching addresses.
157 **       Include         1          Transparent for matching addresses.
158 **       Peek            3          Map matching addresses.
159 **
160 **       + "Off" mode: Runway transactions which match the I/O range
161 **         specified by the IO_IO_LOW/IO_IO_HIGH registers will be ignored.
162 **       + "Include" mode: all addresses within the I/O range specified
163 **         by the IO_IO_LOW and IO_IO_HIGH registers are transparently
164 **         forwarded. This is the I/O Adapter's normal operating mode.
165 **       + "Peek" mode: used during system configuration to initialize the
166 **         GSC+ bus. Runway Write_Shorts in the address range specified by
167 **         IO_IO_LOW and IO_IO_HIGH are forwarded through the I/O Adapter
168 **         *AND* the GSC+ address is remapped to the Broadcast Physical
169 **         Address space by setting the 14 high order address bits of the
170 **         32 bit GSC+ address to ones.
171 **
172 ** o TLB field affects transactions which are forwarded from GSC+ to Runway.
173 **   "Real" mode is the poweron default.
174 ** 
175 **   TLB Mode  Value  Description
176 **   Real        0    No TLB translation. Address is directly mapped and the
177 **                    virtual address is composed of selected physical bits.
178 **   Error       1    Software fills the TLB manually.
179 **   Normal      2    IOA fetches IO TLB misses from IO PDIR (in host memory).
180 **
181 **
182 ** IO_IO_LOW_HV   +0x60 (HV dependent)
183 ** IO_IO_HIGH_HV  +0x64 (HV dependent)
184 ** IO_IO_LOW      +0x78 (Architected register)
185 ** IO_IO_HIGH     +0x7c (Architected register)
186 **
187 ** IO_IO_LOW and IO_IO_HIGH set the lower and upper bounds of the
188 ** I/O Adapter address space, respectively.
189 **
190 ** 0  ... 7 | 8 ... 15 |  16   ...   31 |
191 ** 11111111 | 11111111 |      address   |
192 **
193 ** Each LOW/HIGH pair describes a disjoint address space region.
194 ** (2 per GSC+ port). Each incoming Runway transaction address is compared
195 ** with both sets of LOW/HIGH registers. If the address is in the range
196 ** greater than or equal to IO_IO_LOW and less than IO_IO_HIGH the transaction
197 ** for forwarded to the respective GSC+ bus.
198 ** Specify IO_IO_LOW equal to or greater than IO_IO_HIGH to avoid specifying
199 ** an address space region.
200 **
201 ** In order for a Runway address to reside within GSC+ extended address space:
202 **      Runway Address [0:7]    must identically compare to 8'b11111111
203 **      Runway Address [8:11]   must be equal to IO_IO_LOW(_HV)[16:19]
204 **      Runway Address [12:23]  must be greater than or equal to
205 **                 IO_IO_LOW(_HV)[20:31] and less than IO_IO_HIGH(_HV)[20:31].
206 **      Runway Address [24:39]  is not used in the comparison.
207 **
208 ** When the Runway transaction is forwarded to GSC+, the GSC+ address is
209 ** as follows:
210 **      GSC+ Address[0:3]       4'b1111
211 **      GSC+ Address[4:29]      Runway Address[12:37]
212 **      GSC+ Address[30:31]     2'b00
213 **
214 ** All 4 Low/High registers must be initialized (by PDC) once the lower bus
215 ** is interrogated and address space is defined. The operating system will
216 ** modify the architectural IO_IO_LOW and IO_IO_HIGH registers following
217 ** the PDC initialization.  However, the hardware version dependent IO_IO_LOW
218 ** and IO_IO_HIGH registers should not be subsequently altered by the OS.
219 ** 
220 ** Writes to both sets of registers will take effect immediately, bypassing
221 ** the queues, which ensures that subsequent Runway transactions are checked
222 ** against the updated bounds values. However reads are queued, introducing
223 ** the possibility of a read being bypassed by a subsequent write to the same
224 ** register. This sequence can be avoided by having software wait for read
225 ** returns before issuing subsequent writes.
226 */
227
228 struct ioc {
229         struct ioa_registers *ioc_hpa;  /* I/O MMU base address */
230         u8  *res_map;                   /* resource map, bit == pdir entry */
231         u64 *pdir_base;                 /* physical base address */
232         u32 pdir_size;                  /* bytes, function of IOV Space size */
233         u32 res_hint;                   /* next available IOVP - 
234                                            circular search */
235         u32 res_size;                   /* size of resource map in bytes */
236         spinlock_t res_lock;
237
238 #ifdef CCIO_SEARCH_TIME
239 #define CCIO_SEARCH_SAMPLE 0x100
240         unsigned long avg_search[CCIO_SEARCH_SAMPLE];
241         unsigned long avg_idx;            /* current index into avg_search */
242 #endif
243 #ifdef CCIO_MAP_STATS
244         unsigned long used_pages;
245         unsigned long msingle_calls;
246         unsigned long msingle_pages;
247         unsigned long msg_calls;
248         unsigned long msg_pages;
249         unsigned long usingle_calls;
250         unsigned long usingle_pages;
251         unsigned long usg_calls;
252         unsigned long usg_pages;
253 #endif
254         unsigned short cujo20_bug;
255
256         /* STUFF We don't need in performance path */
257         u32 chainid_shift;              /* specify bit location of chain_id */
258         struct ioc *next;               /* Linked list of discovered iocs */
259         const char *name;               /* device name from firmware */
260         unsigned int hw_path;           /* the hardware path this ioc is associatd with */
261         struct pci_dev *fake_pci_dev;   /* the fake pci_dev for non-pci devs */
262         struct resource mmio_region[2]; /* The "routed" MMIO regions */
263 };
264
265 /* Ratio of Host MEM to IOV Space size */
266 static unsigned long ccio_mem_ratio = 4;
267 static struct ioc *ioc_list;
268 static int ioc_count;
269
270 /**************************************************************
271 *
272 *   I/O Pdir Resource Management
273 *
274 *   Bits set in the resource map are in use.
275 *   Each bit can represent a number of pages.
276 *   LSbs represent lower addresses (IOVA's).
277 *
278 *   This was was copied from sba_iommu.c. Don't try to unify
279 *   the two resource managers unless a way to have different
280 *   allocation policies is also adjusted. We'd like to avoid
281 *   I/O TLB thrashing by having resource allocation policy
282 *   match the I/O TLB replacement policy.
283 *
284 ***************************************************************/
285 #define IOVP_SIZE PAGE_SIZE
286 #define IOVP_SHIFT PAGE_SHIFT
287 #define IOVP_MASK PAGE_MASK
288
289 /* Convert from IOVP to IOVA and vice versa. */
290 #define CCIO_IOVA(iovp,offset) ((iovp) | (offset))
291 #define CCIO_IOVP(iova) ((iova) & IOVP_MASK)
292
293 #define PDIR_INDEX(iovp)    ((iovp)>>IOVP_SHIFT)
294 #define MKIOVP(pdir_idx)    ((long)(pdir_idx) << IOVP_SHIFT)
295 #define MKIOVA(iovp,offset) (dma_addr_t)((long)iovp | (long)offset)
296 #define ROUNDUP(x,y) ((x + ((y)-1)) & ~((y)-1))
297
298 /*
299 ** Don't worry about the 150% average search length on a miss.
300 ** If the search wraps around, and passes the res_hint, it will
301 ** cause the kernel to panic anyhow.
302 */
303 #define CCIO_SEARCH_LOOP(ioc, res_idx, mask, size)  \
304        for(; res_ptr < res_end; ++res_ptr) { \
305                if(0 == (*res_ptr & mask)) { \
306                        *res_ptr |= mask; \
307                        res_idx = (unsigned int)((unsigned long)res_ptr - (unsigned long)ioc->res_map); \
308                        ioc->res_hint = res_idx + (size >> 3); \
309                        goto resource_found; \
310                } \
311        }
312
313 #define CCIO_FIND_FREE_MAPPING(ioa, res_idx, mask, size) \
314        u##size *res_ptr = (u##size *)&((ioc)->res_map[ioa->res_hint & ~((size >> 3) - 1)]); \
315        u##size *res_end = (u##size *)&(ioc)->res_map[ioa->res_size]; \
316        CCIO_SEARCH_LOOP(ioc, res_idx, mask, size); \
317        res_ptr = (u##size *)&(ioc)->res_map[0]; \
318        CCIO_SEARCH_LOOP(ioa, res_idx, mask, size);
319
320 /*
321 ** Find available bit in this ioa's resource map.
322 ** Use a "circular" search:
323 **   o Most IOVA's are "temporary" - avg search time should be small.
324 ** o keep a history of what happened for debugging
325 ** o KISS.
326 **
327 ** Perf optimizations:
328 ** o search for log2(size) bits at a time.
329 ** o search for available resource bits using byte/word/whatever.
330 ** o use different search for "large" (eg > 4 pages) or "very large"
331 **   (eg > 16 pages) mappings.
332 */
333
334 /**
335  * ccio_alloc_range - Allocate pages in the ioc's resource map.
336  * @ioc: The I/O Controller.
337  * @pages_needed: The requested number of pages to be mapped into the
338  * I/O Pdir...
339  *
340  * This function searches the resource map of the ioc to locate a range
341  * of available pages for the requested size.
342  */
343 static int
344 ccio_alloc_range(struct ioc *ioc, size_t size)
345 {
346         unsigned int pages_needed = size >> IOVP_SHIFT;
347         unsigned int res_idx;
348 #ifdef CCIO_SEARCH_TIME
349         unsigned long cr_start = mfctl(16);
350 #endif
351         
352         BUG_ON(pages_needed == 0);
353         BUG_ON((pages_needed * IOVP_SIZE) > DMA_CHUNK_SIZE);
354      
355         DBG_RES("%s() size: %d pages_needed %d\n", 
356                 __FUNCTION__, size, pages_needed);
357
358         /*
359         ** "seek and ye shall find"...praying never hurts either...
360         ** ggg sacrifices another 710 to the computer gods.
361         */
362
363         if (pages_needed <= 8) {
364                 /*
365                  * LAN traffic will not thrash the TLB IFF the same NIC
366                  * uses 8 adjacent pages to map seperate payload data.
367                  * ie the same byte in the resource bit map.
368                  */
369 #if 0
370                 /* FIXME: bit search should shift it's way through
371                  * an unsigned long - not byte at a time. As it is now,
372                  * we effectively allocate this byte to this mapping.
373                  */
374                 unsigned long mask = ~(~0UL >> pages_needed);
375                 CCIO_FIND_FREE_MAPPING(ioc, res_idx, mask, 8);
376 #else
377                 CCIO_FIND_FREE_MAPPING(ioc, res_idx, 0xff, 8);
378 #endif
379         } else if (pages_needed <= 16) {
380                 CCIO_FIND_FREE_MAPPING(ioc, res_idx, 0xffff, 16);
381         } else if (pages_needed <= 32) {
382                 CCIO_FIND_FREE_MAPPING(ioc, res_idx, ~(unsigned int)0, 32);
383 #ifdef __LP64__
384         } else if (pages_needed <= 64) {
385                 CCIO_FIND_FREE_MAPPING(ioc, res_idx, ~0UL, 64);
386 #endif
387         } else {
388                 panic("%s: %s() Too many pages to map. pages_needed: %u\n",
389                        __FILE__,  __FUNCTION__, pages_needed);
390         }
391
392         panic("%s: %s() I/O MMU is out of mapping resources.\n", __FILE__,
393               __FUNCTION__);
394         
395 resource_found:
396         
397         DBG_RES("%s() res_idx %d res_hint: %d\n",
398                 __FUNCTION__, res_idx, ioc->res_hint);
399
400 #ifdef CCIO_SEARCH_TIME
401         {
402                 unsigned long cr_end = mfctl(16);
403                 unsigned long tmp = cr_end - cr_start;
404                 /* check for roll over */
405                 cr_start = (cr_end < cr_start) ?  -(tmp) : (tmp);
406         }
407         ioc->avg_search[ioc->avg_idx++] = cr_start;
408         ioc->avg_idx &= CCIO_SEARCH_SAMPLE - 1;
409 #endif
410 #ifdef CCIO_MAP_STATS
411         ioc->used_pages += pages_needed;
412 #endif
413         /* 
414         ** return the bit address.
415         */
416         return res_idx << 3;
417 }
418
419 #define CCIO_FREE_MAPPINGS(ioc, res_idx, mask, size) \
420         u##size *res_ptr = (u##size *)&((ioc)->res_map[res_idx]); \
421         BUG_ON((*res_ptr & mask) != mask); \
422         *res_ptr &= ~(mask);
423
424 /**
425  * ccio_free_range - Free pages from the ioc's resource map.
426  * @ioc: The I/O Controller.
427  * @iova: The I/O Virtual Address.
428  * @pages_mapped: The requested number of pages to be freed from the
429  * I/O Pdir.
430  *
431  * This function frees the resouces allocated for the iova.
432  */
433 static void
434 ccio_free_range(struct ioc *ioc, dma_addr_t iova, unsigned long pages_mapped)
435 {
436         unsigned long iovp = CCIO_IOVP(iova);
437         unsigned int res_idx = PDIR_INDEX(iovp) >> 3;
438
439         BUG_ON(pages_mapped == 0);
440         BUG_ON((pages_mapped * IOVP_SIZE) > DMA_CHUNK_SIZE);
441         BUG_ON(pages_mapped > BITS_PER_LONG);
442
443         DBG_RES("%s():  res_idx: %d pages_mapped %d\n", 
444                 __FUNCTION__, res_idx, pages_mapped);
445
446 #ifdef CCIO_MAP_STATS
447         ioc->used_pages -= pages_mapped;
448 #endif
449
450         if(pages_mapped <= 8) {
451 #if 0
452                 /* see matching comments in alloc_range */
453                 unsigned long mask = ~(~0UL >> pages_mapped);
454                 CCIO_FREE_MAPPINGS(ioc, res_idx, mask, 8);
455 #else
456                 CCIO_FREE_MAPPINGS(ioc, res_idx, 0xff, 8);
457 #endif
458         } else if(pages_mapped <= 16) {
459                 CCIO_FREE_MAPPINGS(ioc, res_idx, 0xffff, 16);
460         } else if(pages_mapped <= 32) {
461                 CCIO_FREE_MAPPINGS(ioc, res_idx, ~(unsigned int)0, 32);
462 #ifdef __LP64__
463         } else if(pages_mapped <= 64) {
464                 CCIO_FREE_MAPPINGS(ioc, res_idx, ~0UL, 64);
465 #endif
466         } else {
467                 panic("%s:%s() Too many pages to unmap.\n", __FILE__,
468                       __FUNCTION__);
469         }
470 }
471
472 /****************************************************************
473 **
474 **          CCIO dma_ops support routines
475 **
476 *****************************************************************/
477
478 typedef unsigned long space_t;
479 #define KERNEL_SPACE 0
480
481 /*
482 ** DMA "Page Type" and Hints 
483 ** o if SAFE_DMA isn't set, mapping is for FAST_DMA. SAFE_DMA should be
484 **   set for subcacheline DMA transfers since we don't want to damage the
485 **   other part of a cacheline.
486 ** o SAFE_DMA must be set for "memory" allocated via pci_alloc_consistent().
487 **   This bit tells U2 to do R/M/W for partial cachelines. "Streaming"
488 **   data can avoid this if the mapping covers full cache lines.
489 ** o STOP_MOST is needed for atomicity across cachelines.
490 **   Apperently only "some EISA devices" need this.
491 **   Using CONFIG_ISA is hack. Only the IOA with EISA under it needs
492 **   to use this hint iff the EISA devices needs this feature.
493 **   According to the U2 ERS, STOP_MOST enabled pages hurt performance.
494 ** o PREFETCH should *not* be set for cases like Multiple PCI devices
495 **   behind GSCtoPCI (dino) bus converter. Only one cacheline per GSC
496 **   device can be fetched and multiply DMA streams will thrash the
497 **   prefetch buffer and burn memory bandwidth. See 6.7.3 "Prefetch Rules
498 **   and Invalidation of Prefetch Entries".
499 **
500 ** FIXME: the default hints need to be per GSC device - not global.
501 ** 
502 ** HP-UX dorks: linux device driver programming model is totally different
503 **    than HP-UX's. HP-UX always sets HINT_PREFETCH since it's drivers
504 **    do special things to work on non-coherent platforms...linux has to
505 **    be much more careful with this.
506 */
507 #define IOPDIR_VALID    0x01UL
508 #define HINT_SAFE_DMA   0x02UL  /* used for pci_alloc_consistent() pages */
509 #ifdef CONFIG_EISA
510 #define HINT_STOP_MOST  0x04UL  /* LSL support */
511 #else
512 #define HINT_STOP_MOST  0x00UL  /* only needed for "some EISA devices" */
513 #endif
514 #define HINT_UDPATE_ENB 0x08UL  /* not used/supported by U2 */
515 #define HINT_PREFETCH   0x10UL  /* for outbound pages which are not SAFE */
516
517
518 /*
519 ** Use direction (ie PCI_DMA_TODEVICE) to pick hint.
520 ** ccio_alloc_consistent() depends on this to get SAFE_DMA
521 ** when it passes in BIDIRECTIONAL flag.
522 */
523 static u32 hint_lookup[] = {
524         [PCI_DMA_BIDIRECTIONAL] = HINT_STOP_MOST | HINT_SAFE_DMA | IOPDIR_VALID,
525         [PCI_DMA_TODEVICE]      = HINT_STOP_MOST | HINT_PREFETCH | IOPDIR_VALID,
526         [PCI_DMA_FROMDEVICE]    = HINT_STOP_MOST | IOPDIR_VALID,
527 };
528
529 /**
530  * ccio_io_pdir_entry - Initialize an I/O Pdir.
531  * @pdir_ptr: A pointer into I/O Pdir.
532  * @sid: The Space Identifier.
533  * @vba: The virtual address.
534  * @hints: The DMA Hint.
535  *
536  * Given a virtual address (vba, arg2) and space id, (sid, arg1),
537  * load the I/O PDIR entry pointed to by pdir_ptr (arg0). Each IO Pdir
538  * entry consists of 8 bytes as shown below (MSB == bit 0):
539  *
540  *
541  * WORD 0:
542  * +------+----------------+-----------------------------------------------+
543  * | Phys | Virtual Index  |               Phys                            |
544  * | 0:3  |     0:11       |               4:19                            |
545  * |4 bits|   12 bits      |              16 bits                          |
546  * +------+----------------+-----------------------------------------------+
547  * WORD 1:
548  * +-----------------------+-----------------------------------------------+
549  * |      Phys    |  Rsvd  | Prefetch |Update |Rsvd  |Lock  |Safe  |Valid  |
550  * |     20:39    |        | Enable   |Enable |      |Enable|DMA   |       |
551  * |    20 bits   | 5 bits | 1 bit    |1 bit  |2 bits|1 bit |1 bit |1 bit  |
552  * +-----------------------+-----------------------------------------------+
553  *
554  * The virtual index field is filled with the results of the LCI
555  * (Load Coherence Index) instruction.  The 8 bits used for the virtual
556  * index are bits 12:19 of the value returned by LCI.
557  */ 
558 void CCIO_INLINE
559 ccio_io_pdir_entry(u64 *pdir_ptr, space_t sid, unsigned long vba,
560                    unsigned long hints)
561 {
562         register unsigned long pa = (volatile unsigned long) vba;
563         register unsigned long ci; /* coherent index */
564
565         /* We currently only support kernel addresses */
566         BUG_ON(sid != KERNEL_SPACE);
567
568         mtsp(sid,1);
569
570         /*
571         ** WORD 1 - low order word
572         ** "hints" parm includes the VALID bit!
573         ** "dep" clobbers the physical address offset bits as well.
574         */
575         pa = virt_to_phys(vba);
576         asm volatile("depw  %1,31,12,%0" : "+r" (pa) : "r" (hints));
577         ((u32 *)pdir_ptr)[1] = (u32) pa;
578
579         /*
580         ** WORD 0 - high order word
581         */
582
583 #ifdef __LP64__
584         /*
585         ** get bits 12:15 of physical address
586         ** shift bits 16:31 of physical address
587         ** and deposit them
588         */
589         asm volatile ("extrd,u %1,15,4,%0" : "=r" (ci) : "r" (pa));
590         asm volatile ("extrd,u %1,31,16,%0" : "+r" (pa) : "r" (pa));
591         asm volatile ("depd  %1,35,4,%0" : "+r" (pa) : "r" (ci));
592 #else
593         pa = 0;
594 #endif
595         /*
596         ** get CPU coherency index bits
597         ** Grab virtual index [0:11]
598         ** Deposit virt_idx bits into I/O PDIR word
599         */
600         asm volatile ("lci 0(%%sr1, %1), %0" : "=r" (ci) : "r" (vba));
601         asm volatile ("extru %1,19,12,%0" : "+r" (ci) : "r" (ci));
602         asm volatile ("depw  %1,15,12,%0" : "+r" (pa) : "r" (ci));
603
604         ((u32 *)pdir_ptr)[0] = (u32) pa;
605
606
607         /* FIXME: PCX_W platforms don't need FDC/SYNC. (eg C360)
608         **        PCX-U/U+ do. (eg C200/C240)
609         **        PCX-T'? Don't know. (eg C110 or similar K-class)
610         **
611         ** See PDC_MODEL/option 0/SW_CAP word for "Non-coherent IO-PDIR bit".
612         ** Hopefully we can patch (NOP) these out at boot time somehow.
613         **
614         ** "Since PCX-U employs an offset hash that is incompatible with
615         ** the real mode coherence index generation of U2, the PDIR entry
616         ** must be flushed to memory to retain coherence."
617         */
618         asm volatile("fdc 0(%0)" : : "r" (pdir_ptr));
619         asm volatile("sync");
620 }
621
622 /**
623  * ccio_clear_io_tlb - Remove stale entries from the I/O TLB.
624  * @ioc: The I/O Controller.
625  * @iovp: The I/O Virtual Page.
626  * @byte_cnt: The requested number of bytes to be freed from the I/O Pdir.
627  *
628  * Purge invalid I/O PDIR entries from the I/O TLB.
629  *
630  * FIXME: Can we change the byte_cnt to pages_mapped?
631  */
632 static CCIO_INLINE void
633 ccio_clear_io_tlb(struct ioc *ioc, dma_addr_t iovp, size_t byte_cnt)
634 {
635         u32 chain_size = 1 << ioc->chainid_shift;
636
637         iovp &= IOVP_MASK;      /* clear offset bits, just want pagenum */
638         byte_cnt += chain_size;
639
640         while(byte_cnt > chain_size) {
641                 WRITE_U32(CMD_TLB_PURGE | iovp, &ioc->ioc_hpa->io_command);
642                 iovp += chain_size;
643                 byte_cnt -= chain_size;
644         }
645 }
646
647 /**
648  * ccio_mark_invalid - Mark the I/O Pdir entries invalid.
649  * @ioc: The I/O Controller.
650  * @iova: The I/O Virtual Address.
651  * @byte_cnt: The requested number of bytes to be freed from the I/O Pdir.
652  *
653  * Mark the I/O Pdir entries invalid and blow away the corresponding I/O
654  * TLB entries.
655  *
656  * FIXME: at some threshhold it might be "cheaper" to just blow
657  *        away the entire I/O TLB instead of individual entries.
658  *
659  * FIXME: Uturn has 256 TLB entries. We don't need to purge every
660  *        PDIR entry - just once for each possible TLB entry.
661  *        (We do need to maker I/O PDIR entries invalid regardless).
662  *
663  * FIXME: Can we change byte_cnt to pages_mapped?
664  */ 
665 static CCIO_INLINE void
666 ccio_mark_invalid(struct ioc *ioc, dma_addr_t iova, size_t byte_cnt)
667 {
668         u32 iovp = (u32)CCIO_IOVP(iova);
669         size_t saved_byte_cnt;
670
671         /* round up to nearest page size */
672         saved_byte_cnt = byte_cnt = ROUNDUP(byte_cnt, IOVP_SIZE);
673
674         while(byte_cnt > 0) {
675                 /* invalidate one page at a time */
676                 unsigned int idx = PDIR_INDEX(iovp);
677                 char *pdir_ptr = (char *) &(ioc->pdir_base[idx]);
678
679                 BUG_ON(idx >= (ioc->pdir_size / sizeof(u64)));
680                 pdir_ptr[7] = 0;        /* clear only VALID bit */ 
681                 /*
682                 ** FIXME: PCX_W platforms don't need FDC/SYNC. (eg C360)
683                 **   PCX-U/U+ do. (eg C200/C240)
684                 ** See PDC_MODEL/option 0/SW_CAP for "Non-coherent IO-PDIR bit".
685                 **
686                 ** Hopefully someone figures out how to patch (NOP) the
687                 ** FDC/SYNC out at boot time.
688                 */
689                 asm volatile("fdc 0(%0)" : : "r" (pdir_ptr[7]));
690
691                 iovp     += IOVP_SIZE;
692                 byte_cnt -= IOVP_SIZE;
693         }
694
695         asm volatile("sync");
696         ccio_clear_io_tlb(ioc, CCIO_IOVP(iova), saved_byte_cnt);
697 }
698
699 /****************************************************************
700 **
701 **          CCIO dma_ops
702 **
703 *****************************************************************/
704
705 /**
706  * ccio_dma_supported - Verify the IOMMU supports the DMA address range.
707  * @dev: The PCI device.
708  * @mask: A bit mask describing the DMA address range of the device.
709  *
710  * This function implements the pci_dma_supported function.
711  */
712 static int 
713 ccio_dma_supported(struct device *dev, u64 mask)
714 {
715         if(dev == NULL) {
716                 printk(KERN_ERR MODULE_NAME ": EISA/ISA/et al not supported\n");
717                 BUG();
718                 return 0;
719         }
720
721         /* only support 32-bit devices (ie PCI/GSC) */
722         return (int)(mask == 0xffffffffUL);
723 }
724
725 /**
726  * ccio_map_single - Map an address range into the IOMMU.
727  * @dev: The PCI device.
728  * @addr: The start address of the DMA region.
729  * @size: The length of the DMA region.
730  * @direction: The direction of the DMA transaction (to/from device).
731  *
732  * This function implements the pci_map_single function.
733  */
734 static dma_addr_t 
735 ccio_map_single(struct device *dev, void *addr, size_t size,
736                 enum dma_data_direction direction)
737 {
738         int idx;
739         struct ioc *ioc;
740         unsigned long flags;
741         dma_addr_t iovp;
742         dma_addr_t offset;
743         u64 *pdir_start;
744         unsigned long hint = hint_lookup[(int)direction];
745
746         BUG_ON(!dev);
747         ioc = GET_IOC(dev);
748
749         BUG_ON(size <= 0);
750
751         /* save offset bits */
752         offset = ((unsigned long) addr) & ~IOVP_MASK;
753
754         /* round up to nearest IOVP_SIZE */
755         size = ROUNDUP(size + offset, IOVP_SIZE);
756         spin_lock_irqsave(&ioc->res_lock, flags);
757
758 #ifdef CCIO_MAP_STATS
759         ioc->msingle_calls++;
760         ioc->msingle_pages += size >> IOVP_SHIFT;
761 #endif
762
763         idx = ccio_alloc_range(ioc, size);
764         iovp = (dma_addr_t)MKIOVP(idx);
765
766         pdir_start = &(ioc->pdir_base[idx]);
767
768         DBG_RUN("%s() 0x%p -> 0x%lx size: %0x%x\n",
769                 __FUNCTION__, addr, (long)iovp | offset, size);
770
771         /* If not cacheline aligned, force SAFE_DMA on the whole mess */
772         if((size % L1_CACHE_BYTES) || ((unsigned long)addr % L1_CACHE_BYTES))
773                 hint |= HINT_SAFE_DMA;
774
775         while(size > 0) {
776                 ccio_io_pdir_entry(pdir_start, KERNEL_SPACE, (unsigned long)addr, hint);
777
778                 DBG_RUN(" pdir %p %08x%08x\n",
779                         pdir_start,
780                         (u32) (((u32 *) pdir_start)[0]),
781                         (u32) (((u32 *) pdir_start)[1]));
782                 ++pdir_start;
783                 addr += IOVP_SIZE;
784                 size -= IOVP_SIZE;
785         }
786
787         spin_unlock_irqrestore(&ioc->res_lock, flags);
788
789         /* form complete address */
790         return CCIO_IOVA(iovp, offset);
791 }
792
793 /**
794  * ccio_unmap_single - Unmap an address range from the IOMMU.
795  * @dev: The PCI device.
796  * @addr: The start address of the DMA region.
797  * @size: The length of the DMA region.
798  * @direction: The direction of the DMA transaction (to/from device).
799  *
800  * This function implements the pci_unmap_single function.
801  */
802 static void 
803 ccio_unmap_single(struct device *dev, dma_addr_t iova, size_t size, 
804                   enum dma_data_direction direction)
805 {
806         struct ioc *ioc;
807         unsigned long flags; 
808         dma_addr_t offset = iova & ~IOVP_MASK;
809         
810         BUG_ON(!dev);
811         ioc = GET_IOC(dev);
812
813         DBG_RUN("%s() iovp 0x%lx/%x\n",
814                 __FUNCTION__, (long)iova, size);
815
816         iova ^= offset;        /* clear offset bits */
817         size += offset;
818         size = ROUNDUP(size, IOVP_SIZE);
819
820         spin_lock_irqsave(&ioc->res_lock, flags);
821
822 #ifdef CCIO_MAP_STATS
823         ioc->usingle_calls++;
824         ioc->usingle_pages += size >> IOVP_SHIFT;
825 #endif
826
827         ccio_mark_invalid(ioc, iova, size);
828         ccio_free_range(ioc, iova, (size >> IOVP_SHIFT));
829         spin_unlock_irqrestore(&ioc->res_lock, flags);
830 }
831
832 /**
833  * ccio_alloc_consistent - Allocate a consistent DMA mapping.
834  * @dev: The PCI device.
835  * @size: The length of the DMA region.
836  * @dma_handle: The DMA address handed back to the device (not the cpu).
837  *
838  * This function implements the pci_alloc_consistent function.
839  */
840 static void * 
841 ccio_alloc_consistent(struct device *dev, size_t size, dma_addr_t *dma_handle, int flag)
842 {
843       void *ret;
844 #if 0
845 /* GRANT Need to establish hierarchy for non-PCI devs as well
846 ** and then provide matching gsc_map_xxx() functions for them as well.
847 */
848         if(!hwdev) {
849                 /* only support PCI */
850                 *dma_handle = 0;
851                 return 0;
852         }
853 #endif
854         ret = (void *) __get_free_pages(flag, get_order(size));
855
856         if (ret) {
857                 memset(ret, 0, size);
858                 *dma_handle = ccio_map_single(dev, ret, size, PCI_DMA_BIDIRECTIONAL);
859         }
860
861         return ret;
862 }
863
864 /**
865  * ccio_free_consistent - Free a consistent DMA mapping.
866  * @dev: The PCI device.
867  * @size: The length of the DMA region.
868  * @cpu_addr: The cpu address returned from the ccio_alloc_consistent.
869  * @dma_handle: The device address returned from the ccio_alloc_consistent.
870  *
871  * This function implements the pci_free_consistent function.
872  */
873 static void 
874 ccio_free_consistent(struct device *dev, size_t size, void *cpu_addr, 
875                      dma_addr_t dma_handle)
876 {
877         ccio_unmap_single(dev, dma_handle, size, 0);
878         free_pages((unsigned long)cpu_addr, get_order(size));
879 }
880
881 /*
882 ** Since 0 is a valid pdir_base index value, can't use that
883 ** to determine if a value is valid or not. Use a flag to indicate
884 ** the SG list entry contains a valid pdir index.
885 */
886 #define PIDE_FLAG 0x80000000UL
887
888 #ifdef CCIO_MAP_STATS
889 #define IOMMU_MAP_STATS
890 #endif
891 #include "iommu-helpers.h"
892
893 /**
894  * ccio_map_sg - Map the scatter/gather list into the IOMMU.
895  * @dev: The PCI device.
896  * @sglist: The scatter/gather list to be mapped in the IOMMU.
897  * @nents: The number of entries in the scatter/gather list.
898  * @direction: The direction of the DMA transaction (to/from device).
899  *
900  * This function implements the pci_map_sg function.
901  */
902 static int
903 ccio_map_sg(struct device *dev, struct scatterlist *sglist, int nents, 
904             enum dma_data_direction direction)
905 {
906         struct ioc *ioc;
907         int coalesced, filled = 0;
908         unsigned long flags;
909         unsigned long hint = hint_lookup[(int)direction];
910         unsigned long prev_len = 0, current_len = 0;
911         int i;
912         
913         BUG_ON(!dev);
914         ioc = GET_IOC(dev);
915         
916         DBG_RUN_SG("%s() START %d entries\n", __FUNCTION__, nents);
917
918         /* Fast path single entry scatterlists. */
919         if (nents == 1) {
920                 sg_dma_address(sglist) = ccio_map_single(dev,
921                                 (void *)sg_virt_addr(sglist), sglist->length,
922                                 direction);
923                 sg_dma_len(sglist) = sglist->length;
924                 return 1;
925         }
926
927         for(i = 0; i < nents; i++)
928                 prev_len += sglist[i].length;
929         
930         spin_lock_irqsave(&ioc->res_lock, flags);
931
932 #ifdef CCIO_MAP_STATS
933         ioc->msg_calls++;
934 #endif
935
936         /*
937         ** First coalesce the chunks and allocate I/O pdir space
938         **
939         ** If this is one DMA stream, we can properly map using the
940         ** correct virtual address associated with each DMA page.
941         ** w/o this association, we wouldn't have coherent DMA!
942         ** Access to the virtual address is what forces a two pass algorithm.
943         */
944         coalesced = iommu_coalesce_chunks(ioc, sglist, nents, ccio_alloc_range);
945
946         /*
947         ** Program the I/O Pdir
948         **
949         ** map the virtual addresses to the I/O Pdir
950         ** o dma_address will contain the pdir index
951         ** o dma_len will contain the number of bytes to map 
952         ** o page/offset contain the virtual address.
953         */
954         filled = iommu_fill_pdir(ioc, sglist, nents, hint, ccio_io_pdir_entry);
955
956         spin_unlock_irqrestore(&ioc->res_lock, flags);
957
958         BUG_ON(coalesced != filled);
959
960         DBG_RUN_SG("%s() DONE %d mappings\n", __FUNCTION__, filled);
961
962         for (i = 0; i < filled; i++)
963                 current_len += sg_dma_len(sglist + i);
964
965         BUG_ON(current_len != prev_len);
966
967         return filled;
968 }
969
970 /**
971  * ccio_unmap_sg - Unmap the scatter/gather list from the IOMMU.
972  * @dev: The PCI device.
973  * @sglist: The scatter/gather list to be unmapped from the IOMMU.
974  * @nents: The number of entries in the scatter/gather list.
975  * @direction: The direction of the DMA transaction (to/from device).
976  *
977  * This function implements the pci_unmap_sg function.
978  */
979 static void 
980 ccio_unmap_sg(struct device *dev, struct scatterlist *sglist, int nents, 
981               enum dma_data_direction direction)
982 {
983         struct ioc *ioc;
984
985         BUG_ON(!dev);
986         ioc = GET_IOC(dev);
987
988         DBG_RUN_SG("%s() START %d entries,  %08lx,%x\n",
989                 __FUNCTION__, nents, sg_virt_addr(sglist), sglist->length);
990
991 #ifdef CCIO_MAP_STATS
992         ioc->usg_calls++;
993 #endif
994
995         while(sg_dma_len(sglist) && nents--) {
996
997 #ifdef CCIO_MAP_STATS
998                 ioc->usg_pages += sg_dma_len(sglist) >> PAGE_SHIFT;
999 #endif
1000                 ccio_unmap_single(dev, sg_dma_address(sglist),
1001                                   sg_dma_len(sglist), direction);
1002                 ++sglist;
1003         }
1004
1005         DBG_RUN_SG("%s() DONE (nents %d)\n", __FUNCTION__, nents);
1006 }
1007
1008 static struct hppa_dma_ops ccio_ops = {
1009         .dma_supported =        ccio_dma_supported,
1010         .alloc_consistent =     ccio_alloc_consistent,
1011         .alloc_noncoherent =    ccio_alloc_consistent,
1012         .free_consistent =      ccio_free_consistent,
1013         .map_single =           ccio_map_single,
1014         .unmap_single =         ccio_unmap_single,
1015         .map_sg =               ccio_map_sg,
1016         .unmap_sg =             ccio_unmap_sg,
1017         .dma_sync_single_for_cpu =      NULL,   /* NOP for U2/Uturn */
1018         .dma_sync_single_for_device =   NULL,   /* NOP for U2/Uturn */
1019         .dma_sync_sg_for_cpu =          NULL,   /* ditto */
1020         .dma_sync_sg_for_device =               NULL,   /* ditto */
1021 };
1022
1023 #ifdef CONFIG_PROC_FS
1024 static int proc_append(char *src, int len, char **dst, off_t *offset, int *max)
1025 {
1026         if (len < *offset) {
1027                 *offset -= len;
1028                 return 0;
1029         }
1030         if (*offset > 0) {
1031                 src += *offset;
1032                 len -= *offset;
1033                 *offset = 0;
1034         }
1035         if (len > *max) {
1036                 len = *max;
1037         }
1038         memcpy(*dst, src, len);
1039         *dst += len;
1040         *max -= len;
1041         return (*max == 0);
1042 }
1043
1044 static int ccio_proc_info(char *buf, char **start, off_t offset, int count,
1045                           int *eof, void *data)
1046 {
1047         int max = count;
1048         char tmp[80]; /* width of an ANSI-standard terminal */
1049         struct ioc *ioc = ioc_list;
1050
1051         while (ioc != NULL) {
1052                 unsigned int total_pages = ioc->res_size << 3;
1053                 unsigned long avg = 0, min, max;
1054                 int j, len;
1055
1056                 len = sprintf(tmp, "%s\n", ioc->name);
1057                 if (proc_append(tmp, len, &buf, &offset, &count))
1058                         break;
1059                 
1060                 len = sprintf(tmp, "Cujo 2.0 bug    : %s\n",
1061                               (ioc->cujo20_bug ? "yes" : "no"));
1062                 if (proc_append(tmp, len, &buf, &offset, &count))
1063                         break;
1064                 
1065                 len = sprintf(tmp, "IO PDIR size    : %d bytes (%d entries)\n",
1066                               total_pages * 8, total_pages);
1067                 if (proc_append(tmp, len, &buf, &offset, &count))
1068                         break;
1069 #ifdef CCIO_MAP_STATS
1070                 len = sprintf(tmp, "IO PDIR entries : %ld free  %ld used (%d%%)\n",
1071                               total_pages - ioc->used_pages, ioc->used_pages,
1072                               (int)(ioc->used_pages * 100 / total_pages));
1073                 if (proc_append(tmp, len, &buf, &offset, &count))
1074                         break;
1075 #endif
1076                 len = sprintf(tmp, "Resource bitmap : %d bytes (%d pages)\n", 
1077                         ioc->res_size, total_pages);
1078                 if (proc_append(tmp, len, &buf, &offset, &count))
1079                         break;
1080 #ifdef CCIO_SEARCH_TIME
1081                 min = max = ioc->avg_search[0];
1082                 for(j = 0; j < CCIO_SEARCH_SAMPLE; ++j) {
1083                         avg += ioc->avg_search[j];
1084                         if(ioc->avg_search[j] > max) 
1085                                 max = ioc->avg_search[j];
1086                         if(ioc->avg_search[j] < min) 
1087                                 min = ioc->avg_search[j];
1088                 }
1089                 avg /= CCIO_SEARCH_SAMPLE;
1090                 len = sprintf(tmp, "  Bitmap search : %ld/%ld/%ld (min/avg/max CPU Cycles)\n",
1091                               min, avg, max);
1092                 if (proc_append(tmp, len, &buf, &offset, &count))
1093                         break;
1094 #endif
1095 #ifdef CCIO_MAP_STATS
1096                 len = sprintf(tmp, "pci_map_single(): %8ld calls  %8ld pages (avg %d/1000)\n",
1097                               ioc->msingle_calls, ioc->msingle_pages,
1098                               (int)((ioc->msingle_pages * 1000)/ioc->msingle_calls));
1099                 if (proc_append(tmp, len, &buf, &offset, &count))
1100                         break;
1101                 
1102
1103                 /* KLUGE - unmap_sg calls unmap_single for each mapped page */
1104                 min = ioc->usingle_calls - ioc->usg_calls;
1105                 max = ioc->usingle_pages - ioc->usg_pages;
1106                 len = sprintf(tmp, "pci_unmap_single: %8ld calls  %8ld pages (avg %d/1000)\n",
1107                               min, max, (int)((max * 1000)/min));
1108                 if (proc_append(tmp, len, &buf, &offset, &count))
1109                         break;
1110  
1111                 len = sprintf(tmp, "pci_map_sg()    : %8ld calls  %8ld pages (avg %d/1000)\n",
1112                               ioc->msg_calls, ioc->msg_pages,
1113                               (int)((ioc->msg_pages * 1000)/ioc->msg_calls));
1114                 if (proc_append(tmp, len, &buf, &offset, &count))
1115                         break;
1116                 len = sprintf(tmp, "pci_unmap_sg()  : %8ld calls  %8ld pages (avg %d/1000)\n\n\n",
1117                               ioc->usg_calls, ioc->usg_pages,
1118                               (int)((ioc->usg_pages * 1000)/ioc->usg_calls));
1119                 if (proc_append(tmp, len, &buf, &offset, &count))
1120                         break;
1121 #endif  /* CCIO_MAP_STATS */
1122                 ioc = ioc->next;
1123         }
1124
1125         if (count == 0) {
1126                 *eof = 1;
1127         }
1128         return (max - count);
1129 }
1130
1131 static int ccio_resource_map(char *buf, char **start, off_t offset, int len,
1132                              int *eof, void *data)
1133 {
1134         struct ioc *ioc = ioc_list;
1135
1136         buf[0] = '\0';
1137         while (ioc != NULL) {
1138                 u32 *res_ptr = (u32 *)ioc->res_map;
1139                 int j;
1140
1141                 for (j = 0; j < (ioc->res_size / sizeof(u32)); j++) {
1142                         if ((j & 7) == 0)
1143                                 strcat(buf,"\n   ");
1144                         sprintf(buf, "%s %08x", buf, *res_ptr);
1145                         res_ptr++;
1146                 }
1147                 strcat(buf, "\n\n");
1148                 ioc = ioc->next;
1149                 break; /* XXX - remove me */
1150         }
1151
1152         return strlen(buf);
1153 }
1154 #endif
1155
1156 /**
1157  * ccio_find_ioc - Find the ioc in the ioc_list
1158  * @hw_path: The hardware path of the ioc.
1159  *
1160  * This function searches the ioc_list for an ioc that matches
1161  * the provide hardware path.
1162  */
1163 static struct ioc * ccio_find_ioc(int hw_path)
1164 {
1165         int i;
1166         struct ioc *ioc;
1167
1168         ioc = ioc_list;
1169         for (i = 0; i < ioc_count; i++) {
1170                 if (ioc->hw_path == hw_path)
1171                         return ioc;
1172
1173                 ioc = ioc->next;
1174         }
1175
1176         return NULL;
1177 }
1178
1179 /**
1180  * ccio_get_iommu - Find the iommu which controls this device
1181  * @dev: The parisc device.
1182  *
1183  * This function searches through the registered IOMMU's and returns
1184  * the appropriate IOMMU for the device based on its hardware path.
1185  */
1186 void * ccio_get_iommu(const struct parisc_device *dev)
1187 {
1188         dev = find_pa_parent_type(dev, HPHW_IOA);
1189         if (!dev)
1190                 return NULL;
1191
1192         return ccio_find_ioc(dev->hw_path);
1193 }
1194
1195 #define CUJO_20_STEP       0x10000000   /* inc upper nibble */
1196
1197 /* Cujo 2.0 has a bug which will silently corrupt data being transferred
1198  * to/from certain pages.  To avoid this happening, we mark these pages
1199  * as `used', and ensure that nothing will try to allocate from them.
1200  */
1201 void ccio_cujo20_fixup(struct parisc_device *cujo, u32 iovp)
1202 {
1203         unsigned int idx;
1204         struct parisc_device *dev = parisc_parent(cujo);
1205         struct ioc *ioc = ccio_get_iommu(dev);
1206         u8 *res_ptr;
1207
1208         ioc->cujo20_bug = 1;
1209         res_ptr = ioc->res_map;
1210         idx = PDIR_INDEX(iovp) >> 3;
1211
1212         while (idx < ioc->res_size) {
1213                 res_ptr[idx] |= 0xff;
1214                 idx += PDIR_INDEX(CUJO_20_STEP) >> 3;
1215         }
1216 }
1217
1218 #if 0
1219 /* GRANT -  is this needed for U2 or not? */
1220
1221 /*
1222 ** Get the size of the I/O TLB for this I/O MMU.
1223 **
1224 ** If spa_shift is non-zero (ie probably U2),
1225 ** then calculate the I/O TLB size using spa_shift.
1226 **
1227 ** Otherwise we are supposed to get the IODC entry point ENTRY TLB
1228 ** and execute it. However, both U2 and Uturn firmware supplies spa_shift.
1229 ** I think only Java (K/D/R-class too?) systems don't do this.
1230 */
1231 static int
1232 ccio_get_iotlb_size(struct parisc_device *dev)
1233 {
1234         if (dev->spa_shift == 0) {
1235                 panic("%s() : Can't determine I/O TLB size.\n", __FUNCTION__);
1236         }
1237         return (1 << dev->spa_shift);
1238 }
1239 #else
1240
1241 /* Uturn supports 256 TLB entries */
1242 #define CCIO_CHAINID_SHIFT      8
1243 #define CCIO_CHAINID_MASK       0xff
1244 #endif /* 0 */
1245
1246 /**
1247  * ccio_ioc_init - Initalize the I/O Controller
1248  * @ioc: The I/O Controller.
1249  *
1250  * Initalize the I/O Controller which includes setting up the
1251  * I/O Page Directory, the resource map, and initalizing the
1252  * U2/Uturn chip into virtual mode.
1253  */
1254 static void
1255 ccio_ioc_init(struct ioc *ioc)
1256 {
1257         int i, iov_order;
1258         u32 iova_space_size;
1259         unsigned long physmem;
1260
1261         /*
1262         ** Determine IOVA Space size from memory size.
1263         **
1264         ** Ideally, PCI drivers would register the maximum number
1265         ** of DMA they can have outstanding for each device they
1266         ** own.  Next best thing would be to guess how much DMA
1267         ** can be outstanding based on PCI Class/sub-class. Both
1268         ** methods still require some "extra" to support PCI
1269         ** Hot-Plug/Removal of PCI cards. (aka PCI OLARD).
1270         */
1271
1272         /* limit IOVA space size to 1MB-1GB */
1273
1274         physmem = num_physpages << PAGE_SHIFT;
1275         if(physmem < (ccio_mem_ratio * 1024 * 1024)) {
1276                 iova_space_size = 1024 * 1024;
1277 #ifdef __LP64__
1278         } else if(physmem > (ccio_mem_ratio * 512 * 1024 * 1024)) {
1279                 iova_space_size = 512 * 1024 * 1024;
1280 #endif
1281         } else {
1282                 iova_space_size = (u32)(physmem / ccio_mem_ratio);
1283         }
1284
1285         /*
1286         ** iova space must be log2() in size.
1287         ** thus, pdir/res_map will also be log2().
1288         */
1289
1290         /* We could use larger page sizes in order to *decrease* the number
1291         ** of mappings needed.  (ie 8k pages means 1/2 the mappings).
1292         **
1293         ** Note: Grant Grunder says "Using 8k I/O pages isn't trivial either
1294         **   since the pages must also be physically contiguous - typically
1295         **   this is the case under linux."
1296         */
1297
1298         iov_order = get_order(iova_space_size) >> (IOVP_SHIFT - PAGE_SHIFT);
1299         BUG_ON(iov_order > (30 - IOVP_SHIFT));   /* iova_space_size <= 1GB */
1300         BUG_ON(iov_order < (20 - IOVP_SHIFT));   /* iova_space_size >= 1MB */
1301         iova_space_size = 1 << (iov_order + IOVP_SHIFT);
1302
1303         ioc->pdir_size = (iova_space_size / IOVP_SIZE) * sizeof(u64);
1304
1305         BUG_ON(ioc->pdir_size >= 4 * 1024 * 1024);   /* max pdir size < 4MB */
1306
1307         /* Verify it's a power of two */
1308         BUG_ON((1 << get_order(ioc->pdir_size)) != (ioc->pdir_size >> PAGE_SHIFT));
1309
1310         DBG_INIT("%s() hpa 0x%p mem %luMB IOV %dMB (%d bits) PDIR size 0x%0x",
1311                 __FUNCTION__, ioc->ioc_hpa, physmem>>20, iova_space_size>>20,
1312                  iov_order + PAGE_SHIFT, ioc->pdir_size);
1313
1314         ioc->pdir_base = (u64 *)__get_free_pages(GFP_KERNEL, 
1315                                                  get_order(ioc->pdir_size));
1316         if(NULL == ioc->pdir_base) {
1317                 panic("%s:%s() could not allocate I/O Page Table\n", __FILE__,
1318                       __FUNCTION__);
1319         }
1320         memset(ioc->pdir_base, 0, ioc->pdir_size);
1321
1322         BUG_ON((((unsigned long)ioc->pdir_base) & PAGE_MASK) != (unsigned long)ioc->pdir_base);
1323         DBG_INIT(" base %p", ioc->pdir_base);
1324
1325         /* resource map size dictated by pdir_size */
1326         ioc->res_size = (ioc->pdir_size / sizeof(u64)) >> 3;
1327         DBG_INIT("%s() res_size 0x%x\n", __FUNCTION__, ioc->res_size);
1328         
1329         ioc->res_map = (u8 *)__get_free_pages(GFP_KERNEL, 
1330                                               get_order(ioc->res_size));
1331         if(NULL == ioc->res_map) {
1332                 panic("%s:%s() could not allocate resource map\n", __FILE__,
1333                       __FUNCTION__);
1334         }
1335         memset(ioc->res_map, 0, ioc->res_size);
1336
1337         /* Initialize the res_hint to 16 */
1338         ioc->res_hint = 16;
1339
1340         /* Initialize the spinlock */
1341         spin_lock_init(&ioc->res_lock);
1342
1343         /*
1344         ** Chainid is the upper most bits of an IOVP used to determine
1345         ** which TLB entry an IOVP will use.
1346         */
1347         ioc->chainid_shift = get_order(iova_space_size) + PAGE_SHIFT - CCIO_CHAINID_SHIFT;
1348         DBG_INIT(" chainid_shift 0x%x\n", ioc->chainid_shift);
1349
1350         /*
1351         ** Initialize IOA hardware
1352         */
1353         WRITE_U32(CCIO_CHAINID_MASK << ioc->chainid_shift, 
1354                   &ioc->ioc_hpa->io_chain_id_mask);
1355
1356         WRITE_U32(virt_to_phys(ioc->pdir_base), 
1357                   &ioc->ioc_hpa->io_pdir_base);
1358
1359         /*
1360         ** Go to "Virtual Mode"
1361         */
1362         WRITE_U32(IOA_NORMAL_MODE, &ioc->ioc_hpa->io_control);
1363
1364         /*
1365         ** Initialize all I/O TLB entries to 0 (Valid bit off).
1366         */
1367         WRITE_U32(0, &ioc->ioc_hpa->io_tlb_entry_m);
1368         WRITE_U32(0, &ioc->ioc_hpa->io_tlb_entry_l);
1369
1370         for(i = 1 << CCIO_CHAINID_SHIFT; i ; i--) {
1371                 WRITE_U32((CMD_TLB_DIRECT_WRITE | (i << ioc->chainid_shift)),
1372                           &ioc->ioc_hpa->io_command);
1373         }
1374 }
1375
1376 static void
1377 ccio_init_resource(struct resource *res, char *name, unsigned long ioaddr)
1378 {
1379         int result;
1380
1381         res->parent = NULL;
1382         res->flags = IORESOURCE_MEM;
1383         res->start = (unsigned long)(signed) __raw_readl(ioaddr) << 16;
1384         res->end = (unsigned long)(signed) (__raw_readl(ioaddr + 4) << 16) - 1;
1385         res->name = name;
1386         if (res->end + 1 == res->start)
1387                 return;
1388         result = request_resource(&iomem_resource, res);
1389         if (result < 0) {
1390                 printk(KERN_ERR "%s: failed to claim CCIO bus address space (%08lx,%08lx)\n", 
1391                        __FILE__, res->start, res->end);
1392         }
1393 }
1394
1395 static void __init ccio_init_resources(struct ioc *ioc)
1396 {
1397         struct resource *res = ioc->mmio_region;
1398         char *name = kmalloc(14, GFP_KERNEL);
1399
1400         sprintf(name, "GSC Bus [%d/]", ioc->hw_path);
1401
1402         ccio_init_resource(res, name, (unsigned long)&ioc->ioc_hpa->io_io_low);
1403         ccio_init_resource(res + 1, name,
1404                         (unsigned long)&ioc->ioc_hpa->io_io_low_hv);
1405 }
1406
1407 static int new_ioc_area(struct resource *res, unsigned long size,
1408                 unsigned long min, unsigned long max, unsigned long align)
1409 {
1410         if (max <= min)
1411                 return -EBUSY;
1412
1413         res->start = (max - size + 1) &~ (align - 1);
1414         res->end = res->start + size;
1415         if (!request_resource(&iomem_resource, res))
1416                 return 0;
1417
1418         return new_ioc_area(res, size, min, max - size, align);
1419 }
1420
1421 static int expand_ioc_area(struct resource *res, unsigned long size,
1422                 unsigned long min, unsigned long max, unsigned long align)
1423 {
1424         unsigned long start, len;
1425
1426         if (!res->parent)
1427                 return new_ioc_area(res, size, min, max, align);
1428
1429         start = (res->start - size) &~ (align - 1);
1430         len = res->end - start + 1;
1431         if (start >= min) {
1432                 if (!adjust_resource(res, start, len))
1433                         return 0;
1434         }
1435
1436         start = res->start;
1437         len = ((size + res->end + align) &~ (align - 1)) - start;
1438         if (start + len <= max) {
1439                 if (!adjust_resource(res, start, len))
1440                         return 0;
1441         }
1442
1443         return -EBUSY;
1444 }
1445
1446 /*
1447  * Dino calls this function.  Beware that we may get called on systems
1448  * which have no IOC (725, B180, C160L, etc) but do have a Dino.
1449  * So it's legal to find no parent IOC.
1450  *
1451  * Some other issues: one of the resources in the ioc may be unassigned.
1452  */
1453 int ccio_allocate_resource(const struct parisc_device *dev,
1454                 struct resource *res, unsigned long size,
1455                 unsigned long min, unsigned long max, unsigned long align)
1456 {
1457         struct resource *parent = &iomem_resource;
1458         struct ioc *ioc = ccio_get_iommu(dev);
1459         if (!ioc)
1460                 goto out;
1461
1462         parent = ioc->mmio_region;
1463         if (parent->parent &&
1464             !allocate_resource(parent, res, size, min, max, align, NULL, NULL))
1465                 return 0;
1466
1467         if ((parent + 1)->parent &&
1468             !allocate_resource(parent + 1, res, size, min, max, align,
1469                                 NULL, NULL))
1470                 return 0;
1471
1472         if (!expand_ioc_area(parent, size, min, max, align)) {
1473                 __raw_writel(((parent->start)>>16) | 0xffff0000,
1474                              (unsigned long)&(ioc->ioc_hpa->io_io_low));
1475                 __raw_writel(((parent->end)>>16) | 0xffff0000,
1476                              (unsigned long)&(ioc->ioc_hpa->io_io_high));
1477         } else if (!expand_ioc_area(parent + 1, size, min, max, align)) {
1478                 parent++;
1479                 __raw_writel(((parent->start)>>16) | 0xffff0000,
1480                              (unsigned long)&(ioc->ioc_hpa->io_io_low_hv));
1481                 __raw_writel(((parent->end)>>16) | 0xffff0000,
1482                              (unsigned long)&(ioc->ioc_hpa->io_io_high_hv));
1483         } else {
1484                 return -EBUSY;
1485         }
1486
1487  out:
1488         return allocate_resource(parent, res, size, min, max, align, NULL,NULL);
1489 }
1490
1491 int ccio_request_resource(const struct parisc_device *dev,
1492                 struct resource *res)
1493 {
1494         struct resource *parent;
1495         struct ioc *ioc = ccio_get_iommu(dev);
1496
1497         if (!ioc) {
1498                 parent = &iomem_resource;
1499         } else if ((ioc->mmio_region->start <= res->start) &&
1500                         (res->end <= ioc->mmio_region->end)) {
1501                 parent = ioc->mmio_region;
1502         } else if (((ioc->mmio_region + 1)->start <= res->start) &&
1503                         (res->end <= (ioc->mmio_region + 1)->end)) {
1504                 parent = ioc->mmio_region + 1;
1505         } else {
1506                 return -EBUSY;
1507         }
1508
1509         return request_resource(parent, res);
1510 }
1511
1512 /**
1513  * ccio_probe - Determine if ccio should claim this device.
1514  * @dev: The device which has been found
1515  *
1516  * Determine if ccio should claim this chip (return 0) or not (return 1).
1517  * If so, initialize the chip and tell other partners in crime they
1518  * have work to do.
1519  */
1520 static int ccio_probe(struct parisc_device *dev)
1521 {
1522         int i;
1523         struct ioc *ioc, **ioc_p = &ioc_list;
1524         
1525         ioc = kmalloc(sizeof(struct ioc), GFP_KERNEL);
1526         if (ioc == NULL) {
1527                 printk(KERN_ERR MODULE_NAME ": memory allocation failure\n");
1528                 return 1;
1529         }
1530         memset(ioc, 0, sizeof(struct ioc));
1531
1532         ioc->name = dev->id.hversion == U2_IOA_RUNWAY ? "U2" : "UTurn";
1533
1534         printk(KERN_INFO "Found %s at 0x%lx\n", ioc->name, dev->hpa);
1535
1536         for (i = 0; i < ioc_count; i++) {
1537                 ioc_p = &(*ioc_p)->next;
1538         }
1539         *ioc_p = ioc;
1540
1541         ioc->hw_path = dev->hw_path;
1542         ioc->ioc_hpa = (struct ioa_registers *)dev->hpa;
1543         ccio_ioc_init(ioc);
1544         ccio_init_resources(ioc);
1545         hppa_dma_ops = &ccio_ops;
1546         dev->dev.platform_data = kmalloc(sizeof(struct pci_hba_data), GFP_KERNEL);
1547
1548         /* if this fails, no I/O cards will work, so may as well bug */
1549         BUG_ON(dev->dev.platform_data == NULL);
1550         HBA_DATA(dev->dev.platform_data)->iommu = ioc;
1551         
1552
1553         if (ioc_count == 0) {
1554                 /* FIXME: Create separate entries for each ioc */
1555                 create_proc_read_entry(MODULE_NAME, S_IRWXU, proc_runway_root,
1556                                        ccio_proc_info, NULL);
1557                 create_proc_read_entry(MODULE_NAME"-bitmap", S_IRWXU,
1558                                        proc_runway_root, ccio_resource_map, NULL);
1559         }
1560
1561         ioc_count++;
1562
1563         parisc_vmerge_boundary = IOVP_SIZE;
1564         parisc_vmerge_max_size = BITS_PER_LONG * IOVP_SIZE;
1565         parisc_has_iommu();
1566         return 0;
1567 }
1568
1569 /* We *can't* support JAVA (T600). Venture there at your own risk. */
1570 static struct parisc_device_id ccio_tbl[] = {
1571         { HPHW_IOA, HVERSION_REV_ANY_ID, U2_IOA_RUNWAY, 0xb }, /* U2 */
1572         { HPHW_IOA, HVERSION_REV_ANY_ID, UTURN_IOA_RUNWAY, 0xb }, /* UTurn */
1573         { 0, }
1574 };
1575
1576 static struct parisc_driver ccio_driver = {
1577         .name =         "U2:Uturn",
1578         .id_table =     ccio_tbl,
1579         .probe =        ccio_probe,
1580 };
1581
1582 /**
1583  * ccio_init - ccio initalization procedure.
1584  *
1585  * Register this driver.
1586  */
1587 void __init ccio_init(void)
1588 {
1589         register_parisc_driver(&ccio_driver);
1590 }
1591