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