linux-old/arch/ia64/hp/common/sba_iommu.c
<<
>>
Prefs
   1/*
   2**  IA64 System Bus Adapter (SBA) I/O MMU manager
   3**
   4**      (c) Copyright 2002-2004 Alex Williamson
   5**      (c) Copyright 2002-2003 Grant Grundler
   6**      (c) Copyright 2002-2004 Hewlett-Packard Company
   7**
   8**      Portions (c) 2000 Grant Grundler (from parisc I/O MMU code)
   9**      Portions (c) 1999 Dave S. Miller (from sparc64 I/O MMU code)
  10**
  11**      This program is free software; you can redistribute it and/or modify
  12**      it under the terms of the GNU General Public License as published by
  13**      the Free Software Foundation; either version 2 of the License, or
  14**      (at your option) any later version.
  15**
  16**
  17** This module initializes the IOC (I/O Controller) found on HP
  18** McKinley machines and their successors.
  19**
  20*/
  21
  22#include <linux/config.h>
  23#include <linux/types.h>
  24#include <linux/kernel.h>
  25#include <linux/module.h>
  26#include <linux/spinlock.h>
  27#include <linux/slab.h>
  28#include <linux/init.h>
  29#include <linux/mm.h>
  30#include <linux/string.h>
  31#include <linux/pci.h>
  32#include <linux/proc_fs.h>
  33#include <linux/seq_file.h>
  34#include <linux/acpi.h>
  35#include <linux/efi.h>
  36
  37#include <asm/delay.h>          /* ia64_get_itc() */
  38#include <asm/io.h>
  39#include <asm/page.h>           /* PAGE_OFFSET */
  40#include <asm/system.h>         /* wmb() */
  41#include <asm/bitops.h>         /* hweight64() */
  42
  43
  44#define PFX "IOC: "
  45
  46/*
  47** Enabling timing search of the pdir resource map.  Output in /proc.
  48** Disabled by default to optimize performance.
  49*/
  50#undef PDIR_SEARCH_TIMING
  51
  52/*
  53** This option allows cards capable of 64bit DMA to bypass the IOMMU.  If
  54** not defined, all DMA will be 32bit and go through the TLB.
  55*/
  56#define ALLOW_IOV_BYPASS
  57
  58/*
  59** If a device prefetches beyond the end of a valid pdir entry, it will cause
  60** a hard failure, ie. MCA.  Version 3.0 and later of the zx1 LBA should
  61** disconnect on 4k boundaries and prevent such issues.  If the device is
  62** particularly agressive, this option will keep the entire pdir valid such
  63** that prefetching will hit a valid address.  This could severely impact
  64** error containment, and is therefore off by default.  The page that is
  65** used for spill-over is poisoned, so that should help debugging somewhat.
  66*/
  67#undef FULL_VALID_PDIR
  68
  69#define ENABLE_MARK_CLEAN
  70
  71/*
  72** The number of debug flags is a clue - this code is fragile.
  73*/
  74#undef DEBUG_SBA_INIT
  75#undef DEBUG_SBA_RUN
  76#undef DEBUG_SBA_RUN_SG
  77#undef DEBUG_SBA_RESOURCE
  78#undef ASSERT_PDIR_SANITY
  79#undef DEBUG_LARGE_SG_ENTRIES
  80#undef DEBUG_BYPASS
  81
  82#if defined(FULL_VALID_PDIR) && defined(ASSERT_PDIR_SANITY)
  83#error FULL_VALID_PDIR and ASSERT_PDIR_SANITY are mutually exclusive
  84#endif
  85
  86#define SBA_INLINE      __inline__
  87/* #define SBA_INLINE */
  88
  89#ifdef DEBUG_SBA_INIT
  90#define DBG_INIT(x...)  printk(x)
  91#else
  92#define DBG_INIT(x...)
  93#endif
  94
  95#ifdef DEBUG_SBA_RUN
  96#define DBG_RUN(x...)   printk(x)
  97#else
  98#define DBG_RUN(x...)
  99#endif
 100
 101#ifdef DEBUG_SBA_RUN_SG
 102#define DBG_RUN_SG(x...)        printk(x)
 103#else
 104#define DBG_RUN_SG(x...)
 105#endif
 106
 107
 108#ifdef DEBUG_SBA_RESOURCE
 109#define DBG_RES(x...)   printk(x)
 110#else
 111#define DBG_RES(x...)
 112#endif
 113
 114#ifdef DEBUG_BYPASS
 115#define DBG_BYPASS(x...)        printk(x)
 116#else
 117#define DBG_BYPASS(x...)
 118#endif
 119
 120#ifdef ASSERT_PDIR_SANITY
 121#define ASSERT(expr) \
 122        if(!(expr)) { \
 123                printk( "\n" __FILE__ ":%d: Assertion " #expr " failed!\n",__LINE__); \
 124                panic(#expr); \
 125        }
 126#else
 127#define ASSERT(expr)
 128#endif
 129
 130/*
 131** The number of pdir entries to "free" before issuing
 132** a read to PCOM register to flush out PCOM writes.
 133** Interacts with allocation granularity (ie 4 or 8 entries
 134** allocated and free'd/purged at a time might make this
 135** less interesting).
 136*/
 137#define DELAYED_RESOURCE_CNT    16
 138
 139#define DEFAULT_DMA_HINT_REG    0
 140
 141#define ZX1_IOC_ID      ((PCI_DEVICE_ID_HP_ZX1_IOC << 16) | PCI_VENDOR_ID_HP)
 142#define REO_IOC_ID      ((PCI_DEVICE_ID_HP_REO_IOC << 16) | PCI_VENDOR_ID_HP)
 143#define SX1000_IOC_ID   ((PCI_DEVICE_ID_HP_SX1000_IOC << 16) | PCI_VENDOR_ID_HP)
 144
 145#define ZX1_IOC_OFFSET  0x1000  /* ACPI reports SBA, we want IOC */
 146
 147#define IOC_FUNC_ID     0x000
 148#define IOC_FCLASS      0x008   /* function class, bist, header, rev... */
 149#define IOC_IBASE       0x300   /* IO TLB */
 150#define IOC_IMASK       0x308
 151#define IOC_PCOM        0x310
 152#define IOC_TCNFG       0x318
 153#define IOC_PDIR_BASE   0x320
 154
 155/* AGP GART driver looks for this */
 156#define ZX1_SBA_IOMMU_COOKIE    0x0000badbadc0ffeeUL
 157
 158/*
 159** The zx1 IOC supports 4/8/16/64KB page sizes (see TCNFG register)
 160**
 161** Some IOCs (sx1000) can run at the above pages sizes, but are
 162** really only supported using the IOC at a 4k page size.
 163**
 164** iovp_size could only be greater than PAGE_SIZE if we are
 165** confident the drivers really only touch the next physical
 166** page iff that driver instance owns it.
 167*/
 168static unsigned long iovp_size;
 169static unsigned long iovp_shift;
 170static unsigned long iovp_mask;
 171
 172struct ioc {
 173        void            *ioc_hpa;       /* I/O MMU base address */
 174        char            *res_map;       /* resource map, bit == pdir entry */
 175        u64             *pdir_base;     /* physical base address */
 176        unsigned long   ibase;          /* pdir IOV Space base */
 177        unsigned long   imask;          /* pdir IOV Space mask */
 178
 179        unsigned long   *res_hint;      /* next avail IOVP - circular search */
 180        spinlock_t      res_lock;
 181        unsigned long   hint_mask_pdir; /* bits used for DMA hints */
 182        unsigned int    res_bitshift;   /* from the RIGHT! */
 183        unsigned int    res_size;       /* size of resource map in bytes */
 184        unsigned int    hint_shift_pdir;
 185        unsigned long   dma_mask;
 186#if DELAYED_RESOURCE_CNT > 0
 187        int saved_cnt;
 188        struct sba_dma_pair {
 189                dma_addr_t      iova;
 190                size_t          size;
 191        } saved[DELAYED_RESOURCE_CNT];
 192#endif
 193
 194#ifdef PDIR_SEARCH_TIMING
 195#define SBA_SEARCH_SAMPLE       0x100
 196        unsigned long avg_search[SBA_SEARCH_SAMPLE];
 197        unsigned long avg_idx;  /* current index into avg_search */
 198#endif
 199
 200        /* Stuff we don't need in performance path */
 201        struct ioc      *next;          /* list of IOC's in system */
 202        acpi_handle     handle;         /* for multiple IOC's */
 203        const char      *name;
 204        unsigned int    func_id;
 205        unsigned int    rev;            /* HW revision of chip */
 206        u32             iov_size;
 207        unsigned int    pdir_size;      /* in bytes, determined by IOV Space size */
 208        struct pci_dev  *sac_only_dev;
 209};
 210
 211static struct ioc *ioc_list;
 212static int reserve_sba_gart = 1;
 213
 214#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
 215#define sba_sg_address(sg)      (page_address((sg)->page) + (sg)->offset)
 216#else
 217#define sba_sg_address(sg)      ((sg)->address ? (sg)->address : \
 218                                  page_address((sg)->page) + (sg)->offset)
 219#endif
 220
 221#ifdef FULL_VALID_PDIR
 222static u64 prefetch_spill_page;
 223#endif
 224
 225#ifdef CONFIG_PCI
 226# define GET_IOC(dev)   ((struct ioc *) PCI_CONTROLLER(dev)->iommu)
 227#else
 228# define GET_IOC(dev)   NULL
 229#endif
 230
 231/*
 232** DMA_CHUNK_SIZE is used by the SCSI mid-layer to break up
 233** (or rather not merge) DMA's into managable chunks.
 234** On parisc, this is more of the software/tuning constraint
 235** rather than the HW. I/O MMU allocation alogorithms can be
 236** faster with smaller size is (to some degree).
 237*/
 238#define DMA_CHUNK_SIZE  (BITS_PER_LONG*iovp_size)
 239
 240#define ROUNDUP(x,y) ((x + ((y)-1)) & ~((y)-1))
 241
 242/************************************
 243** SBA register read and write support
 244**
 245** BE WARNED: register writes are posted.
 246**  (ie follow writes which must reach HW with a read)
 247**
 248*/
 249#define READ_REG(addr)       __raw_readq(addr)
 250#define WRITE_REG(val, addr) __raw_writeq(val, addr)
 251
 252#ifdef DEBUG_SBA_INIT
 253
 254/**
 255 * sba_dump_tlb - debugging only - print IOMMU operating parameters
 256 * @hpa: base address of the IOMMU
 257 *
 258 * Print the size/location of the IO MMU PDIR.
 259 */
 260static void
 261sba_dump_tlb(char *hpa)
 262{
 263        DBG_INIT("IO TLB at 0x%p\n", (void *)hpa);
 264        DBG_INIT("IOC_IBASE    : %016lx\n", READ_REG(hpa+IOC_IBASE));
 265        DBG_INIT("IOC_IMASK    : %016lx\n", READ_REG(hpa+IOC_IMASK));
 266        DBG_INIT("IOC_TCNFG    : %016lx\n", READ_REG(hpa+IOC_TCNFG));
 267        DBG_INIT("IOC_PDIR_BASE: %016lx\n", READ_REG(hpa+IOC_PDIR_BASE));
 268        DBG_INIT("\n");
 269}
 270#endif
 271
 272
 273#ifdef ASSERT_PDIR_SANITY
 274
 275/**
 276 * sba_dump_pdir_entry - debugging only - print one IOMMU PDIR entry
 277 * @ioc: IO MMU structure which owns the pdir we are interested in.
 278 * @msg: text to print ont the output line.
 279 * @pide: pdir index.
 280 *
 281 * Print one entry of the IO MMU PDIR in human readable form.
 282 */
 283static void
 284sba_dump_pdir_entry(struct ioc *ioc, char *msg, uint pide)
 285{
 286        /* start printing from lowest pde in rval */
 287        u64 *ptr = &ioc->pdir_base[pide  & ~(BITS_PER_LONG - 1)];
 288        unsigned long *rptr = (unsigned long *) &ioc->res_map[(pide >>3) & -sizeof(unsigned long)];
 289        uint rcnt;
 290
 291        printk(KERN_DEBUG "SBA: %s rp %p bit %d rval 0x%lx\n",
 292                 msg, rptr, pide & (BITS_PER_LONG - 1), *rptr);
 293
 294        rcnt = 0;
 295        while (rcnt < BITS_PER_LONG) {
 296                printk(KERN_DEBUG "%s %2d %p %016Lx\n",
 297                       (rcnt == (pide & (BITS_PER_LONG - 1)))
 298                       ? "    -->" : "       ",
 299                       rcnt, ptr, (unsigned long long) *ptr );
 300                rcnt++;
 301                ptr++;
 302        }
 303        printk(KERN_DEBUG "%s", msg);
 304}
 305
 306
 307/**
 308 * sba_check_pdir - debugging only - consistency checker
 309 * @ioc: IO MMU structure which owns the pdir we are interested in.
 310 * @msg: text to print ont the output line.
 311 *
 312 * Verify the resource map and pdir state is consistent
 313 */
 314static int
 315sba_check_pdir(struct ioc *ioc, char *msg)
 316{
 317        u64 *rptr_end = (u64 *) &(ioc->res_map[ioc->res_size]);
 318        u64 *rptr = (u64 *) ioc->res_map;       /* resource map ptr */
 319        u64 *pptr = ioc->pdir_base;     /* pdir ptr */
 320        uint pide = 0;
 321
 322        while (rptr < rptr_end) {
 323                u64 rval;
 324                int rcnt; /* number of bits we might check */
 325
 326                rval = *rptr;
 327                rcnt = 64;
 328
 329                while (rcnt) {
 330                        /* Get last byte and highest bit from that */
 331                        u32 pde = ((u32)((*pptr >> (63)) & 0x1));
 332                        if ((rval & 0x1) ^ pde)
 333                        {
 334                                /*
 335                                ** BUMMER!  -- res_map != pdir --
 336                                ** Dump rval and matching pdir entries
 337                                */
 338                                sba_dump_pdir_entry(ioc, msg, pide);
 339                                return(1);
 340                        }
 341                        rcnt--;
 342                        rval >>= 1;     /* try the next bit */
 343                        pptr++;
 344                        pide++;
 345                }
 346                rptr++; /* look at next word of res_map */
 347        }
 348        /* It'd be nice if we always got here :^) */
 349        return 0;
 350}
 351
 352
 353/**
 354 * sba_dump_sg - debugging only - print Scatter-Gather list
 355 * @ioc: IO MMU structure which owns the pdir we are interested in.
 356 * @startsg: head of the SG list
 357 * @nents: number of entries in SG list
 358 *
 359 * print the SG list so we can verify it's correct by hand.
 360 */
 361static void
 362sba_dump_sg( struct ioc *ioc, struct scatterlist *startsg, int nents)
 363{
 364        while (nents-- > 0) {
 365                printk(KERN_DEBUG " %d : DMA %08lx/%05x CPU %p\n", nents,
 366                       startsg->dma_address, startsg->dma_length,
 367                       sba_sg_address(startsg));
 368                startsg++;
 369        }
 370}
 371
 372static void
 373sba_check_sg( struct ioc *ioc, struct scatterlist *startsg, int nents)
 374{
 375        struct scatterlist *the_sg = startsg;
 376        int the_nents = nents;
 377
 378        while (the_nents-- > 0) {
 379                if (sba_sg_address(the_sg) == 0x0UL)
 380                        sba_dump_sg(NULL, startsg, nents);
 381                the_sg++;
 382        }
 383}
 384
 385#endif /* ASSERT_PDIR_SANITY */
 386
 387
 388
 389
 390/**************************************************************
 391*
 392*   I/O Pdir Resource Management
 393*
 394*   Bits set in the resource map are in use.
 395*   Each bit can represent a number of pages.
 396*   LSbs represent lower addresses (IOVA's).
 397*
 398***************************************************************/
 399#define PAGES_PER_RANGE 1       /* could increase this to 4 or 8 if needed */
 400
 401/* Convert from IOVP to IOVA and vice versa. */
 402#define SBA_IOVA(ioc,iovp,offset,hint_reg) ((ioc->ibase) | (iovp) | (offset))
 403#define SBA_IOVP(ioc,iova) ((iova) & ~(ioc->ibase))
 404
 405#define PDIR_ENTRY_SIZE sizeof(u64)
 406
 407#define PDIR_INDEX(iovp)   ((iovp)>>iovp_shift)
 408
 409#define RESMAP_MASK(n)    ~(~0UL << (n))
 410#define RESMAP_IDX_MASK   (sizeof(unsigned long) - 1)
 411
 412
 413/**
 414 * For most cases the normal get_order is sufficient, however it limits us
 415 * to PAGE_SIZE being the minimum mapping alignment and TC flush granularity.
 416 * It only incurs about 1 clock cycle to use this one with the static variable
 417 * and makes the code more intuitive.
 418 */
 419static SBA_INLINE int
 420get_iovp_order (unsigned long size)
 421{
 422        long double d = size - 1;
 423        long order;
 424
 425        __asm__ ("getf.exp %0=%1" : "=r"(order) : "f"(d));
 426        order = order - iovp_shift - 0xffff + 1;
 427        if (order < 0)
 428                order = 0;
 429        return order;
 430}
 431
 432/**
 433 * sba_search_bitmap - find free space in IO PDIR resource bitmap
 434 * @ioc: IO MMU structure which owns the pdir we are interested in.
 435 * @bits_wanted: number of entries we need.
 436 *
 437 * Find consecutive free bits in resource bitmap.
 438 * Each bit represents one entry in the IO Pdir.
 439 * Cool perf optimization: search for log2(size) bits at a time.
 440 */
 441static SBA_INLINE unsigned long
 442sba_search_bitmap(struct ioc *ioc, unsigned long bits_wanted)
 443{
 444        unsigned long *res_ptr = ioc->res_hint;
 445        unsigned long *res_end = (unsigned long *) &(ioc->res_map[ioc->res_size]);
 446        unsigned long pide = ~0UL;
 447
 448        ASSERT(((unsigned long) ioc->res_hint & (sizeof(unsigned long) - 1UL)) == 0);
 449        ASSERT(res_ptr < res_end);
 450        if (bits_wanted > (BITS_PER_LONG/2)) {
 451                /* Search word at a time - no mask needed */
 452                for(; res_ptr < res_end; ++res_ptr) {
 453                        if (*res_ptr == 0) {
 454                                *res_ptr = RESMAP_MASK(bits_wanted);
 455                                pide = ((unsigned long)res_ptr - (unsigned long)ioc->res_map);
 456                                pide <<= 3;     /* convert to bit address */
 457                                break;
 458                        }
 459                }
 460                /* point to the next word on next pass */
 461                res_ptr++;
 462                ioc->res_bitshift = 0;
 463        } else {
 464                /*
 465                ** Search the resource bit map on well-aligned values.
 466                ** "o" is the alignment.
 467                ** We need the alignment to invalidate I/O TLB using
 468                ** SBA HW features in the unmap path.
 469                */
 470                unsigned long o = 1 << get_iovp_order(bits_wanted << iovp_shift);
 471                uint bitshiftcnt = ROUNDUP(ioc->res_bitshift, o);
 472                unsigned long mask;
 473
 474                if (bitshiftcnt >= BITS_PER_LONG) {
 475                        bitshiftcnt = 0;
 476                        res_ptr++;
 477                }
 478                mask = RESMAP_MASK(bits_wanted) << bitshiftcnt;
 479
 480                DBG_RES("%s() o %ld %p", __FUNCTION__, o, res_ptr);
 481                while(res_ptr < res_end)
 482                { 
 483                        DBG_RES("    %p %lx %lx\n", res_ptr, mask, *res_ptr);
 484                        ASSERT(0 != mask);
 485                        if(0 == ((*res_ptr) & mask)) {
 486                                *res_ptr |= mask;     /* mark resources busy! */
 487                                pide = ((unsigned long)res_ptr - (unsigned long)ioc->res_map);
 488                                pide <<= 3;     /* convert to bit address */
 489                                pide += bitshiftcnt;
 490                                break;
 491                        }
 492                        mask <<= o;
 493                        bitshiftcnt += o;
 494                        if (0 == mask) {
 495                                mask = RESMAP_MASK(bits_wanted);
 496                                bitshiftcnt=0;
 497                                res_ptr++;
 498                        }
 499                }
 500                /* look in the same word on the next pass */
 501                ioc->res_bitshift = bitshiftcnt + bits_wanted;
 502        }
 503
 504        /* wrapped ? */
 505        if (res_end <= res_ptr) {
 506                ioc->res_hint = (unsigned long *) ioc->res_map;
 507                ioc->res_bitshift = 0;
 508        } else {
 509                ioc->res_hint = res_ptr;
 510        }
 511        return (pide);
 512}
 513
 514
 515/**
 516 * sba_alloc_range - find free bits and mark them in IO PDIR resource bitmap
 517 * @ioc: IO MMU structure which owns the pdir we are interested in.
 518 * @size: number of bytes to create a mapping for
 519 *
 520 * Given a size, find consecutive unmarked and then mark those bits in the
 521 * resource bit map.
 522 */
 523static int
 524sba_alloc_range(struct ioc *ioc, size_t size)
 525{
 526        unsigned int pages_needed = size >> iovp_shift;
 527#ifdef PDIR_SEARCH_TIMING
 528        unsigned long itc_start = ia64_get_itc();
 529#endif
 530        unsigned long pide;
 531
 532        ASSERT(pages_needed);
 533        ASSERT(pages_needed <= BITS_PER_LONG);
 534        ASSERT(0 == (size & ~iovp_mask));
 535
 536        /*
 537        ** "seek and ye shall find"...praying never hurts either...
 538        */
 539
 540        pide = sba_search_bitmap(ioc, pages_needed);
 541        if (pide >= (ioc->res_size << 3)) {
 542                pide = sba_search_bitmap(ioc, pages_needed);
 543                if (pide >= (ioc->res_size << 3))
 544                        panic(__FILE__ ": I/O MMU @ %p is out of mapping resources\n",
 545                              ioc->ioc_hpa);
 546        }
 547
 548#ifdef ASSERT_PDIR_SANITY
 549        /* verify the first enable bit is clear */
 550        if(0x00 != ((u8 *) ioc->pdir_base)[pide*PDIR_ENTRY_SIZE + 7]) {
 551                sba_dump_pdir_entry(ioc, "sba_search_bitmap() botched it?", pide);
 552        }
 553#endif
 554
 555        DBG_RES("%s(%x) %d -> %lx hint %x/%x\n",
 556                __FUNCTION__, size, pages_needed, pide,
 557                (uint) ((unsigned long) ioc->res_hint - (unsigned long) ioc->res_map),
 558                ioc->res_bitshift );
 559
 560#ifdef PDIR_SEARCH_TIMING
 561        ioc->avg_search[ioc->avg_idx++] = ia64_get_itc() - itc_start;
 562        ioc->avg_idx &= SBA_SEARCH_SAMPLE - 1;
 563#endif
 564
 565        return (pide);
 566}
 567
 568
 569/**
 570 * sba_free_range - unmark bits in IO PDIR resource bitmap
 571 * @ioc: IO MMU structure which owns the pdir we are interested in.
 572 * @iova: IO virtual address which was previously allocated.
 573 * @size: number of bytes to create a mapping for
 574 *
 575 * clear bits in the ioc's resource map
 576 */
 577static SBA_INLINE void
 578sba_free_range(struct ioc *ioc, dma_addr_t iova, size_t size)
 579{
 580        unsigned long iovp = SBA_IOVP(ioc, iova);
 581        unsigned int pide = PDIR_INDEX(iovp);
 582        unsigned int ridx = pide >> 3;  /* convert bit to byte address */
 583        unsigned long *res_ptr = (unsigned long *) &((ioc)->res_map[ridx & ~RESMAP_IDX_MASK]);
 584
 585        int bits_not_wanted = size >> iovp_shift;
 586
 587        /* 3-bits "bit" address plus 2 (or 3) bits for "byte" == bit in word */
 588        unsigned long m = RESMAP_MASK(bits_not_wanted) << (pide & (BITS_PER_LONG - 1));
 589
 590        DBG_RES("%s( ,%x,%x) %x/%lx %x %p %lx\n",
 591                __FUNCTION__, (uint) iova, size,
 592                bits_not_wanted, m, pide, res_ptr, *res_ptr);
 593
 594        ASSERT(m != 0);
 595        ASSERT(bits_not_wanted);
 596        ASSERT((bits_not_wanted * iovp_size) <= DMA_CHUNK_SIZE);
 597        ASSERT(bits_not_wanted <= BITS_PER_LONG);
 598        ASSERT((*res_ptr & m) == m); /* verify same bits are set */
 599        *res_ptr &= ~m;
 600}
 601
 602
 603/**************************************************************
 604*
 605*   "Dynamic DMA Mapping" support (aka "Coherent I/O")
 606*
 607***************************************************************/
 608
 609#define SBA_DMA_HINT(ioc, val) ((val) << (ioc)->hint_shift_pdir)
 610
 611
 612/**
 613 * sba_io_pdir_entry - fill in one IO PDIR entry
 614 * @pdir_ptr:  pointer to IO PDIR entry
 615 * @vba: Virtual CPU address of buffer to map
 616 *
 617 * SBA Mapping Routine
 618 *
 619 * Given a virtual address (vba, arg1) sba_io_pdir_entry()
 620 * loads the I/O PDIR entry pointed to by pdir_ptr (arg0).
 621 * Each IO Pdir entry consists of 8 bytes as shown below
 622 * (LSB == bit 0):
 623 *
 624 *  63                    40                                 11    7        0
 625 * +-+---------------------+----------------------------------+----+--------+
 626 * |V|        U            |            PPN[39:12]            | U  |   FF   |
 627 * +-+---------------------+----------------------------------+----+--------+
 628 *
 629 *  V  == Valid Bit
 630 *  U  == Unused
 631 * PPN == Physical Page Number
 632 *
 633 * The physical address fields are filled with the results of virt_to_phys()
 634 * on the vba.
 635 */
 636
 637#if 1
 638#define sba_io_pdir_entry(pdir_ptr, vba) *pdir_ptr = ((vba & ~0xE000000000000FFFULL)    \
 639                                                      | 0x8000000000000000ULL)
 640#else
 641void SBA_INLINE
 642sba_io_pdir_entry(u64 *pdir_ptr, unsigned long vba)
 643{
 644        *pdir_ptr = ((vba & ~0xE000000000000FFFULL) | 0x80000000000000FFULL);
 645}
 646#endif
 647
 648#ifdef ENABLE_MARK_CLEAN
 649/**
 650 * Since DMA is i-cache coherent, any (complete) pages that were written via
 651 * DMA can be marked as "clean" so that update_mmu_cache() doesn't have to
 652 * flush them when they get mapped into an executable vm-area.
 653 */
 654static void
 655mark_clean (void *addr, size_t size)
 656{
 657        unsigned long pg_addr, end;
 658
 659        pg_addr = PAGE_ALIGN((unsigned long) addr);
 660        end = (unsigned long) addr + size;
 661        while (pg_addr + PAGE_SIZE <= end) {
 662                struct page *page = virt_to_page((void *)pg_addr);
 663                set_bit(PG_arch_1, &page->flags);
 664                pg_addr += PAGE_SIZE;
 665        }
 666}
 667#endif
 668
 669/**
 670 * sba_mark_invalid - invalidate one or more IO PDIR entries
 671 * @ioc: IO MMU structure which owns the pdir we are interested in.
 672 * @iova:  IO Virtual Address mapped earlier
 673 * @byte_cnt:  number of bytes this mapping covers.
 674 *
 675 * Marking the IO PDIR entry(ies) as Invalid and invalidate
 676 * corresponding IO TLB entry. The PCOM (Purge Command Register)
 677 * is to purge stale entries in the IO TLB when unmapping entries.
 678 *
 679 * The PCOM register supports purging of multiple pages, with a minium
 680 * of 1 page and a maximum of 2GB. Hardware requires the address be
 681 * aligned to the size of the range being purged. The size of the range
 682 * must be a power of 2. The "Cool perf optimization" in the
 683 * allocation routine helps keep that true.
 684 */
 685static SBA_INLINE void
 686sba_mark_invalid(struct ioc *ioc, dma_addr_t iova, size_t byte_cnt)
 687{
 688        u32 iovp = (u32) SBA_IOVP(ioc,iova);
 689
 690        int off = PDIR_INDEX(iovp);
 691
 692        /* Must be non-zero and rounded up */
 693        ASSERT(byte_cnt > 0);
 694        ASSERT(0 == (byte_cnt & ~iovp_mask));
 695
 696#ifdef ASSERT_PDIR_SANITY
 697        /* Assert first pdir entry is set */
 698        if (!(ioc->pdir_base[off] >> 60)) {
 699                sba_dump_pdir_entry(ioc,"sba_mark_invalid()", PDIR_INDEX(iovp));
 700        }
 701#endif
 702
 703        if (byte_cnt <= iovp_size)
 704        {
 705                ASSERT(off < ioc->pdir_size);
 706
 707                iovp |= iovp_shift;     /* set "size" field for PCOM */
 708
 709#ifndef FULL_VALID_PDIR
 710                /*
 711                ** clear I/O PDIR entry "valid" bit
 712                ** Do NOT clear the rest - save it for debugging.
 713                ** We should only clear bits that have previously
 714                ** been enabled.
 715                */
 716                ioc->pdir_base[off] &= ~(0x80000000000000FFULL);
 717#else
 718                /*
 719                ** If we want to maintain the PDIR as valid, put in
 720                ** the spill page so devices prefetching won't
 721                ** cause a hard fail.
 722                */
 723                ioc->pdir_base[off] = (0x80000000000000FFULL | prefetch_spill_page);
 724#endif
 725        } else {
 726                u32 t = get_iovp_order(byte_cnt) + iovp_shift;
 727
 728                iovp |= t;
 729                ASSERT(t <= 31);   /* 2GB! Max value of "size" field */
 730
 731                do {
 732                        /* verify this pdir entry is enabled */
 733                        ASSERT(ioc->pdir_base[off]  >> 63);
 734#ifndef FULL_VALID_PDIR
 735                        /* clear I/O Pdir entry "valid" bit first */
 736                        ioc->pdir_base[off] &= ~(0x80000000000000FFULL);
 737#else
 738                        ioc->pdir_base[off] = (0x80000000000000FFULL | prefetch_spill_page);
 739#endif
 740                        off++;
 741                        byte_cnt -= iovp_size;
 742                } while (byte_cnt > 0);
 743        }
 744
 745        WRITE_REG(iovp | ioc->ibase, ioc->ioc_hpa+IOC_PCOM);
 746}
 747
 748/**
 749 * sba_map_single - map one buffer and return IOVA for DMA
 750 * @dev: instance of PCI owned by the driver that's asking.
 751 * @addr:  driver buffer to map.
 752 * @size:  number of bytes to map in driver buffer.
 753 * @dir:  R/W or both.
 754 *
 755 * See Documentation/DMA-mapping.txt
 756 */
 757dma_addr_t
 758sba_map_single(struct pci_dev *dev, void *addr, size_t size, int dir)
 759{
 760        struct ioc *ioc;
 761        unsigned long flags;
 762        dma_addr_t iovp;
 763        dma_addr_t offset;
 764        u64 *pdir_start;
 765        int pide;
 766#ifdef ALLOW_IOV_BYPASS
 767        unsigned long pci_addr = virt_to_phys(addr);
 768#endif
 769
 770        ioc = GET_IOC(dev);
 771        ASSERT(ioc);
 772
 773#ifdef ALLOW_IOV_BYPASS
 774        /*
 775        ** Check if the PCI device can DMA to ptr... if so, just return ptr
 776        */
 777        if ((pci_addr & ~dev->dma_mask) == 0) {
 778                /*
 779                ** Device is bit capable of DMA'ing to the buffer...
 780                ** just return the PCI address of ptr
 781                */
 782                DBG_BYPASS("sba_map_single() bypass mask/addr: 0x%lx/0x%lx\n",
 783                           dev->dma_mask, pci_addr);
 784                return pci_addr;
 785        }
 786#endif
 787
 788        ASSERT(size > 0);
 789        ASSERT(size <= DMA_CHUNK_SIZE);
 790
 791        /* save offset bits */
 792        offset = ((dma_addr_t) (long) addr) & ~iovp_mask;
 793
 794        /* round up to nearest iovp_size */
 795        size = (size + offset + ~iovp_mask) & iovp_mask;
 796
 797        spin_lock_irqsave(&ioc->res_lock, flags);
 798#ifdef ASSERT_PDIR_SANITY
 799        if (sba_check_pdir(ioc,"Check before sba_map_single()"))
 800                panic("Sanity check failed");
 801#endif
 802
 803        pide = sba_alloc_range(ioc, size);
 804        iovp = (dma_addr_t) pide << iovp_shift;
 805
 806        DBG_RUN("%s() 0x%p -> 0x%lx\n",
 807                __FUNCTION__, addr, (long) iovp | offset);
 808
 809        pdir_start = &(ioc->pdir_base[pide]);
 810
 811        while (size > 0) {
 812                ASSERT(((u8 *)pdir_start)[7] == 0); /* verify availability */
 813                sba_io_pdir_entry(pdir_start, (unsigned long) addr);
 814
 815                DBG_RUN("     pdir 0x%p %lx\n", pdir_start, *pdir_start);
 816
 817                addr += iovp_size;
 818                size -= iovp_size;
 819                pdir_start++;
 820        }
 821        /* force pdir update */
 822        wmb();
 823
 824        /* form complete address */
 825#ifdef ASSERT_PDIR_SANITY
 826        sba_check_pdir(ioc,"Check after sba_map_single()");
 827#endif
 828        spin_unlock_irqrestore(&ioc->res_lock, flags);
 829        return SBA_IOVA(ioc, iovp, offset, DEFAULT_DMA_HINT_REG);
 830}
 831
 832/**
 833 * sba_unmap_single - unmap one IOVA and free resources
 834 * @dev: instance of PCI owned by the driver that's asking.
 835 * @iova:  IOVA of driver buffer previously mapped.
 836 * @size:  number of bytes mapped in driver buffer.
 837 * @dir:  R/W or both.
 838 *
 839 * See Documentation/DMA-mapping.txt
 840 */
 841void sba_unmap_single(struct pci_dev *dev, dma_addr_t iova, size_t size, int dir)
 842{
 843        struct ioc *ioc;
 844#if DELAYED_RESOURCE_CNT > 0
 845        struct sba_dma_pair *d;
 846#endif
 847        unsigned long flags;
 848        dma_addr_t offset;
 849
 850        ioc = GET_IOC(dev);
 851        ASSERT(ioc);
 852
 853#ifdef ALLOW_IOV_BYPASS
 854        if ((iova & ioc->imask) != ioc->ibase) {
 855                /*
 856                ** Address does not fall w/in IOVA, must be bypassing
 857                */
 858                DBG_BYPASS("sba_unmap_single() bypass addr: 0x%lx\n", iova);
 859
 860#ifdef ENABLE_MARK_CLEAN
 861                if (dir == PCI_DMA_FROMDEVICE) {
 862                        mark_clean(phys_to_virt(iova), size);
 863                }
 864#endif
 865                return;
 866        }
 867#endif
 868        offset = iova & ~iovp_mask;
 869
 870        DBG_RUN("%s() iovp 0x%lx/%x\n",
 871                __FUNCTION__, (long) iova, size);
 872
 873        iova ^= offset;        /* clear offset bits */
 874        size += offset;
 875        size = ROUNDUP(size, iovp_size);
 876
 877        spin_lock_irqsave(&ioc->res_lock, flags);
 878
 879#if DELAYED_RESOURCE_CNT > 0
 880        d = &(ioc->saved[ioc->saved_cnt]);
 881        d->iova = iova;
 882        d->size = size;
 883        if (++(ioc->saved_cnt) >= DELAYED_RESOURCE_CNT) {
 884                int cnt = ioc->saved_cnt;
 885                while (cnt--) {
 886                        sba_mark_invalid(ioc, d->iova, d->size);
 887                        sba_free_range(ioc, d->iova, d->size);
 888                        d--;
 889                }
 890                ioc->saved_cnt = 0;
 891                READ_REG(ioc->ioc_hpa+IOC_PCOM);        /* flush purges */
 892        }
 893#else /* DELAYED_RESOURCE_CNT == 0 */
 894        sba_mark_invalid(ioc, iova, size);
 895        sba_free_range(ioc, iova, size);
 896        READ_REG(ioc->ioc_hpa+IOC_PCOM);        /* flush purges */
 897#endif /* DELAYED_RESOURCE_CNT == 0 */
 898#ifdef ENABLE_MARK_CLEAN
 899        if (dir == PCI_DMA_FROMDEVICE) {
 900                u32 iovp = (u32) SBA_IOVP(ioc,iova);
 901                int off = PDIR_INDEX(iovp);
 902                void *addr;
 903
 904                if (size <= iovp_size) {
 905                        addr = phys_to_virt(ioc->pdir_base[off] &
 906                                            ~0xE000000000000FFFULL);
 907                        mark_clean(addr, size);
 908                } else {
 909                        size_t byte_cnt = size;
 910
 911                        do {
 912                                addr = phys_to_virt(ioc->pdir_base[off] &
 913                                                    ~0xE000000000000FFFULL);
 914                                mark_clean(addr, min(byte_cnt, iovp_size));
 915                                off++;
 916                                byte_cnt -= iovp_size;
 917
 918                           } while (byte_cnt > 0);
 919                }
 920        }
 921#endif
 922        spin_unlock_irqrestore(&ioc->res_lock, flags);
 923
 924        /* XXX REVISIT for 2.5 Linux - need syncdma for zero-copy support.
 925        ** For Astro based systems this isn't a big deal WRT performance.
 926        ** As long as 2.4 kernels copyin/copyout data from/to userspace,
 927        ** we don't need the syncdma. The issue here is I/O MMU cachelines
 928        ** are *not* coherent in all cases.  May be hwrev dependent.
 929        ** Need to investigate more.
 930        asm volatile("syncdma");
 931        */
 932}
 933
 934
 935/**
 936 * sba_alloc_coherent - allocate/map shared mem for DMA
 937 * @dev: instance of PCI owned by the driver that's asking.
 938 * @size:  number of bytes mapped in driver buffer.
 939 * @dma_handle:  IOVA of new buffer.
 940 *
 941 * See Documentation/DMA-mapping.txt
 942 */
 943void *
 944sba_alloc_coherent (struct pci_dev *dev, size_t size, dma_addr_t *dma_handle)
 945{
 946        struct ioc *ioc;
 947        void *addr;
 948
 949        if (!dev)
 950                return NULL;    /* only support PCI */
 951
 952        addr = (void *) __get_free_pages(GFP_ATOMIC, get_order(size));
 953        if (!addr)
 954                return NULL;
 955
 956        /*
 957         * REVISIT: if sba_map_single starts needing more than dma_mask from the
 958         * device, this needs to be updated.
 959         */
 960        ioc = GET_IOC(dev);
 961        ASSERT(ioc);
 962        *dma_handle = sba_map_single(ioc->sac_only_dev, addr, size, 0);
 963
 964        memset(addr, 0, size);
 965        return addr;
 966}
 967
 968
 969/**
 970 * sba_free_coherent - free/unmap shared mem for DMA
 971 * @dev: instance of PCI owned by the driver that's asking.
 972 * @size:  number of bytes mapped in driver buffer.
 973 * @vaddr:  virtual address IOVA of "consistent" buffer.
 974 * @dma_handler:  IO virtual address of "consistent" buffer.
 975 *
 976 * See Documentation/DMA-mapping.txt
 977 */
 978void sba_free_coherent (struct pci_dev *dev, size_t size, void *vaddr, dma_addr_t dma_handle)
 979{
 980        sba_unmap_single(dev, dma_handle, size, 0);
 981        free_pages((unsigned long) vaddr, get_order(size));
 982}
 983
 984
 985/*
 986** Since 0 is a valid pdir_base index value, can't use that
 987** to determine if a value is valid or not. Use a flag to indicate
 988** the SG list entry contains a valid pdir index.
 989*/
 990#define PIDE_FLAG 0x1UL
 991
 992#ifdef DEBUG_LARGE_SG_ENTRIES
 993int dump_run_sg = 0;
 994#endif
 995
 996
 997/**
 998 * sba_fill_pdir - write allocated SG entries into IO PDIR
 999 * @ioc: IO MMU structure which owns the pdir we are interested in.
1000 * @startsg:  list of IOVA/size pairs
1001 * @nents: number of entries in startsg list
1002 *
1003 * Take preprocessed SG list and write corresponding entries
1004 * in the IO PDIR.
1005 */
1006
1007static SBA_INLINE int
1008sba_fill_pdir(
1009        struct ioc *ioc,
1010        struct scatterlist *startsg,
1011        int nents)
1012{
1013        struct scatterlist *dma_sg = startsg;   /* pointer to current DMA */
1014        int n_mappings = 0;
1015        u64 *pdirp = 0;
1016        unsigned long dma_offset = 0;
1017
1018        dma_sg--;
1019        while (nents-- > 0) {
1020                int     cnt = startsg->dma_length;
1021                startsg->dma_length = 0;
1022
1023#ifdef DEBUG_LARGE_SG_ENTRIES
1024                if (dump_run_sg)
1025                        printk(" %2d : %08lx/%05x %p\n",
1026                                nents, startsg->dma_address, cnt,
1027                                sba_sg_address(startsg));
1028#else
1029                DBG_RUN_SG(" %d : %08lx/%05x %p\n",
1030                                nents, startsg->dma_address, cnt,
1031                                sba_sg_address(startsg));
1032#endif
1033                /*
1034                ** Look for the start of a new DMA stream
1035                */
1036                if (startsg->dma_address & PIDE_FLAG) {
1037                        u32 pide = startsg->dma_address & ~PIDE_FLAG;
1038                        dma_offset = (unsigned long) pide & ~iovp_mask;
1039                        startsg->dma_address = 0;
1040                        dma_sg++;
1041                        dma_sg->dma_address = pide | ioc->ibase;
1042                        pdirp = &(ioc->pdir_base[pide >> iovp_shift]);
1043                        n_mappings++;
1044                }
1045
1046                /*
1047                ** Look for a VCONTIG chunk
1048                */
1049                if (cnt) {
1050                        unsigned long vaddr = (unsigned long) sba_sg_address(startsg);
1051                        ASSERT(pdirp);
1052
1053                        /* Since multiple Vcontig blocks could make up
1054                        ** one DMA stream, *add* cnt to dma_len.
1055                        */
1056                        dma_sg->dma_length += cnt;
1057                        cnt += dma_offset;
1058                        dma_offset=0;   /* only want offset on first chunk */
1059                        cnt = ROUNDUP(cnt, iovp_size);
1060                        do {
1061                                sba_io_pdir_entry(pdirp, vaddr);
1062                                vaddr += iovp_size;
1063                                cnt -= iovp_size;
1064                                pdirp++;
1065                        } while (cnt > 0);
1066                }
1067                startsg++;
1068        }
1069        /* force pdir update */
1070        wmb();
1071
1072#ifdef DEBUG_LARGE_SG_ENTRIES
1073        dump_run_sg = 0;
1074#endif
1075        return(n_mappings);
1076}
1077
1078
1079/*
1080** Two address ranges are DMA contiguous *iff* "end of prev" and
1081** "start of next" are both on an IOV page boundary.
1082**
1083** (shift left is a quick trick to mask off upper bits)
1084*/
1085#define DMA_CONTIG(__X, __Y) \
1086        (((((unsigned long) __X) | ((unsigned long) __Y)) << (BITS_PER_LONG - iovp_shift)) == 0UL)
1087
1088
1089/**
1090 * sba_coalesce_chunks - preprocess the SG list
1091 * @ioc: IO MMU structure which owns the pdir we are interested in.
1092 * @startsg:  list of IOVA/size pairs
1093 * @nents: number of entries in startsg list
1094 *
1095 * First pass is to walk the SG list and determine where the breaks are
1096 * in the DMA stream. Allocates PDIR entries but does not fill them.
1097 * Returns the number of DMA chunks.
1098 *
1099 * Doing the fill separate from the coalescing/allocation keeps the
1100 * code simpler. Future enhancement could make one pass through
1101 * the sglist do both.
1102 */
1103static SBA_INLINE int
1104sba_coalesce_chunks( struct ioc *ioc,
1105        struct scatterlist *startsg,
1106        int nents)
1107{
1108        struct scatterlist *vcontig_sg;    /* VCONTIG chunk head */
1109        unsigned long vcontig_len;         /* len of VCONTIG chunk */
1110        unsigned long vcontig_end;
1111        struct scatterlist *dma_sg;        /* next DMA stream head */
1112        unsigned long dma_offset, dma_len; /* start/len of DMA stream */
1113        int n_mappings = 0;
1114
1115        while (nents > 0) {
1116                unsigned long vaddr = (unsigned long) sba_sg_address(startsg);
1117
1118                /*
1119                ** Prepare for first/next DMA stream
1120                */
1121                dma_sg = vcontig_sg = startsg;
1122                dma_len = vcontig_len = vcontig_end = startsg->length;
1123                vcontig_end +=  vaddr;
1124                dma_offset = vaddr & ~iovp_mask;
1125
1126                /* PARANOID: clear entries */
1127                startsg->dma_address = startsg->dma_length = 0;
1128
1129                /*
1130                ** This loop terminates one iteration "early" since
1131                ** it's always looking one "ahead".
1132                */
1133                while (--nents > 0) {
1134                        unsigned long vaddr;    /* tmp */
1135
1136                        startsg++;
1137
1138                        /* PARANOID */
1139                        startsg->dma_address = startsg->dma_length = 0;
1140
1141                        /* catch brokenness in SCSI layer */
1142                        ASSERT(startsg->length <= DMA_CHUNK_SIZE);
1143
1144                        /*
1145                        ** First make sure current dma stream won't
1146                        ** exceed DMA_CHUNK_SIZE if we coalesce the
1147                        ** next entry.
1148                        */
1149                        if (((dma_len + dma_offset + startsg->length + ~iovp_mask) & iovp_mask)
1150                            > DMA_CHUNK_SIZE)
1151                                break;
1152
1153                        /*
1154                        ** Then look for virtually contiguous blocks.
1155                        **
1156                        ** append the next transaction?
1157                        */
1158                        vaddr = (unsigned long) sba_sg_address(startsg);
1159                        if  (vcontig_end == vaddr)
1160                        {
1161                                vcontig_len += startsg->length;
1162                                vcontig_end += startsg->length;
1163                                dma_len     += startsg->length;
1164                                continue;
1165                        }
1166
1167#ifdef DEBUG_LARGE_SG_ENTRIES
1168                        dump_run_sg = (vcontig_len > iovp_size);
1169#endif
1170
1171                        /*
1172                        ** Not virtually contigous.
1173                        ** Terminate prev chunk.
1174                        ** Start a new chunk.
1175                        **
1176                        ** Once we start a new VCONTIG chunk, dma_offset
1177                        ** can't change. And we need the offset from the first
1178                        ** chunk - not the last one. Ergo Successive chunks
1179                        ** must start on page boundaries and dove tail
1180                        ** with it's predecessor.
1181                        */
1182                        vcontig_sg->dma_length = vcontig_len;
1183
1184                        vcontig_sg = startsg;
1185                        vcontig_len = startsg->length;
1186
1187                        /*
1188                        ** 3) do the entries end/start on page boundaries?
1189                        **    Don't update vcontig_end until we've checked.
1190                        */
1191                        if (DMA_CONTIG(vcontig_end, vaddr))
1192                        {
1193                                vcontig_end = vcontig_len + vaddr;
1194                                dma_len += vcontig_len;
1195                                continue;
1196                        } else {
1197                                break;
1198                        }
1199                }
1200
1201                /*
1202                ** End of DMA Stream
1203                ** Terminate last VCONTIG block.
1204                ** Allocate space for DMA stream.
1205                */
1206                vcontig_sg->dma_length = vcontig_len;
1207                dma_len = (dma_len + dma_offset + ~iovp_mask) & iovp_mask;
1208                ASSERT(dma_len <= DMA_CHUNK_SIZE);
1209                dma_sg->dma_address = (dma_addr_t) (PIDE_FLAG
1210                        | (sba_alloc_range(ioc, dma_len) << iovp_shift)
1211                        | dma_offset);
1212                n_mappings++;
1213        }
1214
1215        return n_mappings;
1216}
1217
1218
1219/**
1220 * sba_map_sg - map Scatter/Gather list
1221 * @dev: instance of PCI owned by the driver that's asking.
1222 * @sglist:  array of buffer/length pairs
1223 * @nents:  number of entries in list
1224 * @dir:  R/W or both.
1225 *
1226 * See Documentation/DMA-mapping.txt
1227 */
1228int sba_map_sg(struct pci_dev *dev, struct scatterlist *sglist, int nents, int dir)
1229{
1230        struct ioc *ioc;
1231        int coalesced, filled = 0;
1232        unsigned long flags;
1233#ifdef ALLOW_IOV_BYPASS
1234        struct scatterlist *sg;
1235#endif
1236
1237        DBG_RUN_SG("%s() START %d entries\n", __FUNCTION__, nents);
1238        ioc = GET_IOC(dev);
1239        ASSERT(ioc);
1240
1241#ifdef ALLOW_IOV_BYPASS
1242        if (dev->dma_mask >= ioc->dma_mask) {
1243                for (sg = sglist ; filled < nents ; filled++, sg++){
1244                        sg->dma_length = sg->length;
1245                        sg->dma_address = virt_to_phys(sba_sg_address(sg));
1246                }
1247                return filled;
1248        }
1249#endif
1250        /* Fast path single entry scatterlists. */
1251        if (nents == 1) {
1252                sglist->dma_length = sglist->length;
1253                sglist->dma_address = sba_map_single(dev, sba_sg_address(sglist), sglist->length,
1254                                                     dir);
1255                return 1;
1256        }
1257
1258        spin_lock_irqsave(&ioc->res_lock, flags);
1259
1260#ifdef ASSERT_PDIR_SANITY
1261        if (sba_check_pdir(ioc,"Check before sba_map_sg()"))
1262        {
1263                sba_dump_sg(ioc, sglist, nents);
1264                panic("Check before sba_map_sg()");
1265        }
1266#endif
1267
1268        /*
1269        ** First coalesce the chunks and allocate I/O pdir space
1270        **
1271        ** If this is one DMA stream, we can properly map using the
1272        ** correct virtual address associated with each DMA page.
1273        ** w/o this association, we wouldn't have coherent DMA!
1274        ** Access to the virtual address is what forces a two pass algorithm.
1275        */
1276        coalesced = sba_coalesce_chunks(ioc, sglist, nents);
1277
1278        /*
1279        ** Program the I/O Pdir
1280        **
1281        ** map the virtual addresses to the I/O Pdir
1282        ** o dma_address will contain the pdir index
1283        ** o dma_len will contain the number of bytes to map
1284        ** o address contains the virtual address.
1285        */
1286        filled = sba_fill_pdir(ioc, sglist, nents);
1287
1288#ifdef ASSERT_PDIR_SANITY
1289        if (sba_check_pdir(ioc,"Check after sba_map_sg()"))
1290        {
1291                sba_dump_sg(ioc, sglist, nents);
1292                panic("Check after sba_map_sg()\n");
1293        }
1294#endif
1295
1296        spin_unlock_irqrestore(&ioc->res_lock, flags);
1297
1298        ASSERT(coalesced == filled);
1299        DBG_RUN_SG("%s() DONE %d mappings\n", __FUNCTION__, filled);
1300
1301        return filled;
1302}
1303
1304
1305/**
1306 * sba_unmap_sg - unmap Scatter/Gather list
1307 * @dev: instance of PCI owned by the driver that's asking.
1308 * @sglist:  array of buffer/length pairs
1309 * @nents:  number of entries in list
1310 * @dir:  R/W or both.
1311 *
1312 * See Documentation/DMA-mapping.txt
1313 */
1314void sba_unmap_sg (struct pci_dev *dev, struct scatterlist *sglist, int nents, int dir)
1315{
1316        struct ioc *ioc;
1317#ifdef ASSERT_PDIR_SANITY
1318        unsigned long flags;
1319#endif
1320
1321        DBG_RUN_SG("%s() START %d entries,  %p,%x\n",
1322                __FUNCTION__, nents, sba_sg_address(sglist), sglist->length);
1323
1324        ioc = GET_IOC(dev);
1325        ASSERT(ioc);
1326
1327#ifdef ASSERT_PDIR_SANITY
1328        spin_lock_irqsave(&ioc->res_lock, flags);
1329        sba_check_pdir(ioc,"Check before sba_unmap_sg()");
1330        spin_unlock_irqrestore(&ioc->res_lock, flags);
1331#endif
1332
1333        while (nents && sglist->dma_length) {
1334
1335                sba_unmap_single(dev, sglist->dma_address, sglist->dma_length, dir);
1336                sglist++;
1337                nents--;
1338        }
1339
1340        DBG_RUN_SG("%s() DONE (nents %d)\n", __FUNCTION__,  nents);
1341
1342#ifdef ASSERT_PDIR_SANITY
1343        spin_lock_irqsave(&ioc->res_lock, flags);
1344        sba_check_pdir(ioc,"Check after sba_unmap_sg()");
1345        spin_unlock_irqrestore(&ioc->res_lock, flags);
1346#endif
1347
1348}
1349
1350/**************************************************************
1351*
1352*   Initialization and claim
1353*
1354***************************************************************/
1355
1356static void __init
1357ioc_iova_init(struct ioc *ioc)
1358{
1359        int tcnfg;
1360        int agp_found = 0;
1361        struct pci_dev *device = NULL;
1362#ifdef FULL_VALID_PDIR
1363        unsigned long index;
1364#endif
1365
1366        /*
1367        ** Firmware programs the base and size of a "safe IOVA space"
1368        ** (one that doesn't overlap memory or LMMIO space) in the
1369        ** IBASE and IMASK registers.
1370        */
1371        ioc->ibase = READ_REG(ioc->ioc_hpa + IOC_IBASE) & ~0x1UL;
1372        ioc->imask = READ_REG(ioc->ioc_hpa + IOC_IMASK) | 0xFFFFFFFF00000000UL;
1373
1374        ioc->iov_size = ~ioc->imask + 1;
1375
1376        DBG_INIT("%s() hpa %p IOV base 0x%lx mask 0x%lx (%dMB)\n",
1377                __FUNCTION__, ioc->ioc_hpa, ioc->ibase, ioc->imask,
1378                ioc->iov_size >> 20);
1379
1380        switch (iovp_size) {
1381                case  4*1024: tcnfg = 0; break;
1382                case  8*1024: tcnfg = 1; break;
1383                case 16*1024: tcnfg = 2; break;
1384                case 64*1024: tcnfg = 3; break;
1385                default:
1386                        panic(PFX "Unsupported IOTLB page size %ldK",
1387                                iovp_size >> 10);
1388                        break;
1389        }
1390        WRITE_REG(tcnfg, ioc->ioc_hpa + IOC_TCNFG);
1391
1392        ioc->pdir_size = (ioc->iov_size / iovp_size) * PDIR_ENTRY_SIZE;
1393        ioc->pdir_base = (void *) __get_free_pages(GFP_KERNEL,
1394                                                   get_order(ioc->pdir_size));
1395        if (!ioc->pdir_base)
1396                panic(PFX "Couldn't allocate I/O Page Table\n");
1397
1398        memset(ioc->pdir_base, 0, ioc->pdir_size);
1399
1400        DBG_INIT("%s() IOV page size %ldK pdir %p size %x\n", __FUNCTION__,
1401                iovp_size >> 10, ioc->pdir_base, ioc->pdir_size);
1402
1403        ASSERT(ALIGN((unsigned long) ioc->pdir_base, 4*1024) == (unsigned long) ioc->pdir_base);
1404        WRITE_REG(virt_to_phys(ioc->pdir_base), ioc->ioc_hpa + IOC_PDIR_BASE);
1405
1406        /*
1407        ** If an AGP device is present, only use half of the IOV space
1408        ** for PCI DMA.  Unfortunately we can't know ahead of time
1409        ** whether GART support will actually be used, for now we
1410        ** can just key on an AGP device found in the system.
1411        ** We program the next pdir index after we stop w/ a key for
1412        ** the GART code to handshake on.
1413        */
1414        while ((device = pci_find_device(PCI_ANY_ID, PCI_ANY_ID, device)) != NULL)
1415                agp_found |= pci_find_capability(device, PCI_CAP_ID_AGP);
1416
1417        if (agp_found && reserve_sba_gart) {
1418                printk(KERN_INFO PFX "reserving %dMb of IOVA space at 0x%lx for agpgart\n",
1419                        ioc->iov_size/2 >> 20, ioc->ibase + ioc->iov_size/2);
1420                ioc->pdir_size /= 2;
1421                ((u64 *)ioc->pdir_base)[PDIR_INDEX(ioc->iov_size/2)] = ZX1_SBA_IOMMU_COOKIE;
1422        }
1423#ifdef FULL_VALID_PDIR
1424        /*
1425        ** Check to see if the spill page has been allocated, we don't need more than
1426        ** one across multiple SBAs.
1427        */
1428        if (!prefetch_spill_page) {
1429                char *spill_poison = "SBAIOMMU POISON";
1430                int poison_size = 16;
1431                void *poison_addr, *addr;
1432
1433                addr = (void *)__get_free_pages(GFP_KERNEL, get_order(iovp_size));
1434                if (!addr)
1435                        panic(PFX "Couldn't allocate PDIR spill page\n");
1436
1437                poison_addr = addr;
1438                for ( ; (u64) poison_addr < addr + iovp_size; poison_addr += poison_size)
1439                        memcpy(poison_addr, spill_poison, poison_size);
1440
1441                prefetch_spill_page = virt_to_phys(addr);
1442
1443                DBG_INIT("%s() prefetch spill addr: 0x%lx\n", __FUNCTION__, prefetch_spill_page);
1444        }
1445        /*
1446        ** Set all the PDIR entries valid w/ the spill page as the target
1447        */
1448        for (index = 0 ; index < (ioc->pdir_size / PDIR_ENTRY_SIZE) ; index++)
1449                ((u64 *)ioc->pdir_base)[index] = (0x80000000000000FF | prefetch_spill_page);
1450#endif
1451
1452        /* Clear I/O TLB of any possible entries */
1453        WRITE_REG(ioc->ibase | (get_iovp_order(ioc->iov_size) + iovp_shift), ioc->ioc_hpa + IOC_PCOM);
1454        READ_REG(ioc->ioc_hpa + IOC_PCOM);
1455
1456        /* Enable IOVA translation */
1457        WRITE_REG(ioc->ibase | 1, ioc->ioc_hpa + IOC_IBASE);
1458        READ_REG(ioc->ioc_hpa + IOC_IBASE);
1459}
1460
1461static void __init
1462ioc_resource_init(struct ioc *ioc)
1463{
1464        spin_lock_init(&ioc->res_lock);
1465
1466        /* resource map size dictated by pdir_size */
1467        ioc->res_size = ioc->pdir_size / PDIR_ENTRY_SIZE; /* entries */
1468        ioc->res_size >>= 3;  /* convert bit count to byte count */
1469        DBG_INIT("%s() res_size 0x%x\n", __FUNCTION__, ioc->res_size);
1470
1471        ioc->res_map = (char *) __get_free_pages(GFP_KERNEL,
1472                                                 get_order(ioc->res_size));
1473        if (!ioc->res_map)
1474                panic(PFX "Couldn't allocate resource map\n");
1475
1476        memset(ioc->res_map, 0, ioc->res_size);
1477        /* next available IOVP - circular search */
1478        ioc->res_hint = (unsigned long *) ioc->res_map;
1479
1480#ifdef ASSERT_PDIR_SANITY
1481        /* Mark first bit busy - ie no IOVA 0 */
1482        ioc->res_map[0] = 0x1;
1483        ioc->pdir_base[0] = 0x8000000000000000ULL | ZX1_SBA_IOMMU_COOKIE;
1484#endif
1485#ifdef FULL_VALID_PDIR
1486        /* Mark the last resource used so we don't prefetch beyond IOVA space */
1487        ioc->res_map[ioc->res_size - 1] |= 0x80UL; /* res_map is chars */
1488        ioc->pdir_base[(ioc->pdir_size / PDIR_ENTRY_SIZE) - 1] = (0x80000000000000FF
1489                                                              | prefetch_spill_page);
1490#endif
1491
1492        DBG_INIT("%s() res_map %x %p\n", __FUNCTION__,
1493                 ioc->res_size, (void *) ioc->res_map);
1494}
1495
1496static void __init
1497ioc_sac_init(struct ioc *ioc)
1498{
1499        struct pci_dev *sac = NULL;
1500        struct pci_controller *controller = NULL;
1501
1502        /*
1503         * pci_alloc_coherent() must return a DMA address which is
1504         * SAC (single address cycle) addressable, so allocate a
1505         * pseudo-device to enforce that.
1506         */
1507        sac = kmalloc(sizeof(*sac), GFP_KERNEL);
1508        if (!sac)
1509                panic(PFX "Couldn't allocate struct pci_dev");
1510        memset(sac, 0, sizeof(*sac));
1511
1512        controller = kmalloc(sizeof(*controller), GFP_KERNEL);
1513        if (!controller)
1514                panic(PFX "Couldn't allocate struct pci_controller");
1515        memset(controller, 0, sizeof(*controller));
1516
1517        controller->iommu = ioc;
1518        sac->sysdata = controller;
1519        sac->dma_mask = 0xFFFFFFFFUL;
1520        ioc->sac_only_dev = sac;
1521}
1522
1523static void __init
1524ioc_zx1_init(struct ioc *ioc)
1525{
1526        if (ioc->rev < 0x20)
1527                panic(PFX "IOC 2.0 or later required for IOMMU support\n");
1528
1529        ioc->dma_mask = 0xFFFFFFFFFFUL;
1530
1531        if (!iovp_shift) {
1532                /* 64k is max iommu page size */
1533                iovp_shift = min(PAGE_SHIFT, 16);
1534                iovp_size = (1 << iovp_shift);
1535                iovp_mask = ~(iovp_size - 1);
1536        }
1537}
1538
1539static void __init
1540ioc_sx1000_init(struct ioc *ioc)
1541{
1542        if (!iovp_shift) {
1543                iovp_shift = 12;        /* 4K for now */
1544                iovp_size = (1 << iovp_shift);
1545                iovp_mask = ~(iovp_size - 1);
1546        }
1547}
1548
1549typedef void (initfunc)(struct ioc *);
1550
1551struct ioc_iommu {
1552        u32 func_id;
1553        char *name;
1554        initfunc *init;
1555};
1556
1557static struct ioc_iommu ioc_iommu_info[] __initdata = {
1558        { ZX1_IOC_ID, "zx1", ioc_zx1_init },
1559        { REO_IOC_ID, "REO", ioc_sx1000_init },
1560        { SX1000_IOC_ID, "sx1000", ioc_sx1000_init },
1561};
1562
1563static struct ioc * __init
1564ioc_init(u64 hpa, void *handle)
1565{
1566        struct ioc *ioc;
1567        struct ioc_iommu *info;
1568
1569        ioc = kmalloc(sizeof(*ioc), GFP_KERNEL);
1570        if (!ioc)
1571                return NULL;
1572
1573        memset(ioc, 0, sizeof(*ioc));
1574
1575        ioc->next = ioc_list;
1576        ioc_list = ioc;
1577
1578        ioc->handle = handle;
1579        ioc->ioc_hpa = ioremap(hpa, 0x1000);
1580
1581        ioc->func_id = READ_REG(ioc->ioc_hpa + IOC_FUNC_ID);
1582        ioc->rev = READ_REG(ioc->ioc_hpa + IOC_FCLASS) & 0xFFUL;
1583        ioc->dma_mask = 0xFFFFFFFFFFFFFFFFUL;   /* conservative */
1584
1585        if (iovp_shift) {
1586                iovp_size = (1 << iovp_shift);
1587                iovp_mask = ~(iovp_size - 1);
1588        }
1589
1590        for (info = ioc_iommu_info; info < ioc_iommu_info + ARRAY_SIZE(ioc_iommu_info); info++) {
1591                if (ioc->func_id == info->func_id) {
1592                        ioc->name = info->name;
1593                        if (info->init)
1594                                (info->init)(ioc);
1595                }
1596        }
1597        DBG_INIT("%s: PAGE_SIZE %ldK, iovp_size %ldK\n", __FUNCTION__,
1598                PAGE_SIZE >> 10, iovp_size >> 10);
1599
1600        if (!ioc->name) {
1601                ioc->name = kmalloc(24, GFP_KERNEL);
1602                if (ioc->name)
1603                        sprintf((char *) ioc->name, "Unknown (%04x:%04x)",
1604                                ioc->func_id & 0xFFFF, (ioc->func_id >> 16) & 0xFFFF);
1605                else
1606                        ioc->name = "Unknown";
1607        }
1608
1609        ioc_iova_init(ioc);
1610        ioc_resource_init(ioc);
1611        ioc_sac_init(ioc);
1612
1613        printk(KERN_INFO PFX
1614                "%s %d.%d HPA 0x%lx IOVA space %dMb at 0x%lx\n",
1615                ioc->name, (ioc->rev >> 4) & 0xF, ioc->rev & 0xF,
1616                hpa, ioc->iov_size >> 20, ioc->ibase);
1617
1618        return ioc;
1619}
1620
1621
1622
1623/**************************************************************************
1624**
1625**   SBA initialization code (HW and SW)
1626**
1627**   o identify SBA chip itself
1628**   o FIXME: initialize DMA hints for reasonable defaults
1629**
1630**************************************************************************/
1631
1632#ifdef CONFIG_PROC_FS
1633static void *
1634ioc_start(struct seq_file *s, loff_t *pos)
1635{
1636        struct ioc *ioc;
1637        loff_t n = *pos;
1638
1639        for (ioc = ioc_list; ioc; ioc = ioc->next)
1640                if (!n--)
1641                        return ioc;
1642
1643        return NULL;
1644}
1645
1646static void *
1647ioc_next(struct seq_file *s, void *v, loff_t *pos)
1648{
1649        struct ioc *ioc = v;
1650
1651        ++*pos;
1652        return ioc->next;
1653}
1654
1655static void
1656ioc_stop(struct seq_file *s, void *v)
1657{
1658}
1659
1660static int
1661ioc_show(struct seq_file *s, void *v)
1662{
1663        struct ioc *ioc = v;
1664        unsigned long *res_ptr = (unsigned long *)ioc->res_map;
1665        int i, used = 0;
1666
1667        seq_printf(s, "Hewlett Packard %s IOC rev %d.%d\n",
1668                ioc->name, ((ioc->rev >> 4) & 0xF), (ioc->rev & 0xF));
1669        seq_printf(s, "IOVA size       : %d MB\n", ioc->iov_size/(1024*1024));
1670        seq_printf(s, "IOVA page size  : %ld kb\n", iovp_size/1024);
1671
1672        for (i = 0; i < (ioc->res_size / sizeof(unsigned long)); ++i, ++res_ptr)
1673                used += hweight64(*res_ptr);
1674
1675        seq_printf(s, "PDIR size       : %d entries\n", ioc->res_size << 3);
1676        seq_printf(s, "PDIR used       : %d entries\n", used);
1677
1678#ifdef PDIR_SEARCH_TIMING
1679        {
1680                unsigned long i = 0, avg = 0, min, max;
1681                min = max = ioc->avg_search[0];
1682                for (i = 0; i < SBA_SEARCH_SAMPLE; i++) {
1683                        avg += ioc->avg_search[i];
1684                        if (ioc->avg_search[i] > max) max = ioc->avg_search[i];
1685                        if (ioc->avg_search[i] < min) min = ioc->avg_search[i];
1686                }
1687                avg /= SBA_SEARCH_SAMPLE;
1688                seq_printf(s, "Bitmap search   : %ld/%ld/%ld (min/avg/max CPU Cycles)\n",
1689                           min, avg, max);
1690        }
1691#endif
1692#ifndef ALLOW_IOV_BYPASS
1693         seq_printf(s, "IOVA bypass disabled\n");
1694#endif
1695        return 0;
1696}
1697
1698static struct seq_operations ioc_seq_ops = {
1699        .start = ioc_start,
1700        .next  = ioc_next,
1701        .stop  = ioc_stop,
1702        .show  = ioc_show
1703};
1704
1705static int
1706ioc_open(struct inode *inode, struct file *file)
1707{
1708        return seq_open(file, &ioc_seq_ops);
1709}
1710
1711static struct file_operations ioc_fops = {
1712        .open    = ioc_open,
1713        .read    = seq_read,
1714        .llseek  = seq_lseek,
1715        .release = seq_release
1716};
1717
1718static void __init
1719ioc_proc_init(void)
1720{
1721        struct proc_dir_entry *dir, *entry;
1722
1723        dir = proc_mkdir("bus/mckinley", 0);
1724        if (!dir)
1725                return;
1726
1727        entry = create_proc_entry(ioc_list->name, 0, dir);
1728        if (entry)
1729                entry->proc_fops = &ioc_fops;
1730}
1731#endif
1732
1733static void
1734sba_connect_bus(struct pci_bus *bus)
1735{
1736        acpi_handle handle, parent;
1737        acpi_status status;
1738        struct ioc *ioc;
1739
1740        if (!PCI_CONTROLLER(bus))
1741                panic(PFX "no sysdata on bus %d!\n", bus->number);
1742
1743        if (PCI_CONTROLLER(bus)->iommu)
1744                return;
1745
1746        handle = PCI_CONTROLLER(bus)->acpi_handle;
1747        if (!handle)
1748                return;
1749
1750        /*
1751         * The IOC scope encloses PCI root bridges in the ACPI
1752         * namespace, so work our way out until we find an IOC we
1753         * claimed previously.
1754         */
1755        do {
1756                for (ioc = ioc_list; ioc; ioc = ioc->next)
1757                        if (ioc->handle == handle) {
1758                                PCI_CONTROLLER(bus)->iommu = ioc;
1759                                return;
1760                        }
1761
1762                status = acpi_get_parent(handle, &parent);
1763                handle = parent;
1764        } while (ACPI_SUCCESS(status));
1765
1766        printk(KERN_WARNING "No IOC for PCI Bus %04x:%02x in ACPI\n", PCI_SEGMENT(bus), bus->number);
1767}
1768
1769extern acpi_status acpi_hp_csr_space (acpi_handle obj, u64 *csr_base, u64 *csr_length);
1770
1771static int __init
1772acpi_sba_ioc_add(struct acpi_device *device)
1773{
1774        struct ioc *ioc;
1775        acpi_status status;
1776        u64 hpa, length;
1777        struct acpi_buffer buffer;
1778        struct acpi_device_info *dev_info;
1779
1780        status = acpi_hp_csr_space(device->handle, &hpa, &length);
1781        if (ACPI_FAILURE(status))
1782                return 1;
1783
1784        buffer.length = ACPI_ALLOCATE_LOCAL_BUFFER;
1785        status = acpi_get_object_info(device->handle, &buffer);
1786        if (ACPI_FAILURE(status))
1787                return 1;
1788        dev_info = buffer.pointer;
1789
1790        /*
1791         * For HWP0001, only SBA appears in ACPI namespace.  It encloses the PCI
1792         * root bridges, and its CSR space includes the IOC function.
1793         */
1794        if (strncmp("HWP0001", dev_info->hardware_id.value, 7) == 0)
1795                hpa += ZX1_IOC_OFFSET;
1796        ACPI_MEM_FREE(dev_info);
1797
1798        ioc = ioc_init(hpa, device->handle);
1799        if (!ioc)
1800                return 1;
1801
1802        return 0;
1803}
1804
1805static struct acpi_driver acpi_sba_ioc_driver = {
1806        .name           = "IOC IOMMU Driver",
1807        .ids            = "HWP0001,HWP0004",
1808        .ops            = {
1809                .add    = acpi_sba_ioc_add,
1810        },
1811};
1812
1813void __init
1814sba_init(void)
1815{
1816        acpi_bus_register_driver(&acpi_sba_ioc_driver);
1817        if (!ioc_list)
1818                return;
1819
1820#ifdef CONFIG_PCI
1821        {
1822                struct pci_bus *b = NULL;
1823                pci_for_each_bus(b)
1824                        sba_connect_bus(b);
1825        }
1826#endif
1827
1828#ifdef CONFIG_PROC_FS
1829        ioc_proc_init();
1830#endif
1831}
1832
1833static int __init
1834nosbagart(char *str)
1835{
1836        reserve_sba_gart = 0;
1837        return 1;
1838}
1839
1840int
1841sba_dma_supported (struct pci_dev *dev, u64 mask)
1842{
1843        /* make sure it's at least 32bit capable */
1844        return ((mask & 0xFFFFFFFFUL) == 0xFFFFFFFFUL);
1845}
1846
1847__setup("nosbagart", nosbagart);
1848
1849static int __init
1850sba_page_override(char *str)
1851{
1852        unsigned long page_size;
1853
1854        page_size = memparse(str, &str);
1855        switch (page_size) {
1856                case 4096:
1857                case 8192:
1858                case 16384:
1859                case 65536:
1860                        iovp_shift = ffs(page_size) - 1;
1861                        break;
1862                default:
1863                        printk("%s: unknown/unsupported iommu page size %ld\n",
1864                               __FUNCTION__, page_size);
1865        }
1866
1867        return 1;
1868}
1869
1870__setup("sbapagesize=",sba_page_override);
1871
1872EXPORT_SYMBOL(sba_init);
1873EXPORT_SYMBOL(sba_map_single);
1874EXPORT_SYMBOL(sba_unmap_single);
1875EXPORT_SYMBOL(sba_map_sg);
1876EXPORT_SYMBOL(sba_unmap_sg);
1877EXPORT_SYMBOL(sba_dma_supported);
1878EXPORT_SYMBOL(sba_alloc_coherent);
1879EXPORT_SYMBOL(sba_free_coherent);
1880
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.