vserver 1.9.5.x5
[linux-2.6.git] / drivers / parisc / sba_iommu.c
1 /*
2 **  System Bus Adapter (SBA) I/O MMU manager
3 **
4 **      (c) Copyright 2000-2004 Grant Grundler <grundler @ parisc-linux x org>
5 **      (c) Copyright 2004 Naresh Kumar Inna <knaresh at india x hp x com>
6 **      (c) Copyright 2000-2004 Hewlett-Packard Company
7 **
8 **      Portions (c) 1999 Dave S. Miller (from sparc64 I/O MMU code)
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 ** This module initializes the IOC (I/O Controller) found on B1000/C3000/
17 ** J5000/J7000/N-class/L-class machines and their successors.
18 **
19 ** FIXME: add DMA hint support programming in both sba and lba modules.
20 */
21
22 #include <linux/config.h>
23 #include <linux/types.h>
24 #include <linux/kernel.h>
25 #include <linux/spinlock.h>
26 #include <linux/slab.h>
27 #include <linux/init.h>
28
29 #include <linux/mm.h>
30 #include <linux/string.h>
31 #include <linux/pci.h>
32
33 #include <asm/byteorder.h>
34 #include <asm/io.h>
35 #include <asm/dma.h>            /* for DMA_CHUNK_SIZE */
36
37 #include <asm/hardware.h>       /* for register_parisc_driver() stuff */
38
39 #include <linux/proc_fs.h>
40 #include <asm/runway.h>         /* for proc_runway_root */
41 #include <asm/pdc.h>            /* for PDC_MODEL_* */
42 #include <asm/pdcpat.h>         /* for is_pdc_pat() */
43 #include <asm/parisc-device.h>
44
45
46 /* declared in arch/parisc/kernel/setup.c */
47 extern struct proc_dir_entry * proc_mckinley_root;
48
49 #define MODULE_NAME "SBA"
50
51 #ifdef CONFIG_PROC_FS
52 /* depends on proc fs support. But costs CPU performance */
53 #undef SBA_COLLECT_STATS
54 #endif
55
56 /*
57 ** The number of debug flags is a clue - this code is fragile.
58 ** Don't even think about messing with it unless you have
59 ** plenty of 710's to sacrifice to the computer gods. :^)
60 */
61 #undef DEBUG_SBA_ASSERT
62 #undef DEBUG_SBA_INIT
63 #undef DEBUG_SBA_RUN
64 #undef DEBUG_SBA_RUN_SG
65 #undef DEBUG_SBA_RESOURCE
66 #undef ASSERT_PDIR_SANITY
67 #undef DEBUG_LARGE_SG_ENTRIES
68 #undef DEBUG_DMB_TRAP
69
70 #ifdef DEBUG_SBA_INIT
71 #define DBG_INIT(x...)  printk(x)
72 #else
73 #define DBG_INIT(x...)
74 #endif
75
76 #ifdef DEBUG_SBA_RUN
77 #define DBG_RUN(x...)   printk(x)
78 #else
79 #define DBG_RUN(x...)
80 #endif
81
82 #ifdef DEBUG_SBA_RUN_SG
83 #define DBG_RUN_SG(x...)        printk(x)
84 #else
85 #define DBG_RUN_SG(x...)
86 #endif
87
88
89 #ifdef DEBUG_SBA_RESOURCE
90 #define DBG_RES(x...)   printk(x)
91 #else
92 #define DBG_RES(x...)
93 #endif
94
95 #ifdef DEBUG_SBA_ASSERT
96 #undef ASSERT
97 #define ASSERT(expr) \
98         if(!(expr)) { \
99                 printk("\n%s:%d: Assertion " #expr " failed!\n", \
100                                 __FILE__, __LINE__); \
101                 panic(#expr); \
102         }
103 #else
104 #define ASSERT(expr)
105 #endif
106
107
108 #if defined(__LP64__) && !defined(CONFIG_PDC_NARROW)
109 /* "low end" PA8800 machines use ZX1 chipset */
110 #define ZX1_SUPPORT
111 #endif
112
113 #define SBA_INLINE      __inline__
114
115
116 /*
117 ** The number of pdir entries to "free" before issueing
118 ** a read to PCOM register to flush out PCOM writes.
119 ** Interacts with allocation granularity (ie 4 or 8 entries
120 ** allocated and free'd/purged at a time might make this
121 ** less interesting).
122 */
123 #define DELAYED_RESOURCE_CNT    16
124
125 #define DEFAULT_DMA_HINT_REG    0
126
127 #define ASTRO_RUNWAY_PORT       0x582
128 #define ASTRO_ROPES_PORT        0x780
129
130 #define IKE_MERCED_PORT         0x803
131 #define IKE_ROPES_PORT          0x781
132
133 #define REO_MERCED_PORT         0x804
134 #define REO_ROPES_PORT          0x782
135
136 #define REOG_MERCED_PORT        0x805
137 #define REOG_ROPES_PORT         0x783
138
139 #define PLUTO_MCKINLEY_PORT     0x880
140 #define PLUTO_ROPES_PORT        0x784
141
142 #define SBA_FUNC_ID     0x0000  /* function id */
143 #define SBA_FCLASS      0x0008  /* function class, bist, header, rev... */
144
145 #define IS_ASTRO(id) \
146 (((id)->hversion == ASTRO_RUNWAY_PORT) || ((id)->hversion == ASTRO_ROPES_PORT))
147
148 #define IS_IKE(id) \
149 (((id)->hversion == IKE_MERCED_PORT) || ((id)->hversion == IKE_ROPES_PORT))
150
151 #define IS_PLUTO(id) \
152 (((id)->hversion == PLUTO_MCKINLEY_PORT) || ((id)->hversion == PLUTO_ROPES_PORT))
153
154 #define SBA_FUNC_SIZE 4096   /* SBA configuration function reg set */
155
156 #define ASTRO_IOC_OFFSET 0x20000
157 /* Ike's IOC's occupy functions 2 and 3 (not 0 and 1) */
158 #define IKE_IOC_OFFSET(p) ((p+2)*SBA_FUNC_SIZE)
159
160 #define PLUTO_IOC_OFFSET 0x1000
161
162 #define IOC_CTRL          0x8   /* IOC_CTRL offset */
163 #define IOC_CTRL_TC       (1 << 0) /* TOC Enable */
164 #define IOC_CTRL_CE       (1 << 1) /* Coalesce Enable */
165 #define IOC_CTRL_DE       (1 << 2) /* Dillon Enable */
166 #define IOC_CTRL_RM       (1 << 8) /* Real Mode */
167 #define IOC_CTRL_NC       (1 << 9) /* Non Coherent Mode */
168
169 #define MAX_IOC         2       /* per Ike. Pluto/Astro only have 1. */
170
171 #define ROPES_PER_IOC   8       /* per Ike half or Pluto/Astro */
172
173
174 /*
175 ** Offsets into MBIB (Function 0 on Ike and hopefully Astro)
176 ** Firmware programs this stuff. Don't touch it.
177 */
178 #define LMMIO_DIRECT0_BASE  0x300
179 #define LMMIO_DIRECT0_MASK  0x308
180 #define LMMIO_DIRECT0_ROUTE 0x310
181
182 #define LMMIO_DIST_BASE  0x360
183 #define LMMIO_DIST_MASK  0x368
184 #define LMMIO_DIST_ROUTE 0x370
185
186 #define IOS_DIST_BASE   0x390
187 #define IOS_DIST_MASK   0x398
188 #define IOS_DIST_ROUTE  0x3A0
189
190 #define IOS_DIRECT_BASE 0x3C0
191 #define IOS_DIRECT_MASK 0x3C8
192 #define IOS_DIRECT_ROUTE 0x3D0
193
194 /*
195 ** Offsets into I/O TLB (Function 2 and 3 on Ike)
196 */
197 #define ROPE0_CTL       0x200  /* "regbus pci0" */
198 #define ROPE1_CTL       0x208
199 #define ROPE2_CTL       0x210
200 #define ROPE3_CTL       0x218
201 #define ROPE4_CTL       0x220
202 #define ROPE5_CTL       0x228
203 #define ROPE6_CTL       0x230
204 #define ROPE7_CTL       0x238
205
206 #define HF_ENABLE       0x40
207
208
209 #define IOC_IBASE       0x300   /* IO TLB */
210 #define IOC_IMASK       0x308
211 #define IOC_PCOM        0x310
212 #define IOC_TCNFG       0x318
213 #define IOC_PDIR_BASE   0x320
214
215 /* AGP GART driver looks for this */
216 #define SBA_IOMMU_COOKIE    0x0000badbadc0ffeeUL
217
218
219 /*
220 ** IOC supports 4/8/16/64KB page sizes (see TCNFG register)
221 ** It's safer (avoid memory corruption) to keep DMA page mappings
222 ** equivalently sized to VM PAGE_SIZE.
223 **
224 ** We really can't avoid generating a new mapping for each
225 ** page since the Virtual Coherence Index has to be generated
226 ** and updated for each page.
227 **
228 ** PAGE_SIZE could be greater than IOVP_SIZE. But not the inverse.
229 */
230 #define IOVP_SIZE       PAGE_SIZE
231 #define IOVP_SHIFT      PAGE_SHIFT
232 #define IOVP_MASK       PAGE_MASK
233
234 #define SBA_PERF_CFG    0x708   /* Performance Counter stuff */
235 #define SBA_PERF_MASK1  0x718
236 #define SBA_PERF_MASK2  0x730
237
238
239 /*
240 ** Offsets into PCI Performance Counters (functions 12 and 13)
241 ** Controlled by PERF registers in function 2 & 3 respectively.
242 */
243 #define SBA_PERF_CNT1   0x200
244 #define SBA_PERF_CNT2   0x208
245 #define SBA_PERF_CNT3   0x210
246
247
248 struct ioc {
249         unsigned long   ioc_hpa;        /* I/O MMU base address */
250         char    *res_map;       /* resource map, bit == pdir entry */
251         u64     *pdir_base;     /* physical base address */
252         unsigned long   ibase;  /* pdir IOV Space base - shared w/lba_pci */
253         unsigned long   imask;  /* pdir IOV Space mask - shared w/lba_pci */
254 #ifdef ZX1_SUPPORT
255         unsigned long   iovp_mask;      /* help convert IOVA to IOVP */
256 #endif
257         unsigned long   *res_hint;      /* next avail IOVP - circular search */
258         spinlock_t      res_lock;
259         unsigned int    res_bitshift;   /* from the LEFT! */
260         unsigned int    res_size;       /* size of resource map in bytes */
261 #if SBA_HINT_SUPPORT
262 /* FIXME : DMA HINTs not used */
263         unsigned long   hint_mask_pdir; /* bits used for DMA hints */
264         unsigned int    hint_shift_pdir;
265 #endif
266 #if DELAYED_RESOURCE_CNT > 0
267         int saved_cnt;
268         struct sba_dma_pair {
269                 dma_addr_t      iova;
270                 size_t          size;
271         } saved[DELAYED_RESOURCE_CNT];
272 #endif
273
274 #ifdef SBA_COLLECT_STATS
275 #define SBA_SEARCH_SAMPLE       0x100
276         unsigned long avg_search[SBA_SEARCH_SAMPLE];
277         unsigned long avg_idx;  /* current index into avg_search */
278         unsigned long used_pages;
279         unsigned long msingle_calls;
280         unsigned long msingle_pages;
281         unsigned long msg_calls;
282         unsigned long msg_pages;
283         unsigned long usingle_calls;
284         unsigned long usingle_pages;
285         unsigned long usg_calls;
286         unsigned long usg_pages;
287 #endif
288
289         /* STUFF We don't need in performance path */
290         unsigned int    pdir_size;      /* in bytes, determined by IOV Space size */
291 };
292
293 struct sba_device {
294         struct sba_device       *next;  /* list of SBA's in system */
295         struct parisc_device    *dev;   /* dev found in bus walk */
296         struct parisc_device_id *iodc;  /* data about dev from firmware */
297         const char              *name;
298         unsigned long           sba_hpa; /* base address */
299         spinlock_t              sba_lock;
300         unsigned int            flags;  /* state/functionality enabled */
301         unsigned int            hw_rev;  /* HW revision of chip */
302
303         struct resource         chip_resv; /* MMIO reserved for chip */
304         struct resource         iommu_resv; /* MMIO reserved for iommu */
305
306         unsigned int            num_ioc;  /* number of on-board IOC's */
307         struct ioc              ioc[MAX_IOC];
308 };
309
310
311 static struct sba_device *sba_list;
312
313 static unsigned long ioc_needs_fdc = 0;
314
315 /* Ratio of Host MEM to IOV Space size */
316 static unsigned long sba_mem_ratio = 8;
317
318 /* global count of IOMMUs in the system */
319 static unsigned int global_ioc_cnt = 0;
320
321 /* PA8700 (Piranha 2.2) bug workaround */
322 static unsigned long piranha_bad_128k = 0;
323
324 /* Looks nice and keeps the compiler happy */
325 #define SBA_DEV(d) ((struct sba_device *) (d))
326
327 #if SBA_AGP_SUPPORT
328 static int reserve_sba_gart = 1;
329 #endif
330
331 #define ROUNDUP(x,y) ((x + ((y)-1)) & ~((y)-1))
332
333
334 /************************************
335 ** SBA register read and write support
336 **
337 ** BE WARNED: register writes are posted.
338 **  (ie follow writes which must reach HW with a read)
339 **
340 ** Superdome (in particular, REO) allows only 64-bit CSR accesses.
341 */
342 #define READ_REG32(addr)         le32_to_cpu(__raw_readl(addr))
343 #define READ_REG64(addr)         le64_to_cpu(__raw_readq(addr))
344 #define WRITE_REG32(val, addr) __raw_writel(cpu_to_le32(val), addr)
345 #define WRITE_REG64(val, addr) __raw_writeq(cpu_to_le64(val), addr)
346
347 #ifdef __LP64__
348 #define READ_REG(addr)          READ_REG64(addr)
349 #define WRITE_REG(value, addr)  WRITE_REG64(value, addr)
350 #else
351 #define READ_REG(addr)          READ_REG32(addr)
352 #define WRITE_REG(value, addr)  WRITE_REG32(value, addr)
353 #endif
354
355 #ifdef DEBUG_SBA_INIT
356
357 /* NOTE: When __LP64__ isn't defined, READ_REG64() is two 32-bit reads */
358
359 /**
360  * sba_dump_ranges - debugging only - print ranges assigned to this IOA
361  * @hpa: base address of the sba
362  *
363  * Print the MMIO and IO Port address ranges forwarded by an Astro/Ike/RIO
364  * IO Adapter (aka Bus Converter).
365  */
366 static void
367 sba_dump_ranges(unsigned long hpa)
368 {
369         DBG_INIT("SBA at 0x%lx\n", hpa);
370         DBG_INIT("IOS_DIST_BASE   : %Lx\n", READ_REG64(hpa+IOS_DIST_BASE));
371         DBG_INIT("IOS_DIST_MASK   : %Lx\n", READ_REG64(hpa+IOS_DIST_MASK));
372         DBG_INIT("IOS_DIST_ROUTE  : %Lx\n", READ_REG64(hpa+IOS_DIST_ROUTE));
373         DBG_INIT("\n");
374         DBG_INIT("IOS_DIRECT_BASE : %Lx\n", READ_REG64(hpa+IOS_DIRECT_BASE));
375         DBG_INIT("IOS_DIRECT_MASK : %Lx\n", READ_REG64(hpa+IOS_DIRECT_MASK));
376         DBG_INIT("IOS_DIRECT_ROUTE: %Lx\n", READ_REG64(hpa+IOS_DIRECT_ROUTE));
377 }
378
379 /**
380  * sba_dump_tlb - debugging only - print IOMMU operating parameters
381  * @hpa: base address of the IOMMU
382  *
383  * Print the size/location of the IO MMU PDIR.
384  */
385 static void
386 sba_dump_tlb(unsigned long hpa)
387 {
388         DBG_INIT("IO TLB at 0x%lx\n", hpa);
389         DBG_INIT("IOC_IBASE    : 0x%Lx\n", READ_REG64(hpa+IOC_IBASE));
390         DBG_INIT("IOC_IMASK    : 0x%Lx\n", READ_REG64(hpa+IOC_IMASK));
391         DBG_INIT("IOC_TCNFG    : 0x%Lx\n", READ_REG64(hpa+IOC_TCNFG));
392         DBG_INIT("IOC_PDIR_BASE: 0x%Lx\n", READ_REG64(hpa+IOC_PDIR_BASE));
393         DBG_INIT("\n");
394 }
395 #else
396 #define sba_dump_ranges(x)
397 #define sba_dump_tlb(x)
398 #endif
399
400
401 #ifdef ASSERT_PDIR_SANITY
402
403 /**
404  * sba_dump_pdir_entry - debugging only - print one IOMMU PDIR entry
405  * @ioc: IO MMU structure which owns the pdir we are interested in.
406  * @msg: text to print ont the output line.
407  * @pide: pdir index.
408  *
409  * Print one entry of the IO MMU PDIR in human readable form.
410  */
411 static void
412 sba_dump_pdir_entry(struct ioc *ioc, char *msg, uint pide)
413 {
414         /* start printing from lowest pde in rval */
415         u64 *ptr = &(ioc->pdir_base[pide & (~0U * BITS_PER_LONG)]);
416         unsigned long *rptr = (unsigned long *) &(ioc->res_map[(pide >>3) & ~(sizeof(unsigned long) - 1)]);
417         uint rcnt;
418
419         printk(KERN_DEBUG "SBA: %s rp %p bit %d rval 0x%lx\n",
420                  msg,
421                  rptr, pide & (BITS_PER_LONG - 1), *rptr);
422
423         rcnt = 0;
424         while (rcnt < BITS_PER_LONG) {
425                 printk(KERN_DEBUG "%s %2d %p %016Lx\n",
426                         (rcnt == (pide & (BITS_PER_LONG - 1)))
427                                 ? "    -->" : "       ",
428                         rcnt, ptr, *ptr );
429                 rcnt++;
430                 ptr++;
431         }
432         printk(KERN_DEBUG "%s", msg);
433 }
434
435
436 /**
437  * sba_check_pdir - debugging only - consistency checker
438  * @ioc: IO MMU structure which owns the pdir we are interested in.
439  * @msg: text to print ont the output line.
440  *
441  * Verify the resource map and pdir state is consistent
442  */
443 static int
444 sba_check_pdir(struct ioc *ioc, char *msg)
445 {
446         u32 *rptr_end = (u32 *) &(ioc->res_map[ioc->res_size]);
447         u32 *rptr = (u32 *) ioc->res_map;       /* resource map ptr */
448         u64 *pptr = ioc->pdir_base;     /* pdir ptr */
449         uint pide = 0;
450
451         while (rptr < rptr_end) {
452                 u32 rval = *rptr;
453                 int rcnt = 32;  /* number of bits we might check */
454
455                 while (rcnt) {
456                         /* Get last byte and highest bit from that */
457                         u32 pde = ((u32) (((char *)pptr)[7])) << 24;
458                         if ((rval ^ pde) & 0x80000000)
459                         {
460                                 /*
461                                 ** BUMMER!  -- res_map != pdir --
462                                 ** Dump rval and matching pdir entries
463                                 */
464                                 sba_dump_pdir_entry(ioc, msg, pide);
465                                 return(1);
466                         }
467                         rcnt--;
468                         rval <<= 1;     /* try the next bit */
469                         pptr++;
470                         pide++;
471                 }
472                 rptr++; /* look at next word of res_map */
473         }
474         /* It'd be nice if we always got here :^) */
475         return 0;
476 }
477
478
479 /**
480  * sba_dump_sg - debugging only - print Scatter-Gather list
481  * @ioc: IO MMU structure which owns the pdir we are interested in.
482  * @startsg: head of the SG list
483  * @nents: number of entries in SG list
484  *
485  * print the SG list so we can verify it's correct by hand.
486  */
487 static void
488 sba_dump_sg( struct ioc *ioc, struct scatterlist *startsg, int nents)
489 {
490         while (nents-- > 0) {
491                 printk(KERN_DEBUG " %d : %08lx/%05x %p/%05x\n",
492                                 nents,
493                                 (unsigned long) sg_dma_address(startsg),
494                                 sg_dma_len(startsg),
495                                 sg_virt_addr(startsg), startsg->length);
496                 startsg++;
497         }
498 }
499
500 #endif /* ASSERT_PDIR_SANITY */
501
502
503
504
505 /**************************************************************
506 *
507 *   I/O Pdir Resource Management
508 *
509 *   Bits set in the resource map are in use.
510 *   Each bit can represent a number of pages.
511 *   LSbs represent lower addresses (IOVA's).
512 *
513 ***************************************************************/
514 #define PAGES_PER_RANGE 1       /* could increase this to 4 or 8 if needed */
515
516 /* Convert from IOVP to IOVA and vice versa. */
517
518 #ifdef ZX1_SUPPORT
519 /* Pluto (aka ZX1) boxes need to set or clear the ibase bits appropriately */
520 #define SBA_IOVA(ioc,iovp,offset,hint_reg) ((ioc->ibase) | (iovp) | (offset))
521 #define SBA_IOVP(ioc,iova) ((iova) & (ioc)->iovp_mask)
522 #else
523 /* only support Astro and ancestors. Saves a few cycles in key places */
524 #define SBA_IOVA(ioc,iovp,offset,hint_reg) ((iovp) | (offset))
525 #define SBA_IOVP(ioc,iova) (iova)
526 #endif
527
528 #define PDIR_INDEX(iovp)   ((iovp)>>IOVP_SHIFT)
529
530 #define RESMAP_MASK(n)    (~0UL << (BITS_PER_LONG - (n)))
531 #define RESMAP_IDX_MASK   (sizeof(unsigned long) - 1)
532
533
534 /**
535  * sba_search_bitmap - find free space in IO PDIR resource bitmap
536  * @ioc: IO MMU structure which owns the pdir we are interested in.
537  * @bits_wanted: number of entries we need.
538  *
539  * Find consecutive free bits in resource bitmap.
540  * Each bit represents one entry in the IO Pdir.
541  * Cool perf optimization: search for log2(size) bits at a time.
542  */
543 static SBA_INLINE unsigned long
544 sba_search_bitmap(struct ioc *ioc, unsigned long bits_wanted)
545 {
546         unsigned long *res_ptr = ioc->res_hint;
547         unsigned long *res_end = (unsigned long *) &(ioc->res_map[ioc->res_size]);
548         unsigned long pide = ~0UL;
549
550         ASSERT(((unsigned long) ioc->res_hint & (sizeof(unsigned long) - 1UL)) == 0);
551         ASSERT(res_ptr < res_end);
552         if (bits_wanted > (BITS_PER_LONG/2)) {
553                 /* Search word at a time - no mask needed */
554                 for(; res_ptr < res_end; ++res_ptr) {
555                         if (*res_ptr == 0) {
556                                 *res_ptr = RESMAP_MASK(bits_wanted);
557                                 pide = ((unsigned long)res_ptr - (unsigned long)ioc->res_map);
558                                 pide <<= 3;     /* convert to bit address */
559                                 break;
560                         }
561                 }
562                 /* point to the next word on next pass */
563                 res_ptr++;
564                 ioc->res_bitshift = 0;
565         } else {
566                 /*
567                 ** Search the resource bit map on well-aligned values.
568                 ** "o" is the alignment.
569                 ** We need the alignment to invalidate I/O TLB using
570                 ** SBA HW features in the unmap path.
571                 */
572                 unsigned long o = 1 << get_order(bits_wanted << PAGE_SHIFT);
573                 uint bitshiftcnt = ROUNDUP(ioc->res_bitshift, o);
574                 unsigned long mask;
575
576                 if (bitshiftcnt >= BITS_PER_LONG) {
577                         bitshiftcnt = 0;
578                         res_ptr++;
579                 }
580                 mask = RESMAP_MASK(bits_wanted) >> bitshiftcnt;
581
582                 DBG_RES("%s() o %ld %p", __FUNCTION__, o, res_ptr);
583                 while(res_ptr < res_end)
584                 { 
585                         DBG_RES("    %p %lx %lx\n", res_ptr, mask, *res_ptr);
586                         BUG_ON(0 == mask);
587                         if(0 == ((*res_ptr) & mask)) {
588                                 *res_ptr |= mask;     /* mark resources busy! */
589                                 pide = ((unsigned long)res_ptr - (unsigned long)ioc->res_map);
590                                 pide <<= 3;     /* convert to bit address */
591                                 pide += bitshiftcnt;
592                                 break;
593                         }
594                         mask >>= o;
595                         bitshiftcnt += o;
596                         if (0 == mask) {
597                                 mask = RESMAP_MASK(bits_wanted);
598                                 bitshiftcnt=0;
599                                 res_ptr++;
600                         }
601                 }
602                 /* look in the same word on the next pass */
603                 ioc->res_bitshift = bitshiftcnt + bits_wanted;
604         }
605
606         /* wrapped ? */
607         if (res_end <= res_ptr) {
608                 ioc->res_hint = (unsigned long *) ioc->res_map;
609                 ioc->res_bitshift = 0;
610         } else {
611                 ioc->res_hint = res_ptr;
612         }
613         return (pide);
614 }
615
616
617 /**
618  * sba_alloc_range - find free bits and mark them in IO PDIR resource bitmap
619  * @ioc: IO MMU structure which owns the pdir we are interested in.
620  * @size: number of bytes to create a mapping for
621  *
622  * Given a size, find consecutive unmarked and then mark those bits in the
623  * resource bit map.
624  */
625 static int
626 sba_alloc_range(struct ioc *ioc, size_t size)
627 {
628         unsigned int pages_needed = size >> IOVP_SHIFT;
629 #ifdef SBA_COLLECT_STATS
630         unsigned long cr_start = mfctl(16);
631 #endif
632         unsigned long pide;
633
634         ASSERT(pages_needed);
635         ASSERT((pages_needed * IOVP_SIZE) <= DMA_CHUNK_SIZE);
636         ASSERT(pages_needed <= BITS_PER_LONG);
637         ASSERT(0 == (size & ~IOVP_MASK));
638
639         /*
640         ** "seek and ye shall find"...praying never hurts either...
641         ** ggg sacrifices another 710 to the computer gods.
642         */
643
644         pide = sba_search_bitmap(ioc, pages_needed);
645         if (pide >= (ioc->res_size << 3)) {
646                 pide = sba_search_bitmap(ioc, pages_needed);
647                 if (pide >= (ioc->res_size << 3))
648                         panic("%s: I/O MMU @ %lx is out of mapping resources\n",
649                               __FILE__, ioc->ioc_hpa);
650         }
651
652 #ifdef ASSERT_PDIR_SANITY
653         /* verify the first enable bit is clear */
654         if(0x00 != ((u8 *) ioc->pdir_base)[pide*sizeof(u64) + 7]) {
655                 sba_dump_pdir_entry(ioc, "sba_search_bitmap() botched it?", pide);
656         }
657 #endif
658
659         DBG_RES("%s(%x) %d -> %lx hint %x/%x\n",
660                 __FUNCTION__, size, pages_needed, pide,
661                 (uint) ((unsigned long) ioc->res_hint - (unsigned long) ioc->res_map),
662                 ioc->res_bitshift );
663
664 #ifdef SBA_COLLECT_STATS
665         {
666                 unsigned long cr_end = mfctl(16);
667                 unsigned long tmp = cr_end - cr_start;
668                 /* check for roll over */
669                 cr_start = (cr_end < cr_start) ?  -(tmp) : (tmp);
670         }
671         ioc->avg_search[ioc->avg_idx++] = cr_start;
672         ioc->avg_idx &= SBA_SEARCH_SAMPLE - 1;
673
674         ioc->used_pages += pages_needed;
675 #endif
676
677         return (pide);
678 }
679
680
681 /**
682  * sba_free_range - unmark bits in IO PDIR resource bitmap
683  * @ioc: IO MMU structure which owns the pdir we are interested in.
684  * @iova: IO virtual address which was previously allocated.
685  * @size: number of bytes to create a mapping for
686  *
687  * clear bits in the ioc's resource map
688  */
689 static SBA_INLINE void
690 sba_free_range(struct ioc *ioc, dma_addr_t iova, size_t size)
691 {
692         unsigned long iovp = SBA_IOVP(ioc, iova);
693         unsigned int pide = PDIR_INDEX(iovp);
694         unsigned int ridx = pide >> 3;  /* convert bit to byte address */
695         unsigned long *res_ptr = (unsigned long *) &((ioc)->res_map[ridx & ~RESMAP_IDX_MASK]);
696
697         int bits_not_wanted = size >> IOVP_SHIFT;
698
699         /* 3-bits "bit" address plus 2 (or 3) bits for "byte" == bit in word */
700         unsigned long m = RESMAP_MASK(bits_not_wanted) >> (pide & (BITS_PER_LONG - 1));
701
702         DBG_RES("%s( ,%x,%x) %x/%lx %x %p %lx\n",
703                 __FUNCTION__, (uint) iova, size,
704                 bits_not_wanted, m, pide, res_ptr, *res_ptr);
705
706 #ifdef SBA_COLLECT_STATS
707         ioc->used_pages -= bits_not_wanted;
708 #endif
709
710         ASSERT(m != 0);
711         ASSERT(bits_not_wanted);
712         ASSERT((bits_not_wanted * IOVP_SIZE) <= DMA_CHUNK_SIZE);
713         ASSERT(bits_not_wanted <= BITS_PER_LONG);
714         ASSERT((*res_ptr & m) == m); /* verify same bits are set */
715         *res_ptr &= ~m;
716 }
717
718
719 /**************************************************************
720 *
721 *   "Dynamic DMA Mapping" support (aka "Coherent I/O")
722 *
723 ***************************************************************/
724
725 #if SBA_HINT_SUPPORT
726 #define SBA_DMA_HINT(ioc, val) ((val) << (ioc)->hint_shift_pdir)
727 #endif
728
729 typedef unsigned long space_t;
730 #define KERNEL_SPACE 0
731
732 /**
733  * sba_io_pdir_entry - fill in one IO PDIR entry
734  * @pdir_ptr:  pointer to IO PDIR entry
735  * @sid: process Space ID
736  * @vba: Virtual CPU address of buffer to map
737  *
738  * SBA Mapping Routine
739  *
740  * Given a virtual address (vba, arg2) and space id, (sid, arg1)
741  * sba_io_pdir_entry() loads the I/O PDIR entry pointed to by
742  * pdir_ptr (arg0). 
743  * Using the bass-ackwards HP bit numbering, Each IO Pdir entry
744  * for Astro/Ike looks like:
745  *
746  *
747  *  0                    19                                 51   55       63
748  * +-+---------------------+----------------------------------+----+--------+
749  * |V|        U            |            PPN[43:12]            | U  |   VI   |
750  * +-+---------------------+----------------------------------+----+--------+
751  *
752  * Pluto is basically identical, supports fewer physical address bits:
753  *
754  *  0                       23                              51   55       63
755  * +-+------------------------+-------------------------------+----+--------+
756  * |V|        U               |         PPN[39:12]            | U  |   VI   |
757  * +-+------------------------+-------------------------------+----+--------+
758  *
759  *  V  == Valid Bit  (Most Significant Bit is bit 0)
760  *  U  == Unused
761  * PPN == Physical Page Number
762  * VI  == Virtual Index (aka Coherent Index)
763  *
764  * LPA instruction output is put into PPN field.
765  * LCI (Load Coherence Index) instruction provides the "VI" bits.
766  *
767  * We pre-swap the bytes since PCX-W is Big Endian and the
768  * IOMMU uses little endian for the pdir.
769  */
770
771
772 void SBA_INLINE
773 sba_io_pdir_entry(u64 *pdir_ptr, space_t sid, unsigned long vba,
774                   unsigned long hint)
775 {
776         u64 pa; /* physical address */
777         register unsigned ci; /* coherent index */
778
779         /* We currently only support kernel addresses.
780          * fdc instr below will need to reload sr1 with KERNEL_SPACE
781          * once we try to support direct DMA to user space.
782          */
783         ASSERT(sid == KERNEL_SPACE);
784
785         pa = virt_to_phys(vba);
786         pa &= IOVP_MASK;
787
788         mtsp(sid,1);
789         asm("lci 0(%%sr1, %1), %0" : "=r" (ci) : "r" (vba));
790         pa |= (ci >> 12) & 0xff;  /* move CI (8 bits) into lowest byte */
791
792         pa |= 0x8000000000000000ULL;    /* set "valid" bit */
793         *pdir_ptr = cpu_to_le64(pa);    /* swap and store into I/O Pdir */
794
795         /*
796          * If the PDC_MODEL capabilities has Non-coherent IO-PDIR bit set
797          * (bit #61, big endian), we have to flush and sync every time
798          * IO-PDIR is changed in Ike/Astro.
799          */
800         if (ioc_needs_fdc) {
801                 asm volatile("fdc 0(%%sr1,%0)\n\tsync" : : "r" (pdir_ptr));
802         }
803 }
804
805
806 /**
807  * sba_mark_invalid - invalidate one or more IO PDIR entries
808  * @ioc: IO MMU structure which owns the pdir we are interested in.
809  * @iova:  IO Virtual Address mapped earlier
810  * @byte_cnt:  number of bytes this mapping covers.
811  *
812  * Marking the IO PDIR entry(ies) as Invalid and invalidate
813  * corresponding IO TLB entry. The Ike PCOM (Purge Command Register)
814  * is to purge stale entries in the IO TLB when unmapping entries.
815  *
816  * The PCOM register supports purging of multiple pages, with a minium
817  * of 1 page and a maximum of 2GB. Hardware requires the address be
818  * aligned to the size of the range being purged. The size of the range
819  * must be a power of 2. The "Cool perf optimization" in the
820  * allocation routine helps keep that true.
821  */
822 static SBA_INLINE void
823 sba_mark_invalid(struct ioc *ioc, dma_addr_t iova, size_t byte_cnt)
824 {
825         u32 iovp = (u32) SBA_IOVP(ioc,iova);
826
827         /* Even though this is a big-endian machine, the entries
828         ** in the iopdir are little endian. That's why we clear the byte
829         ** at +7 instead of at +0.
830         */
831         int off = PDIR_INDEX(iovp)*sizeof(u64)+7;
832
833         /* Must be non-zero and rounded up */
834         ASSERT(byte_cnt > 0);
835         ASSERT(0 == (byte_cnt & ~IOVP_MASK));
836
837 #ifdef ASSERT_PDIR_SANITY
838         /* Assert first pdir entry is set */
839         if (0x80 != (((u8 *) ioc->pdir_base)[off])) {
840                 sba_dump_pdir_entry(ioc,"sba_mark_invalid()", PDIR_INDEX(iovp));
841         }
842 #endif
843
844         if (byte_cnt <= IOVP_SIZE)
845         {
846                 ASSERT( off < ioc->pdir_size);
847
848                 iovp |= IOVP_SHIFT;     /* set "size" field for PCOM */
849
850                 /*
851                 ** clear I/O PDIR entry "valid" bit
852                 ** Do NOT clear the rest - save it for debugging.
853                 ** We should only clear bits that have previously
854                 ** been enabled.
855                 */
856                 ((u8 *)(ioc->pdir_base))[off] = 0;
857         } else {
858                 u32 t = get_order(byte_cnt) + PAGE_SHIFT;
859
860                 iovp |= t;
861                 ASSERT(t <= 31);   /* 2GB! Max value of "size" field */
862
863                 do {
864                         /* verify this pdir entry is enabled */
865                         ASSERT(0x80 == (((u8 *) ioc->pdir_base)[off] & 0x80));
866                         /* clear I/O Pdir entry "valid" bit first */
867                         ((u8 *)(ioc->pdir_base))[off] = 0;
868                         off += sizeof(u64);
869                         byte_cnt -= IOVP_SIZE;
870                 } while (byte_cnt > 0);
871         }
872
873         WRITE_REG( SBA_IOVA(ioc, iovp, 0, 0), ioc->ioc_hpa+IOC_PCOM);
874 }
875
876 /**
877  * sba_dma_supported - PCI driver can query DMA support
878  * @dev: instance of PCI owned by the driver that's asking
879  * @mask:  number of address bits this PCI device can handle
880  *
881  * See Documentation/DMA-mapping.txt
882  */
883 static int
884 sba_dma_supported( struct device *dev, u64 mask)
885 {
886         if (dev == NULL) {
887                 printk(KERN_ERR MODULE_NAME ": EISA/ISA/et al not supported\n");
888                 BUG();
889                 return(0);
890         }
891
892         /* only support 32-bit PCI devices - no DAC support (yet) */
893         return((int) (mask == 0xffffffffUL));
894 }
895
896
897 /**
898  * sba_map_single - map one buffer and return IOVA for DMA
899  * @dev: instance of PCI owned by the driver that's asking.
900  * @addr:  driver buffer to map.
901  * @size:  number of bytes to map in driver buffer.
902  * @direction:  R/W or both.
903  *
904  * See Documentation/DMA-mapping.txt
905  */
906 static dma_addr_t
907 sba_map_single(struct device *dev, void *addr, size_t size,
908                enum dma_data_direction direction)
909 {
910         struct ioc *ioc;
911         unsigned long flags; 
912         dma_addr_t iovp;
913         dma_addr_t offset;
914         u64 *pdir_start;
915         int pide;
916
917         ASSERT(size > 0);
918         ASSERT(size <= DMA_CHUNK_SIZE);
919
920         ioc = GET_IOC(dev);
921         ASSERT(ioc);
922
923         /* save offset bits */
924         offset = ((dma_addr_t) (long) addr) & ~IOVP_MASK;
925
926         /* round up to nearest IOVP_SIZE */
927         size = (size + offset + ~IOVP_MASK) & IOVP_MASK;
928
929         spin_lock_irqsave(&ioc->res_lock, flags);
930 #ifdef ASSERT_PDIR_SANITY
931         sba_check_pdir(ioc,"Check before sba_map_single()");
932 #endif
933
934 #ifdef SBA_COLLECT_STATS
935         ioc->msingle_calls++;
936         ioc->msingle_pages += size >> IOVP_SHIFT;
937 #endif
938         pide = sba_alloc_range(ioc, size);
939         iovp = (dma_addr_t) pide << IOVP_SHIFT;
940
941         DBG_RUN("%s() 0x%p -> 0x%lx\n",
942                 __FUNCTION__, addr, (long) iovp | offset);
943
944         pdir_start = &(ioc->pdir_base[pide]);
945
946         while (size > 0) {
947                 ASSERT(((u8 *)pdir_start)[7] == 0); /* verify availability */
948                 sba_io_pdir_entry(pdir_start, KERNEL_SPACE, (unsigned long) addr, 0);
949
950                 DBG_RUN("       pdir 0x%p %02x%02x%02x%02x%02x%02x%02x%02x\n",
951                         pdir_start,
952                         (u8) (((u8 *) pdir_start)[7]),
953                         (u8) (((u8 *) pdir_start)[6]),
954                         (u8) (((u8 *) pdir_start)[5]),
955                         (u8) (((u8 *) pdir_start)[4]),
956                         (u8) (((u8 *) pdir_start)[3]),
957                         (u8) (((u8 *) pdir_start)[2]),
958                         (u8) (((u8 *) pdir_start)[1]),
959                         (u8) (((u8 *) pdir_start)[0])
960                         );
961
962                 addr += IOVP_SIZE;
963                 size -= IOVP_SIZE;
964                 pdir_start++;
965         }
966         /* form complete address */
967 #ifdef ASSERT_PDIR_SANITY
968         sba_check_pdir(ioc,"Check after sba_map_single()");
969 #endif
970         spin_unlock_irqrestore(&ioc->res_lock, flags);
971         return SBA_IOVA(ioc, iovp, offset, DEFAULT_DMA_HINT_REG);
972 }
973
974
975 /**
976  * sba_unmap_single - unmap one IOVA and free resources
977  * @dev: instance of PCI owned by the driver that's asking.
978  * @iova:  IOVA of driver buffer previously mapped.
979  * @size:  number of bytes mapped in driver buffer.
980  * @direction:  R/W or both.
981  *
982  * See Documentation/DMA-mapping.txt
983  */
984 static void
985 sba_unmap_single(struct device *dev, dma_addr_t iova, size_t size,
986                  enum dma_data_direction direction)
987 {
988         struct ioc *ioc;
989 #if DELAYED_RESOURCE_CNT > 0
990         struct sba_dma_pair *d;
991 #endif
992         unsigned long flags; 
993         dma_addr_t offset;
994
995         ioc = GET_IOC(dev);
996         ASSERT(ioc);
997
998         offset = iova & ~IOVP_MASK;
999
1000         DBG_RUN("%s() iovp 0x%lx/%x\n",
1001                 __FUNCTION__, (long) iova, size);
1002
1003         iova ^= offset;        /* clear offset bits */
1004         size += offset;
1005         size = ROUNDUP(size, IOVP_SIZE);
1006
1007         spin_lock_irqsave(&ioc->res_lock, flags);
1008
1009 #ifdef SBA_COLLECT_STATS
1010         ioc->usingle_calls++;
1011         ioc->usingle_pages += size >> IOVP_SHIFT;
1012 #endif
1013
1014         sba_mark_invalid(ioc, iova, size);
1015
1016 #if DELAYED_RESOURCE_CNT > 0
1017         /* Delaying when we re-use a IO Pdir entry reduces the number
1018          * of MMIO reads needed to flush writes to the PCOM register.
1019          */
1020         d = &(ioc->saved[ioc->saved_cnt]);
1021         d->iova = iova;
1022         d->size = size;
1023         if (++(ioc->saved_cnt) >= DELAYED_RESOURCE_CNT) {
1024                 int cnt = ioc->saved_cnt;
1025                 while (cnt--) {
1026                         sba_free_range(ioc, d->iova, d->size);
1027                         d--;
1028                 }
1029                 ioc->saved_cnt = 0;
1030                 READ_REG(ioc->ioc_hpa+IOC_PCOM);        /* flush purges */
1031         }
1032 #else /* DELAYED_RESOURCE_CNT == 0 */
1033         sba_free_range(ioc, iova, size);
1034         READ_REG(ioc->ioc_hpa+IOC_PCOM);        /* flush purges */
1035 #endif /* DELAYED_RESOURCE_CNT == 0 */
1036         spin_unlock_irqrestore(&ioc->res_lock, flags);
1037
1038         /* XXX REVISIT for 2.5 Linux - need syncdma for zero-copy support.
1039         ** For Astro based systems this isn't a big deal WRT performance.
1040         ** As long as 2.4 kernels copyin/copyout data from/to userspace,
1041         ** we don't need the syncdma. The issue here is I/O MMU cachelines
1042         ** are *not* coherent in all cases.  May be hwrev dependent.
1043         ** Need to investigate more.
1044         asm volatile("syncdma");        
1045         */
1046 }
1047
1048
1049 /**
1050  * sba_alloc_consistent - allocate/map shared mem for DMA
1051  * @hwdev: instance of PCI owned by the driver that's asking.
1052  * @size:  number of bytes mapped in driver buffer.
1053  * @dma_handle:  IOVA of new buffer.
1054  *
1055  * See Documentation/DMA-mapping.txt
1056  */
1057 static void *sba_alloc_consistent(struct device *hwdev, size_t size,
1058                                         dma_addr_t *dma_handle, int gfp)
1059 {
1060         void *ret;
1061
1062         if (!hwdev) {
1063                 /* only support PCI */
1064                 *dma_handle = 0;
1065                 return 0;
1066         }
1067
1068         ret = (void *) __get_free_pages(gfp, get_order(size));
1069
1070         if (ret) {
1071                 memset(ret, 0, size);
1072                 *dma_handle = sba_map_single(hwdev, ret, size, 0);
1073         }
1074
1075         return ret;
1076 }
1077
1078
1079 /**
1080  * sba_free_consistent - free/unmap shared mem for DMA
1081  * @hwdev: instance of PCI owned by the driver that's asking.
1082  * @size:  number of bytes mapped in driver buffer.
1083  * @vaddr:  virtual address IOVA of "consistent" buffer.
1084  * @dma_handler:  IO virtual address of "consistent" buffer.
1085  *
1086  * See Documentation/DMA-mapping.txt
1087  */
1088 static void
1089 sba_free_consistent(struct device *hwdev, size_t size, void *vaddr,
1090                     dma_addr_t dma_handle)
1091 {
1092         sba_unmap_single(hwdev, dma_handle, size, 0);
1093         free_pages((unsigned long) vaddr, get_order(size));
1094 }
1095
1096
1097 /*
1098 ** Since 0 is a valid pdir_base index value, can't use that
1099 ** to determine if a value is valid or not. Use a flag to indicate
1100 ** the SG list entry contains a valid pdir index.
1101 */
1102 #define PIDE_FLAG 0x80000000UL
1103
1104 #ifdef SBA_COLLECT_STATS
1105 #define IOMMU_MAP_STATS
1106 #endif
1107 #include "iommu-helpers.h"
1108
1109 #ifdef DEBUG_LARGE_SG_ENTRIES
1110 int dump_run_sg = 0;
1111 #endif
1112
1113
1114 /**
1115  * sba_map_sg - map Scatter/Gather list
1116  * @dev: instance of PCI owned by the driver that's asking.
1117  * @sglist:  array of buffer/length pairs
1118  * @nents:  number of entries in list
1119  * @direction:  R/W or both.
1120  *
1121  * See Documentation/DMA-mapping.txt
1122  */
1123 static int
1124 sba_map_sg(struct device *dev, struct scatterlist *sglist, int nents,
1125            enum dma_data_direction direction)
1126 {
1127         struct ioc *ioc;
1128         int coalesced, filled = 0;
1129         unsigned long flags;
1130
1131         DBG_RUN_SG("%s() START %d entries\n", __FUNCTION__, nents);
1132
1133         ioc = GET_IOC(dev);
1134         ASSERT(ioc);
1135
1136         /* Fast path single entry scatterlists. */
1137         if (nents == 1) {
1138                 sg_dma_address(sglist) = sba_map_single(dev,
1139                                                 (void *)sg_virt_addr(sglist),
1140                                                 sglist->length, direction);
1141                 sg_dma_len(sglist)     = sglist->length;
1142                 return 1;
1143         }
1144
1145         spin_lock_irqsave(&ioc->res_lock, flags);
1146
1147 #ifdef ASSERT_PDIR_SANITY
1148         if (sba_check_pdir(ioc,"Check before sba_map_sg()"))
1149         {
1150                 sba_dump_sg(ioc, sglist, nents);
1151                 panic("Check before sba_map_sg()");
1152         }
1153 #endif
1154
1155 #ifdef SBA_COLLECT_STATS
1156         ioc->msg_calls++;
1157 #endif
1158
1159         /*
1160         ** First coalesce the chunks and allocate I/O pdir space
1161         **
1162         ** If this is one DMA stream, we can properly map using the
1163         ** correct virtual address associated with each DMA page.
1164         ** w/o this association, we wouldn't have coherent DMA!
1165         ** Access to the virtual address is what forces a two pass algorithm.
1166         */
1167         coalesced = iommu_coalesce_chunks(ioc, sglist, nents, sba_alloc_range);
1168
1169         /*
1170         ** Program the I/O Pdir
1171         **
1172         ** map the virtual addresses to the I/O Pdir
1173         ** o dma_address will contain the pdir index
1174         ** o dma_len will contain the number of bytes to map 
1175         ** o address contains the virtual address.
1176         */
1177         filled = iommu_fill_pdir(ioc, sglist, nents, 0, sba_io_pdir_entry);
1178
1179 #ifdef ASSERT_PDIR_SANITY
1180         if (sba_check_pdir(ioc,"Check after sba_map_sg()"))
1181         {
1182                 sba_dump_sg(ioc, sglist, nents);
1183                 panic("Check after sba_map_sg()\n");
1184         }
1185 #endif
1186
1187         spin_unlock_irqrestore(&ioc->res_lock, flags);
1188
1189         ASSERT(coalesced == filled);
1190         DBG_RUN_SG("%s() DONE %d mappings\n", __FUNCTION__, filled);
1191
1192         return filled;
1193 }
1194
1195
1196 /**
1197  * sba_unmap_sg - unmap Scatter/Gather list
1198  * @dev: instance of PCI owned by the driver that's asking.
1199  * @sglist:  array of buffer/length pairs
1200  * @nents:  number of entries in list
1201  * @direction:  R/W or both.
1202  *
1203  * See Documentation/DMA-mapping.txt
1204  */
1205 static void 
1206 sba_unmap_sg(struct device *dev, struct scatterlist *sglist, int nents,
1207              enum dma_data_direction direction)
1208 {
1209         struct ioc *ioc;
1210 #ifdef ASSERT_PDIR_SANITY
1211         unsigned long flags;
1212 #endif
1213
1214         DBG_RUN_SG("%s() START %d entries,  %p,%x\n",
1215                 __FUNCTION__, nents, sg_virt_addr(sglist), sglist->length);
1216
1217         ioc = GET_IOC(dev);
1218         ASSERT(ioc);
1219
1220 #ifdef SBA_COLLECT_STATS
1221         ioc->usg_calls++;
1222 #endif
1223
1224 #ifdef ASSERT_PDIR_SANITY
1225         spin_lock_irqsave(&ioc->res_lock, flags);
1226         sba_check_pdir(ioc,"Check before sba_unmap_sg()");
1227         spin_unlock_irqrestore(&ioc->res_lock, flags);
1228 #endif
1229
1230         while (sg_dma_len(sglist) && nents--) {
1231
1232                 sba_unmap_single(dev, sg_dma_address(sglist), sg_dma_len(sglist), direction);
1233 #ifdef SBA_COLLECT_STATS
1234                 ioc->usg_pages += ((sg_dma_address(sglist) & ~IOVP_MASK) + sg_dma_len(sglist) + IOVP_SIZE - 1) >> PAGE_SHIFT;
1235                 ioc->usingle_calls--;   /* kluge since call is unmap_sg() */
1236 #endif
1237                 ++sglist;
1238         }
1239
1240         DBG_RUN_SG("%s() DONE (nents %d)\n", __FUNCTION__,  nents);
1241
1242 #ifdef ASSERT_PDIR_SANITY
1243         spin_lock_irqsave(&ioc->res_lock, flags);
1244         sba_check_pdir(ioc,"Check after sba_unmap_sg()");
1245         spin_unlock_irqrestore(&ioc->res_lock, flags);
1246 #endif
1247
1248 }
1249
1250 static struct hppa_dma_ops sba_ops = {
1251         .dma_supported =        sba_dma_supported,
1252         .alloc_consistent =     sba_alloc_consistent,
1253         .alloc_noncoherent =    sba_alloc_consistent,
1254         .free_consistent =      sba_free_consistent,
1255         .map_single =           sba_map_single,
1256         .unmap_single =         sba_unmap_single,
1257         .map_sg =               sba_map_sg,
1258         .unmap_sg =             sba_unmap_sg,
1259         .dma_sync_single_for_cpu =      NULL,
1260         .dma_sync_single_for_device =   NULL,
1261         .dma_sync_sg_for_cpu =          NULL,
1262         .dma_sync_sg_for_device =       NULL,
1263 };
1264
1265
1266 /**************************************************************************
1267 **
1268 **   SBA PAT PDC support
1269 **
1270 **   o call pdc_pat_cell_module()
1271 **   o store ranges in PCI "resource" structures
1272 **
1273 **************************************************************************/
1274
1275 static void
1276 sba_get_pat_resources(struct sba_device *sba_dev)
1277 {
1278 #if 0
1279 /*
1280 ** TODO/REVISIT/FIXME: support for directed ranges requires calls to
1281 **      PAT PDC to program the SBA/LBA directed range registers...this
1282 **      burden may fall on the LBA code since it directly supports the
1283 **      PCI subsystem. It's not clear yet. - ggg
1284 */
1285 PAT_MOD(mod)->mod_info.mod_pages   = PAT_GET_MOD_PAGES(temp);
1286         FIXME : ???
1287 PAT_MOD(mod)->mod_info.dvi         = PAT_GET_DVI(temp);
1288         Tells where the dvi bits are located in the address.
1289 PAT_MOD(mod)->mod_info.ioc         = PAT_GET_IOC(temp);
1290         FIXME : ???
1291 #endif
1292 }
1293
1294
1295 /**************************************************************
1296 *
1297 *   Initialization and claim
1298 *
1299 ***************************************************************/
1300 #define PIRANHA_ADDR_MASK       0x00160000UL /* bit 17,18,20 */
1301 #define PIRANHA_ADDR_VAL        0x00060000UL /* bit 17,18 on */
1302 static void *
1303 sba_alloc_pdir(unsigned int pdir_size)
1304 {
1305         unsigned long pdir_base;
1306         unsigned long pdir_order = get_order(pdir_size);
1307
1308         pdir_base = __get_free_pages(GFP_KERNEL, pdir_order);
1309         if (NULL == (void *) pdir_base)
1310                 panic("sba_ioc_init() could not allocate I/O Page Table\n");
1311
1312         /* If this is not PA8700 (PCX-W2)
1313         **      OR newer than ver 2.2
1314         **      OR in a system that doesn't need VINDEX bits from SBA,
1315         **
1316         ** then we aren't exposed to the HW bug.
1317         */
1318         if ( ((boot_cpu_data.pdc.cpuid >> 5) & 0x7f) != 0x13
1319                         || (boot_cpu_data.pdc.versions > 0x202)
1320                         || (boot_cpu_data.pdc.capabilities & 0x08L) )
1321                 return (void *) pdir_base;
1322
1323         /*
1324          * PA8700 (PCX-W2, aka piranha) silent data corruption fix
1325          *
1326          * An interaction between PA8700 CPU (Ver 2.2 or older) and
1327          * Ike/Astro can cause silent data corruption. This is only
1328          * a problem if the I/O PDIR is located in memory such that
1329          * (little-endian)  bits 17 and 18 are on and bit 20 is off.
1330          *
1331          * Since the max IO Pdir size is 2MB, by cleverly allocating the
1332          * right physical address, we can either avoid (IOPDIR <= 1MB)
1333          * or minimize (2MB IO Pdir) the problem if we restrict the
1334          * IO Pdir to a maximum size of 2MB-128K (1902K).
1335          *
1336          * Because we always allocate 2^N sized IO pdirs, either of the
1337          * "bad" regions will be the last 128K if at all. That's easy
1338          * to test for.
1339          * 
1340          */
1341         if (pdir_order <= (19-12)) {
1342                 if (((virt_to_phys(pdir_base)+pdir_size-1) & PIRANHA_ADDR_MASK) == PIRANHA_ADDR_VAL) {
1343                         /* allocate a new one on 512k alignment */
1344                         unsigned long new_pdir = __get_free_pages(GFP_KERNEL, (19-12));
1345                         /* release original */
1346                         free_pages(pdir_base, pdir_order);
1347
1348                         pdir_base = new_pdir;
1349
1350                         /* release excess */
1351                         while (pdir_order < (19-12)) {
1352                                 new_pdir += pdir_size;
1353                                 free_pages(new_pdir, pdir_order);
1354                                 pdir_order +=1;
1355                                 pdir_size <<=1;
1356                         }
1357                 }
1358         } else {
1359                 /*
1360                 ** 1MB or 2MB Pdir
1361                 ** Needs to be aligned on an "odd" 1MB boundary.
1362                 */
1363                 unsigned long new_pdir = __get_free_pages(GFP_KERNEL, pdir_order+1); /* 2 or 4MB */
1364
1365                 /* release original */
1366                 free_pages( pdir_base, pdir_order);
1367
1368                 /* release first 1MB */
1369                 free_pages(new_pdir, 20-12);
1370
1371                 pdir_base = new_pdir + 1024*1024;
1372
1373                 if (pdir_order > (20-12)) {
1374                         /*
1375                         ** 2MB Pdir.
1376                         **
1377                         ** Flag tells init_bitmap() to mark bad 128k as used
1378                         ** and to reduce the size by 128k.
1379                         */
1380                         piranha_bad_128k = 1;
1381
1382                         new_pdir += 3*1024*1024;
1383                         /* release last 1MB */
1384                         free_pages(new_pdir, 20-12);
1385
1386                         /* release unusable 128KB */
1387                         free_pages(new_pdir - 128*1024 , 17-12);
1388
1389                         pdir_size -= 128*1024;
1390                 }
1391         }
1392
1393         memset((void *) pdir_base, 0, pdir_size);
1394         return (void *) pdir_base;
1395 }
1396
1397 static void
1398 sba_ioc_init_pluto(struct parisc_device *sba, struct ioc *ioc, int ioc_num)
1399 {
1400         /* lba_set_iregs() is in arch/parisc/kernel/lba_pci.c */
1401         extern void lba_set_iregs(struct parisc_device *, u32, u32);
1402
1403         u32 iova_space_mask;
1404         u32 iova_space_size;
1405         int iov_order, tcnfg;
1406         struct parisc_device *lba;
1407 #if SBA_AGP_SUPPORT
1408         int agp_found = 0;
1409 #endif
1410         /*
1411         ** Firmware programs the base and size of a "safe IOVA space"
1412         ** (one that doesn't overlap memory or LMMIO space) in the
1413         ** IBASE and IMASK registers.
1414         */
1415         ioc->ibase = READ_REG(ioc->ioc_hpa + IOC_IBASE);
1416         iova_space_size = ~(READ_REG(ioc->ioc_hpa + IOC_IMASK) & 0xFFFFFFFFUL) + 1;
1417
1418         if ((ioc->ibase < 0xfed00000UL) && ((ioc->ibase + iova_space_size) > 0xfee00000UL)) {
1419                 printk("WARNING: IOV space overlaps local config and interrupt message, truncating\n");
1420                 iova_space_size /= 2;
1421         }
1422
1423         /*
1424         ** iov_order is always based on a 1GB IOVA space since we want to
1425         ** turn on the other half for AGP GART.
1426         */
1427         iov_order = get_order(iova_space_size >> (IOVP_SHIFT - PAGE_SHIFT));
1428         ioc->pdir_size = (iova_space_size / IOVP_SIZE) * sizeof(u64);
1429
1430         DBG_INIT("%s() hpa 0x%lx IOV %dMB (%d bits)\n",
1431                 __FUNCTION__, ioc->ioc_hpa, iova_space_size >> 20,
1432                 iov_order + PAGE_SHIFT);
1433
1434         ioc->pdir_base = (void *) __get_free_pages(GFP_KERNEL,
1435                                                    get_order(ioc->pdir_size));
1436         if (!ioc->pdir_base)
1437                 panic("Couldn't allocate I/O Page Table\n");
1438
1439         memset(ioc->pdir_base, 0, ioc->pdir_size);
1440
1441         DBG_INIT("%s() pdir %p size %x\n",
1442                         __FUNCTION__, ioc->pdir_base, ioc->pdir_size);
1443
1444 #if SBA_HINT_SUPPORT
1445         ioc->hint_shift_pdir = iov_order + PAGE_SHIFT;
1446         ioc->hint_mask_pdir = ~(0x3 << (iov_order + PAGE_SHIFT));
1447
1448         DBG_INIT("      hint_shift_pdir %x hint_mask_pdir %lx\n",
1449                 ioc->hint_shift_pdir, ioc->hint_mask_pdir);
1450 #endif
1451
1452         ASSERT((((unsigned long) ioc->pdir_base) & PAGE_MASK) == (unsigned long) ioc->pdir_base);
1453         WRITE_REG(virt_to_phys(ioc->pdir_base), ioc->ioc_hpa + IOC_PDIR_BASE);
1454
1455         /* build IMASK for IOC and Elroy */
1456         iova_space_mask =  0xffffffff;
1457         iova_space_mask <<= (iov_order + PAGE_SHIFT);
1458         ioc->imask = iova_space_mask;
1459 #ifdef ZX1_SUPPORT
1460         ioc->iovp_mask = ~(iova_space_mask + PAGE_SIZE - 1);
1461 #endif
1462         sba_dump_tlb(ioc->ioc_hpa);
1463
1464         /*
1465         ** setup Mercury IBASE/IMASK registers as well.
1466         */
1467         for (lba = sba->child; lba; lba = lba->sibling) {
1468                 int rope_num = (lba->hpa >> 13) & 0xf;
1469                 if (rope_num >> 3 == ioc_num)
1470                         lba_set_iregs(lba, ioc->ibase, ioc->imask);
1471         }
1472
1473         WRITE_REG(ioc->imask, ioc->ioc_hpa + IOC_IMASK);
1474
1475 #ifdef __LP64__
1476         /*
1477         ** Setting the upper bits makes checking for bypass addresses
1478         ** a little faster later on.
1479         */
1480         ioc->imask |= 0xFFFFFFFF00000000UL;
1481 #endif
1482
1483         /* Set I/O PDIR Page size to system page size */
1484         switch (PAGE_SHIFT) {
1485                 case 12: tcnfg = 0; break;      /*  4K */
1486                 case 13: tcnfg = 1; break;      /*  8K */
1487                 case 14: tcnfg = 2; break;      /* 16K */
1488                 case 16: tcnfg = 3; break;      /* 64K */
1489                 default:
1490                         panic(__FILE__ "Unsupported system page size %d",
1491                                 1 << PAGE_SHIFT);
1492                         break;
1493         }
1494         WRITE_REG(tcnfg, ioc->ioc_hpa + IOC_TCNFG);
1495
1496         /*
1497         ** Program the IOC's ibase and enable IOVA translation
1498         ** Bit zero == enable bit.
1499         */
1500         WRITE_REG(ioc->ibase | 1, ioc->ioc_hpa + IOC_IBASE);
1501
1502         /*
1503         ** Clear I/O TLB of any possible entries.
1504         ** (Yes. This is a bit paranoid...but so what)
1505         */
1506         WRITE_REG(ioc->ibase | 31, ioc->ioc_hpa + IOC_PCOM);
1507
1508 #if SBA_AGP_SUPPORT
1509         /*
1510         ** If an AGP device is present, only use half of the IOV space
1511         ** for PCI DMA.  Unfortunately we can't know ahead of time
1512         ** whether GART support will actually be used, for now we
1513         ** can just key on any AGP device found in the system.
1514         ** We program the next pdir index after we stop w/ a key for
1515         ** the GART code to handshake on.
1516         */
1517         device=NULL;
1518         for (lba = sba->child; lba; lba = lba->sibling) {
1519                 if (IS_QUICKSILVER(lba))
1520                         break;
1521         }
1522
1523         if (lba) {
1524                 DBG_INIT("%s: Reserving half of IOVA space for AGP GART support\n", __FUNCTION__);
1525                 ioc->pdir_size /= 2;
1526                 ((u64 *)ioc->pdir_base)[PDIR_INDEX(iova_space_size/2)] = SBA_IOMMU_COOKIE;
1527         } else {
1528                 DBG_INIT("%s: No GART needed - no AGP controller found\n", __FUNCTION__);
1529         }
1530 #endif /* 0 */
1531
1532 }
1533
1534 static void
1535 sba_ioc_init(struct parisc_device *sba, struct ioc *ioc, int ioc_num)
1536 {
1537         /* lba_set_iregs() is in arch/parisc/kernel/lba_pci.c */
1538         extern void lba_set_iregs(struct parisc_device *, u32, u32);
1539
1540         u32 iova_space_size, iova_space_mask;
1541         int pdir_size, iov_order;
1542         unsigned long physmem;
1543         struct parisc_device *lba;
1544
1545         /*
1546         ** Determine IOVA Space size from memory size.
1547         **
1548         ** Ideally, PCI drivers would register the maximum number
1549         ** of DMA they can have outstanding for each device they
1550         ** own.  Next best thing would be to guess how much DMA
1551         ** can be outstanding based on PCI Class/sub-class. Both
1552         ** methods still require some "extra" to support PCI
1553         ** Hot-Plug/Removal of PCI cards. (aka PCI OLARD).
1554         **
1555         ** While we have 32-bits "IOVA" space, top two 2 bits are used
1556         ** for DMA hints - ergo only 30 bits max.
1557         */
1558
1559         physmem = num_physpages << PAGE_SHIFT;
1560         iova_space_size = (u32) (physmem/(sba_mem_ratio*global_ioc_cnt));
1561
1562         /* limit IOVA space size to 1MB-1GB */
1563         if (iova_space_size < 1024*1024) {
1564                 iova_space_size = 1024*1024;
1565         }
1566 #ifdef __LP64__
1567         else if (iova_space_size > 512*1024*1024) {
1568                 iova_space_size = 512*1024*1024;
1569         }
1570 #endif
1571
1572         /*
1573         ** iova space must be log2() in size.
1574         ** thus, pdir/res_map will also be log2().
1575         ** PIRANHA BUG: Exception is when IO Pdir is 2MB (gets reduced)
1576         */
1577         iov_order = get_order(iova_space_size >> (IOVP_SHIFT-PAGE_SHIFT));
1578         ASSERT(iov_order <= (30 - IOVP_SHIFT));   /* iova_space_size <= 1GB */
1579         ASSERT(iov_order >= (20 - IOVP_SHIFT));   /* iova_space_size >= 1MB */
1580         iova_space_size = 1 << (iov_order + IOVP_SHIFT);
1581
1582         ioc->pdir_size = pdir_size = (iova_space_size/IOVP_SIZE) * sizeof(u64);
1583
1584         ASSERT(pdir_size < 4*1024*1024);   /* max pdir size == 2MB */
1585
1586         /* Verify it's a power of two */
1587         ASSERT((1 << get_order(pdir_size)) == (pdir_size >> PAGE_SHIFT));
1588
1589         DBG_INIT("%s() hpa 0x%lx mem %dMB IOV %dMB (%d bits) PDIR size 0x%0x\n",
1590                 __FUNCTION__, ioc->ioc_hpa, (int) (physmem>>20),
1591                 iova_space_size>>20, iov_order + PAGE_SHIFT, pdir_size);
1592
1593         ioc->pdir_base = sba_alloc_pdir(pdir_size);
1594
1595         DBG_INIT("%s() pdir %p size %x\n",
1596                         __FUNCTION__, ioc->pdir_base, pdir_size);
1597
1598 #if SBA_HINT_SUPPORT
1599         /* FIXME : DMA HINTs not used */
1600         ioc->hint_shift_pdir = iov_order + PAGE_SHIFT;
1601         ioc->hint_mask_pdir = ~(0x3 << (iov_order + PAGE_SHIFT));
1602
1603         DBG_INIT("      hint_shift_pdir %x hint_mask_pdir %lx\n",
1604                         ioc->hint_shift_pdir, ioc->hint_mask_pdir);
1605 #endif
1606
1607         ASSERT((((unsigned long) ioc->pdir_base) & PAGE_MASK) == (unsigned long) ioc->pdir_base);
1608         WRITE_REG64(virt_to_phys(ioc->pdir_base), ioc->ioc_hpa + IOC_PDIR_BASE);
1609
1610         /* build IMASK for IOC and Elroy */
1611         iova_space_mask =  0xffffffff;
1612         iova_space_mask <<= (iov_order + PAGE_SHIFT);
1613
1614         /*
1615         ** On C3000 w/512MB mem, HP-UX 10.20 reports:
1616         **     ibase=0, imask=0xFE000000, size=0x2000000.
1617         */
1618         ioc->ibase = 0;
1619         ioc->imask = iova_space_mask;   /* save it */
1620 #ifdef ZX1_SUPPORT
1621         ioc->iovp_mask = ~(iova_space_mask + PAGE_SIZE - 1);
1622 #endif
1623
1624         DBG_INIT("%s() IOV base 0x%lx mask 0x%0lx\n",
1625                 __FUNCTION__, ioc->ibase, ioc->imask);
1626
1627         /*
1628         ** FIXME: Hint registers are programmed with default hint
1629         ** values during boot, so hints should be sane even if we
1630         ** can't reprogram them the way drivers want.
1631         */
1632
1633         /*
1634         ** setup Elroy IBASE/IMASK registers as well.
1635         */
1636         for (lba = sba->child; lba; lba = lba->sibling) {
1637                 int rope_num = (lba->hpa >> 13) & 0xf;
1638                 if (rope_num >> 3 == ioc_num)
1639                         lba_set_iregs(lba, ioc->ibase, ioc->imask);
1640         }
1641
1642         /*
1643         ** Program the IOC's ibase and enable IOVA translation
1644         */
1645         WRITE_REG(ioc->ibase | 1, ioc->ioc_hpa+IOC_IBASE);
1646         WRITE_REG(ioc->imask, ioc->ioc_hpa+IOC_IMASK);
1647
1648         /* Set I/O PDIR Page size to 4K */
1649         WRITE_REG(0, ioc->ioc_hpa+IOC_TCNFG);
1650
1651         /*
1652         ** Clear I/O TLB of any possible entries.
1653         ** (Yes. This is a bit paranoid...but so what)
1654         */
1655         WRITE_REG(0 | 31, ioc->ioc_hpa+IOC_PCOM);
1656
1657         ioc->ibase = 0; /* used by SBA_IOVA and related macros */       
1658
1659         DBG_INIT("%s() DONE\n", __FUNCTION__);
1660 }
1661
1662
1663
1664 /**************************************************************************
1665 **
1666 **   SBA initialization code (HW and SW)
1667 **
1668 **   o identify SBA chip itself
1669 **   o initialize SBA chip modes (HardFail)
1670 **   o initialize SBA chip modes (HardFail)
1671 **   o FIXME: initialize DMA hints for reasonable defaults
1672 **
1673 **************************************************************************/
1674
1675 static void
1676 sba_hw_init(struct sba_device *sba_dev)
1677
1678         int i;
1679         int num_ioc;
1680         u64 ioc_ctl;
1681
1682         if (!is_pdc_pat()) {
1683                 /* Shutdown the USB controller on Astro-based workstations.
1684                 ** Once we reprogram the IOMMU, the next DMA performed by
1685                 ** USB will HPMC the box.
1686                 */
1687                 pdc_io_reset_devices();
1688
1689                 /*
1690                 ** XXX May need something more sophisticated to deal
1691                 **     with DMA from LAN. Maybe use page zero boot device
1692                 **     as a handle to talk to PDC about which device to
1693                 **     shutdown. This also needs to work for is_pdc_pat(). 
1694                 */
1695         }
1696
1697         if (!IS_PLUTO(sba_dev->iodc)) {
1698                 ioc_ctl = READ_REG(sba_dev->sba_hpa+IOC_CTRL);
1699                 DBG_INIT("%s() hpa 0x%lx ioc_ctl 0x%Lx ->",
1700                         __FUNCTION__, sba_dev->sba_hpa, ioc_ctl);
1701                 ioc_ctl &= ~(IOC_CTRL_RM | IOC_CTRL_NC | IOC_CTRL_CE);
1702                 ioc_ctl |= IOC_CTRL_TC; /* Astro: firmware enables this */
1703
1704                 WRITE_REG(ioc_ctl, sba_dev->sba_hpa+IOC_CTRL);
1705
1706 #ifdef DEBUG_SBA_INIT
1707                 ioc_ctl = READ_REG64(sba_dev->sba_hpa+IOC_CTRL);
1708                 DBG_INIT(" 0x%Lx\n", ioc_ctl);
1709 #endif
1710         } /* if !PLUTO */
1711
1712         if (IS_ASTRO(sba_dev->iodc)) {
1713                 int err;
1714                 /* PAT_PDC (L-class) also reports the same goofy base */
1715                 sba_dev->ioc[0].ioc_hpa = ASTRO_IOC_OFFSET;
1716                 num_ioc = 1;
1717
1718                 sba_dev->chip_resv.name = "Astro Intr Ack";
1719                 sba_dev->chip_resv.start = PCI_F_EXTEND | 0xfef00000UL;
1720                 sba_dev->chip_resv.end   = PCI_F_EXTEND | (0xff000000UL - 1) ;
1721                 err = request_resource(&iomem_resource, &(sba_dev->chip_resv));
1722                 if (err < 0) {
1723                         BUG();
1724                 }
1725
1726         } else if (IS_PLUTO(sba_dev->iodc)) {
1727                 int err;
1728
1729                 /* We use a negative value for IOC HPA so it gets 
1730                  * corrected when we add it with IKE's IOC offset.
1731                  * Doesnt look clean, but fewer code. 
1732                  */
1733                 sba_dev->ioc[0].ioc_hpa = -PLUTO_IOC_OFFSET;
1734                 num_ioc = 1;
1735
1736                 sba_dev->chip_resv.name = "Pluto Intr/PIOP/VGA";
1737                 sba_dev->chip_resv.start = PCI_F_EXTEND | 0xfee00000UL;
1738                 sba_dev->chip_resv.end   = PCI_F_EXTEND | (0xff200000UL - 1);
1739                 err = request_resource(&iomem_resource, &(sba_dev->chip_resv));
1740                 BUG_ON(err < 0);
1741
1742                 sba_dev->iommu_resv.name = "IOVA Space";
1743                 sba_dev->iommu_resv.start = 0x40000000UL;
1744                 sba_dev->iommu_resv.end   = 0x50000000UL - 1;
1745                 err = request_resource(&iomem_resource, &(sba_dev->iommu_resv));
1746                 BUG_ON(err < 0);
1747         } else {
1748                 /* IS_IKE (ie N-class, L3000, L1500) */
1749                 sba_dev->ioc[0].ioc_hpa = sba_dev->ioc[1].ioc_hpa = 0;
1750                 num_ioc = 2;
1751
1752                 /* TODO - LOOKUP Ike/Stretch chipset mem map */
1753         }
1754
1755         sba_dev->num_ioc = num_ioc;
1756         for (i = 0; i < num_ioc; i++) {
1757                 sba_dev->ioc[i].ioc_hpa += sba_dev->sba_hpa + IKE_IOC_OFFSET(i);
1758
1759                 /*
1760                 ** Make sure the box crashes if we get any errors on a rope.
1761                 */
1762                 WRITE_REG(HF_ENABLE, sba_dev->ioc[i].ioc_hpa + ROPE0_CTL);
1763                 WRITE_REG(HF_ENABLE, sba_dev->ioc[i].ioc_hpa + ROPE1_CTL);
1764                 WRITE_REG(HF_ENABLE, sba_dev->ioc[i].ioc_hpa + ROPE2_CTL);
1765                 WRITE_REG(HF_ENABLE, sba_dev->ioc[i].ioc_hpa + ROPE3_CTL);
1766                 WRITE_REG(HF_ENABLE, sba_dev->ioc[i].ioc_hpa + ROPE4_CTL);
1767                 WRITE_REG(HF_ENABLE, sba_dev->ioc[i].ioc_hpa + ROPE5_CTL);
1768                 WRITE_REG(HF_ENABLE, sba_dev->ioc[i].ioc_hpa + ROPE6_CTL);
1769                 WRITE_REG(HF_ENABLE, sba_dev->ioc[i].ioc_hpa + ROPE7_CTL);
1770
1771                 /* flush out the writes */
1772                 READ_REG(sba_dev->ioc[i].ioc_hpa + ROPE7_CTL);
1773
1774                 if (IS_PLUTO(sba_dev->iodc)) {
1775                         sba_ioc_init_pluto(sba_dev->dev, &(sba_dev->ioc[i]), i);
1776                 } else {
1777                         sba_ioc_init(sba_dev->dev, &(sba_dev->ioc[i]), i);
1778                 }
1779         }
1780 }
1781
1782 static void
1783 sba_common_init(struct sba_device *sba_dev)
1784 {
1785         int i;
1786
1787         /* add this one to the head of the list (order doesn't matter)
1788         ** This will be useful for debugging - especially if we get coredumps
1789         */
1790         sba_dev->next = sba_list;
1791         sba_list = sba_dev;
1792
1793         for(i=0; i< sba_dev->num_ioc; i++) {
1794                 int res_size;
1795 #ifdef DEBUG_DMB_TRAP
1796                 extern void iterate_pages(unsigned long , unsigned long ,
1797                                           void (*)(pte_t * , unsigned long),
1798                                           unsigned long );
1799                 void set_data_memory_break(pte_t * , unsigned long);
1800 #endif
1801                 /* resource map size dictated by pdir_size */
1802                 res_size = sba_dev->ioc[i].pdir_size/sizeof(u64); /* entries */
1803
1804                 /* Second part of PIRANHA BUG */
1805                 if (piranha_bad_128k) {
1806                         res_size -= (128*1024)/sizeof(u64);
1807                 }
1808
1809                 res_size >>= 3;  /* convert bit count to byte count */
1810                 DBG_INIT("%s() res_size 0x%x\n",
1811                         __FUNCTION__, res_size);
1812
1813                 sba_dev->ioc[i].res_size = res_size;
1814                 sba_dev->ioc[i].res_map = (char *) __get_free_pages(GFP_KERNEL, get_order(res_size));
1815
1816 #ifdef DEBUG_DMB_TRAP
1817                 iterate_pages( sba_dev->ioc[i].res_map, res_size,
1818                                 set_data_memory_break, 0);
1819 #endif
1820
1821                 if (NULL == sba_dev->ioc[i].res_map)
1822                 {
1823                         panic("%s:%s() could not allocate resource map\n",
1824                               __FILE__, __FUNCTION__ );
1825                 }
1826
1827                 memset(sba_dev->ioc[i].res_map, 0, res_size);
1828                 /* next available IOVP - circular search */
1829                 sba_dev->ioc[i].res_hint = (unsigned long *)
1830                                 &(sba_dev->ioc[i].res_map[L1_CACHE_BYTES]);
1831
1832 #ifdef ASSERT_PDIR_SANITY
1833                 /* Mark first bit busy - ie no IOVA 0 */
1834                 sba_dev->ioc[i].res_map[0] = 0x80;
1835                 sba_dev->ioc[i].pdir_base[0] = 0xeeffc0addbba0080ULL;
1836 #endif
1837
1838                 /* Third (and last) part of PIRANHA BUG */
1839                 if (piranha_bad_128k) {
1840                         /* region from +1408K to +1536 is un-usable. */
1841
1842                         int idx_start = (1408*1024/sizeof(u64)) >> 3;
1843                         int idx_end   = (1536*1024/sizeof(u64)) >> 3;
1844                         long *p_start = (long *) &(sba_dev->ioc[i].res_map[idx_start]);
1845                         long *p_end   = (long *) &(sba_dev->ioc[i].res_map[idx_end]);
1846
1847                         /* mark that part of the io pdir busy */
1848                         while (p_start < p_end)
1849                                 *p_start++ = -1;
1850                                 
1851                 }
1852
1853 #ifdef DEBUG_DMB_TRAP
1854                 iterate_pages( sba_dev->ioc[i].res_map, res_size,
1855                                 set_data_memory_break, 0);
1856                 iterate_pages( sba_dev->ioc[i].pdir_base, sba_dev->ioc[i].pdir_size,
1857                                 set_data_memory_break, 0);
1858 #endif
1859
1860                 DBG_INIT("%s() %d res_map %x %p\n",
1861                         __FUNCTION__, i, res_size, sba_dev->ioc[i].res_map);
1862         }
1863
1864         spin_lock_init(&sba_dev->sba_lock);
1865         ioc_needs_fdc = boot_cpu_data.pdc.capabilities & PDC_MODEL_IOPDIR_FDC;
1866
1867 #ifdef DEBUG_SBA_INIT
1868         /*
1869          * If the PDC_MODEL capabilities has Non-coherent IO-PDIR bit set
1870          * (bit #61, big endian), we have to flush and sync every time
1871          * IO-PDIR is changed in Ike/Astro.
1872          */
1873         if (boot_cpu_data.pdc.capabilities & PDC_MODEL_IOPDIR_FDC) {
1874                 printk(KERN_INFO MODULE_NAME " FDC/SYNC required.\n");
1875         } else {
1876                 printk(KERN_INFO MODULE_NAME " IOC has cache coherent PDIR.\n");
1877         }
1878 #endif
1879 }
1880
1881 #ifdef CONFIG_PROC_FS
1882 static int sba_proc_info(char *buf, char **start, off_t offset, int len)
1883 {
1884         struct sba_device *sba_dev = sba_list;
1885         struct ioc *ioc = &sba_dev->ioc[0];     /* FIXME: Multi-IOC support! */
1886         int total_pages = (int) (ioc->res_size << 3); /* 8 bits per byte */
1887         unsigned long i;
1888 #ifdef SBA_COLLECT_STATS
1889         unsigned long avg = 0, min, max;
1890 #endif
1891
1892         sprintf(buf, "%s rev %d.%d\n",
1893                 sba_dev->name,
1894                 (sba_dev->hw_rev & 0x7) + 1,
1895                 (sba_dev->hw_rev & 0x18) >> 3
1896                 );
1897         sprintf(buf, "%sIO PDIR size    : %d bytes (%d entries)\n",
1898                 buf,
1899                 (int) ((ioc->res_size << 3) * sizeof(u64)), /* 8 bits/byte */
1900                 total_pages);
1901
1902         sprintf(buf, "%sResource bitmap : %d bytes (%d pages)\n", 
1903                 buf, ioc->res_size, ioc->res_size << 3);   /* 8 bits per byte */
1904
1905         sprintf(buf, "%sLMMIO_BASE/MASK/ROUTE %08x %08x %08x\n",
1906                 buf,
1907                 READ_REG32(sba_dev->sba_hpa + LMMIO_DIST_BASE),
1908                 READ_REG32(sba_dev->sba_hpa + LMMIO_DIST_MASK),
1909                 READ_REG32(sba_dev->sba_hpa + LMMIO_DIST_ROUTE)
1910                 );
1911
1912         for (i=0; i<4; i++)
1913                 sprintf(buf, "%sDIR%ld_BASE/MASK/ROUTE %08x %08x %08x\n",
1914                         buf, i,
1915                         READ_REG32(sba_dev->sba_hpa + LMMIO_DIRECT0_BASE  + i*0x18),
1916                         READ_REG32(sba_dev->sba_hpa + LMMIO_DIRECT0_MASK  + i*0x18),
1917                         READ_REG32(sba_dev->sba_hpa + LMMIO_DIRECT0_ROUTE + i*0x18)
1918                 );
1919
1920 #ifdef SBA_COLLECT_STATS
1921         sprintf(buf, "%sIO PDIR entries : %ld free  %ld used (%d%%)\n", buf,
1922                 total_pages - ioc->used_pages, ioc->used_pages,
1923                 (int) (ioc->used_pages * 100 / total_pages));
1924
1925         min = max = ioc->avg_search[0];
1926         for (i = 0; i < SBA_SEARCH_SAMPLE; i++) {
1927                 avg += ioc->avg_search[i];
1928                 if (ioc->avg_search[i] > max) max = ioc->avg_search[i];
1929                 if (ioc->avg_search[i] < min) min = ioc->avg_search[i];
1930         }
1931         avg /= SBA_SEARCH_SAMPLE;
1932         sprintf(buf, "%s  Bitmap search : %ld/%ld/%ld (min/avg/max CPU Cycles)\n",
1933                 buf, min, avg, max);
1934
1935         sprintf(buf, "%spci_map_single(): %12ld calls  %12ld pages (avg %d/1000)\n",
1936                 buf, ioc->msingle_calls, ioc->msingle_pages,
1937                 (int) ((ioc->msingle_pages * 1000)/ioc->msingle_calls));
1938
1939         /* KLUGE - unmap_sg calls unmap_single for each mapped page */
1940         min = ioc->usingle_calls;
1941         max = ioc->usingle_pages - ioc->usg_pages;
1942         sprintf(buf, "%spci_unmap_single: %12ld calls  %12ld pages (avg %d/1000)\n",
1943                 buf, min, max,
1944                 (int) ((max * 1000)/min));
1945
1946         sprintf(buf, "%spci_map_sg()    : %12ld calls  %12ld pages (avg %d/1000)\n",
1947                 buf, ioc->msg_calls, ioc->msg_pages,
1948                 (int) ((ioc->msg_pages * 1000)/ioc->msg_calls));
1949
1950         sprintf(buf, "%spci_unmap_sg()  : %12ld calls  %12ld pages (avg %d/1000)\n",
1951                 buf, ioc->usg_calls, ioc->usg_pages,
1952                 (int) ((ioc->usg_pages * 1000)/ioc->usg_calls));
1953 #endif
1954
1955         return strlen(buf);
1956 }
1957
1958 #if 0
1959 /* XXX too much output - exceeds 4k limit and needs to be re-written */
1960 static int
1961 sba_resource_map(char *buf, char **start, off_t offset, int len)
1962 {
1963         struct sba_device *sba_dev = sba_list;
1964         struct ioc *ioc = &sba_dev->ioc[0];     /* FIXME: Mutli-IOC suppoer! */
1965         unsigned int *res_ptr = (unsigned int *)ioc->res_map;
1966         int i;
1967
1968         buf[0] = '\0';
1969         for(i = 0; i < (ioc->res_size / sizeof(unsigned int)); ++i, ++res_ptr) {
1970                 if ((i & 7) == 0)
1971                     strcat(buf,"\n   ");
1972                 sprintf(buf, "%s %08x", buf, *res_ptr);
1973         }
1974         strcat(buf, "\n");
1975
1976         return strlen(buf);
1977 }
1978 #endif /* 0 */
1979 #endif /* CONFIG_PROC_FS */
1980
1981 static struct parisc_device_id sba_tbl[] = {
1982         { HPHW_IOA, HVERSION_REV_ANY_ID, ASTRO_RUNWAY_PORT, 0xb },
1983         { HPHW_BCPORT, HVERSION_REV_ANY_ID, IKE_MERCED_PORT, 0xc },
1984         { HPHW_BCPORT, HVERSION_REV_ANY_ID, REO_MERCED_PORT, 0xc },
1985         { HPHW_BCPORT, HVERSION_REV_ANY_ID, REOG_MERCED_PORT, 0xc },
1986         { HPHW_IOA, HVERSION_REV_ANY_ID, PLUTO_MCKINLEY_PORT, 0xc },
1987 /* These two entries commented out because we don't find them in a
1988  * buswalk yet.  If/when we do, they would cause us to think we had
1989  * many more SBAs then we really do.
1990  *      { HPHW_BCPORT, HVERSION_REV_ANY_ID, ASTRO_ROPES_PORT, 0xc },
1991  *      { HPHW_BCPORT, HVERSION_REV_ANY_ID, IKE_ROPES_PORT, 0xc },
1992  */
1993 /* We shall also comment out Pluto Ropes Port since bus walk doesnt
1994  * report it yet. 
1995  *      { HPHW_BCPORT, HVERSION_REV_ANY_ID, PLUTO_ROPES_PORT, 0xc },
1996  */
1997         { 0, }
1998 };
1999
2000 int sba_driver_callback(struct parisc_device *);
2001
2002 static struct parisc_driver sba_driver = {
2003         .name =         MODULE_NAME,
2004         .id_table =     sba_tbl,
2005         .probe =        sba_driver_callback,
2006 };
2007
2008 /*
2009 ** Determine if sba should claim this chip (return 0) or not (return 1).
2010 ** If so, initialize the chip and tell other partners in crime they
2011 ** have work to do.
2012 */
2013 int
2014 sba_driver_callback(struct parisc_device *dev)
2015 {
2016         struct sba_device *sba_dev;
2017         u32 func_class;
2018         int i;
2019         char *version;
2020
2021         sba_dump_ranges(dev->hpa);
2022
2023         /* Read HW Rev First */
2024         func_class = READ_REG(dev->hpa + SBA_FCLASS);
2025
2026         if (IS_ASTRO(&dev->id)) {
2027                 unsigned long fclass;
2028                 static char astro_rev[]="Astro ?.?";
2029
2030                 /* Astro is broken...Read HW Rev First */
2031                 fclass = READ_REG(dev->hpa);
2032
2033                 astro_rev[6] = '1' + (char) (fclass & 0x7);
2034                 astro_rev[8] = '0' + (char) ((fclass & 0x18) >> 3);
2035                 version = astro_rev;
2036
2037         } else if (IS_IKE(&dev->id)) {
2038                 static char ike_rev[] = "Ike rev ?";
2039                 ike_rev[8] = '0' + (char) (func_class & 0xff);
2040                 version = ike_rev;
2041         } else if (IS_PLUTO(&dev->id)) {
2042                 static char pluto_rev[]="Pluto ?.?";
2043                 pluto_rev[6] = '0' + (char) ((func_class & 0xf0) >> 4); 
2044                 pluto_rev[8] = '0' + (char) (func_class & 0x0f); 
2045                 version = pluto_rev;
2046         } else {
2047                 static char reo_rev[] = "REO rev ?";
2048                 reo_rev[8] = '0' + (char) (func_class & 0xff);
2049                 version = reo_rev;
2050         }
2051
2052         if (!global_ioc_cnt) {
2053                 global_ioc_cnt = count_parisc_driver(&sba_driver);
2054
2055                 /* Astro and Pluto have one IOC per SBA */
2056                 if ((!IS_ASTRO(&dev->id)) || (!IS_PLUTO(&dev->id)))
2057                         global_ioc_cnt *= 2;
2058         }
2059
2060         printk(KERN_INFO "%s found %s at 0x%lx\n",
2061                 MODULE_NAME, version, dev->hpa);
2062
2063         sba_dev = kmalloc(sizeof(struct sba_device), GFP_KERNEL);
2064         if (NULL == sba_dev) {
2065                 printk(KERN_ERR MODULE_NAME " - couldn't alloc sba_device\n");
2066                 return(1);
2067         }
2068
2069         dev->sysdata = (void *) sba_dev;
2070         memset(sba_dev, 0, sizeof(struct sba_device));
2071
2072         for(i=0; i<MAX_IOC; i++)
2073                 spin_lock_init(&(sba_dev->ioc[i].res_lock));
2074
2075         sba_dev->dev = dev;
2076         sba_dev->hw_rev = func_class;
2077         sba_dev->iodc = &dev->id;
2078         sba_dev->name = dev->name;
2079         sba_dev->sba_hpa = dev->hpa;  /* faster access */
2080
2081         sba_get_pat_resources(sba_dev);
2082         sba_hw_init(sba_dev);
2083         sba_common_init(sba_dev);
2084
2085         hppa_dma_ops = &sba_ops;
2086
2087 #ifdef CONFIG_PROC_FS
2088         if (IS_ASTRO(&dev->id)) {
2089                 create_proc_info_entry("Astro", 0, proc_runway_root, sba_proc_info);
2090         } else if (IS_IKE(&dev->id)) {
2091                 create_proc_info_entry("Ike", 0, proc_runway_root, sba_proc_info);
2092         } else if (IS_PLUTO(&dev->id)) {
2093                 create_proc_info_entry("Pluto", 0, proc_mckinley_root, sba_proc_info);
2094         } else {
2095                 create_proc_info_entry("Reo", 0, proc_runway_root, sba_proc_info);
2096         }
2097 #if 0
2098         create_proc_info_entry("bitmap", 0, proc_runway_root, sba_resource_map);
2099 #endif
2100 #endif
2101         parisc_vmerge_boundary = IOVP_SIZE;
2102         parisc_vmerge_max_size = IOVP_SIZE * BITS_PER_LONG;
2103
2104         return 0;
2105 }
2106
2107 /*
2108 ** One time initialization to let the world know the SBA was found.
2109 ** This is the only routine which is NOT static.
2110 ** Must be called exactly once before pci_init().
2111 */
2112 void __init sba_init(void)
2113 {
2114         register_parisc_driver(&sba_driver);
2115 }
2116
2117
2118 /**
2119  * sba_get_iommu - Assign the iommu pointer for the pci bus controller.
2120  * @dev: The parisc device.
2121  *
2122  * Returns the appropriate IOMMU data for the given parisc PCI controller.
2123  * This is cached and used later for PCI DMA Mapping.
2124  */
2125 void * sba_get_iommu(struct parisc_device *pci_hba)
2126 {
2127         struct parisc_device *sba_dev = parisc_parent(pci_hba);
2128         struct sba_device *sba = sba_dev->dev.driver_data;
2129         char t = sba_dev->id.hw_type;
2130         int iocnum = (pci_hba->hw_path >> 3);   /* rope # */
2131
2132         BUG_ON((t != HPHW_IOA) && (t != HPHW_BCPORT));
2133
2134         return &(sba->ioc[iocnum]);
2135 }
2136
2137
2138 /**
2139  * sba_directed_lmmio - return first directed LMMIO range routed to rope
2140  * @pa_dev: The parisc device.
2141  * @r: resource PCI host controller wants start/end fields assigned.
2142  *
2143  * For the given parisc PCI controller, determine if any direct ranges
2144  * are routed down the corresponding rope.
2145  */
2146 void sba_directed_lmmio(struct parisc_device *pci_hba, struct resource *r)
2147 {
2148         struct parisc_device *sba_dev = parisc_parent(pci_hba);
2149         struct sba_device *sba = sba_dev->dev.driver_data;
2150         char t = sba_dev->id.hw_type;
2151         int i;
2152         int rope = (pci_hba->hw_path & (ROPES_PER_IOC-1));  /* rope # */
2153
2154         if ((t!=HPHW_IOA) && (t!=HPHW_BCPORT))
2155                 BUG();
2156
2157         r->start = r->end = 0;
2158
2159         /* Astro has 4 directed ranges. Not sure about Ike/Pluto/et al */
2160         for (i=0; i<4; i++) {
2161                 int base, size;
2162                 unsigned long reg = sba->sba_hpa + i*0x18;
2163
2164                 base = READ_REG32(reg + LMMIO_DIRECT0_BASE);
2165                 if ((base & 1) == 0)
2166                         continue;       /* not enabled */
2167
2168                 size = READ_REG32(reg + LMMIO_DIRECT0_ROUTE);
2169
2170                 if ((size & (ROPES_PER_IOC-1)) != rope)
2171                         continue;       /* directed down different rope */
2172                 
2173                 r->start = (base & ~1UL) | PCI_F_EXTEND;
2174                 size = ~ READ_REG32(reg + LMMIO_DIRECT0_MASK);
2175                 r->end = r->start + size;
2176         }
2177 }
2178
2179
2180 /**
2181  * sba_distributed_lmmio - return portion of distributed LMMIO range
2182  * @pa_dev: The parisc device.
2183  * @r: resource PCI host controller wants start/end fields assigned.
2184  *
2185  * For the given parisc PCI controller, return portion of distributed LMMIO
2186  * range. The distributed LMMIO is always present and it's just a question
2187  * of the base address and size of the range.
2188  */
2189 void sba_distributed_lmmio(struct parisc_device *pci_hba, struct resource *r )
2190 {
2191         struct parisc_device *sba_dev = parisc_parent(pci_hba);
2192         struct sba_device *sba = sba_dev->dev.driver_data;
2193         char t = sba_dev->id.hw_type;
2194         int base, size;
2195         int rope = (pci_hba->hw_path & (ROPES_PER_IOC-1));  /* rope # */
2196
2197         if ((t!=HPHW_IOA) && (t!=HPHW_BCPORT))
2198                 BUG();
2199
2200         r->start = r->end = 0;
2201
2202         base = READ_REG32(sba->sba_hpa + LMMIO_DIST_BASE);
2203         if ((base & 1) == 0) {
2204                 BUG();  /* Gah! Distr Range wasn't enabled! */
2205                 return;
2206         }
2207
2208         r->start = (base & ~1UL) | PCI_F_EXTEND;
2209
2210         size = (~READ_REG32(sba->sba_hpa + LMMIO_DIST_MASK)) / ROPES_PER_IOC;
2211         r->start += rope * (size + 1);  /* adjust base for this rope */
2212         r->end = r->start + size;
2213 }