cleanup
[linux-2.4.21-pre4.git] / arch / ppc64 / kernel / pci_dma.c
1 /*
2  * pci_dma.c
3  * Copyright (C) 2001 Mike Corrigan & Dave Engebretsen, IBM Corporation
4  *
5  * Dynamic DMA mapping support.
6  * 
7  * Manages the TCE space assigned to this partition.
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  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  * 
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
22  */
23
24 #include <linux/init.h>
25 #include <linux/types.h>
26 #include <linux/slab.h>
27 #include <linux/mm.h>
28 #include <linux/spinlock.h>
29 #include <linux/string.h>
30 #include <linux/pci.h>
31 #include <asm/io.h>
32 #include <asm/prom.h>
33 #include <asm/rtas.h>
34 #include <asm/ppcdebug.h>
35
36 #include <asm/iSeries/HvCallXm.h>
37 #include <asm/iSeries/LparData.h>
38 #include <asm/pci_dma.h>
39 #include <asm/pci-bridge.h>
40 #include <asm/iSeries/iSeries_pci.h>
41
42 #include <asm/machdep.h>
43
44 #include "pci.h"
45
46 /* #define DEBUG_TCE 1   */
47 /* #define MONITOR_TCE 1 */ /* Turn on to sanity check TCE generation. */
48
49
50 /* Initialize so this guy does not end up in the BSS section.
51  * Only used to pass OF initialization data set in prom.c into the main 
52  * kernel code -- data ultimately copied into tceTables[].
53  */
54 extern struct _of_tce_table of_tce_table[];
55
56 extern struct pci_controller* hose_head;
57 extern struct pci_controller** hose_tail;
58 extern struct list_head iSeries_Global_Device_List;
59
60 struct TceTable   virtBusVethTceTable;  /* Tce table for virtual ethernet */
61 struct TceTable   virtBusVioTceTable;   /* Tce table for virtual I/O */
62
63 struct iSeries_Device_Node iSeries_veth_dev_node = { LogicalSlot: 0xFF, DevTceTable: &virtBusVethTceTable };
64 struct iSeries_Device_Node iSeries_vio_dev_node  = { LogicalSlot: 0xFF, DevTceTable: &virtBusVioTceTable };
65
66 struct pci_dev    iSeries_veth_dev_st = { sysdata: &iSeries_veth_dev_node };
67 struct pci_dev    iSeries_vio_dev_st  = { sysdata: &iSeries_vio_dev_node  };
68
69 struct pci_dev  * iSeries_veth_dev = &iSeries_veth_dev_st;
70 struct pci_dev  * iSeries_vio_dev  = &iSeries_vio_dev_st;
71
72 /* Device TceTable is stored in Device Node */
73 /* struct TceTable * tceTables[256]; */ /* Tce tables for 256 busses
74                                          * Bus 255 is the virtual bus
75                                          * zero indicates no bus defined
76                                          */
77 /* allocates a contiguous range of tces (power-of-2 size) */
78 static inline long alloc_tce_range(struct TceTable *, 
79                                    unsigned order );
80
81 /* allocates a contiguous range of tces (power-of-2 size)
82  * assumes lock already held
83  */
84 static long alloc_tce_range_nolock(struct TceTable *, 
85                                    unsigned order );
86
87 /* frees a contiguous range of tces (power-of-2 size) */
88 static inline void free_tce_range(struct TceTable *, 
89                                   long tcenum, 
90                                   unsigned order );
91
92 /* frees a contiguous rnage of tces (power-of-2 size)
93  * assumes lock already held
94  */
95 void free_tce_range_nolock(struct TceTable *, 
96                            long tcenum, 
97                            unsigned order );
98
99 /* allocates a range of tces and sets them to the pages  */
100 static inline dma_addr_t get_tces( struct TceTable *, 
101                                    unsigned order, 
102                                    void *page, 
103                                    unsigned numPages,
104                                    int direction );
105
106 static long test_tce_range( struct TceTable *, 
107                             long tcenum, 
108                             unsigned order );
109
110 static unsigned fill_scatterlist_sg(struct scatterlist *sg, int nents, 
111                                     dma_addr_t dma_addr, 
112                                     unsigned long numTces );
113
114 static unsigned long num_tces_sg( struct scatterlist *sg, 
115                                   int nents );
116         
117 static dma_addr_t create_tces_sg( struct TceTable *tbl, 
118                                   struct scatterlist *sg, 
119                                   int nents, 
120                                   unsigned numTces,
121                                   int direction );
122
123 static void getTceTableParmsiSeries(struct iSeries_Device_Node* DevNode,
124                                       struct TceTable *tce_table_parms );
125
126 static void getTceTableParmsPSeries( struct pci_controller *phb, 
127                                      struct device_node *dn,
128                                      struct TceTable *tce_table_parms );
129
130 static void getTceTableParmsPSeriesLP(struct pci_controller *phb,
131                                     struct device_node *dn,
132                                     struct TceTable *newTceTable );
133
134 static struct TceTable* findHwTceTable(struct TceTable * newTceTable );
135
136 void create_pci_bus_tce_table( unsigned long token );
137
138 u8 iSeries_Get_Bus( struct pci_dev * dv )
139 {
140         return 0;
141 }
142
143 static inline struct TceTable *get_tce_table(struct pci_dev *dev)
144 {
145         if (!dev)
146                 dev = ppc64_isabridge_dev;
147         if (!dev)
148                 return NULL;
149         if (systemcfg->platform == PLATFORM_ISERIES_LPAR) {
150                 return ISERIES_DEVNODE(dev)->DevTceTable;
151         } else {
152                 return PCI_GET_DN(dev)->tce_table;
153         }
154 }
155
156 static unsigned long __inline__ count_leading_zeros64( unsigned long x )
157 {
158         unsigned long lz;
159         asm("cntlzd %0,%1" : "=r"(lz) : "r"(x));
160         return lz;
161 }
162
163 static void tce_build_iSeries(struct TceTable *tbl, long tcenum, 
164                                unsigned long uaddr, int direction )
165 {
166         u64 setTceRc;
167         union Tce tce;
168         
169         PPCDBG(PPCDBG_TCE, "build_tce: uaddr = 0x%lx\n", uaddr);
170         PPCDBG(PPCDBG_TCE, "\ttcenum = 0x%lx, tbl = 0x%lx, index=%lx\n", 
171                tcenum, tbl, tbl->index);
172
173         tce.wholeTce = 0;
174         tce.tceBits.rpn = (virt_to_absolute(uaddr)) >> PAGE_SHIFT;
175
176         /* If for virtual bus */
177         if ( tbl->tceType == TCE_VB ) {
178                 tce.tceBits.valid = 1;
179                 tce.tceBits.allIo = 1;
180                 if ( direction != PCI_DMA_TODEVICE )
181                         tce.tceBits.readWrite = 1;
182         } else {
183                 /* If for PCI bus */
184                 tce.tceBits.readWrite = 1; // Read allowed 
185                 if ( direction != PCI_DMA_TODEVICE )
186                         tce.tceBits.pciWrite = 1;
187         }
188
189         setTceRc = HvCallXm_setTce((u64)tbl->index, 
190                                    (u64)tcenum, 
191                                    tce.wholeTce );
192         if(setTceRc) {
193                 panic("PCI_DMA: HvCallXm_setTce failed, Rc: 0x%lx\n", setTceRc);
194         }
195 }
196
197 static void tce_build_pSeries(struct TceTable *tbl, long tcenum, 
198                                unsigned long uaddr, int direction )
199 {
200         union Tce tce;
201         union Tce *tce_addr;
202         
203         PPCDBG(PPCDBG_TCE, "build_tce: uaddr = 0x%lx\n", uaddr);
204         PPCDBG(PPCDBG_TCE, "\ttcenum = 0x%lx, tbl = 0x%lx, index=%lx\n", 
205                tcenum, tbl, tbl->index);
206
207         tce.wholeTce = 0;
208         tce.tceBits.rpn = (virt_to_absolute(uaddr)) >> PAGE_SHIFT;
209
210         tce.tceBits.readWrite = 1; // Read allowed 
211         if ( direction != PCI_DMA_TODEVICE ) tce.tceBits.pciWrite = 1;
212
213         tce_addr = ((union Tce *)tbl->base) + tcenum;
214         *tce_addr = (union Tce)tce.wholeTce;
215
216 }
217
218 /* 
219  * Build a TceTable structure.  This contains a multi-level bit map which
220  * is used to manage allocation of the tce space.
221  */
222 static struct TceTable *build_tce_table( struct TceTable * tbl )
223 {
224         unsigned long bits, bytes, totalBytes;
225         unsigned long numBits[NUM_TCE_LEVELS], numBytes[NUM_TCE_LEVELS];
226         unsigned i, k, m;
227         unsigned char * pos, * p, b;
228
229         PPCDBG(PPCDBG_TCEINIT, "build_tce_table: tbl = 0x%lx\n", tbl);
230         spin_lock_init( &(tbl->lock) );
231         
232         tbl->mlbm.maxLevel = 0;
233
234         /* Compute number of bits and bytes for each level of the
235          * multi-level bit map
236          */ 
237         totalBytes = 0;
238         bits = tbl->size * (PAGE_SIZE / sizeof( union Tce ));
239         
240         for ( i=0; i<NUM_TCE_LEVELS; ++i ) {
241                 bytes = ((bits+63)/64) * 8;
242                 PPCDBG(PPCDBG_TCEINIT, "build_tce_table: level %d bits=%ld, bytes=%ld\n", i, bits, bytes );
243                 numBits[i] = bits;
244                 numBytes[i] = bytes;
245                 bits /= 2;
246                 totalBytes += bytes;
247         }
248         PPCDBG(PPCDBG_TCEINIT, "build_tce_table: totalBytes=%ld\n", totalBytes );
249         
250         pos = (char *)__get_free_pages( GFP_ATOMIC, get_order( totalBytes ));
251  
252         if ( pos == NULL ) {
253                 panic("PCI_DMA: Allocation failed in build_tce_table!\n");
254         }
255
256         /* For each level, fill in the pointer to the bit map,
257          * and turn on the last bit in the bit map (if the
258          * number of bits in the map is odd).  The highest
259          * level will get all of its bits turned on.
260          */
261         memset( pos, 0, totalBytes );
262         for (i=0; i<NUM_TCE_LEVELS; ++i) {
263                 if ( numBytes[i] ) {
264                         tbl->mlbm.level[i].map = pos;
265                         tbl->mlbm.maxLevel = i;
266
267                         if ( numBits[i] & 1 ) {
268                                 p = pos + numBytes[i] - 1;
269                                 m = (( numBits[i] % 8) - 1) & 7;
270                                 *p = 0x80 >> m;
271                                 PPCDBG(PPCDBG_TCEINIT, "build_tce_table: level %d last bit %x\n", i, 0x80>>m );
272                         }
273                 }
274                 else
275                         tbl->mlbm.level[i].map = 0;
276                 pos += numBytes[i];
277                 tbl->mlbm.level[i].numBits = numBits[i];
278                 tbl->mlbm.level[i].numBytes = numBytes[i];
279         }
280
281         /* For the highest level, turn on all the bits */
282         
283         i = tbl->mlbm.maxLevel;
284         p = tbl->mlbm.level[i].map;
285         m = numBits[i];
286         PPCDBG(PPCDBG_TCEINIT, "build_tce_table: highest level (%d) has all bits set\n", i);
287         for (k=0; k<numBytes[i]; ++k) {
288                 if ( m >= 8 ) {
289                         /* handle full bytes */
290                         *p++ = 0xff;
291                         m -= 8;
292                 }
293                 else if(m>0) {
294                         /* handle the last partial byte */
295                         b = 0x80;
296                         *p = 0;
297                         while (m) {
298                                 *p |= b;
299                                 b >>= 1;
300                                 --m;
301                         }
302                 } else {
303                         break;
304                 }
305         }
306
307         return tbl;
308 }
309
310 static inline long alloc_tce_range( struct TceTable *tbl, unsigned order )
311 {
312         long retval;
313         unsigned long flags;
314         
315         /* Lock the tce allocation bitmap */
316         spin_lock_irqsave( &(tbl->lock), flags );
317
318         /* Do the actual work */
319         retval = alloc_tce_range_nolock( tbl, order );
320         
321         /* Unlock the tce allocation bitmap */
322         spin_unlock_irqrestore( &(tbl->lock), flags );
323
324         return retval;
325 }
326
327 static long alloc_tce_range_nolock( struct TceTable *tbl, unsigned order )
328 {
329         unsigned long numBits, numBytes;
330         unsigned long i, bit, block, mask;
331         long tcenum;
332         u64 * map;
333
334         /* If the order (power of 2 size) requested is larger than our
335          * biggest, indicate failure
336          */
337         if(order >= NUM_TCE_LEVELS) {
338                 /* This can happen if block of TCE's are not found. This code      */
339                 /*  maybe in a recursive loop looking up the bit map for the range.*/
340                 panic("PCI_DMA: alloc_tce_range_nolock: invalid order: %d\n",order);
341         }
342         
343         numBits =  tbl->mlbm.level[order].numBits;
344         numBytes = tbl->mlbm.level[order].numBytes;
345         map =      (u64 *)tbl->mlbm.level[order].map;
346
347         /* Initialize return value to -1 (failure) */
348         tcenum = -1;
349
350         /* Loop through the bytes of the bitmap */
351         for (i=0; i<numBytes/8; ++i) {
352                 if ( *map ) {
353                         /* A free block is found, compute the block
354                          * number (of this size)
355                          */
356                         bit = count_leading_zeros64( *map );
357                         block = (i * 64) + bit;    /* Bit count to free entry */
358
359                         /* turn off the bit in the map to indicate
360                          * that the block is now in use
361                          */
362                         mask = 0x1UL << (63 - bit);
363                         *map &= ~mask;
364
365                         /* compute the index into our tce table for
366                          * the first tce in the block
367                          */
368                         PPCDBG(PPCDBG_TCE, "alloc_tce_range_nolock: allocating block %ld, (byte=%ld, bit=%ld) order %d\n", block, i, bit, order );
369                         tcenum = block << order;
370                         return tcenum;
371                 }
372                 ++map;
373         }
374
375 #ifdef DEBUG_TCE
376         if ( tcenum == -1 ) {
377                 PPCDBG(PPCDBG_TCE, "alloc_tce_range_nolock: no available blocks of order = %d\n", order );
378                 if ( order < tbl->mlbm.maxLevel ) {
379                         PPCDBG(PPCDBG_TCE, "alloc_tce_range_nolock: trying next bigger size\n" );
380                 }
381                 else {
382                         panic("PCI_DMA: alloc_tce_range_nolock: maximum size reached...failing\n");
383                 }
384         }
385 #endif  
386         
387         /* If no block of the requested size was found, try the next
388          * size bigger.  If one of those is found, return the second
389          * half of the block to freespace and keep the first half
390          */
391         if((tcenum == -1) && (order < (NUM_TCE_LEVELS - 1))) {
392                 tcenum = alloc_tce_range_nolock( tbl, order+1 );
393                 if ( tcenum != -1 ) {
394                         free_tce_range_nolock( tbl, tcenum+(1<<order), order );
395                 }
396         }
397         
398         /* Return the index of the first tce in the block
399          * (or -1 if we failed)
400          */
401         return tcenum;
402 }
403
404 static inline void free_tce_range(struct TceTable *tbl, 
405                                   long tcenum, unsigned order )
406 {
407         unsigned long flags;
408
409         /* Lock the tce allocation bitmap */
410         spin_lock_irqsave( &(tbl->lock), flags );
411
412         /* Do the actual work */
413         free_tce_range_nolock( tbl, tcenum, order );
414         
415         /* Unlock the tce allocation bitmap */
416         spin_unlock_irqrestore( &(tbl->lock), flags );
417
418 }
419
420 void free_tce_range_nolock(struct TceTable *tbl, 
421                            long tcenum, unsigned order )
422 {
423         unsigned long block;
424         unsigned byte, bit, mask, b;
425         unsigned char  * map, * bytep;
426
427         if (order >= NUM_TCE_LEVELS) {
428                 panic("PCI_DMA: free_tce_range: invalid order: 0x%x\n",order);
429                 return;
430         }
431
432         block = tcenum >> order;
433
434 #ifdef MONITOR_TCE
435         if ( tcenum != (block << order ) ) {
436                 printk("PCI_DMA: Free_tce_range: tcenum %lx misaligned for order %x\n",tcenum, order);
437                 return;
438         }
439         if ( block >= tbl->mlbm.level[order].numBits ) {
440                 printk("PCI_DMA: Free_tce_range: tcenum %lx is outside the range of this map (order %x, numBits %lx\n", 
441                        tcenum, order, tbl->mlbm.level[order].numBits );
442                 return;
443         }
444         if ( test_tce_range( tbl, tcenum, order ) ) {
445                 printk("PCI_DMA: Freeing range not allocated: tTceTable %p, tcenum %lx, order %x\n",tbl, tcenum, order );
446                 return;
447         }
448 #endif
449
450         map = tbl->mlbm.level[order].map;
451         byte  = block / 8;
452         bit   = block % 8;
453         mask  = 0x80 >> bit;
454         bytep = map + byte;
455
456 #ifdef DEBUG_TCE
457         PPCDBG(PPCDBG_TCE,"free_tce_range_nolock: freeing block %ld (byte=%d, bit=%d) of order %d\n",
458                block, byte, bit, order);
459 #endif  
460
461 #ifdef MONITOR_TCE
462         if ( *bytep & mask ) {
463                 panic("PCI_DMA: Tce already free: TceTable %p, tcenum %lx, order %x\n",tbl,tcenum,order);
464         }
465 #endif  
466
467         *bytep |= mask;
468
469         /* If there is a higher level in the bit map than this we may be
470          * able to buddy up this block with its partner.
471          *   If this is the highest level we can't buddy up
472          *   If this level has an odd number of bits and
473          *      we are freeing the last block we can't buddy up
474          * Don't buddy up if it's in the first 1/4 of the level
475          */
476         if (( order < tbl->mlbm.maxLevel ) &&
477             ( block > (tbl->mlbm.level[order].numBits/4) ) &&
478             (( block < tbl->mlbm.level[order].numBits-1 ) ||
479               ( 0 == ( tbl->mlbm.level[order].numBits & 1)))) {
480                 /* See if we can buddy up the block we just freed */
481                 bit  &= 6;              /* get to the first of the buddy bits */
482                 mask  = 0xc0 >> bit;    /* build two bit mask */
483                 b     = *bytep & mask;  /* Get the two bits */
484                 if ( 0 == (b ^ mask) ) { /* If both bits are on */
485                         /* both of the buddy blocks are free we can combine them */
486                         *bytep ^= mask; /* turn off the two bits */
487                         block = ( byte * 8 ) + bit; /* block of first of buddies */
488                         tcenum = block << order;
489                         /* free the buddied block */
490                         PPCDBG(PPCDBG_TCE, 
491                                "free_tce_range: buddying blocks %ld & %ld\n",
492                                block, block+1);
493                         free_tce_range_nolock( tbl, tcenum, order+1 ); 
494                 }       
495         }
496 }
497
498 static long test_tce_range( struct TceTable *tbl, long tcenum, unsigned order )
499 {
500         unsigned long block;
501         unsigned byte, bit, mask, b;
502         long    retval, retLeft, retRight;
503         unsigned char  * map;
504         
505         map = tbl->mlbm.level[order].map;
506         block = tcenum >> order;
507         byte = block / 8;               /* Byte within bitmap */
508         bit  = block % 8;               /* Bit within byte */
509         mask = 0x80 >> bit;             
510         b    = (*(map+byte) & mask );   /* 0 if block is allocated, else free */
511         if ( b ) 
512                 retval = 1;             /* 1 == block is free */
513         else
514                 retval = 0;             /* 0 == block is allocated */
515         /* Test bits at all levels below this to ensure that all agree */
516
517         if (order) {
518                 retLeft  = test_tce_range( tbl, tcenum, order-1 );
519                 retRight = test_tce_range( tbl, tcenum+(1<<(order-1)), order-1 );
520                 if ( retLeft || retRight ) {
521                         retval = 2;             
522                 }
523         }
524
525         /* Test bits at all levels above this to ensure that all agree */
526         
527         return retval;
528 }
529
530 static inline dma_addr_t get_tces( struct TceTable *tbl, unsigned order, void *page, unsigned numPages, int direction )
531 {
532         long tcenum;
533         unsigned long uaddr;
534         unsigned i;
535         dma_addr_t retTce = NO_TCE;
536
537         uaddr = (unsigned long)page & PAGE_MASK;
538         
539         /* Allocate a range of tces */
540         tcenum = alloc_tce_range( tbl, order );
541         if ( tcenum != -1 ) {
542                 /* We got the tces we wanted */
543                 tcenum += tbl->startOffset;     /* Offset into real TCE table */
544                 retTce = tcenum << PAGE_SHIFT;  /* Set the return dma address */
545                 /* Setup a tce for each page */
546                 for (i=0; i<numPages; ++i) {
547                         ppc_md.tce_build(tbl, tcenum, uaddr, direction); 
548                         ++tcenum;
549                         uaddr += PAGE_SIZE;
550                 }
551                 /* Make sure the update is visible to hardware. 
552                    sync required to synchronize the update to 
553                    the TCE table with the MMIO that will send
554                    the bus address to the IOA */
555                 __asm__ __volatile__ ("sync" : : : "memory");
556         }
557         else {
558                 panic("PCI_DMA: Tce Allocation failure in get_tces. 0x%p\n",tbl);
559         }
560
561         return retTce; 
562 }
563
564 static void tce_free_one_iSeries( struct TceTable *tbl, long tcenum )
565 {
566         u64 set_tce_rc;
567         union Tce tce;
568         tce.wholeTce = 0;
569         set_tce_rc = HvCallXm_setTce((u64)tbl->index,
570                                    (u64)tcenum,
571                                    tce.wholeTce);
572         if ( set_tce_rc ) 
573                 panic("PCI_DMA: HvCallXm_setTce failed, Rc: 0x%lx\n", set_tce_rc);
574
575 }
576
577 static void tce_free_one_pSeries( struct TceTable *tbl, long tcenum )
578 {
579         union Tce tce;
580         union Tce *tce_addr;
581
582         tce.wholeTce = 0;
583
584         tce_addr  = ((union Tce *)tbl->base) + tcenum;
585         *tce_addr = (union Tce)tce.wholeTce;
586
587 }
588
589 static void tce_free(struct TceTable *tbl, dma_addr_t dma_addr, 
590                              unsigned order, unsigned num_pages)
591 {
592         long tcenum, total_tces, free_tce;
593         unsigned i;
594
595         total_tces = (tbl->size * (PAGE_SIZE / sizeof(union Tce)));
596         
597         tcenum = dma_addr >> PAGE_SHIFT;
598         free_tce = tcenum - tbl->startOffset;
599
600         if ( ( (free_tce + num_pages) > total_tces ) ||
601              ( tcenum < tbl->startOffset ) ) {
602                 printk("tce_free: invalid tcenum\n");
603                 printk("\ttcenum    = 0x%lx\n", tcenum); 
604                 printk("\tTCE Table = 0x%lx\n", (u64)tbl);
605                 printk("\tbus#      = 0x%lx\n", (u64)tbl->busNumber );
606                 printk("\tsize      = 0x%lx\n", (u64)tbl->size);
607                 printk("\tstartOff  = 0x%lx\n", (u64)tbl->startOffset );
608                 printk("\tindex     = 0x%lx\n", (u64)tbl->index);
609                 return;
610         }
611         
612         for (i=0; i<num_pages; ++i) {
613                 ppc_md.tce_free_one(tbl, tcenum);
614                 ++tcenum;
615         }
616
617         /* No sync (to make TCE change visible) is required here.
618            The lwsync when acquiring the lock in free_tce_range
619            is sufficient to synchronize with the bitmap.
620         */
621
622         free_tce_range( tbl, free_tce, order );
623 }
624
625 void __init create_virtual_bus_tce_table(void)
626 {
627         struct TceTable *t;
628         struct TceTableManagerCB virtBusTceTableParms;
629         u64 absParmsPtr;
630
631         virtBusTceTableParms.busNumber = 255;   /* Bus 255 is the virtual bus */
632         virtBusTceTableParms.virtualBusFlag = 0xff; /* Ask for virtual bus */
633         
634         absParmsPtr = virt_to_absolute( (u64)&virtBusTceTableParms );
635         HvCallXm_getTceTableParms( absParmsPtr );
636         
637         virtBusVethTceTable.size = virtBusTceTableParms.size / 2;
638         virtBusVethTceTable.busNumber = virtBusTceTableParms.busNumber;
639         virtBusVethTceTable.startOffset = virtBusTceTableParms.startOffset;
640         virtBusVethTceTable.index = virtBusTceTableParms.index;
641         virtBusVethTceTable.tceType = TCE_VB;
642
643         virtBusVioTceTable.size = virtBusTceTableParms.size - virtBusVethTceTable.size;
644         virtBusVioTceTable.busNumber = virtBusTceTableParms.busNumber;
645         virtBusVioTceTable.startOffset = virtBusTceTableParms.startOffset +
646                         virtBusVethTceTable.size * (PAGE_SIZE/sizeof(union Tce));
647         virtBusVioTceTable.index = virtBusTceTableParms.index;
648         virtBusVioTceTable.tceType = TCE_VB; 
649
650         t = build_tce_table( &virtBusVethTceTable );
651         if ( t ) {
652                 /* tceTables[255] = t; */
653                 //VirtBusVethTceTable = t;
654                 printk( "Virtual Bus VETH TCE table built successfully.\n");
655                 printk( "  TCE table size = %ld entries\n", 
656                                 (unsigned long)t->size*(PAGE_SIZE/sizeof(union Tce)) );
657                 printk( "  TCE table token = %d\n",
658                                 (unsigned)t->index );
659                 printk( "  TCE table start entry = 0x%lx\n",
660                                 (unsigned long)t->startOffset );
661         }
662         else printk( "Virtual Bus VETH TCE table failed.\n");
663
664         t = build_tce_table( &virtBusVioTceTable );
665         if ( t ) {
666                 //VirtBusVioTceTable = t;
667                 printk( "Virtual Bus VIO TCE table built successfully.\n");
668                 printk( "  TCE table size = %ld entries\n", 
669                                 (unsigned long)t->size*(PAGE_SIZE/sizeof(union Tce)) );
670                 printk( "  TCE table token = %d\n",
671                                 (unsigned)t->index );
672                 printk( "  TCE table start entry = 0x%lx\n",
673                                 (unsigned long)t->startOffset );
674         }
675         else printk( "Virtual Bus VIO TCE table failed.\n");
676 }
677
678 void create_tce_tables_for_buses(struct list_head *bus_list)
679 {
680         struct pci_controller* phb;
681         struct device_node *dn, *first_dn;
682         int num_slots, num_slots_ilog2;
683         int first_phb = 1;
684
685         for (phb=hose_head;phb;phb=phb->next) {
686                 first_dn = ((struct device_node *)phb->arch_data)->child;
687                 /* Carve 2GB into the largest dma_window_size possible */
688                 for (dn = first_dn, num_slots = 0; dn != NULL; dn = dn->sibling)
689                         num_slots++;
690                 num_slots_ilog2 = __ilog2(num_slots);
691                 if ((1<<num_slots_ilog2) != num_slots)
692                         num_slots_ilog2++;
693                 phb->dma_window_size = 1 << (22 - num_slots_ilog2);
694                 /* Reserve 16MB of DMA space on the first PHB.
695                  * We should probably be more careful and use firmware props.
696                  * In reality this space is remapped, not lost.  But we don't
697                  * want to get that smart to handle it -- too much work.
698                  */
699                 phb->dma_window_base_cur = first_phb ? (1 << 12) : 0;
700                 first_phb = 0;
701                 for (dn = first_dn, num_slots = 0; dn != NULL; dn = dn->sibling) {
702                         create_pci_bus_tce_table((unsigned long)dn);
703                 }
704         }
705 }
706
707 void create_tce_tables_for_busesLP(struct list_head *bus_list)
708 {
709         struct list_head *ln;
710         struct pci_bus *bus;
711         struct device_node *busdn;
712         u32 *dma_window;
713         for (ln=bus_list->next; ln != bus_list; ln=ln->next) {
714                 bus = pci_bus_b(ln);
715                 busdn = PCI_GET_DN(bus);
716                 /* NOTE: there should never be a window declared on a bus when
717                  * child devices also have a window.  If this should ever be
718                  * architected, we probably want children to have priority.
719                  * In reality, the PHB containing ISA has the property, but otherwise
720                  * it is the pci-bridges that have the property.
721                  */
722                 dma_window = (u32 *)get_property(busdn, "ibm,dma-window", 0);
723                 if (dma_window) {
724                         /* Busno hasn't been copied yet.
725                          * Do it now because getTceTableParmsPSeriesLP needs it.
726                          */
727                         busdn->busno = bus->number;
728                         create_pci_bus_tce_table((unsigned long)busdn);
729                 } else
730                         create_tce_tables_for_busesLP(&bus->children);
731         }
732 }
733
734 void create_tce_tables(void) {
735         struct pci_dev *dev;
736         struct device_node *dn, *mydn;
737
738         if (systemcfg->platform == PLATFORM_PSERIES_LPAR) {
739                 create_tce_tables_for_busesLP(&pci_root_buses);
740         }
741         else {
742                 create_tce_tables_for_buses(&pci_root_buses);
743         }
744         /* Now copy the tce_table ptr from the bus devices down to every
745          * pci device_node.  This means get_tce_table() won't need to search
746          * up the device tree to find it.
747          */
748         pci_for_each_dev(dev) {
749                 mydn = dn = PCI_GET_DN(dev);
750                 while (dn && dn->tce_table == NULL)
751                         dn = dn->parent;
752                 if (dn) {
753                         mydn->tce_table = dn->tce_table;
754                 }
755         }
756 }
757
758
759 /*
760  * iSeries token = iSeries_device_Node*
761  * pSeries token = pci_controller*
762  *
763  */
764 void create_pci_bus_tce_table( unsigned long token ) {
765         struct TceTable * newTceTable;
766
767         PPCDBG(PPCDBG_TCE, "Entering create_pci_bus_tce_table.\n");
768         PPCDBG(PPCDBG_TCE, "\ttoken = 0x%lx\n", token);
769
770         newTceTable = (struct TceTable *)kmalloc( sizeof(struct TceTable), GFP_KERNEL );
771
772         /*****************************************************************/
773         /* For the iSeries machines, the HvTce Table can be one of three */
774         /* flavors,                                                      */
775         /* - Single bus TCE table,                                       */
776         /* - Tce Table Share between buses,                              */
777         /* - Tce Table per logical slot.                                 */
778         /*****************************************************************/
779         if(systemcfg->platform == PLATFORM_ISERIES_LPAR) {
780
781                 struct iSeries_Device_Node* DevNode = (struct iSeries_Device_Node*)token;
782                 getTceTableParmsiSeries(DevNode,newTceTable);
783
784                 /* Look for existing TCE table for this device.          */
785                 DevNode->DevTceTable = findHwTceTable(newTceTable );
786                 if( DevNode->DevTceTable == NULL) {
787                         DevNode->DevTceTable = build_tce_table( newTceTable );
788                 }
789                 else {
790                     /* We're using a shared table, free this new one.    */
791                     kfree(newTceTable);
792                 }
793                 printk("Pci Device 0x%p TceTable: %p\n",DevNode,DevNode->DevTceTable);
794                 return;
795         }
796         /* pSeries Leg */
797         else {
798                 struct device_node *dn;
799                 struct pci_controller *phb;
800
801                 dn = (struct device_node *)token;
802                 phb = dn->phb;
803                 if (systemcfg->platform == PLATFORM_PSERIES)
804                         getTceTableParmsPSeries(phb, dn, newTceTable);
805                 else
806                         getTceTableParmsPSeriesLP(phb, dn, newTceTable);
807
808                 dn->tce_table  = build_tce_table( newTceTable );
809         }
810 }
811
812 /***********************************************************************/
813 /* This function compares the known Tce tables to find a TceTable that */
814 /* has already been built for hardware TCEs.                           */
815 /* Search the complete(all devices) for a TCE table assigned.  If the  */
816 /* startOffset, index, and size match, then the TCE for this device has*/
817 /* already been built and it should be shared with this device         */
818 /***********************************************************************/
819 static struct TceTable* findHwTceTable(struct TceTable * newTceTable )
820 {
821         struct list_head* Device_Node_Ptr    = iSeries_Global_Device_List.next;
822         /* Cache the compare values. */
823         u64  startOffset = newTceTable->startOffset;
824         u64  index       = newTceTable->index;
825         u64  size        = newTceTable->size;
826
827         while(Device_Node_Ptr != &iSeries_Global_Device_List) {
828                 struct iSeries_Device_Node* CmprNode = (struct iSeries_Device_Node*)Device_Node_Ptr;
829                 if( CmprNode->DevTceTable != NULL &&
830                     CmprNode->DevTceTable->tceType == TCE_PCI) {
831                         if( CmprNode->DevTceTable->startOffset == startOffset &&
832                             CmprNode->DevTceTable->index       == index       &&
833                             CmprNode->DevTceTable->size        == size        ) {
834                                 printk("PCI TCE table matches 0x%p \n",CmprNode->DevTceTable);
835                                 return CmprNode->DevTceTable;
836                         }
837                 }
838                 /* Get next Device Node in List             */
839                 Device_Node_Ptr = Device_Node_Ptr->next;
840         }
841         return NULL;
842 }
843
844 /***********************************************************************/
845 /* Call Hv with the architected data structure to get TCE table info.  */
846 /* info. Put the returned data into the Linux representation of the    */
847 /* TCE table data.                                                     */
848 /* The Hardware Tce table comes in three flavors.                      */ 
849 /* 1. TCE table shared between Buses.                                  */
850 /* 2. TCE table per Bus.                                               */
851 /* 3. TCE Table per IOA.                                               */
852 /***********************************************************************/
853 static void getTceTableParmsiSeries(struct iSeries_Device_Node* DevNode,
854                                     struct TceTable* newTceTable )
855 {
856         struct TceTableManagerCB* pciBusTceTableParms = (struct TceTableManagerCB*)kmalloc( sizeof(struct TceTableManagerCB), GFP_KERNEL );
857         if(pciBusTceTableParms == NULL) panic("PCI_DMA: TCE Table Allocation failed.");
858
859         memset( (void*)pciBusTceTableParms,0,sizeof(struct TceTableManagerCB) );
860         pciBusTceTableParms->busNumber      = ISERIES_BUS(DevNode);
861         pciBusTceTableParms->logicalSlot    = DevNode->LogicalSlot;
862         pciBusTceTableParms->virtualBusFlag = 0;
863
864         HvCallXm_getTceTableParms( REALADDR(pciBusTceTableParms) );
865
866         /* PciTceTableParms Bus:0x18 Slot:0x04 Start:0x000000 Offset:0x04c000 Size:0x0020 */
867         printk("PciTceTableParms Bus:0x%02lx Slot:0x%02x Start:0x%06lx Offset:0x%06lx Size:0x%04lx\n",
868                pciBusTceTableParms->busNumber,
869                pciBusTceTableParms->logicalSlot,
870                pciBusTceTableParms->start,
871                pciBusTceTableParms->startOffset,
872                pciBusTceTableParms->size);
873
874         if(pciBusTceTableParms->size == 0) {
875                 printk("PCI_DMA: Possible Structure mismatch, 0x%p\n",pciBusTceTableParms);
876                 panic( "PCI_DMA: pciBusTceTableParms->size is zero, halt here!");
877         }
878
879         newTceTable->size        = pciBusTceTableParms->size;
880         newTceTable->busNumber   = pciBusTceTableParms->busNumber;
881         newTceTable->startOffset = pciBusTceTableParms->startOffset;
882         newTceTable->index       = pciBusTceTableParms->index;
883         newTceTable->tceType     = TCE_PCI;
884
885         kfree(pciBusTceTableParms);
886 }
887
888 static void getTceTableParmsPSeries(struct pci_controller *phb,
889                                     struct device_node *dn,
890                                     struct TceTable *newTceTable ) {
891         phandle node;
892         unsigned long i;
893
894         node = ((struct device_node *)(phb->arch_data))->node;
895
896         PPCDBG(PPCDBG_TCEINIT, "getTceTableParms: start\n"); 
897         PPCDBG(PPCDBG_TCEINIT, "\tof_tce_table = 0x%lx\n", of_tce_table); 
898         PPCDBG(PPCDBG_TCEINIT, "\tphb          = 0x%lx\n", phb); 
899         PPCDBG(PPCDBG_TCEINIT, "\tdn           = 0x%lx\n", dn); 
900         PPCDBG(PPCDBG_TCEINIT, "\tdn->name     = %s\n", dn->name); 
901         PPCDBG(PPCDBG_TCEINIT, "\tdn->full_name= %s\n", dn->full_name); 
902         PPCDBG(PPCDBG_TCEINIT, "\tnewTceTable  = 0x%lx\n", newTceTable); 
903         PPCDBG(PPCDBG_TCEINIT, "\tdma_window_size = 0x%lx\n", phb->dma_window_size); 
904
905         i = 0;
906         while(of_tce_table[i].node) {
907                 PPCDBG(PPCDBG_TCEINIT, "\tof_tce_table[%d].node = 0x%lx\n", 
908                        i, of_tce_table[i].node);
909                 PPCDBG(PPCDBG_TCEINIT, "\tof_tce_table[%d].base = 0x%lx\n", 
910                        i, of_tce_table[i].base);
911                 PPCDBG(PPCDBG_TCEINIT, "\tof_tce_table[%d].size = 0x%lx\n", 
912                        i, of_tce_table[i].size >> PAGE_SHIFT);
913                 PPCDBG(PPCDBG_TCEINIT, "\tphb->arch_data->node = 0x%lx\n", 
914                        node);
915
916                 if(of_tce_table[i].node == node) {
917                         memset((void *)of_tce_table[i].base, 
918                                0, of_tce_table[i].size);
919                         newTceTable->busNumber = phb->bus->number;
920
921                         /* Units of tce entries.                        */
922                         newTceTable->startOffset = phb->dma_window_base_cur;
923
924                         /* Adjust the current table offset to the next  */
925                         /* region.  Measured in TCE entries. Force an   */
926                         /* alignment to the size alloted per IOA. This  */
927                         /* makes it easier to remove the 1st 16MB.      */
928                         phb->dma_window_base_cur += (phb->dma_window_size>>3);
929                         phb->dma_window_base_cur &= 
930                                 ~((phb->dma_window_size>>3)-1);
931
932                         /* Set the tce table size - measured in units   */
933                         /* of pages of tce table.                       */
934                         newTceTable->size = ((phb->dma_window_base_cur -
935                                               newTceTable->startOffset) << 3)
936                                               >> PAGE_SHIFT;
937
938                         /* Test if we are going over 2GB of DMA space.  */
939                         if(phb->dma_window_base_cur > (1 << 19)) { 
940                                 panic("PCI_DMA: Unexpected number of IOAs under this PHB.\n"); 
941                         }
942
943                         newTceTable->base = of_tce_table[i].base;
944                         newTceTable->index = 0;
945                         
946                         PPCDBG(PPCDBG_TCEINIT, 
947                                "\tnewTceTable->base        = 0x%lx\n",
948                                newTceTable->base);
949                         PPCDBG(PPCDBG_TCEINIT, 
950                                "\tnewTceTable->startOffset = 0x%lx"
951                                "(# tce entries)\n", 
952                                newTceTable->startOffset);
953                         PPCDBG(PPCDBG_TCEINIT, 
954                                "\tnewTceTable->size        = 0x%lx"
955                                "(# pages of tce table)\n", 
956                                newTceTable->size);
957                 }
958                 i++;
959         }
960 }
961
962 /*
963  * getTceTableParmsPSeriesLP
964  *
965  * Function: On pSeries LPAR systems, return TCE table info, given a pci bus.
966  *
967  * ToDo: properly interpret the ibm,dma-window property.  The definition is:
968  *      logical-bus-number      (1 word)
969  *      phys-address            (#address-cells words)
970  *      size                    (#cell-size words)
971  *
972  * Currently we hard code these sizes (more or less).
973  */
974 static void getTceTableParmsPSeriesLP(struct pci_controller *phb,
975                                     struct device_node *dn,
976                                     struct TceTable *newTceTable ) {
977         u32 *dma_window = (u32 *)get_property(dn, "ibm,dma-window", 0);
978         if (!dma_window) {
979                 panic("PCI_DMA: getTceTableParmsPSeriesLP: device %s has no ibm,dma-window property!\n", dn->full_name);
980         }
981
982         newTceTable->busNumber = dn->busno;
983         newTceTable->size = (((((unsigned long)dma_window[4] << 32) | (unsigned long)dma_window[5]) >> PAGE_SHIFT) << 3) >> PAGE_SHIFT;
984         newTceTable->startOffset = ((((unsigned long)dma_window[2] << 32) | (unsigned long)dma_window[3]) >> 12);
985         newTceTable->base = 0;
986         newTceTable->index = dma_window[0];
987         PPCDBG(PPCDBG_TCEINIT, "getTceTableParmsPSeriesLP for bus 0x%lx:\n", dn->busno);
988         PPCDBG(PPCDBG_TCEINIT, "\tDevice = %s\n", dn->full_name);
989         PPCDBG(PPCDBG_TCEINIT, "\tnewTceTable->index       = 0x%lx\n", newTceTable->index);
990         PPCDBG(PPCDBG_TCEINIT, "\tnewTceTable->startOffset = 0x%lx\n", newTceTable->startOffset);
991         PPCDBG(PPCDBG_TCEINIT, "\tnewTceTable->size        = 0x%lx\n", newTceTable->size);
992 }
993
994 /* Allocates a contiguous real buffer and creates TCEs over it.
995  * Returns the virtual address of the buffer and sets dma_handle
996  * to the dma address (tce) of the first page.
997  */
998 void *pci_alloc_consistent(struct pci_dev *hwdev, size_t size,
999                            dma_addr_t *dma_handle)
1000 {
1001         struct TceTable * tbl;
1002         void *ret = NULL;
1003         unsigned order, nPages;
1004         dma_addr_t tce;
1005
1006         PPCDBG(PPCDBG_TCE, "pci_alloc_consistent:\n");
1007         PPCDBG(PPCDBG_TCE, "\thwdev      = 0x%16.16lx\n", hwdev);
1008         PPCDBG(PPCDBG_TCE, "\tsize       = 0x%16.16lx\n", size);
1009         PPCDBG(PPCDBG_TCE, "\tdma_handle = 0x%16.16lx\n", dma_handle);  
1010
1011         size = PAGE_ALIGN(size);
1012         order = get_order(size);
1013         nPages = 1 << order;
1014
1015         /* Client asked for way to much space.  This is checked later anyway */
1016         /* It is easier to debug here for the drivers than in the tce tables.*/
1017         if(order >= NUM_TCE_LEVELS) {
1018                 printk("PCI_DMA: pci_alloc_consistent size to large: 0x%lx \n",size);
1019                 return (void *)NO_TCE;
1020         }
1021
1022         tbl = get_tce_table(hwdev); 
1023
1024         if ( tbl ) {
1025                 /* Alloc enough pages (and possibly more) */
1026                 ret = (void *)__get_free_pages( GFP_ATOMIC, order );
1027                 if ( ret ) {
1028                         /* Page allocation succeeded */
1029                         memset(ret, 0, nPages << PAGE_SHIFT);
1030                         /* Set up tces to cover the allocated range */
1031                         tce = get_tces( tbl, order, ret, nPages, PCI_DMA_BIDIRECTIONAL );
1032                         if ( tce == NO_TCE ) {
1033                                 PPCDBG(PPCDBG_TCE, "pci_alloc_consistent: get_tces failed\n" );
1034                                 free_pages( (unsigned long)ret, order );
1035                                 ret = NULL;
1036                         }
1037                         else
1038                         {
1039                                 *dma_handle = tce;
1040                         }
1041                 }
1042                 else PPCDBG(PPCDBG_TCE, "pci_alloc_consistent: __get_free_pages failed for order = %d\n", order);
1043         }
1044         else PPCDBG(PPCDBG_TCE, "pci_alloc_consistent: get_tce_table failed for 0x%016lx\n", hwdev);
1045
1046         PPCDBG(PPCDBG_TCE, "\tpci_alloc_consistent: dma_handle = 0x%16.16lx\n", *dma_handle);   
1047         PPCDBG(PPCDBG_TCE, "\tpci_alloc_consistent: return     = 0x%16.16lx\n", ret);   
1048         return ret;
1049 }
1050
1051 void pci_free_consistent(struct pci_dev *hwdev, size_t size,
1052                          void *vaddr, dma_addr_t dma_handle)
1053 {
1054         struct TceTable * tbl;
1055         unsigned order, nPages;
1056         
1057         PPCDBG(PPCDBG_TCE, "pci_free_consistent:\n");
1058         PPCDBG(PPCDBG_TCE, "\thwdev = 0x%16.16lx, size = 0x%16.16lx, dma_handle = 0x%16.16lx, vaddr = 0x%16.16lx\n", hwdev, size, dma_handle, vaddr);   
1059
1060         size = PAGE_ALIGN(size);
1061         order = get_order(size);
1062         nPages = 1 << order;
1063
1064         /* Client asked for way to much space.  This is checked later anyway */
1065         /* It is easier to debug here for the drivers than in the tce tables.*/
1066         if(order >= NUM_TCE_LEVELS) {
1067                 printk("PCI_DMA: pci_free_consistent size to large: 0x%lx \n",size);
1068                 return;
1069         }
1070         
1071         tbl = get_tce_table(hwdev); 
1072
1073         if ( tbl ) {
1074                 tce_free(tbl, dma_handle, order, nPages);
1075                 free_pages( (unsigned long)vaddr, order );
1076         }
1077 }
1078
1079 /* Creates TCEs for a user provided buffer.  The user buffer must be 
1080  * contiguous real kernel storage (not vmalloc).  The address of the buffer
1081  * passed here is the kernel (virtual) address of the buffer.  The buffer
1082  * need not be page aligned, the dma_addr_t returned will point to the same
1083  * byte within the page as vaddr.
1084  */
1085 dma_addr_t pci_map_single(struct pci_dev *hwdev, void *vaddr, 
1086                           size_t size, int direction )
1087 {
1088         struct TceTable * tbl;
1089         dma_addr_t dma_handle = NO_TCE;
1090         unsigned long uaddr;
1091         unsigned order, nPages;
1092
1093         PPCDBG(PPCDBG_TCE, "pci_map_single:\n");
1094         PPCDBG(PPCDBG_TCE, "\thwdev = 0x%16.16lx, size = 0x%16.16lx, direction = 0x%16.16lx, vaddr = 0x%16.16lx\n", hwdev, size, direction, vaddr);     
1095         if ( direction == PCI_DMA_NONE )
1096                 BUG();
1097         
1098         uaddr = (unsigned long)vaddr;
1099         nPages = PAGE_ALIGN( uaddr + size ) - ( uaddr & PAGE_MASK );
1100         order = get_order( nPages & PAGE_MASK );
1101         nPages >>= PAGE_SHIFT;
1102         
1103         /* Client asked for way to much space.  This is checked later anyway */
1104         /* It is easier to debug here for the drivers than in the tce tables.*/
1105         if(order >= NUM_TCE_LEVELS) {
1106                 printk("PCI_DMA: pci_map_single size to large: 0x%lx \n",size);
1107                 return NO_TCE;
1108         }
1109
1110         tbl = get_tce_table(hwdev); 
1111
1112         if ( tbl ) {
1113                 dma_handle = get_tces( tbl, order, vaddr, nPages, direction );
1114                 dma_handle |= ( uaddr & ~PAGE_MASK );
1115         }
1116
1117         return dma_handle;
1118 }
1119
1120 void pci_unmap_single( struct pci_dev *hwdev, dma_addr_t dma_handle, size_t size, int direction )
1121 {
1122         struct TceTable * tbl;
1123         unsigned order, nPages;
1124         
1125         PPCDBG(PPCDBG_TCE, "pci_unmap_single:\n");
1126         PPCDBG(PPCDBG_TCE, "\thwdev = 0x%16.16lx, size = 0x%16.16lx, direction = 0x%16.16lx, dma_handle = 0x%16.16lx\n", hwdev, size, direction, dma_handle);   
1127         if ( direction == PCI_DMA_NONE )
1128                 BUG();
1129
1130         nPages = PAGE_ALIGN( dma_handle + size ) - ( dma_handle & PAGE_MASK );
1131         order = get_order( nPages & PAGE_MASK );
1132         nPages >>= PAGE_SHIFT;
1133
1134         /* Client asked for way to much space.  This is checked later anyway */
1135         /* It is easier to debug here for the drivers than in the tce tables.*/
1136         if(order >= NUM_TCE_LEVELS) {
1137                 printk("PCI_DMA: pci_unmap_single size to large: 0x%lx \n",size);
1138                 return;
1139         }
1140         
1141         tbl = get_tce_table(hwdev); 
1142
1143         if ( tbl ) 
1144                 tce_free(tbl, dma_handle, order, nPages);
1145
1146 }
1147
1148 /* Figure out how many TCEs are actually going to be required
1149  * to map this scatterlist.  This code is not optimal.  It 
1150  * takes into account the case where entry n ends in the same
1151  * page in which entry n+1 starts.  It does not handle the 
1152  * general case of entry n ending in the same page in which 
1153  * entry m starts.   
1154  */
1155 static unsigned long num_tces_sg( struct scatterlist *sg, int nents )
1156 {
1157         unsigned long nTces, numPages, startPage, endPage, prevEndPage;
1158         unsigned i;
1159
1160         prevEndPage = 0;
1161         nTces = 0;
1162
1163         for (i=0; i<nents; ++i) {
1164                 /* Compute the starting page number and
1165                  * the ending page number for this entry
1166                  */
1167                 startPage = (unsigned long)sg->address >> PAGE_SHIFT;
1168                 endPage = ((unsigned long)sg->address + sg->length - 1) >> PAGE_SHIFT;
1169                 numPages = endPage - startPage + 1;
1170                 /* Simple optimization: if the previous entry ended
1171                  * in the same page in which this entry starts
1172                  * then we can reduce the required pages by one.
1173                  * This matches assumptions in fill_scatterlist_sg and
1174                  * create_tces_sg
1175                  */
1176                 if ( startPage == prevEndPage )
1177                         --numPages;
1178                 nTces += numPages;
1179                 prevEndPage = endPage;
1180                 sg++;
1181         }
1182         return nTces;
1183 }
1184
1185 /* Fill in the dma data in the scatterlist
1186  * return the number of dma sg entries created
1187  */
1188 static unsigned fill_scatterlist_sg( struct scatterlist *sg, int nents, 
1189                                  dma_addr_t dma_addr , unsigned long numTces)
1190 {
1191         struct scatterlist *dma_sg;
1192         u32 cur_start_dma;
1193         unsigned long cur_len_dma, cur_end_virt, uaddr;
1194         unsigned num_dma_ents;
1195
1196         dma_sg = sg;
1197         num_dma_ents = 1;
1198
1199         /* Process the first sg entry */
1200         cur_start_dma = dma_addr + ((unsigned long)sg->address & (~PAGE_MASK));
1201         cur_len_dma = sg->length;
1202         /* cur_end_virt holds the address of the byte immediately after the
1203          * end of the current buffer.
1204          */
1205         cur_end_virt = (unsigned long)sg->address + cur_len_dma;
1206         /* Later code assumes that unused sg->dma_address and sg->dma_length
1207          * fields will be zero.  Other archs seem to assume that the user
1208          * (device driver) guarantees that...I don't want to depend on that
1209          */
1210         sg->dma_address = sg->dma_length = 0;
1211         
1212         /* Process the rest of the sg entries */
1213         while (--nents) {
1214                 ++sg;
1215                 /* Clear possibly unused fields. Note: sg >= dma_sg so
1216                  * this can't be clearing a field we've already set
1217                  */
1218                 sg->dma_address = sg->dma_length = 0;
1219
1220                 /* Check if it is possible to make this next entry
1221                  * contiguous (in dma space) with the previous entry.
1222                  */
1223                 
1224                 /* The entries can be contiguous in dma space if
1225                  * the previous entry ends immediately before the
1226                  * start of the current entry (in virtual space)
1227                  * or if the previous entry ends at a page boundary
1228                  * and the current entry starts at a page boundary.
1229                  */
1230                 uaddr = (unsigned long)sg->address;
1231                 if ( ( uaddr != cur_end_virt ) &&
1232                      ( ( ( uaddr | cur_end_virt ) & (~PAGE_MASK) ) ||
1233                        ( ( uaddr & PAGE_MASK ) == ( ( cur_end_virt-1 ) & PAGE_MASK ) ) ) ) {
1234                         /* This entry can not be contiguous in dma space.
1235                          * save the previous dma entry and start a new one
1236                          */
1237                         dma_sg->dma_address = cur_start_dma;
1238                         dma_sg->dma_length  = cur_len_dma;
1239
1240                         ++dma_sg;
1241                         ++num_dma_ents;
1242                         
1243                         cur_start_dma += cur_len_dma-1;
1244                         /* If the previous entry ends and this entry starts
1245                          * in the same page then they share a tce.  In that
1246                          * case don't bump cur_start_dma to the next page 
1247                          * in dma space.  This matches assumptions made in
1248                          * num_tces_sg and create_tces_sg.
1249                          */
1250                         if ((uaddr & PAGE_MASK) == ((cur_end_virt-1) & PAGE_MASK))
1251                                 cur_start_dma &= PAGE_MASK;
1252                         else
1253                                 cur_start_dma = PAGE_ALIGN(cur_start_dma+1);
1254                         cur_start_dma += ( uaddr & (~PAGE_MASK) );
1255                         cur_len_dma = 0;
1256                 }
1257                 /* Accumulate the length of this entry for the next 
1258                  * dma entry
1259                  */
1260                 cur_len_dma += sg->length;
1261                 cur_end_virt = uaddr + sg->length;
1262         }
1263         /* Fill in the last dma entry */
1264         dma_sg->dma_address = cur_start_dma;
1265         dma_sg->dma_length  = cur_len_dma;
1266
1267         if ((((cur_start_dma +cur_len_dma - 1)>> PAGE_SHIFT) - (dma_addr >> PAGE_SHIFT) + 1) != numTces)
1268           {
1269             PPCDBG(PPCDBG_TCE, "fill_scatterlist_sg: numTces %ld, used tces %d\n",
1270                    numTces,
1271                    (unsigned)(((cur_start_dma + cur_len_dma - 1) >> PAGE_SHIFT) - (dma_addr >> PAGE_SHIFT) + 1));
1272           }
1273         
1274
1275         return num_dma_ents;
1276 }
1277
1278 /* Call the hypervisor to create the TCE entries.
1279  * return the number of TCEs created
1280  */
1281 static dma_addr_t create_tces_sg( struct TceTable *tbl, struct scatterlist *sg, 
1282                    int nents, unsigned numTces, int direction )
1283 {
1284         unsigned order, i, j;
1285         unsigned long startPage, endPage, prevEndPage, numPages, uaddr;
1286         long tcenum, starttcenum;
1287         dma_addr_t dmaAddr;
1288
1289         dmaAddr = NO_TCE;
1290
1291         order = get_order( numTces << PAGE_SHIFT );
1292         /* Client asked for way to much space.  This is checked later anyway */
1293         /* It is easier to debug here for the drivers than in the tce tables.*/
1294         if(order >= NUM_TCE_LEVELS) {
1295                 printk("PCI_DMA: create_tces_sg size to large: 0x%x \n",(numTces << PAGE_SHIFT));
1296                 return NO_TCE;
1297         }
1298
1299         /* allocate a block of tces */
1300         tcenum = alloc_tce_range( tbl, order );
1301         if ( tcenum != -1 ) {
1302                 tcenum += tbl->startOffset;
1303                 starttcenum = tcenum;
1304                 dmaAddr = tcenum << PAGE_SHIFT;
1305                 prevEndPage = 0;
1306                 for (j=0; j<nents; ++j) {
1307                         startPage = (unsigned long)sg->address >> PAGE_SHIFT;
1308                         endPage = ((unsigned long)sg->address + sg->length - 1) >> PAGE_SHIFT;
1309                         numPages = endPage - startPage + 1;
1310                         
1311                         uaddr = (unsigned long)sg->address;
1312
1313                         /* If the previous entry ended in the same page that
1314                          * the current page starts then they share that
1315                          * tce and we reduce the number of tces we need
1316                          * by one.  This matches assumptions made in
1317                          * num_tces_sg and fill_scatterlist_sg
1318                          */
1319                         if ( startPage == prevEndPage ) {
1320                                 --numPages;
1321                                 uaddr += PAGE_SIZE;
1322                         }
1323                         
1324                         for (i=0; i<numPages; ++i) {
1325                           ppc_md.tce_build(tbl, tcenum, uaddr, direction); 
1326                           ++tcenum;
1327                           uaddr += PAGE_SIZE;
1328                         }
1329                 
1330                         prevEndPage = endPage;
1331                         sg++;
1332                 }
1333                 /* Make sure the update is visible to hardware. 
1334                    sync required to synchronize the update to 
1335                    the TCE table with the MMIO that will send
1336                    the bus address to the IOA */
1337                 __asm__ __volatile__ ("sync" : : : "memory");
1338
1339                 if ((tcenum - starttcenum) != numTces)
1340                         PPCDBG(PPCDBG_TCE, "create_tces_sg: numTces %d, tces used %d\n",
1341                                 numTces, (unsigned)(tcenum - starttcenum));
1342
1343         }
1344
1345         return dmaAddr;
1346 }
1347
1348 int pci_map_sg( struct pci_dev *hwdev, struct scatterlist *sg, int nents, int direction )
1349 {
1350         struct TceTable * tbl;
1351         unsigned numTces;
1352         int num_dma;
1353         dma_addr_t dma_handle;
1354
1355         PPCDBG(PPCDBG_TCE, "pci_map_sg:\n");
1356         PPCDBG(PPCDBG_TCE, "\thwdev = 0x%16.16lx, sg = 0x%16.16lx, direction = 0x%16.16lx, nents = 0x%16.16lx\n", hwdev, sg, direction, nents); 
1357         /* Fast path for a single entry scatterlist */
1358         if ( nents == 1 ) {
1359                 sg->dma_address = pci_map_single( hwdev, sg->address, 
1360                                         sg->length, direction );
1361                 sg->dma_length = sg->length;
1362                 return 1;
1363         }
1364         
1365         if ( direction == PCI_DMA_NONE )
1366                 BUG();
1367         
1368         tbl = get_tce_table(hwdev); 
1369
1370         if ( tbl ) {
1371                 /* Compute the number of tces required */
1372                 numTces = num_tces_sg( sg, nents );
1373                 /* Create the tces and get the dma address */ 
1374                 dma_handle = create_tces_sg( tbl, sg, nents, numTces, direction );
1375
1376                 /* Fill in the dma scatterlist */
1377                 num_dma = fill_scatterlist_sg( sg, nents, dma_handle, numTces );
1378         }
1379
1380         return num_dma;
1381 }
1382
1383 void pci_unmap_sg( struct pci_dev *hwdev, struct scatterlist *sg, int nelms, int direction )
1384 {
1385         struct TceTable * tbl;
1386         unsigned order, numTces, i;
1387         dma_addr_t dma_end_page, dma_start_page;
1388         
1389         PPCDBG(PPCDBG_TCE, "pci_unmap_sg:\n");
1390         PPCDBG(PPCDBG_TCE, "\thwdev = 0x%16.16lx, sg = 0x%16.16lx, direction = 0x%16.16lx, nelms = 0x%16.16lx\n", hwdev, sg, direction, nelms); 
1391
1392         if ( direction == PCI_DMA_NONE || nelms == 0 )
1393                 BUG();
1394
1395         dma_start_page = sg->dma_address & PAGE_MASK;
1396         dma_end_page   = 0;
1397         for ( i=nelms; i>0; --i ) {
1398                 unsigned k = i - 1;
1399                 if ( sg[k].dma_length ) {
1400                         dma_end_page = ( sg[k].dma_address +
1401                                          sg[k].dma_length - 1 ) & PAGE_MASK;
1402                         break;
1403                 }
1404         }
1405
1406         numTces = ((dma_end_page - dma_start_page ) >> PAGE_SHIFT) + 1;
1407         order = get_order( numTces << PAGE_SHIFT );
1408
1409         /* Client asked for way to much space.  This is checked later anyway */
1410         /* It is easier to debug here for the drivers than in the tce tables.*/
1411         if(order >= NUM_TCE_LEVELS) {
1412                 printk("PCI_DMA: dma_start_page:0x%x  dma_end_page:0x%x\n",dma_start_page,dma_end_page);
1413                 printk("PCI_DMA: pci_unmap_sg size to large: 0x%x \n",(numTces << PAGE_SHIFT));
1414                 return;
1415         }
1416         
1417         tbl = get_tce_table(hwdev); 
1418
1419         if ( tbl ) 
1420                 tce_free( tbl, dma_start_page, order, numTces );
1421
1422 }
1423
1424 /*
1425  * phb_tce_table_init
1426  * 
1427  * Function: Display TCE config registers.  Could be easily changed
1428  *           to initialize the hardware to use TCEs.
1429  */
1430 unsigned long phb_tce_table_init(struct pci_controller *phb) {
1431         unsigned int r, cfg_rw, i;      
1432         unsigned long r64;      
1433         phandle node;
1434
1435         PPCDBG(PPCDBG_TCE, "phb_tce_table_init: start.\n"); 
1436
1437         node = ((struct device_node *)(phb->arch_data))->node;
1438
1439         PPCDBG(PPCDBG_TCEINIT, "\tphb            = 0x%lx\n", phb); 
1440         PPCDBG(PPCDBG_TCEINIT, "\tphb->type      = 0x%lx\n", phb->type); 
1441         PPCDBG(PPCDBG_TCEINIT, "\tphb->phb_regs  = 0x%lx\n", phb->phb_regs); 
1442         PPCDBG(PPCDBG_TCEINIT, "\tphb->chip_regs = 0x%lx\n", phb->chip_regs); 
1443         PPCDBG(PPCDBG_TCEINIT, "\tphb: node      = 0x%lx\n", node);
1444         PPCDBG(PPCDBG_TCEINIT, "\tphb->arch_data = 0x%lx\n", phb->arch_data); 
1445
1446         i = 0;
1447         while(of_tce_table[i].node) {
1448                 if(of_tce_table[i].node == node) {
1449                         if(phb->type == phb_type_python) {
1450                                 r = *(((unsigned int *)phb->phb_regs) + (0xf10>>2)); 
1451                                 PPCDBG(PPCDBG_TCEINIT, "\tTAR(low)    = 0x%x\n", r);
1452                                 r = *(((unsigned int *)phb->phb_regs) + (0xf00>>2)); 
1453                                 PPCDBG(PPCDBG_TCEINIT, "\tTAR(high)   = 0x%x\n", r);
1454                                 r = *(((unsigned int *)phb->phb_regs) + (0xfd0>>2)); 
1455                                 PPCDBG(PPCDBG_TCEINIT, "\tPHB cfg(rw) = 0x%x\n", r);
1456                                 break;
1457                         } else if(phb->type == phb_type_speedwagon) {
1458                                 r64 = *(((unsigned long *)phb->chip_regs) + 
1459                                         (0x800>>3)); 
1460                                 PPCDBG(PPCDBG_TCEINIT, "\tNCFG    = 0x%lx\n", r64);
1461                                 r64 = *(((unsigned long *)phb->chip_regs) + 
1462                                         (0x580>>3)); 
1463                                 PPCDBG(PPCDBG_TCEINIT, "\tTAR0    = 0x%lx\n", r64);
1464                                 r64 = *(((unsigned long *)phb->chip_regs) + 
1465                                         (0x588>>3)); 
1466                                 PPCDBG(PPCDBG_TCEINIT, "\tTAR1    = 0x%lx\n", r64);
1467                                 r64 = *(((unsigned long *)phb->chip_regs) + 
1468                                         (0x590>>3)); 
1469                                 PPCDBG(PPCDBG_TCEINIT, "\tTAR2    = 0x%lx\n", r64);
1470                                 r64 = *(((unsigned long *)phb->chip_regs) + 
1471                                         (0x598>>3)); 
1472                                 PPCDBG(PPCDBG_TCEINIT, "\tTAR3    = 0x%lx\n", r64);
1473                                 cfg_rw = *(((unsigned int *)phb->chip_regs) + 
1474                                            ((0x160 +
1475                                              (((phb->local_number)+8)<<12))>>2)); 
1476                                 PPCDBG(PPCDBG_TCEINIT, "\tcfg_rw = 0x%x\n", cfg_rw);
1477                         }
1478                 }
1479                 i++;
1480         }
1481
1482         PPCDBG(PPCDBG_TCEINIT, "phb_tce_table_init: done\n"); 
1483
1484         return(0); 
1485 }
1486
1487 /* These are called very early. */
1488 void tce_init_pSeries(void)
1489 {
1490         ppc_md.tce_build = tce_build_pSeries;
1491         ppc_md.tce_free_one = tce_free_one_pSeries;
1492 }
1493
1494 void tce_init_iSeries(void)
1495 {
1496         ppc_md.tce_build = tce_build_iSeries;
1497         ppc_md.tce_free_one = tce_free_one_iSeries;
1498 }