powerpc/powernv: Implement pcibios_iov_resource_alignment() on powernv
[firefly-linux-kernel-4.4.55.git] / arch / powerpc / platforms / powernv / pci-ioda.c
1 /*
2  * Support PCI/PCIe on PowerNV platforms
3  *
4  * Copyright 2011 Benjamin Herrenschmidt, IBM Corp.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  */
11
12 #undef DEBUG
13
14 #include <linux/kernel.h>
15 #include <linux/pci.h>
16 #include <linux/crash_dump.h>
17 #include <linux/debugfs.h>
18 #include <linux/delay.h>
19 #include <linux/string.h>
20 #include <linux/init.h>
21 #include <linux/bootmem.h>
22 #include <linux/irq.h>
23 #include <linux/io.h>
24 #include <linux/msi.h>
25 #include <linux/memblock.h>
26
27 #include <asm/sections.h>
28 #include <asm/io.h>
29 #include <asm/prom.h>
30 #include <asm/pci-bridge.h>
31 #include <asm/machdep.h>
32 #include <asm/msi_bitmap.h>
33 #include <asm/ppc-pci.h>
34 #include <asm/opal.h>
35 #include <asm/iommu.h>
36 #include <asm/tce.h>
37 #include <asm/xics.h>
38 #include <asm/debug.h>
39 #include <asm/firmware.h>
40 #include <asm/pnv-pci.h>
41
42 #include <misc/cxl.h>
43
44 #include "powernv.h"
45 #include "pci.h"
46
47 static void pe_level_printk(const struct pnv_ioda_pe *pe, const char *level,
48                             const char *fmt, ...)
49 {
50         struct va_format vaf;
51         va_list args;
52         char pfix[32];
53
54         va_start(args, fmt);
55
56         vaf.fmt = fmt;
57         vaf.va = &args;
58
59         if (pe->pdev)
60                 strlcpy(pfix, dev_name(&pe->pdev->dev), sizeof(pfix));
61         else
62                 sprintf(pfix, "%04x:%02x     ",
63                         pci_domain_nr(pe->pbus), pe->pbus->number);
64
65         printk("%spci %s: [PE# %.3d] %pV",
66                level, pfix, pe->pe_number, &vaf);
67
68         va_end(args);
69 }
70
71 #define pe_err(pe, fmt, ...)                                    \
72         pe_level_printk(pe, KERN_ERR, fmt, ##__VA_ARGS__)
73 #define pe_warn(pe, fmt, ...)                                   \
74         pe_level_printk(pe, KERN_WARNING, fmt, ##__VA_ARGS__)
75 #define pe_info(pe, fmt, ...)                                   \
76         pe_level_printk(pe, KERN_INFO, fmt, ##__VA_ARGS__)
77
78 static bool pnv_iommu_bypass_disabled __read_mostly;
79
80 static int __init iommu_setup(char *str)
81 {
82         if (!str)
83                 return -EINVAL;
84
85         while (*str) {
86                 if (!strncmp(str, "nobypass", 8)) {
87                         pnv_iommu_bypass_disabled = true;
88                         pr_info("PowerNV: IOMMU bypass window disabled.\n");
89                         break;
90                 }
91                 str += strcspn(str, ",");
92                 if (*str == ',')
93                         str++;
94         }
95
96         return 0;
97 }
98 early_param("iommu", iommu_setup);
99
100 /*
101  * stdcix is only supposed to be used in hypervisor real mode as per
102  * the architecture spec
103  */
104 static inline void __raw_rm_writeq(u64 val, volatile void __iomem *paddr)
105 {
106         __asm__ __volatile__("stdcix %0,0,%1"
107                 : : "r" (val), "r" (paddr) : "memory");
108 }
109
110 static inline bool pnv_pci_is_mem_pref_64(unsigned long flags)
111 {
112         return ((flags & (IORESOURCE_MEM_64 | IORESOURCE_PREFETCH)) ==
113                 (IORESOURCE_MEM_64 | IORESOURCE_PREFETCH));
114 }
115
116 static void pnv_ioda_reserve_pe(struct pnv_phb *phb, int pe_no)
117 {
118         if (!(pe_no >= 0 && pe_no < phb->ioda.total_pe)) {
119                 pr_warn("%s: Invalid PE %d on PHB#%x\n",
120                         __func__, pe_no, phb->hose->global_number);
121                 return;
122         }
123
124         if (test_and_set_bit(pe_no, phb->ioda.pe_alloc)) {
125                 pr_warn("%s: PE %d was assigned on PHB#%x\n",
126                         __func__, pe_no, phb->hose->global_number);
127                 return;
128         }
129
130         phb->ioda.pe_array[pe_no].phb = phb;
131         phb->ioda.pe_array[pe_no].pe_number = pe_no;
132 }
133
134 static int pnv_ioda_alloc_pe(struct pnv_phb *phb)
135 {
136         unsigned long pe;
137
138         do {
139                 pe = find_next_zero_bit(phb->ioda.pe_alloc,
140                                         phb->ioda.total_pe, 0);
141                 if (pe >= phb->ioda.total_pe)
142                         return IODA_INVALID_PE;
143         } while(test_and_set_bit(pe, phb->ioda.pe_alloc));
144
145         phb->ioda.pe_array[pe].phb = phb;
146         phb->ioda.pe_array[pe].pe_number = pe;
147         return pe;
148 }
149
150 static void pnv_ioda_free_pe(struct pnv_phb *phb, int pe)
151 {
152         WARN_ON(phb->ioda.pe_array[pe].pdev);
153
154         memset(&phb->ioda.pe_array[pe], 0, sizeof(struct pnv_ioda_pe));
155         clear_bit(pe, phb->ioda.pe_alloc);
156 }
157
158 /* The default M64 BAR is shared by all PEs */
159 static int pnv_ioda2_init_m64(struct pnv_phb *phb)
160 {
161         const char *desc;
162         struct resource *r;
163         s64 rc;
164
165         /* Configure the default M64 BAR */
166         rc = opal_pci_set_phb_mem_window(phb->opal_id,
167                                          OPAL_M64_WINDOW_TYPE,
168                                          phb->ioda.m64_bar_idx,
169                                          phb->ioda.m64_base,
170                                          0, /* unused */
171                                          phb->ioda.m64_size);
172         if (rc != OPAL_SUCCESS) {
173                 desc = "configuring";
174                 goto fail;
175         }
176
177         /* Enable the default M64 BAR */
178         rc = opal_pci_phb_mmio_enable(phb->opal_id,
179                                       OPAL_M64_WINDOW_TYPE,
180                                       phb->ioda.m64_bar_idx,
181                                       OPAL_ENABLE_M64_SPLIT);
182         if (rc != OPAL_SUCCESS) {
183                 desc = "enabling";
184                 goto fail;
185         }
186
187         /* Mark the M64 BAR assigned */
188         set_bit(phb->ioda.m64_bar_idx, &phb->ioda.m64_bar_alloc);
189
190         /*
191          * Strip off the segment used by the reserved PE, which is
192          * expected to be 0 or last one of PE capabicity.
193          */
194         r = &phb->hose->mem_resources[1];
195         if (phb->ioda.reserved_pe == 0)
196                 r->start += phb->ioda.m64_segsize;
197         else if (phb->ioda.reserved_pe == (phb->ioda.total_pe - 1))
198                 r->end -= phb->ioda.m64_segsize;
199         else
200                 pr_warn("  Cannot strip M64 segment for reserved PE#%d\n",
201                         phb->ioda.reserved_pe);
202
203         return 0;
204
205 fail:
206         pr_warn("  Failure %lld %s M64 BAR#%d\n",
207                 rc, desc, phb->ioda.m64_bar_idx);
208         opal_pci_phb_mmio_enable(phb->opal_id,
209                                  OPAL_M64_WINDOW_TYPE,
210                                  phb->ioda.m64_bar_idx,
211                                  OPAL_DISABLE_M64);
212         return -EIO;
213 }
214
215 static void pnv_ioda2_reserve_m64_pe(struct pnv_phb *phb)
216 {
217         resource_size_t sgsz = phb->ioda.m64_segsize;
218         struct pci_dev *pdev;
219         struct resource *r;
220         int base, step, i;
221
222         /*
223          * Root bus always has full M64 range and root port has
224          * M64 range used in reality. So we're checking root port
225          * instead of root bus.
226          */
227         list_for_each_entry(pdev, &phb->hose->bus->devices, bus_list) {
228                 for (i = 0; i < PCI_BRIDGE_RESOURCE_NUM; i++) {
229                         r = &pdev->resource[PCI_BRIDGE_RESOURCES + i];
230                         if (!r->parent ||
231                             !pnv_pci_is_mem_pref_64(r->flags))
232                                 continue;
233
234                         base = (r->start - phb->ioda.m64_base) / sgsz;
235                         for (step = 0; step < resource_size(r) / sgsz; step++)
236                                 pnv_ioda_reserve_pe(phb, base + step);
237                 }
238         }
239 }
240
241 static int pnv_ioda2_pick_m64_pe(struct pnv_phb *phb,
242                                  struct pci_bus *bus, int all)
243 {
244         resource_size_t segsz = phb->ioda.m64_segsize;
245         struct pci_dev *pdev;
246         struct resource *r;
247         struct pnv_ioda_pe *master_pe, *pe;
248         unsigned long size, *pe_alloc;
249         bool found;
250         int start, i, j;
251
252         /* Root bus shouldn't use M64 */
253         if (pci_is_root_bus(bus))
254                 return IODA_INVALID_PE;
255
256         /* We support only one M64 window on each bus */
257         found = false;
258         pci_bus_for_each_resource(bus, r, i) {
259                 if (r && r->parent &&
260                     pnv_pci_is_mem_pref_64(r->flags)) {
261                         found = true;
262                         break;
263                 }
264         }
265
266         /* No M64 window found ? */
267         if (!found)
268                 return IODA_INVALID_PE;
269
270         /* Allocate bitmap */
271         size = _ALIGN_UP(phb->ioda.total_pe / 8, sizeof(unsigned long));
272         pe_alloc = kzalloc(size, GFP_KERNEL);
273         if (!pe_alloc) {
274                 pr_warn("%s: Out of memory !\n",
275                         __func__);
276                 return IODA_INVALID_PE;
277         }
278
279         /*
280          * Figure out reserved PE numbers by the PE
281          * the its child PEs.
282          */
283         start = (r->start - phb->ioda.m64_base) / segsz;
284         for (i = 0; i < resource_size(r) / segsz; i++)
285                 set_bit(start + i, pe_alloc);
286
287         if (all)
288                 goto done;
289
290         /*
291          * If the PE doesn't cover all subordinate buses,
292          * we need subtract from reserved PEs for children.
293          */
294         list_for_each_entry(pdev, &bus->devices, bus_list) {
295                 if (!pdev->subordinate)
296                         continue;
297
298                 pci_bus_for_each_resource(pdev->subordinate, r, i) {
299                         if (!r || !r->parent ||
300                             !pnv_pci_is_mem_pref_64(r->flags))
301                                 continue;
302
303                         start = (r->start - phb->ioda.m64_base) / segsz;
304                         for (j = 0; j < resource_size(r) / segsz ; j++)
305                                 clear_bit(start + j, pe_alloc);
306                 }
307         }
308
309         /*
310          * the current bus might not own M64 window and that's all
311          * contributed by its child buses. For the case, we needn't
312          * pick M64 dependent PE#.
313          */
314         if (bitmap_empty(pe_alloc, phb->ioda.total_pe)) {
315                 kfree(pe_alloc);
316                 return IODA_INVALID_PE;
317         }
318
319         /*
320          * Figure out the master PE and put all slave PEs to master
321          * PE's list to form compound PE.
322          */
323 done:
324         master_pe = NULL;
325         i = -1;
326         while ((i = find_next_bit(pe_alloc, phb->ioda.total_pe, i + 1)) <
327                 phb->ioda.total_pe) {
328                 pe = &phb->ioda.pe_array[i];
329
330                 if (!master_pe) {
331                         pe->flags |= PNV_IODA_PE_MASTER;
332                         INIT_LIST_HEAD(&pe->slaves);
333                         master_pe = pe;
334                 } else {
335                         pe->flags |= PNV_IODA_PE_SLAVE;
336                         pe->master = master_pe;
337                         list_add_tail(&pe->list, &master_pe->slaves);
338                 }
339         }
340
341         kfree(pe_alloc);
342         return master_pe->pe_number;
343 }
344
345 static void __init pnv_ioda_parse_m64_window(struct pnv_phb *phb)
346 {
347         struct pci_controller *hose = phb->hose;
348         struct device_node *dn = hose->dn;
349         struct resource *res;
350         const u32 *r;
351         u64 pci_addr;
352
353         /* FIXME: Support M64 for P7IOC */
354         if (phb->type != PNV_PHB_IODA2) {
355                 pr_info("  Not support M64 window\n");
356                 return;
357         }
358
359         if (!firmware_has_feature(FW_FEATURE_OPALv3)) {
360                 pr_info("  Firmware too old to support M64 window\n");
361                 return;
362         }
363
364         r = of_get_property(dn, "ibm,opal-m64-window", NULL);
365         if (!r) {
366                 pr_info("  No <ibm,opal-m64-window> on %s\n",
367                         dn->full_name);
368                 return;
369         }
370
371         res = &hose->mem_resources[1];
372         res->start = of_translate_address(dn, r + 2);
373         res->end = res->start + of_read_number(r + 4, 2) - 1;
374         res->flags = (IORESOURCE_MEM | IORESOURCE_MEM_64 | IORESOURCE_PREFETCH);
375         pci_addr = of_read_number(r, 2);
376         hose->mem_offset[1] = res->start - pci_addr;
377
378         phb->ioda.m64_size = resource_size(res);
379         phb->ioda.m64_segsize = phb->ioda.m64_size / phb->ioda.total_pe;
380         phb->ioda.m64_base = pci_addr;
381
382         pr_info(" MEM64 0x%016llx..0x%016llx -> 0x%016llx\n",
383                         res->start, res->end, pci_addr);
384
385         /* Use last M64 BAR to cover M64 window */
386         phb->ioda.m64_bar_idx = 15;
387         phb->init_m64 = pnv_ioda2_init_m64;
388         phb->reserve_m64_pe = pnv_ioda2_reserve_m64_pe;
389         phb->pick_m64_pe = pnv_ioda2_pick_m64_pe;
390 }
391
392 static void pnv_ioda_freeze_pe(struct pnv_phb *phb, int pe_no)
393 {
394         struct pnv_ioda_pe *pe = &phb->ioda.pe_array[pe_no];
395         struct pnv_ioda_pe *slave;
396         s64 rc;
397
398         /* Fetch master PE */
399         if (pe->flags & PNV_IODA_PE_SLAVE) {
400                 pe = pe->master;
401                 if (WARN_ON(!pe || !(pe->flags & PNV_IODA_PE_MASTER)))
402                         return;
403
404                 pe_no = pe->pe_number;
405         }
406
407         /* Freeze master PE */
408         rc = opal_pci_eeh_freeze_set(phb->opal_id,
409                                      pe_no,
410                                      OPAL_EEH_ACTION_SET_FREEZE_ALL);
411         if (rc != OPAL_SUCCESS) {
412                 pr_warn("%s: Failure %lld freezing PHB#%x-PE#%x\n",
413                         __func__, rc, phb->hose->global_number, pe_no);
414                 return;
415         }
416
417         /* Freeze slave PEs */
418         if (!(pe->flags & PNV_IODA_PE_MASTER))
419                 return;
420
421         list_for_each_entry(slave, &pe->slaves, list) {
422                 rc = opal_pci_eeh_freeze_set(phb->opal_id,
423                                              slave->pe_number,
424                                              OPAL_EEH_ACTION_SET_FREEZE_ALL);
425                 if (rc != OPAL_SUCCESS)
426                         pr_warn("%s: Failure %lld freezing PHB#%x-PE#%x\n",
427                                 __func__, rc, phb->hose->global_number,
428                                 slave->pe_number);
429         }
430 }
431
432 static int pnv_ioda_unfreeze_pe(struct pnv_phb *phb, int pe_no, int opt)
433 {
434         struct pnv_ioda_pe *pe, *slave;
435         s64 rc;
436
437         /* Find master PE */
438         pe = &phb->ioda.pe_array[pe_no];
439         if (pe->flags & PNV_IODA_PE_SLAVE) {
440                 pe = pe->master;
441                 WARN_ON(!pe || !(pe->flags & PNV_IODA_PE_MASTER));
442                 pe_no = pe->pe_number;
443         }
444
445         /* Clear frozen state for master PE */
446         rc = opal_pci_eeh_freeze_clear(phb->opal_id, pe_no, opt);
447         if (rc != OPAL_SUCCESS) {
448                 pr_warn("%s: Failure %lld clear %d on PHB#%x-PE#%x\n",
449                         __func__, rc, opt, phb->hose->global_number, pe_no);
450                 return -EIO;
451         }
452
453         if (!(pe->flags & PNV_IODA_PE_MASTER))
454                 return 0;
455
456         /* Clear frozen state for slave PEs */
457         list_for_each_entry(slave, &pe->slaves, list) {
458                 rc = opal_pci_eeh_freeze_clear(phb->opal_id,
459                                              slave->pe_number,
460                                              opt);
461                 if (rc != OPAL_SUCCESS) {
462                         pr_warn("%s: Failure %lld clear %d on PHB#%x-PE#%x\n",
463                                 __func__, rc, opt, phb->hose->global_number,
464                                 slave->pe_number);
465                         return -EIO;
466                 }
467         }
468
469         return 0;
470 }
471
472 static int pnv_ioda_get_pe_state(struct pnv_phb *phb, int pe_no)
473 {
474         struct pnv_ioda_pe *slave, *pe;
475         u8 fstate, state;
476         __be16 pcierr;
477         s64 rc;
478
479         /* Sanity check on PE number */
480         if (pe_no < 0 || pe_no >= phb->ioda.total_pe)
481                 return OPAL_EEH_STOPPED_PERM_UNAVAIL;
482
483         /*
484          * Fetch the master PE and the PE instance might be
485          * not initialized yet.
486          */
487         pe = &phb->ioda.pe_array[pe_no];
488         if (pe->flags & PNV_IODA_PE_SLAVE) {
489                 pe = pe->master;
490                 WARN_ON(!pe || !(pe->flags & PNV_IODA_PE_MASTER));
491                 pe_no = pe->pe_number;
492         }
493
494         /* Check the master PE */
495         rc = opal_pci_eeh_freeze_status(phb->opal_id, pe_no,
496                                         &state, &pcierr, NULL);
497         if (rc != OPAL_SUCCESS) {
498                 pr_warn("%s: Failure %lld getting "
499                         "PHB#%x-PE#%x state\n",
500                         __func__, rc,
501                         phb->hose->global_number, pe_no);
502                 return OPAL_EEH_STOPPED_TEMP_UNAVAIL;
503         }
504
505         /* Check the slave PE */
506         if (!(pe->flags & PNV_IODA_PE_MASTER))
507                 return state;
508
509         list_for_each_entry(slave, &pe->slaves, list) {
510                 rc = opal_pci_eeh_freeze_status(phb->opal_id,
511                                                 slave->pe_number,
512                                                 &fstate,
513                                                 &pcierr,
514                                                 NULL);
515                 if (rc != OPAL_SUCCESS) {
516                         pr_warn("%s: Failure %lld getting "
517                                 "PHB#%x-PE#%x state\n",
518                                 __func__, rc,
519                                 phb->hose->global_number, slave->pe_number);
520                         return OPAL_EEH_STOPPED_TEMP_UNAVAIL;
521                 }
522
523                 /*
524                  * Override the result based on the ascending
525                  * priority.
526                  */
527                 if (fstate > state)
528                         state = fstate;
529         }
530
531         return state;
532 }
533
534 /* Currently those 2 are only used when MSIs are enabled, this will change
535  * but in the meantime, we need to protect them to avoid warnings
536  */
537 #ifdef CONFIG_PCI_MSI
538 static struct pnv_ioda_pe *pnv_ioda_get_pe(struct pci_dev *dev)
539 {
540         struct pci_controller *hose = pci_bus_to_host(dev->bus);
541         struct pnv_phb *phb = hose->private_data;
542         struct pci_dn *pdn = pci_get_pdn(dev);
543
544         if (!pdn)
545                 return NULL;
546         if (pdn->pe_number == IODA_INVALID_PE)
547                 return NULL;
548         return &phb->ioda.pe_array[pdn->pe_number];
549 }
550 #endif /* CONFIG_PCI_MSI */
551
552 static int pnv_ioda_set_one_peltv(struct pnv_phb *phb,
553                                   struct pnv_ioda_pe *parent,
554                                   struct pnv_ioda_pe *child,
555                                   bool is_add)
556 {
557         const char *desc = is_add ? "adding" : "removing";
558         uint8_t op = is_add ? OPAL_ADD_PE_TO_DOMAIN :
559                               OPAL_REMOVE_PE_FROM_DOMAIN;
560         struct pnv_ioda_pe *slave;
561         long rc;
562
563         /* Parent PE affects child PE */
564         rc = opal_pci_set_peltv(phb->opal_id, parent->pe_number,
565                                 child->pe_number, op);
566         if (rc != OPAL_SUCCESS) {
567                 pe_warn(child, "OPAL error %ld %s to parent PELTV\n",
568                         rc, desc);
569                 return -ENXIO;
570         }
571
572         if (!(child->flags & PNV_IODA_PE_MASTER))
573                 return 0;
574
575         /* Compound case: parent PE affects slave PEs */
576         list_for_each_entry(slave, &child->slaves, list) {
577                 rc = opal_pci_set_peltv(phb->opal_id, parent->pe_number,
578                                         slave->pe_number, op);
579                 if (rc != OPAL_SUCCESS) {
580                         pe_warn(slave, "OPAL error %ld %s to parent PELTV\n",
581                                 rc, desc);
582                         return -ENXIO;
583                 }
584         }
585
586         return 0;
587 }
588
589 static int pnv_ioda_set_peltv(struct pnv_phb *phb,
590                               struct pnv_ioda_pe *pe,
591                               bool is_add)
592 {
593         struct pnv_ioda_pe *slave;
594         struct pci_dev *pdev;
595         int ret;
596
597         /*
598          * Clear PE frozen state. If it's master PE, we need
599          * clear slave PE frozen state as well.
600          */
601         if (is_add) {
602                 opal_pci_eeh_freeze_clear(phb->opal_id, pe->pe_number,
603                                           OPAL_EEH_ACTION_CLEAR_FREEZE_ALL);
604                 if (pe->flags & PNV_IODA_PE_MASTER) {
605                         list_for_each_entry(slave, &pe->slaves, list)
606                                 opal_pci_eeh_freeze_clear(phb->opal_id,
607                                                           slave->pe_number,
608                                                           OPAL_EEH_ACTION_CLEAR_FREEZE_ALL);
609                 }
610         }
611
612         /*
613          * Associate PE in PELT. We need add the PE into the
614          * corresponding PELT-V as well. Otherwise, the error
615          * originated from the PE might contribute to other
616          * PEs.
617          */
618         ret = pnv_ioda_set_one_peltv(phb, pe, pe, is_add);
619         if (ret)
620                 return ret;
621
622         /* For compound PEs, any one affects all of them */
623         if (pe->flags & PNV_IODA_PE_MASTER) {
624                 list_for_each_entry(slave, &pe->slaves, list) {
625                         ret = pnv_ioda_set_one_peltv(phb, slave, pe, is_add);
626                         if (ret)
627                                 return ret;
628                 }
629         }
630
631         if (pe->flags & (PNV_IODA_PE_BUS_ALL | PNV_IODA_PE_BUS))
632                 pdev = pe->pbus->self;
633         else
634                 pdev = pe->pdev->bus->self;
635         while (pdev) {
636                 struct pci_dn *pdn = pci_get_pdn(pdev);
637                 struct pnv_ioda_pe *parent;
638
639                 if (pdn && pdn->pe_number != IODA_INVALID_PE) {
640                         parent = &phb->ioda.pe_array[pdn->pe_number];
641                         ret = pnv_ioda_set_one_peltv(phb, parent, pe, is_add);
642                         if (ret)
643                                 return ret;
644                 }
645
646                 pdev = pdev->bus->self;
647         }
648
649         return 0;
650 }
651
652 static int pnv_ioda_configure_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe)
653 {
654         struct pci_dev *parent;
655         uint8_t bcomp, dcomp, fcomp;
656         long rc, rid_end, rid;
657
658         /* Bus validation ? */
659         if (pe->pbus) {
660                 int count;
661
662                 dcomp = OPAL_IGNORE_RID_DEVICE_NUMBER;
663                 fcomp = OPAL_IGNORE_RID_FUNCTION_NUMBER;
664                 parent = pe->pbus->self;
665                 if (pe->flags & PNV_IODA_PE_BUS_ALL)
666                         count = pe->pbus->busn_res.end - pe->pbus->busn_res.start + 1;
667                 else
668                         count = 1;
669
670                 switch(count) {
671                 case  1: bcomp = OpalPciBusAll;         break;
672                 case  2: bcomp = OpalPciBus7Bits;       break;
673                 case  4: bcomp = OpalPciBus6Bits;       break;
674                 case  8: bcomp = OpalPciBus5Bits;       break;
675                 case 16: bcomp = OpalPciBus4Bits;       break;
676                 case 32: bcomp = OpalPciBus3Bits;       break;
677                 default:
678                         pr_err("%s: Number of subordinate busses %d"
679                                " unsupported\n",
680                                pci_name(pe->pbus->self), count);
681                         /* Do an exact match only */
682                         bcomp = OpalPciBusAll;
683                 }
684                 rid_end = pe->rid + (count << 8);
685         } else {
686                 parent = pe->pdev->bus->self;
687                 bcomp = OpalPciBusAll;
688                 dcomp = OPAL_COMPARE_RID_DEVICE_NUMBER;
689                 fcomp = OPAL_COMPARE_RID_FUNCTION_NUMBER;
690                 rid_end = pe->rid + 1;
691         }
692
693         /*
694          * Associate PE in PELT. We need add the PE into the
695          * corresponding PELT-V as well. Otherwise, the error
696          * originated from the PE might contribute to other
697          * PEs.
698          */
699         rc = opal_pci_set_pe(phb->opal_id, pe->pe_number, pe->rid,
700                              bcomp, dcomp, fcomp, OPAL_MAP_PE);
701         if (rc) {
702                 pe_err(pe, "OPAL error %ld trying to setup PELT table\n", rc);
703                 return -ENXIO;
704         }
705
706         /* Configure PELTV */
707         pnv_ioda_set_peltv(phb, pe, true);
708
709         /* Setup reverse map */
710         for (rid = pe->rid; rid < rid_end; rid++)
711                 phb->ioda.pe_rmap[rid] = pe->pe_number;
712
713         /* Setup one MVTs on IODA1 */
714         if (phb->type != PNV_PHB_IODA1) {
715                 pe->mve_number = 0;
716                 goto out;
717         }
718
719         pe->mve_number = pe->pe_number;
720         rc = opal_pci_set_mve(phb->opal_id, pe->mve_number, pe->pe_number);
721         if (rc != OPAL_SUCCESS) {
722                 pe_err(pe, "OPAL error %ld setting up MVE %d\n",
723                        rc, pe->mve_number);
724                 pe->mve_number = -1;
725         } else {
726                 rc = opal_pci_set_mve_enable(phb->opal_id,
727                                              pe->mve_number, OPAL_ENABLE_MVE);
728                 if (rc) {
729                         pe_err(pe, "OPAL error %ld enabling MVE %d\n",
730                                rc, pe->mve_number);
731                         pe->mve_number = -1;
732                 }
733         }
734
735 out:
736         return 0;
737 }
738
739 static void pnv_ioda_link_pe_by_weight(struct pnv_phb *phb,
740                                        struct pnv_ioda_pe *pe)
741 {
742         struct pnv_ioda_pe *lpe;
743
744         list_for_each_entry(lpe, &phb->ioda.pe_dma_list, dma_link) {
745                 if (lpe->dma_weight < pe->dma_weight) {
746                         list_add_tail(&pe->dma_link, &lpe->dma_link);
747                         return;
748                 }
749         }
750         list_add_tail(&pe->dma_link, &phb->ioda.pe_dma_list);
751 }
752
753 static unsigned int pnv_ioda_dma_weight(struct pci_dev *dev)
754 {
755         /* This is quite simplistic. The "base" weight of a device
756          * is 10. 0 means no DMA is to be accounted for it.
757          */
758
759         /* If it's a bridge, no DMA */
760         if (dev->hdr_type != PCI_HEADER_TYPE_NORMAL)
761                 return 0;
762
763         /* Reduce the weight of slow USB controllers */
764         if (dev->class == PCI_CLASS_SERIAL_USB_UHCI ||
765             dev->class == PCI_CLASS_SERIAL_USB_OHCI ||
766             dev->class == PCI_CLASS_SERIAL_USB_EHCI)
767                 return 3;
768
769         /* Increase the weight of RAID (includes Obsidian) */
770         if ((dev->class >> 8) == PCI_CLASS_STORAGE_RAID)
771                 return 15;
772
773         /* Default */
774         return 10;
775 }
776
777 #if 0
778 static struct pnv_ioda_pe *pnv_ioda_setup_dev_PE(struct pci_dev *dev)
779 {
780         struct pci_controller *hose = pci_bus_to_host(dev->bus);
781         struct pnv_phb *phb = hose->private_data;
782         struct pci_dn *pdn = pci_get_pdn(dev);
783         struct pnv_ioda_pe *pe;
784         int pe_num;
785
786         if (!pdn) {
787                 pr_err("%s: Device tree node not associated properly\n",
788                            pci_name(dev));
789                 return NULL;
790         }
791         if (pdn->pe_number != IODA_INVALID_PE)
792                 return NULL;
793
794         /* PE#0 has been pre-set */
795         if (dev->bus->number == 0)
796                 pe_num = 0;
797         else
798                 pe_num = pnv_ioda_alloc_pe(phb);
799         if (pe_num == IODA_INVALID_PE) {
800                 pr_warning("%s: Not enough PE# available, disabling device\n",
801                            pci_name(dev));
802                 return NULL;
803         }
804
805         /* NOTE: We get only one ref to the pci_dev for the pdn, not for the
806          * pointer in the PE data structure, both should be destroyed at the
807          * same time. However, this needs to be looked at more closely again
808          * once we actually start removing things (Hotplug, SR-IOV, ...)
809          *
810          * At some point we want to remove the PDN completely anyways
811          */
812         pe = &phb->ioda.pe_array[pe_num];
813         pci_dev_get(dev);
814         pdn->pcidev = dev;
815         pdn->pe_number = pe_num;
816         pe->pdev = dev;
817         pe->pbus = NULL;
818         pe->tce32_seg = -1;
819         pe->mve_number = -1;
820         pe->rid = dev->bus->number << 8 | pdn->devfn;
821
822         pe_info(pe, "Associated device to PE\n");
823
824         if (pnv_ioda_configure_pe(phb, pe)) {
825                 /* XXX What do we do here ? */
826                 if (pe_num)
827                         pnv_ioda_free_pe(phb, pe_num);
828                 pdn->pe_number = IODA_INVALID_PE;
829                 pe->pdev = NULL;
830                 pci_dev_put(dev);
831                 return NULL;
832         }
833
834         /* Assign a DMA weight to the device */
835         pe->dma_weight = pnv_ioda_dma_weight(dev);
836         if (pe->dma_weight != 0) {
837                 phb->ioda.dma_weight += pe->dma_weight;
838                 phb->ioda.dma_pe_count++;
839         }
840
841         /* Link the PE */
842         pnv_ioda_link_pe_by_weight(phb, pe);
843
844         return pe;
845 }
846 #endif /* Useful for SRIOV case */
847
848 static void pnv_ioda_setup_same_PE(struct pci_bus *bus, struct pnv_ioda_pe *pe)
849 {
850         struct pci_dev *dev;
851
852         list_for_each_entry(dev, &bus->devices, bus_list) {
853                 struct pci_dn *pdn = pci_get_pdn(dev);
854
855                 if (pdn == NULL) {
856                         pr_warn("%s: No device node associated with device !\n",
857                                 pci_name(dev));
858                         continue;
859                 }
860                 pdn->pcidev = dev;
861                 pdn->pe_number = pe->pe_number;
862                 pe->dma_weight += pnv_ioda_dma_weight(dev);
863                 if ((pe->flags & PNV_IODA_PE_BUS_ALL) && dev->subordinate)
864                         pnv_ioda_setup_same_PE(dev->subordinate, pe);
865         }
866 }
867
868 /*
869  * There're 2 types of PCI bus sensitive PEs: One that is compromised of
870  * single PCI bus. Another one that contains the primary PCI bus and its
871  * subordinate PCI devices and buses. The second type of PE is normally
872  * orgiriated by PCIe-to-PCI bridge or PLX switch downstream ports.
873  */
874 static void pnv_ioda_setup_bus_PE(struct pci_bus *bus, int all)
875 {
876         struct pci_controller *hose = pci_bus_to_host(bus);
877         struct pnv_phb *phb = hose->private_data;
878         struct pnv_ioda_pe *pe;
879         int pe_num = IODA_INVALID_PE;
880
881         /* Check if PE is determined by M64 */
882         if (phb->pick_m64_pe)
883                 pe_num = phb->pick_m64_pe(phb, bus, all);
884
885         /* The PE number isn't pinned by M64 */
886         if (pe_num == IODA_INVALID_PE)
887                 pe_num = pnv_ioda_alloc_pe(phb);
888
889         if (pe_num == IODA_INVALID_PE) {
890                 pr_warning("%s: Not enough PE# available for PCI bus %04x:%02x\n",
891                         __func__, pci_domain_nr(bus), bus->number);
892                 return;
893         }
894
895         pe = &phb->ioda.pe_array[pe_num];
896         pe->flags |= (all ? PNV_IODA_PE_BUS_ALL : PNV_IODA_PE_BUS);
897         pe->pbus = bus;
898         pe->pdev = NULL;
899         pe->tce32_seg = -1;
900         pe->mve_number = -1;
901         pe->rid = bus->busn_res.start << 8;
902         pe->dma_weight = 0;
903
904         if (all)
905                 pe_info(pe, "Secondary bus %d..%d associated with PE#%d\n",
906                         bus->busn_res.start, bus->busn_res.end, pe_num);
907         else
908                 pe_info(pe, "Secondary bus %d associated with PE#%d\n",
909                         bus->busn_res.start, pe_num);
910
911         if (pnv_ioda_configure_pe(phb, pe)) {
912                 /* XXX What do we do here ? */
913                 if (pe_num)
914                         pnv_ioda_free_pe(phb, pe_num);
915                 pe->pbus = NULL;
916                 return;
917         }
918
919         pe->tce32_table = kzalloc_node(sizeof(struct iommu_table),
920                         GFP_KERNEL, hose->node);
921         pe->tce32_table->data = pe;
922
923         /* Associate it with all child devices */
924         pnv_ioda_setup_same_PE(bus, pe);
925
926         /* Put PE to the list */
927         list_add_tail(&pe->list, &phb->ioda.pe_list);
928
929         /* Account for one DMA PE if at least one DMA capable device exist
930          * below the bridge
931          */
932         if (pe->dma_weight != 0) {
933                 phb->ioda.dma_weight += pe->dma_weight;
934                 phb->ioda.dma_pe_count++;
935         }
936
937         /* Link the PE */
938         pnv_ioda_link_pe_by_weight(phb, pe);
939 }
940
941 static void pnv_ioda_setup_PEs(struct pci_bus *bus)
942 {
943         struct pci_dev *dev;
944
945         pnv_ioda_setup_bus_PE(bus, 0);
946
947         list_for_each_entry(dev, &bus->devices, bus_list) {
948                 if (dev->subordinate) {
949                         if (pci_pcie_type(dev) == PCI_EXP_TYPE_PCI_BRIDGE)
950                                 pnv_ioda_setup_bus_PE(dev->subordinate, 1);
951                         else
952                                 pnv_ioda_setup_PEs(dev->subordinate);
953                 }
954         }
955 }
956
957 /*
958  * Configure PEs so that the downstream PCI buses and devices
959  * could have their associated PE#. Unfortunately, we didn't
960  * figure out the way to identify the PLX bridge yet. So we
961  * simply put the PCI bus and the subordinate behind the root
962  * port to PE# here. The game rule here is expected to be changed
963  * as soon as we can detected PLX bridge correctly.
964  */
965 static void pnv_pci_ioda_setup_PEs(void)
966 {
967         struct pci_controller *hose, *tmp;
968         struct pnv_phb *phb;
969
970         list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
971                 phb = hose->private_data;
972
973                 /* M64 layout might affect PE allocation */
974                 if (phb->reserve_m64_pe)
975                         phb->reserve_m64_pe(phb);
976
977                 pnv_ioda_setup_PEs(hose->bus);
978         }
979 }
980
981 #ifdef CONFIG_PCI_IOV
982 int pcibios_sriov_disable(struct pci_dev *pdev)
983 {
984         /* Release PCI data */
985         remove_dev_pci_data(pdev);
986         return 0;
987 }
988
989 int pcibios_sriov_enable(struct pci_dev *pdev, u16 num_vfs)
990 {
991         /* Allocate PCI data */
992         add_dev_pci_data(pdev);
993         return 0;
994 }
995 #endif /* CONFIG_PCI_IOV */
996
997 static void pnv_pci_ioda_dma_dev_setup(struct pnv_phb *phb, struct pci_dev *pdev)
998 {
999         struct pci_dn *pdn = pci_get_pdn(pdev);
1000         struct pnv_ioda_pe *pe;
1001
1002         /*
1003          * The function can be called while the PE#
1004          * hasn't been assigned. Do nothing for the
1005          * case.
1006          */
1007         if (!pdn || pdn->pe_number == IODA_INVALID_PE)
1008                 return;
1009
1010         pe = &phb->ioda.pe_array[pdn->pe_number];
1011         WARN_ON(get_dma_ops(&pdev->dev) != &dma_iommu_ops);
1012         set_iommu_table_base_and_group(&pdev->dev, pe->tce32_table);
1013 }
1014
1015 static int pnv_pci_ioda_dma_set_mask(struct pnv_phb *phb,
1016                                      struct pci_dev *pdev, u64 dma_mask)
1017 {
1018         struct pci_dn *pdn = pci_get_pdn(pdev);
1019         struct pnv_ioda_pe *pe;
1020         uint64_t top;
1021         bool bypass = false;
1022
1023         if (WARN_ON(!pdn || pdn->pe_number == IODA_INVALID_PE))
1024                 return -ENODEV;;
1025
1026         pe = &phb->ioda.pe_array[pdn->pe_number];
1027         if (pe->tce_bypass_enabled) {
1028                 top = pe->tce_bypass_base + memblock_end_of_DRAM() - 1;
1029                 bypass = (dma_mask >= top);
1030         }
1031
1032         if (bypass) {
1033                 dev_info(&pdev->dev, "Using 64-bit DMA iommu bypass\n");
1034                 set_dma_ops(&pdev->dev, &dma_direct_ops);
1035                 set_dma_offset(&pdev->dev, pe->tce_bypass_base);
1036         } else {
1037                 dev_info(&pdev->dev, "Using 32-bit DMA via iommu\n");
1038                 set_dma_ops(&pdev->dev, &dma_iommu_ops);
1039                 set_iommu_table_base(&pdev->dev, pe->tce32_table);
1040         }
1041         *pdev->dev.dma_mask = dma_mask;
1042         return 0;
1043 }
1044
1045 static u64 pnv_pci_ioda_dma_get_required_mask(struct pnv_phb *phb,
1046                                               struct pci_dev *pdev)
1047 {
1048         struct pci_dn *pdn = pci_get_pdn(pdev);
1049         struct pnv_ioda_pe *pe;
1050         u64 end, mask;
1051
1052         if (WARN_ON(!pdn || pdn->pe_number == IODA_INVALID_PE))
1053                 return 0;
1054
1055         pe = &phb->ioda.pe_array[pdn->pe_number];
1056         if (!pe->tce_bypass_enabled)
1057                 return __dma_get_required_mask(&pdev->dev);
1058
1059
1060         end = pe->tce_bypass_base + memblock_end_of_DRAM();
1061         mask = 1ULL << (fls64(end) - 1);
1062         mask += mask - 1;
1063
1064         return mask;
1065 }
1066
1067 static void pnv_ioda_setup_bus_dma(struct pnv_ioda_pe *pe,
1068                                    struct pci_bus *bus,
1069                                    bool add_to_iommu_group)
1070 {
1071         struct pci_dev *dev;
1072
1073         list_for_each_entry(dev, &bus->devices, bus_list) {
1074                 if (add_to_iommu_group)
1075                         set_iommu_table_base_and_group(&dev->dev,
1076                                                        pe->tce32_table);
1077                 else
1078                         set_iommu_table_base(&dev->dev, pe->tce32_table);
1079
1080                 if (dev->subordinate)
1081                         pnv_ioda_setup_bus_dma(pe, dev->subordinate,
1082                                                add_to_iommu_group);
1083         }
1084 }
1085
1086 static void pnv_pci_ioda1_tce_invalidate(struct pnv_ioda_pe *pe,
1087                                          struct iommu_table *tbl,
1088                                          __be64 *startp, __be64 *endp, bool rm)
1089 {
1090         __be64 __iomem *invalidate = rm ?
1091                 (__be64 __iomem *)pe->tce_inval_reg_phys :
1092                 (__be64 __iomem *)tbl->it_index;
1093         unsigned long start, end, inc;
1094         const unsigned shift = tbl->it_page_shift;
1095
1096         start = __pa(startp);
1097         end = __pa(endp);
1098
1099         /* BML uses this case for p6/p7/galaxy2: Shift addr and put in node */
1100         if (tbl->it_busno) {
1101                 start <<= shift;
1102                 end <<= shift;
1103                 inc = 128ull << shift;
1104                 start |= tbl->it_busno;
1105                 end |= tbl->it_busno;
1106         } else if (tbl->it_type & TCE_PCI_SWINV_PAIR) {
1107                 /* p7ioc-style invalidation, 2 TCEs per write */
1108                 start |= (1ull << 63);
1109                 end |= (1ull << 63);
1110                 inc = 16;
1111         } else {
1112                 /* Default (older HW) */
1113                 inc = 128;
1114         }
1115
1116         end |= inc - 1; /* round up end to be different than start */
1117
1118         mb(); /* Ensure above stores are visible */
1119         while (start <= end) {
1120                 if (rm)
1121                         __raw_rm_writeq(cpu_to_be64(start), invalidate);
1122                 else
1123                         __raw_writeq(cpu_to_be64(start), invalidate);
1124                 start += inc;
1125         }
1126
1127         /*
1128          * The iommu layer will do another mb() for us on build()
1129          * and we don't care on free()
1130          */
1131 }
1132
1133 static void pnv_pci_ioda2_tce_invalidate(struct pnv_ioda_pe *pe,
1134                                          struct iommu_table *tbl,
1135                                          __be64 *startp, __be64 *endp, bool rm)
1136 {
1137         unsigned long start, end, inc;
1138         __be64 __iomem *invalidate = rm ?
1139                 (__be64 __iomem *)pe->tce_inval_reg_phys :
1140                 (__be64 __iomem *)tbl->it_index;
1141         const unsigned shift = tbl->it_page_shift;
1142
1143         /* We'll invalidate DMA address in PE scope */
1144         start = 0x2ull << 60;
1145         start |= (pe->pe_number & 0xFF);
1146         end = start;
1147
1148         /* Figure out the start, end and step */
1149         inc = tbl->it_offset + (((u64)startp - tbl->it_base) / sizeof(u64));
1150         start |= (inc << shift);
1151         inc = tbl->it_offset + (((u64)endp - tbl->it_base) / sizeof(u64));
1152         end |= (inc << shift);
1153         inc = (0x1ull << shift);
1154         mb();
1155
1156         while (start <= end) {
1157                 if (rm)
1158                         __raw_rm_writeq(cpu_to_be64(start), invalidate);
1159                 else
1160                         __raw_writeq(cpu_to_be64(start), invalidate);
1161                 start += inc;
1162         }
1163 }
1164
1165 void pnv_pci_ioda_tce_invalidate(struct iommu_table *tbl,
1166                                  __be64 *startp, __be64 *endp, bool rm)
1167 {
1168         struct pnv_ioda_pe *pe = tbl->data;
1169         struct pnv_phb *phb = pe->phb;
1170
1171         if (phb->type == PNV_PHB_IODA1)
1172                 pnv_pci_ioda1_tce_invalidate(pe, tbl, startp, endp, rm);
1173         else
1174                 pnv_pci_ioda2_tce_invalidate(pe, tbl, startp, endp, rm);
1175 }
1176
1177 static void pnv_pci_ioda_setup_dma_pe(struct pnv_phb *phb,
1178                                       struct pnv_ioda_pe *pe, unsigned int base,
1179                                       unsigned int segs)
1180 {
1181
1182         struct page *tce_mem = NULL;
1183         const __be64 *swinvp;
1184         struct iommu_table *tbl;
1185         unsigned int i;
1186         int64_t rc;
1187         void *addr;
1188
1189         /* 256M DMA window, 4K TCE pages, 8 bytes TCE */
1190 #define TCE32_TABLE_SIZE        ((0x10000000 / 0x1000) * 8)
1191
1192         /* XXX FIXME: Handle 64-bit only DMA devices */
1193         /* XXX FIXME: Provide 64-bit DMA facilities & non-4K TCE tables etc.. */
1194         /* XXX FIXME: Allocate multi-level tables on PHB3 */
1195
1196         /* We shouldn't already have a 32-bit DMA associated */
1197         if (WARN_ON(pe->tce32_seg >= 0))
1198                 return;
1199
1200         /* Grab a 32-bit TCE table */
1201         pe->tce32_seg = base;
1202         pe_info(pe, " Setting up 32-bit TCE table at %08x..%08x\n",
1203                 (base << 28), ((base + segs) << 28) - 1);
1204
1205         /* XXX Currently, we allocate one big contiguous table for the
1206          * TCEs. We only really need one chunk per 256M of TCE space
1207          * (ie per segment) but that's an optimization for later, it
1208          * requires some added smarts with our get/put_tce implementation
1209          */
1210         tce_mem = alloc_pages_node(phb->hose->node, GFP_KERNEL,
1211                                    get_order(TCE32_TABLE_SIZE * segs));
1212         if (!tce_mem) {
1213                 pe_err(pe, " Failed to allocate a 32-bit TCE memory\n");
1214                 goto fail;
1215         }
1216         addr = page_address(tce_mem);
1217         memset(addr, 0, TCE32_TABLE_SIZE * segs);
1218
1219         /* Configure HW */
1220         for (i = 0; i < segs; i++) {
1221                 rc = opal_pci_map_pe_dma_window(phb->opal_id,
1222                                               pe->pe_number,
1223                                               base + i, 1,
1224                                               __pa(addr) + TCE32_TABLE_SIZE * i,
1225                                               TCE32_TABLE_SIZE, 0x1000);
1226                 if (rc) {
1227                         pe_err(pe, " Failed to configure 32-bit TCE table,"
1228                                " err %ld\n", rc);
1229                         goto fail;
1230                 }
1231         }
1232
1233         /* Setup linux iommu table */
1234         tbl = pe->tce32_table;
1235         pnv_pci_setup_iommu_table(tbl, addr, TCE32_TABLE_SIZE * segs,
1236                                   base << 28, IOMMU_PAGE_SHIFT_4K);
1237
1238         /* OPAL variant of P7IOC SW invalidated TCEs */
1239         swinvp = of_get_property(phb->hose->dn, "ibm,opal-tce-kill", NULL);
1240         if (swinvp) {
1241                 /* We need a couple more fields -- an address and a data
1242                  * to or.  Since the bus is only printed out on table free
1243                  * errors, and on the first pass the data will be a relative
1244                  * bus number, print that out instead.
1245                  */
1246                 pe->tce_inval_reg_phys = be64_to_cpup(swinvp);
1247                 tbl->it_index = (unsigned long)ioremap(pe->tce_inval_reg_phys,
1248                                 8);
1249                 tbl->it_type |= (TCE_PCI_SWINV_CREATE |
1250                                  TCE_PCI_SWINV_FREE   |
1251                                  TCE_PCI_SWINV_PAIR);
1252         }
1253         iommu_init_table(tbl, phb->hose->node);
1254         iommu_register_group(tbl, phb->hose->global_number, pe->pe_number);
1255
1256         if (pe->pdev)
1257                 set_iommu_table_base_and_group(&pe->pdev->dev, tbl);
1258         else
1259                 pnv_ioda_setup_bus_dma(pe, pe->pbus, true);
1260
1261         return;
1262  fail:
1263         /* XXX Failure: Try to fallback to 64-bit only ? */
1264         if (pe->tce32_seg >= 0)
1265                 pe->tce32_seg = -1;
1266         if (tce_mem)
1267                 __free_pages(tce_mem, get_order(TCE32_TABLE_SIZE * segs));
1268 }
1269
1270 static void pnv_pci_ioda2_set_bypass(struct iommu_table *tbl, bool enable)
1271 {
1272         struct pnv_ioda_pe *pe = tbl->data;
1273         uint16_t window_id = (pe->pe_number << 1 ) + 1;
1274         int64_t rc;
1275
1276         pe_info(pe, "%sabling 64-bit DMA bypass\n", enable ? "En" : "Dis");
1277         if (enable) {
1278                 phys_addr_t top = memblock_end_of_DRAM();
1279
1280                 top = roundup_pow_of_two(top);
1281                 rc = opal_pci_map_pe_dma_window_real(pe->phb->opal_id,
1282                                                      pe->pe_number,
1283                                                      window_id,
1284                                                      pe->tce_bypass_base,
1285                                                      top);
1286         } else {
1287                 rc = opal_pci_map_pe_dma_window_real(pe->phb->opal_id,
1288                                                      pe->pe_number,
1289                                                      window_id,
1290                                                      pe->tce_bypass_base,
1291                                                      0);
1292
1293                 /*
1294                  * EEH needs the mapping between IOMMU table and group
1295                  * of those VFIO/KVM pass-through devices. We can postpone
1296                  * resetting DMA ops until the DMA mask is configured in
1297                  * host side.
1298                  */
1299                 if (pe->pdev)
1300                         set_iommu_table_base(&pe->pdev->dev, tbl);
1301                 else
1302                         pnv_ioda_setup_bus_dma(pe, pe->pbus, false);
1303         }
1304         if (rc)
1305                 pe_err(pe, "OPAL error %lld configuring bypass window\n", rc);
1306         else
1307                 pe->tce_bypass_enabled = enable;
1308 }
1309
1310 static void pnv_pci_ioda2_setup_bypass_pe(struct pnv_phb *phb,
1311                                           struct pnv_ioda_pe *pe)
1312 {
1313         /* TVE #1 is selected by PCI address bit 59 */
1314         pe->tce_bypass_base = 1ull << 59;
1315
1316         /* Install set_bypass callback for VFIO */
1317         pe->tce32_table->set_bypass = pnv_pci_ioda2_set_bypass;
1318
1319         /* Enable bypass by default */
1320         pnv_pci_ioda2_set_bypass(pe->tce32_table, true);
1321 }
1322
1323 static void pnv_pci_ioda2_setup_dma_pe(struct pnv_phb *phb,
1324                                        struct pnv_ioda_pe *pe)
1325 {
1326         struct page *tce_mem = NULL;
1327         void *addr;
1328         const __be64 *swinvp;
1329         struct iommu_table *tbl;
1330         unsigned int tce_table_size, end;
1331         int64_t rc;
1332
1333         /* We shouldn't already have a 32-bit DMA associated */
1334         if (WARN_ON(pe->tce32_seg >= 0))
1335                 return;
1336
1337         /* The PE will reserve all possible 32-bits space */
1338         pe->tce32_seg = 0;
1339         end = (1 << ilog2(phb->ioda.m32_pci_base));
1340         tce_table_size = (end / 0x1000) * 8;
1341         pe_info(pe, "Setting up 32-bit TCE table at 0..%08x\n",
1342                 end);
1343
1344         /* Allocate TCE table */
1345         tce_mem = alloc_pages_node(phb->hose->node, GFP_KERNEL,
1346                                    get_order(tce_table_size));
1347         if (!tce_mem) {
1348                 pe_err(pe, "Failed to allocate a 32-bit TCE memory\n");
1349                 goto fail;
1350         }
1351         addr = page_address(tce_mem);
1352         memset(addr, 0, tce_table_size);
1353
1354         /*
1355          * Map TCE table through TVT. The TVE index is the PE number
1356          * shifted by 1 bit for 32-bits DMA space.
1357          */
1358         rc = opal_pci_map_pe_dma_window(phb->opal_id, pe->pe_number,
1359                                         pe->pe_number << 1, 1, __pa(addr),
1360                                         tce_table_size, 0x1000);
1361         if (rc) {
1362                 pe_err(pe, "Failed to configure 32-bit TCE table,"
1363                        " err %ld\n", rc);
1364                 goto fail;
1365         }
1366
1367         /* Setup linux iommu table */
1368         tbl = pe->tce32_table;
1369         pnv_pci_setup_iommu_table(tbl, addr, tce_table_size, 0,
1370                         IOMMU_PAGE_SHIFT_4K);
1371
1372         /* OPAL variant of PHB3 invalidated TCEs */
1373         swinvp = of_get_property(phb->hose->dn, "ibm,opal-tce-kill", NULL);
1374         if (swinvp) {
1375                 /* We need a couple more fields -- an address and a data
1376                  * to or.  Since the bus is only printed out on table free
1377                  * errors, and on the first pass the data will be a relative
1378                  * bus number, print that out instead.
1379                  */
1380                 pe->tce_inval_reg_phys = be64_to_cpup(swinvp);
1381                 tbl->it_index = (unsigned long)ioremap(pe->tce_inval_reg_phys,
1382                                 8);
1383                 tbl->it_type |= (TCE_PCI_SWINV_CREATE | TCE_PCI_SWINV_FREE);
1384         }
1385         iommu_init_table(tbl, phb->hose->node);
1386         iommu_register_group(tbl, phb->hose->global_number, pe->pe_number);
1387
1388         if (pe->pdev)
1389                 set_iommu_table_base_and_group(&pe->pdev->dev, tbl);
1390         else
1391                 pnv_ioda_setup_bus_dma(pe, pe->pbus, true);
1392
1393         /* Also create a bypass window */
1394         if (!pnv_iommu_bypass_disabled)
1395                 pnv_pci_ioda2_setup_bypass_pe(phb, pe);
1396
1397         return;
1398 fail:
1399         if (pe->tce32_seg >= 0)
1400                 pe->tce32_seg = -1;
1401         if (tce_mem)
1402                 __free_pages(tce_mem, get_order(tce_table_size));
1403 }
1404
1405 static void pnv_ioda_setup_dma(struct pnv_phb *phb)
1406 {
1407         struct pci_controller *hose = phb->hose;
1408         unsigned int residual, remaining, segs, tw, base;
1409         struct pnv_ioda_pe *pe;
1410
1411         /* If we have more PE# than segments available, hand out one
1412          * per PE until we run out and let the rest fail. If not,
1413          * then we assign at least one segment per PE, plus more based
1414          * on the amount of devices under that PE
1415          */
1416         if (phb->ioda.dma_pe_count > phb->ioda.tce32_count)
1417                 residual = 0;
1418         else
1419                 residual = phb->ioda.tce32_count -
1420                         phb->ioda.dma_pe_count;
1421
1422         pr_info("PCI: Domain %04x has %ld available 32-bit DMA segments\n",
1423                 hose->global_number, phb->ioda.tce32_count);
1424         pr_info("PCI: %d PE# for a total weight of %d\n",
1425                 phb->ioda.dma_pe_count, phb->ioda.dma_weight);
1426
1427         /* Walk our PE list and configure their DMA segments, hand them
1428          * out one base segment plus any residual segments based on
1429          * weight
1430          */
1431         remaining = phb->ioda.tce32_count;
1432         tw = phb->ioda.dma_weight;
1433         base = 0;
1434         list_for_each_entry(pe, &phb->ioda.pe_dma_list, dma_link) {
1435                 if (!pe->dma_weight)
1436                         continue;
1437                 if (!remaining) {
1438                         pe_warn(pe, "No DMA32 resources available\n");
1439                         continue;
1440                 }
1441                 segs = 1;
1442                 if (residual) {
1443                         segs += ((pe->dma_weight * residual)  + (tw / 2)) / tw;
1444                         if (segs > remaining)
1445                                 segs = remaining;
1446                 }
1447
1448                 /*
1449                  * For IODA2 compliant PHB3, we needn't care about the weight.
1450                  * The all available 32-bits DMA space will be assigned to
1451                  * the specific PE.
1452                  */
1453                 if (phb->type == PNV_PHB_IODA1) {
1454                         pe_info(pe, "DMA weight %d, assigned %d DMA32 segments\n",
1455                                 pe->dma_weight, segs);
1456                         pnv_pci_ioda_setup_dma_pe(phb, pe, base, segs);
1457                 } else {
1458                         pe_info(pe, "Assign DMA32 space\n");
1459                         segs = 0;
1460                         pnv_pci_ioda2_setup_dma_pe(phb, pe);
1461                 }
1462
1463                 remaining -= segs;
1464                 base += segs;
1465         }
1466 }
1467
1468 #ifdef CONFIG_PCI_MSI
1469 static void pnv_ioda2_msi_eoi(struct irq_data *d)
1470 {
1471         unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d);
1472         struct irq_chip *chip = irq_data_get_irq_chip(d);
1473         struct pnv_phb *phb = container_of(chip, struct pnv_phb,
1474                                            ioda.irq_chip);
1475         int64_t rc;
1476
1477         rc = opal_pci_msi_eoi(phb->opal_id, hw_irq);
1478         WARN_ON_ONCE(rc);
1479
1480         icp_native_eoi(d);
1481 }
1482
1483
1484 static void set_msi_irq_chip(struct pnv_phb *phb, unsigned int virq)
1485 {
1486         struct irq_data *idata;
1487         struct irq_chip *ichip;
1488
1489         if (phb->type != PNV_PHB_IODA2)
1490                 return;
1491
1492         if (!phb->ioda.irq_chip_init) {
1493                 /*
1494                  * First time we setup an MSI IRQ, we need to setup the
1495                  * corresponding IRQ chip to route correctly.
1496                  */
1497                 idata = irq_get_irq_data(virq);
1498                 ichip = irq_data_get_irq_chip(idata);
1499                 phb->ioda.irq_chip_init = 1;
1500                 phb->ioda.irq_chip = *ichip;
1501                 phb->ioda.irq_chip.irq_eoi = pnv_ioda2_msi_eoi;
1502         }
1503         irq_set_chip(virq, &phb->ioda.irq_chip);
1504 }
1505
1506 #ifdef CONFIG_CXL_BASE
1507
1508 struct device_node *pnv_pci_get_phb_node(struct pci_dev *dev)
1509 {
1510         struct pci_controller *hose = pci_bus_to_host(dev->bus);
1511
1512         return of_node_get(hose->dn);
1513 }
1514 EXPORT_SYMBOL(pnv_pci_get_phb_node);
1515
1516 int pnv_phb_to_cxl_mode(struct pci_dev *dev, uint64_t mode)
1517 {
1518         struct pci_controller *hose = pci_bus_to_host(dev->bus);
1519         struct pnv_phb *phb = hose->private_data;
1520         struct pnv_ioda_pe *pe;
1521         int rc;
1522
1523         pe = pnv_ioda_get_pe(dev);
1524         if (!pe)
1525                 return -ENODEV;
1526
1527         pe_info(pe, "Switching PHB to CXL\n");
1528
1529         rc = opal_pci_set_phb_cxl_mode(phb->opal_id, mode, pe->pe_number);
1530         if (rc)
1531                 dev_err(&dev->dev, "opal_pci_set_phb_cxl_mode failed: %i\n", rc);
1532
1533         return rc;
1534 }
1535 EXPORT_SYMBOL(pnv_phb_to_cxl_mode);
1536
1537 /* Find PHB for cxl dev and allocate MSI hwirqs?
1538  * Returns the absolute hardware IRQ number
1539  */
1540 int pnv_cxl_alloc_hwirqs(struct pci_dev *dev, int num)
1541 {
1542         struct pci_controller *hose = pci_bus_to_host(dev->bus);
1543         struct pnv_phb *phb = hose->private_data;
1544         int hwirq = msi_bitmap_alloc_hwirqs(&phb->msi_bmp, num);
1545
1546         if (hwirq < 0) {
1547                 dev_warn(&dev->dev, "Failed to find a free MSI\n");
1548                 return -ENOSPC;
1549         }
1550
1551         return phb->msi_base + hwirq;
1552 }
1553 EXPORT_SYMBOL(pnv_cxl_alloc_hwirqs);
1554
1555 void pnv_cxl_release_hwirqs(struct pci_dev *dev, int hwirq, int num)
1556 {
1557         struct pci_controller *hose = pci_bus_to_host(dev->bus);
1558         struct pnv_phb *phb = hose->private_data;
1559
1560         msi_bitmap_free_hwirqs(&phb->msi_bmp, hwirq - phb->msi_base, num);
1561 }
1562 EXPORT_SYMBOL(pnv_cxl_release_hwirqs);
1563
1564 void pnv_cxl_release_hwirq_ranges(struct cxl_irq_ranges *irqs,
1565                                   struct pci_dev *dev)
1566 {
1567         struct pci_controller *hose = pci_bus_to_host(dev->bus);
1568         struct pnv_phb *phb = hose->private_data;
1569         int i, hwirq;
1570
1571         for (i = 1; i < CXL_IRQ_RANGES; i++) {
1572                 if (!irqs->range[i])
1573                         continue;
1574                 pr_devel("cxl release irq range 0x%x: offset: 0x%lx  limit: %ld\n",
1575                          i, irqs->offset[i],
1576                          irqs->range[i]);
1577                 hwirq = irqs->offset[i] - phb->msi_base;
1578                 msi_bitmap_free_hwirqs(&phb->msi_bmp, hwirq,
1579                                        irqs->range[i]);
1580         }
1581 }
1582 EXPORT_SYMBOL(pnv_cxl_release_hwirq_ranges);
1583
1584 int pnv_cxl_alloc_hwirq_ranges(struct cxl_irq_ranges *irqs,
1585                                struct pci_dev *dev, int num)
1586 {
1587         struct pci_controller *hose = pci_bus_to_host(dev->bus);
1588         struct pnv_phb *phb = hose->private_data;
1589         int i, hwirq, try;
1590
1591         memset(irqs, 0, sizeof(struct cxl_irq_ranges));
1592
1593         /* 0 is reserved for the multiplexed PSL DSI interrupt */
1594         for (i = 1; i < CXL_IRQ_RANGES && num; i++) {
1595                 try = num;
1596                 while (try) {
1597                         hwirq = msi_bitmap_alloc_hwirqs(&phb->msi_bmp, try);
1598                         if (hwirq >= 0)
1599                                 break;
1600                         try /= 2;
1601                 }
1602                 if (!try)
1603                         goto fail;
1604
1605                 irqs->offset[i] = phb->msi_base + hwirq;
1606                 irqs->range[i] = try;
1607                 pr_devel("cxl alloc irq range 0x%x: offset: 0x%lx  limit: %li\n",
1608                          i, irqs->offset[i], irqs->range[i]);
1609                 num -= try;
1610         }
1611         if (num)
1612                 goto fail;
1613
1614         return 0;
1615 fail:
1616         pnv_cxl_release_hwirq_ranges(irqs, dev);
1617         return -ENOSPC;
1618 }
1619 EXPORT_SYMBOL(pnv_cxl_alloc_hwirq_ranges);
1620
1621 int pnv_cxl_get_irq_count(struct pci_dev *dev)
1622 {
1623         struct pci_controller *hose = pci_bus_to_host(dev->bus);
1624         struct pnv_phb *phb = hose->private_data;
1625
1626         return phb->msi_bmp.irq_count;
1627 }
1628 EXPORT_SYMBOL(pnv_cxl_get_irq_count);
1629
1630 int pnv_cxl_ioda_msi_setup(struct pci_dev *dev, unsigned int hwirq,
1631                            unsigned int virq)
1632 {
1633         struct pci_controller *hose = pci_bus_to_host(dev->bus);
1634         struct pnv_phb *phb = hose->private_data;
1635         unsigned int xive_num = hwirq - phb->msi_base;
1636         struct pnv_ioda_pe *pe;
1637         int rc;
1638
1639         if (!(pe = pnv_ioda_get_pe(dev)))
1640                 return -ENODEV;
1641
1642         /* Assign XIVE to PE */
1643         rc = opal_pci_set_xive_pe(phb->opal_id, pe->pe_number, xive_num);
1644         if (rc) {
1645                 pe_warn(pe, "%s: OPAL error %d setting msi_base 0x%x "
1646                         "hwirq 0x%x XIVE 0x%x PE\n",
1647                         pci_name(dev), rc, phb->msi_base, hwirq, xive_num);
1648                 return -EIO;
1649         }
1650         set_msi_irq_chip(phb, virq);
1651
1652         return 0;
1653 }
1654 EXPORT_SYMBOL(pnv_cxl_ioda_msi_setup);
1655 #endif
1656
1657 static int pnv_pci_ioda_msi_setup(struct pnv_phb *phb, struct pci_dev *dev,
1658                                   unsigned int hwirq, unsigned int virq,
1659                                   unsigned int is_64, struct msi_msg *msg)
1660 {
1661         struct pnv_ioda_pe *pe = pnv_ioda_get_pe(dev);
1662         unsigned int xive_num = hwirq - phb->msi_base;
1663         __be32 data;
1664         int rc;
1665
1666         /* No PE assigned ? bail out ... no MSI for you ! */
1667         if (pe == NULL)
1668                 return -ENXIO;
1669
1670         /* Check if we have an MVE */
1671         if (pe->mve_number < 0)
1672                 return -ENXIO;
1673
1674         /* Force 32-bit MSI on some broken devices */
1675         if (dev->no_64bit_msi)
1676                 is_64 = 0;
1677
1678         /* Assign XIVE to PE */
1679         rc = opal_pci_set_xive_pe(phb->opal_id, pe->pe_number, xive_num);
1680         if (rc) {
1681                 pr_warn("%s: OPAL error %d setting XIVE %d PE\n",
1682                         pci_name(dev), rc, xive_num);
1683                 return -EIO;
1684         }
1685
1686         if (is_64) {
1687                 __be64 addr64;
1688
1689                 rc = opal_get_msi_64(phb->opal_id, pe->mve_number, xive_num, 1,
1690                                      &addr64, &data);
1691                 if (rc) {
1692                         pr_warn("%s: OPAL error %d getting 64-bit MSI data\n",
1693                                 pci_name(dev), rc);
1694                         return -EIO;
1695                 }
1696                 msg->address_hi = be64_to_cpu(addr64) >> 32;
1697                 msg->address_lo = be64_to_cpu(addr64) & 0xfffffffful;
1698         } else {
1699                 __be32 addr32;
1700
1701                 rc = opal_get_msi_32(phb->opal_id, pe->mve_number, xive_num, 1,
1702                                      &addr32, &data);
1703                 if (rc) {
1704                         pr_warn("%s: OPAL error %d getting 32-bit MSI data\n",
1705                                 pci_name(dev), rc);
1706                         return -EIO;
1707                 }
1708                 msg->address_hi = 0;
1709                 msg->address_lo = be32_to_cpu(addr32);
1710         }
1711         msg->data = be32_to_cpu(data);
1712
1713         set_msi_irq_chip(phb, virq);
1714
1715         pr_devel("%s: %s-bit MSI on hwirq %x (xive #%d),"
1716                  " address=%x_%08x data=%x PE# %d\n",
1717                  pci_name(dev), is_64 ? "64" : "32", hwirq, xive_num,
1718                  msg->address_hi, msg->address_lo, data, pe->pe_number);
1719
1720         return 0;
1721 }
1722
1723 static void pnv_pci_init_ioda_msis(struct pnv_phb *phb)
1724 {
1725         unsigned int count;
1726         const __be32 *prop = of_get_property(phb->hose->dn,
1727                                              "ibm,opal-msi-ranges", NULL);
1728         if (!prop) {
1729                 /* BML Fallback */
1730                 prop = of_get_property(phb->hose->dn, "msi-ranges", NULL);
1731         }
1732         if (!prop)
1733                 return;
1734
1735         phb->msi_base = be32_to_cpup(prop);
1736         count = be32_to_cpup(prop + 1);
1737         if (msi_bitmap_alloc(&phb->msi_bmp, count, phb->hose->dn)) {
1738                 pr_err("PCI %d: Failed to allocate MSI bitmap !\n",
1739                        phb->hose->global_number);
1740                 return;
1741         }
1742
1743         phb->msi_setup = pnv_pci_ioda_msi_setup;
1744         phb->msi32_support = 1;
1745         pr_info("  Allocated bitmap for %d MSIs (base IRQ 0x%x)\n",
1746                 count, phb->msi_base);
1747 }
1748 #else
1749 static void pnv_pci_init_ioda_msis(struct pnv_phb *phb) { }
1750 #endif /* CONFIG_PCI_MSI */
1751
1752 #ifdef CONFIG_PCI_IOV
1753 static void pnv_pci_ioda_fixup_iov_resources(struct pci_dev *pdev)
1754 {
1755         struct pci_controller *hose;
1756         struct pnv_phb *phb;
1757         struct resource *res;
1758         int i;
1759         resource_size_t size;
1760         struct pci_dn *pdn;
1761
1762         if (!pdev->is_physfn || pdev->is_added)
1763                 return;
1764
1765         hose = pci_bus_to_host(pdev->bus);
1766         phb = hose->private_data;
1767
1768         pdn = pci_get_pdn(pdev);
1769         pdn->vfs_expanded = 0;
1770
1771         for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
1772                 res = &pdev->resource[i + PCI_IOV_RESOURCES];
1773                 if (!res->flags || res->parent)
1774                         continue;
1775                 if (!pnv_pci_is_mem_pref_64(res->flags)) {
1776                         dev_warn(&pdev->dev, "Skipping expanding VF BAR%d: %pR\n",
1777                                  i, res);
1778                         continue;
1779                 }
1780
1781                 dev_dbg(&pdev->dev, " Fixing VF BAR%d: %pR to\n", i, res);
1782                 size = pci_iov_resource_size(pdev, i + PCI_IOV_RESOURCES);
1783                 res->end = res->start + size * phb->ioda.total_pe - 1;
1784                 dev_dbg(&pdev->dev, "                       %pR\n", res);
1785                 dev_info(&pdev->dev, "VF BAR%d: %pR (expanded to %d VFs for PE alignment)",
1786                                 i, res, phb->ioda.total_pe);
1787         }
1788         pdn->vfs_expanded = phb->ioda.total_pe;
1789 }
1790 #endif /* CONFIG_PCI_IOV */
1791
1792 /*
1793  * This function is supposed to be called on basis of PE from top
1794  * to bottom style. So the the I/O or MMIO segment assigned to
1795  * parent PE could be overrided by its child PEs if necessary.
1796  */
1797 static void pnv_ioda_setup_pe_seg(struct pci_controller *hose,
1798                                   struct pnv_ioda_pe *pe)
1799 {
1800         struct pnv_phb *phb = hose->private_data;
1801         struct pci_bus_region region;
1802         struct resource *res;
1803         int i, index;
1804         int rc;
1805
1806         /*
1807          * NOTE: We only care PCI bus based PE for now. For PCI
1808          * device based PE, for example SRIOV sensitive VF should
1809          * be figured out later.
1810          */
1811         BUG_ON(!(pe->flags & (PNV_IODA_PE_BUS | PNV_IODA_PE_BUS_ALL)));
1812
1813         pci_bus_for_each_resource(pe->pbus, res, i) {
1814                 if (!res || !res->flags ||
1815                     res->start > res->end)
1816                         continue;
1817
1818                 if (res->flags & IORESOURCE_IO) {
1819                         region.start = res->start - phb->ioda.io_pci_base;
1820                         region.end   = res->end - phb->ioda.io_pci_base;
1821                         index = region.start / phb->ioda.io_segsize;
1822
1823                         while (index < phb->ioda.total_pe &&
1824                                region.start <= region.end) {
1825                                 phb->ioda.io_segmap[index] = pe->pe_number;
1826                                 rc = opal_pci_map_pe_mmio_window(phb->opal_id,
1827                                         pe->pe_number, OPAL_IO_WINDOW_TYPE, 0, index);
1828                                 if (rc != OPAL_SUCCESS) {
1829                                         pr_err("%s: OPAL error %d when mapping IO "
1830                                                "segment #%d to PE#%d\n",
1831                                                __func__, rc, index, pe->pe_number);
1832                                         break;
1833                                 }
1834
1835                                 region.start += phb->ioda.io_segsize;
1836                                 index++;
1837                         }
1838                 } else if (res->flags & IORESOURCE_MEM) {
1839                         region.start = res->start -
1840                                        hose->mem_offset[0] -
1841                                        phb->ioda.m32_pci_base;
1842                         region.end   = res->end -
1843                                        hose->mem_offset[0] -
1844                                        phb->ioda.m32_pci_base;
1845                         index = region.start / phb->ioda.m32_segsize;
1846
1847                         while (index < phb->ioda.total_pe &&
1848                                region.start <= region.end) {
1849                                 phb->ioda.m32_segmap[index] = pe->pe_number;
1850                                 rc = opal_pci_map_pe_mmio_window(phb->opal_id,
1851                                         pe->pe_number, OPAL_M32_WINDOW_TYPE, 0, index);
1852                                 if (rc != OPAL_SUCCESS) {
1853                                         pr_err("%s: OPAL error %d when mapping M32 "
1854                                                "segment#%d to PE#%d",
1855                                                __func__, rc, index, pe->pe_number);
1856                                         break;
1857                                 }
1858
1859                                 region.start += phb->ioda.m32_segsize;
1860                                 index++;
1861                         }
1862                 }
1863         }
1864 }
1865
1866 static void pnv_pci_ioda_setup_seg(void)
1867 {
1868         struct pci_controller *tmp, *hose;
1869         struct pnv_phb *phb;
1870         struct pnv_ioda_pe *pe;
1871
1872         list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
1873                 phb = hose->private_data;
1874                 list_for_each_entry(pe, &phb->ioda.pe_list, list) {
1875                         pnv_ioda_setup_pe_seg(hose, pe);
1876                 }
1877         }
1878 }
1879
1880 static void pnv_pci_ioda_setup_DMA(void)
1881 {
1882         struct pci_controller *hose, *tmp;
1883         struct pnv_phb *phb;
1884
1885         list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
1886                 pnv_ioda_setup_dma(hose->private_data);
1887
1888                 /* Mark the PHB initialization done */
1889                 phb = hose->private_data;
1890                 phb->initialized = 1;
1891         }
1892 }
1893
1894 static void pnv_pci_ioda_create_dbgfs(void)
1895 {
1896 #ifdef CONFIG_DEBUG_FS
1897         struct pci_controller *hose, *tmp;
1898         struct pnv_phb *phb;
1899         char name[16];
1900
1901         list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
1902                 phb = hose->private_data;
1903
1904                 sprintf(name, "PCI%04x", hose->global_number);
1905                 phb->dbgfs = debugfs_create_dir(name, powerpc_debugfs_root);
1906                 if (!phb->dbgfs)
1907                         pr_warning("%s: Error on creating debugfs on PHB#%x\n",
1908                                 __func__, hose->global_number);
1909         }
1910 #endif /* CONFIG_DEBUG_FS */
1911 }
1912
1913 static void pnv_pci_ioda_fixup(void)
1914 {
1915         pnv_pci_ioda_setup_PEs();
1916         pnv_pci_ioda_setup_seg();
1917         pnv_pci_ioda_setup_DMA();
1918
1919         pnv_pci_ioda_create_dbgfs();
1920
1921 #ifdef CONFIG_EEH
1922         eeh_init();
1923         eeh_addr_cache_build();
1924 #endif
1925 }
1926
1927 /*
1928  * Returns the alignment for I/O or memory windows for P2P
1929  * bridges. That actually depends on how PEs are segmented.
1930  * For now, we return I/O or M32 segment size for PE sensitive
1931  * P2P bridges. Otherwise, the default values (4KiB for I/O,
1932  * 1MiB for memory) will be returned.
1933  *
1934  * The current PCI bus might be put into one PE, which was
1935  * create against the parent PCI bridge. For that case, we
1936  * needn't enlarge the alignment so that we can save some
1937  * resources.
1938  */
1939 static resource_size_t pnv_pci_window_alignment(struct pci_bus *bus,
1940                                                 unsigned long type)
1941 {
1942         struct pci_dev *bridge;
1943         struct pci_controller *hose = pci_bus_to_host(bus);
1944         struct pnv_phb *phb = hose->private_data;
1945         int num_pci_bridges = 0;
1946
1947         bridge = bus->self;
1948         while (bridge) {
1949                 if (pci_pcie_type(bridge) == PCI_EXP_TYPE_PCI_BRIDGE) {
1950                         num_pci_bridges++;
1951                         if (num_pci_bridges >= 2)
1952                                 return 1;
1953                 }
1954
1955                 bridge = bridge->bus->self;
1956         }
1957
1958         /* We fail back to M32 if M64 isn't supported */
1959         if (phb->ioda.m64_segsize &&
1960             pnv_pci_is_mem_pref_64(type))
1961                 return phb->ioda.m64_segsize;
1962         if (type & IORESOURCE_MEM)
1963                 return phb->ioda.m32_segsize;
1964
1965         return phb->ioda.io_segsize;
1966 }
1967
1968 #ifdef CONFIG_PCI_IOV
1969 static resource_size_t pnv_pci_iov_resource_alignment(struct pci_dev *pdev,
1970                                                       int resno)
1971 {
1972         struct pci_dn *pdn = pci_get_pdn(pdev);
1973         resource_size_t align, iov_align;
1974
1975         iov_align = resource_size(&pdev->resource[resno]);
1976         if (iov_align)
1977                 return iov_align;
1978
1979         align = pci_iov_resource_size(pdev, resno);
1980         if (pdn->vfs_expanded)
1981                 return pdn->vfs_expanded * align;
1982
1983         return align;
1984 }
1985 #endif /* CONFIG_PCI_IOV */
1986
1987 /* Prevent enabling devices for which we couldn't properly
1988  * assign a PE
1989  */
1990 static int pnv_pci_enable_device_hook(struct pci_dev *dev)
1991 {
1992         struct pci_controller *hose = pci_bus_to_host(dev->bus);
1993         struct pnv_phb *phb = hose->private_data;
1994         struct pci_dn *pdn;
1995
1996         /* The function is probably called while the PEs have
1997          * not be created yet. For example, resource reassignment
1998          * during PCI probe period. We just skip the check if
1999          * PEs isn't ready.
2000          */
2001         if (!phb->initialized)
2002                 return 0;
2003
2004         pdn = pci_get_pdn(dev);
2005         if (!pdn || pdn->pe_number == IODA_INVALID_PE)
2006                 return -EINVAL;
2007
2008         return 0;
2009 }
2010
2011 static u32 pnv_ioda_bdfn_to_pe(struct pnv_phb *phb, struct pci_bus *bus,
2012                                u32 devfn)
2013 {
2014         return phb->ioda.pe_rmap[(bus->number << 8) | devfn];
2015 }
2016
2017 static void pnv_pci_ioda_shutdown(struct pnv_phb *phb)
2018 {
2019         opal_pci_reset(phb->opal_id, OPAL_RESET_PCI_IODA_TABLE,
2020                        OPAL_ASSERT_RESET);
2021 }
2022
2023 static void __init pnv_pci_init_ioda_phb(struct device_node *np,
2024                                          u64 hub_id, int ioda_type)
2025 {
2026         struct pci_controller *hose;
2027         struct pnv_phb *phb;
2028         unsigned long size, m32map_off, pemap_off, iomap_off = 0;
2029         const __be64 *prop64;
2030         const __be32 *prop32;
2031         int len;
2032         u64 phb_id;
2033         void *aux;
2034         long rc;
2035
2036         pr_info("Initializing IODA%d OPAL PHB %s\n", ioda_type, np->full_name);
2037
2038         prop64 = of_get_property(np, "ibm,opal-phbid", NULL);
2039         if (!prop64) {
2040                 pr_err("  Missing \"ibm,opal-phbid\" property !\n");
2041                 return;
2042         }
2043         phb_id = be64_to_cpup(prop64);
2044         pr_debug("  PHB-ID  : 0x%016llx\n", phb_id);
2045
2046         phb = memblock_virt_alloc(sizeof(struct pnv_phb), 0);
2047
2048         /* Allocate PCI controller */
2049         phb->hose = hose = pcibios_alloc_controller(np);
2050         if (!phb->hose) {
2051                 pr_err("  Can't allocate PCI controller for %s\n",
2052                        np->full_name);
2053                 memblock_free(__pa(phb), sizeof(struct pnv_phb));
2054                 return;
2055         }
2056
2057         spin_lock_init(&phb->lock);
2058         prop32 = of_get_property(np, "bus-range", &len);
2059         if (prop32 && len == 8) {
2060                 hose->first_busno = be32_to_cpu(prop32[0]);
2061                 hose->last_busno = be32_to_cpu(prop32[1]);
2062         } else {
2063                 pr_warn("  Broken <bus-range> on %s\n", np->full_name);
2064                 hose->first_busno = 0;
2065                 hose->last_busno = 0xff;
2066         }
2067         hose->private_data = phb;
2068         phb->hub_id = hub_id;
2069         phb->opal_id = phb_id;
2070         phb->type = ioda_type;
2071
2072         /* Detect specific models for error handling */
2073         if (of_device_is_compatible(np, "ibm,p7ioc-pciex"))
2074                 phb->model = PNV_PHB_MODEL_P7IOC;
2075         else if (of_device_is_compatible(np, "ibm,power8-pciex"))
2076                 phb->model = PNV_PHB_MODEL_PHB3;
2077         else
2078                 phb->model = PNV_PHB_MODEL_UNKNOWN;
2079
2080         /* Parse 32-bit and IO ranges (if any) */
2081         pci_process_bridge_OF_ranges(hose, np, !hose->global_number);
2082
2083         /* Get registers */
2084         phb->regs = of_iomap(np, 0);
2085         if (phb->regs == NULL)
2086                 pr_err("  Failed to map registers !\n");
2087
2088         /* Initialize more IODA stuff */
2089         phb->ioda.total_pe = 1;
2090         prop32 = of_get_property(np, "ibm,opal-num-pes", NULL);
2091         if (prop32)
2092                 phb->ioda.total_pe = be32_to_cpup(prop32);
2093         prop32 = of_get_property(np, "ibm,opal-reserved-pe", NULL);
2094         if (prop32)
2095                 phb->ioda.reserved_pe = be32_to_cpup(prop32);
2096
2097         /* Parse 64-bit MMIO range */
2098         pnv_ioda_parse_m64_window(phb);
2099
2100         phb->ioda.m32_size = resource_size(&hose->mem_resources[0]);
2101         /* FW Has already off top 64k of M32 space (MSI space) */
2102         phb->ioda.m32_size += 0x10000;
2103
2104         phb->ioda.m32_segsize = phb->ioda.m32_size / phb->ioda.total_pe;
2105         phb->ioda.m32_pci_base = hose->mem_resources[0].start - hose->mem_offset[0];
2106         phb->ioda.io_size = hose->pci_io_size;
2107         phb->ioda.io_segsize = phb->ioda.io_size / phb->ioda.total_pe;
2108         phb->ioda.io_pci_base = 0; /* XXX calculate this ? */
2109
2110         /* Allocate aux data & arrays. We don't have IO ports on PHB3 */
2111         size = _ALIGN_UP(phb->ioda.total_pe / 8, sizeof(unsigned long));
2112         m32map_off = size;
2113         size += phb->ioda.total_pe * sizeof(phb->ioda.m32_segmap[0]);
2114         if (phb->type == PNV_PHB_IODA1) {
2115                 iomap_off = size;
2116                 size += phb->ioda.total_pe * sizeof(phb->ioda.io_segmap[0]);
2117         }
2118         pemap_off = size;
2119         size += phb->ioda.total_pe * sizeof(struct pnv_ioda_pe);
2120         aux = memblock_virt_alloc(size, 0);
2121         phb->ioda.pe_alloc = aux;
2122         phb->ioda.m32_segmap = aux + m32map_off;
2123         if (phb->type == PNV_PHB_IODA1)
2124                 phb->ioda.io_segmap = aux + iomap_off;
2125         phb->ioda.pe_array = aux + pemap_off;
2126         set_bit(phb->ioda.reserved_pe, phb->ioda.pe_alloc);
2127
2128         INIT_LIST_HEAD(&phb->ioda.pe_dma_list);
2129         INIT_LIST_HEAD(&phb->ioda.pe_list);
2130
2131         /* Calculate how many 32-bit TCE segments we have */
2132         phb->ioda.tce32_count = phb->ioda.m32_pci_base >> 28;
2133
2134 #if 0 /* We should really do that ... */
2135         rc = opal_pci_set_phb_mem_window(opal->phb_id,
2136                                          window_type,
2137                                          window_num,
2138                                          starting_real_address,
2139                                          starting_pci_address,
2140                                          segment_size);
2141 #endif
2142
2143         pr_info("  %03d (%03d) PE's M32: 0x%x [segment=0x%x]\n",
2144                 phb->ioda.total_pe, phb->ioda.reserved_pe,
2145                 phb->ioda.m32_size, phb->ioda.m32_segsize);
2146         if (phb->ioda.m64_size)
2147                 pr_info("                 M64: 0x%lx [segment=0x%lx]\n",
2148                         phb->ioda.m64_size, phb->ioda.m64_segsize);
2149         if (phb->ioda.io_size)
2150                 pr_info("                  IO: 0x%x [segment=0x%x]\n",
2151                         phb->ioda.io_size, phb->ioda.io_segsize);
2152
2153
2154         phb->hose->ops = &pnv_pci_ops;
2155         phb->get_pe_state = pnv_ioda_get_pe_state;
2156         phb->freeze_pe = pnv_ioda_freeze_pe;
2157         phb->unfreeze_pe = pnv_ioda_unfreeze_pe;
2158
2159         /* Setup RID -> PE mapping function */
2160         phb->bdfn_to_pe = pnv_ioda_bdfn_to_pe;
2161
2162         /* Setup TCEs */
2163         phb->dma_dev_setup = pnv_pci_ioda_dma_dev_setup;
2164         phb->dma_set_mask = pnv_pci_ioda_dma_set_mask;
2165         phb->dma_get_required_mask = pnv_pci_ioda_dma_get_required_mask;
2166
2167         /* Setup shutdown function for kexec */
2168         phb->shutdown = pnv_pci_ioda_shutdown;
2169
2170         /* Setup MSI support */
2171         pnv_pci_init_ioda_msis(phb);
2172
2173         /*
2174          * We pass the PCI probe flag PCI_REASSIGN_ALL_RSRC here
2175          * to let the PCI core do resource assignment. It's supposed
2176          * that the PCI core will do correct I/O and MMIO alignment
2177          * for the P2P bridge bars so that each PCI bus (excluding
2178          * the child P2P bridges) can form individual PE.
2179          */
2180         ppc_md.pcibios_fixup = pnv_pci_ioda_fixup;
2181         ppc_md.pcibios_enable_device_hook = pnv_pci_enable_device_hook;
2182         ppc_md.pcibios_window_alignment = pnv_pci_window_alignment;
2183         ppc_md.pcibios_reset_secondary_bus = pnv_pci_reset_secondary_bus;
2184 #ifdef CONFIG_PCI_IOV
2185         ppc_md.pcibios_fixup_sriov = pnv_pci_ioda_fixup_iov_resources;
2186         ppc_md.pcibios_iov_resource_alignment = pnv_pci_iov_resource_alignment;
2187 #endif /* CONFIG_PCI_IOV */
2188         pci_add_flags(PCI_REASSIGN_ALL_RSRC);
2189
2190         /* Reset IODA tables to a clean state */
2191         rc = opal_pci_reset(phb_id, OPAL_RESET_PCI_IODA_TABLE, OPAL_ASSERT_RESET);
2192         if (rc)
2193                 pr_warning("  OPAL Error %ld performing IODA table reset !\n", rc);
2194
2195         /* If we're running in kdump kerenl, the previous kerenl never
2196          * shutdown PCI devices correctly. We already got IODA table
2197          * cleaned out. So we have to issue PHB reset to stop all PCI
2198          * transactions from previous kerenl.
2199          */
2200         if (is_kdump_kernel()) {
2201                 pr_info("  Issue PHB reset ...\n");
2202                 pnv_eeh_phb_reset(hose, EEH_RESET_FUNDAMENTAL);
2203                 pnv_eeh_phb_reset(hose, EEH_RESET_DEACTIVATE);
2204         }
2205
2206         /* Remove M64 resource if we can't configure it successfully */
2207         if (!phb->init_m64 || phb->init_m64(phb))
2208                 hose->mem_resources[1].flags = 0;
2209 }
2210
2211 void __init pnv_pci_init_ioda2_phb(struct device_node *np)
2212 {
2213         pnv_pci_init_ioda_phb(np, 0, PNV_PHB_IODA2);
2214 }
2215
2216 void __init pnv_pci_init_ioda_hub(struct device_node *np)
2217 {
2218         struct device_node *phbn;
2219         const __be64 *prop64;
2220         u64 hub_id;
2221
2222         pr_info("Probing IODA IO-Hub %s\n", np->full_name);
2223
2224         prop64 = of_get_property(np, "ibm,opal-hubid", NULL);
2225         if (!prop64) {
2226                 pr_err(" Missing \"ibm,opal-hubid\" property !\n");
2227                 return;
2228         }
2229         hub_id = be64_to_cpup(prop64);
2230         pr_devel(" HUB-ID : 0x%016llx\n", hub_id);
2231
2232         /* Count child PHBs */
2233         for_each_child_of_node(np, phbn) {
2234                 /* Look for IODA1 PHBs */
2235                 if (of_device_is_compatible(phbn, "ibm,ioda-phb"))
2236                         pnv_pci_init_ioda_phb(phbn, hub_id, PNV_PHB_IODA1);
2237         }
2238 }