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