f647c8d083a8025090d1b925ecdbb4815e90cbed
[cascardo/linux.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 #include <linux/iommu.h>
27 #include <linux/rculist.h>
28 #include <linux/sizes.h>
29
30 #include <asm/sections.h>
31 #include <asm/io.h>
32 #include <asm/prom.h>
33 #include <asm/pci-bridge.h>
34 #include <asm/machdep.h>
35 #include <asm/msi_bitmap.h>
36 #include <asm/ppc-pci.h>
37 #include <asm/opal.h>
38 #include <asm/iommu.h>
39 #include <asm/tce.h>
40 #include <asm/xics.h>
41 #include <asm/debug.h>
42 #include <asm/firmware.h>
43 #include <asm/pnv-pci.h>
44 #include <asm/mmzone.h>
45
46 #include <misc/cxl-base.h>
47
48 #include "powernv.h"
49 #include "pci.h"
50
51 #define PNV_IODA1_M64_NUM       16      /* Number of M64 BARs   */
52 #define PNV_IODA1_M64_SEGS      8       /* Segments per M64 BAR */
53 #define PNV_IODA1_DMA32_SEGSIZE 0x10000000
54
55 #define POWERNV_IOMMU_DEFAULT_LEVELS    1
56 #define POWERNV_IOMMU_MAX_LEVELS        5
57
58 static void pnv_pci_ioda2_table_free_pages(struct iommu_table *tbl);
59
60 void pe_level_printk(const struct pnv_ioda_pe *pe, const char *level,
61                             const char *fmt, ...)
62 {
63         struct va_format vaf;
64         va_list args;
65         char pfix[32];
66
67         va_start(args, fmt);
68
69         vaf.fmt = fmt;
70         vaf.va = &args;
71
72         if (pe->flags & PNV_IODA_PE_DEV)
73                 strlcpy(pfix, dev_name(&pe->pdev->dev), sizeof(pfix));
74         else if (pe->flags & (PNV_IODA_PE_BUS | PNV_IODA_PE_BUS_ALL))
75                 sprintf(pfix, "%04x:%02x     ",
76                         pci_domain_nr(pe->pbus), pe->pbus->number);
77 #ifdef CONFIG_PCI_IOV
78         else if (pe->flags & PNV_IODA_PE_VF)
79                 sprintf(pfix, "%04x:%02x:%2x.%d",
80                         pci_domain_nr(pe->parent_dev->bus),
81                         (pe->rid & 0xff00) >> 8,
82                         PCI_SLOT(pe->rid), PCI_FUNC(pe->rid));
83 #endif /* CONFIG_PCI_IOV*/
84
85         printk("%spci %s: [PE# %.3d] %pV",
86                level, pfix, pe->pe_number, &vaf);
87
88         va_end(args);
89 }
90
91 static bool pnv_iommu_bypass_disabled __read_mostly;
92
93 static int __init iommu_setup(char *str)
94 {
95         if (!str)
96                 return -EINVAL;
97
98         while (*str) {
99                 if (!strncmp(str, "nobypass", 8)) {
100                         pnv_iommu_bypass_disabled = true;
101                         pr_info("PowerNV: IOMMU bypass window disabled.\n");
102                         break;
103                 }
104                 str += strcspn(str, ",");
105                 if (*str == ',')
106                         str++;
107         }
108
109         return 0;
110 }
111 early_param("iommu", iommu_setup);
112
113 static inline bool pnv_pci_is_mem_pref_64(unsigned long flags)
114 {
115         return ((flags & (IORESOURCE_MEM_64 | IORESOURCE_PREFETCH)) ==
116                 (IORESOURCE_MEM_64 | IORESOURCE_PREFETCH));
117 }
118
119 static struct pnv_ioda_pe *pnv_ioda_init_pe(struct pnv_phb *phb, int pe_no)
120 {
121         phb->ioda.pe_array[pe_no].phb = phb;
122         phb->ioda.pe_array[pe_no].pe_number = pe_no;
123
124         return &phb->ioda.pe_array[pe_no];
125 }
126
127 static void pnv_ioda_reserve_pe(struct pnv_phb *phb, int pe_no)
128 {
129         if (!(pe_no >= 0 && pe_no < phb->ioda.total_pe_num)) {
130                 pr_warn("%s: Invalid PE %d on PHB#%x\n",
131                         __func__, pe_no, phb->hose->global_number);
132                 return;
133         }
134
135         if (test_and_set_bit(pe_no, phb->ioda.pe_alloc))
136                 pr_debug("%s: PE %d was reserved on PHB#%x\n",
137                          __func__, pe_no, phb->hose->global_number);
138
139         pnv_ioda_init_pe(phb, pe_no);
140 }
141
142 static struct pnv_ioda_pe *pnv_ioda_alloc_pe(struct pnv_phb *phb)
143 {
144         unsigned long pe = phb->ioda.total_pe_num - 1;
145
146         for (pe = phb->ioda.total_pe_num - 1; pe >= 0; pe--) {
147                 if (!test_and_set_bit(pe, phb->ioda.pe_alloc))
148                         return pnv_ioda_init_pe(phb, pe);
149         }
150
151         return NULL;
152 }
153
154 static void pnv_ioda_free_pe(struct pnv_ioda_pe *pe)
155 {
156         struct pnv_phb *phb = pe->phb;
157
158         WARN_ON(pe->pdev);
159
160         memset(pe, 0, sizeof(struct pnv_ioda_pe));
161         clear_bit(pe->pe_number, phb->ioda.pe_alloc);
162 }
163
164 /* The default M64 BAR is shared by all PEs */
165 static int pnv_ioda2_init_m64(struct pnv_phb *phb)
166 {
167         const char *desc;
168         struct resource *r;
169         s64 rc;
170
171         /* Configure the default M64 BAR */
172         rc = opal_pci_set_phb_mem_window(phb->opal_id,
173                                          OPAL_M64_WINDOW_TYPE,
174                                          phb->ioda.m64_bar_idx,
175                                          phb->ioda.m64_base,
176                                          0, /* unused */
177                                          phb->ioda.m64_size);
178         if (rc != OPAL_SUCCESS) {
179                 desc = "configuring";
180                 goto fail;
181         }
182
183         /* Enable the default M64 BAR */
184         rc = opal_pci_phb_mmio_enable(phb->opal_id,
185                                       OPAL_M64_WINDOW_TYPE,
186                                       phb->ioda.m64_bar_idx,
187                                       OPAL_ENABLE_M64_SPLIT);
188         if (rc != OPAL_SUCCESS) {
189                 desc = "enabling";
190                 goto fail;
191         }
192
193         /* Mark the M64 BAR assigned */
194         set_bit(phb->ioda.m64_bar_idx, &phb->ioda.m64_bar_alloc);
195
196         /*
197          * Exclude the segments for reserved and root bus PE, which
198          * are first or last two PEs.
199          */
200         r = &phb->hose->mem_resources[1];
201         if (phb->ioda.reserved_pe_idx == 0)
202                 r->start += (2 * phb->ioda.m64_segsize);
203         else if (phb->ioda.reserved_pe_idx == (phb->ioda.total_pe_num - 1))
204                 r->end -= (2 * phb->ioda.m64_segsize);
205         else
206                 pr_warn("  Cannot strip M64 segment for reserved PE#%d\n",
207                         phb->ioda.reserved_pe_idx);
208
209         return 0;
210
211 fail:
212         pr_warn("  Failure %lld %s M64 BAR#%d\n",
213                 rc, desc, phb->ioda.m64_bar_idx);
214         opal_pci_phb_mmio_enable(phb->opal_id,
215                                  OPAL_M64_WINDOW_TYPE,
216                                  phb->ioda.m64_bar_idx,
217                                  OPAL_DISABLE_M64);
218         return -EIO;
219 }
220
221 static void pnv_ioda_reserve_dev_m64_pe(struct pci_dev *pdev,
222                                          unsigned long *pe_bitmap)
223 {
224         struct pci_controller *hose = pci_bus_to_host(pdev->bus);
225         struct pnv_phb *phb = hose->private_data;
226         struct resource *r;
227         resource_size_t base, sgsz, start, end;
228         int segno, i;
229
230         base = phb->ioda.m64_base;
231         sgsz = phb->ioda.m64_segsize;
232         for (i = 0; i <= PCI_ROM_RESOURCE; i++) {
233                 r = &pdev->resource[i];
234                 if (!r->parent || !pnv_pci_is_mem_pref_64(r->flags))
235                         continue;
236
237                 start = _ALIGN_DOWN(r->start - base, sgsz);
238                 end = _ALIGN_UP(r->end - base, sgsz);
239                 for (segno = start / sgsz; segno < end / sgsz; segno++) {
240                         if (pe_bitmap)
241                                 set_bit(segno, pe_bitmap);
242                         else
243                                 pnv_ioda_reserve_pe(phb, segno);
244                 }
245         }
246 }
247
248 static int pnv_ioda1_init_m64(struct pnv_phb *phb)
249 {
250         struct resource *r;
251         int index;
252
253         /*
254          * There are 16 M64 BARs, each of which has 8 segments. So
255          * there are as many M64 segments as the maximum number of
256          * PEs, which is 128.
257          */
258         for (index = 0; index < PNV_IODA1_M64_NUM; index++) {
259                 unsigned long base, segsz = phb->ioda.m64_segsize;
260                 int64_t rc;
261
262                 base = phb->ioda.m64_base +
263                        index * PNV_IODA1_M64_SEGS * segsz;
264                 rc = opal_pci_set_phb_mem_window(phb->opal_id,
265                                 OPAL_M64_WINDOW_TYPE, index, base, 0,
266                                 PNV_IODA1_M64_SEGS * segsz);
267                 if (rc != OPAL_SUCCESS) {
268                         pr_warn("  Error %lld setting M64 PHB#%d-BAR#%d\n",
269                                 rc, phb->hose->global_number, index);
270                         goto fail;
271                 }
272
273                 rc = opal_pci_phb_mmio_enable(phb->opal_id,
274                                 OPAL_M64_WINDOW_TYPE, index,
275                                 OPAL_ENABLE_M64_SPLIT);
276                 if (rc != OPAL_SUCCESS) {
277                         pr_warn("  Error %lld enabling M64 PHB#%d-BAR#%d\n",
278                                 rc, phb->hose->global_number, index);
279                         goto fail;
280                 }
281         }
282
283         /*
284          * Exclude the segments for reserved and root bus PE, which
285          * are first or last two PEs.
286          */
287         r = &phb->hose->mem_resources[1];
288         if (phb->ioda.reserved_pe_idx == 0)
289                 r->start += (2 * phb->ioda.m64_segsize);
290         else if (phb->ioda.reserved_pe_idx == (phb->ioda.total_pe_num - 1))
291                 r->end -= (2 * phb->ioda.m64_segsize);
292         else
293                 WARN(1, "Wrong reserved PE#%d on PHB#%d\n",
294                      phb->ioda.reserved_pe_idx, phb->hose->global_number);
295
296         return 0;
297
298 fail:
299         for ( ; index >= 0; index--)
300                 opal_pci_phb_mmio_enable(phb->opal_id,
301                         OPAL_M64_WINDOW_TYPE, index, OPAL_DISABLE_M64);
302
303         return -EIO;
304 }
305
306 static void pnv_ioda_reserve_m64_pe(struct pci_bus *bus,
307                                     unsigned long *pe_bitmap,
308                                     bool all)
309 {
310         struct pci_dev *pdev;
311
312         list_for_each_entry(pdev, &bus->devices, bus_list) {
313                 pnv_ioda_reserve_dev_m64_pe(pdev, pe_bitmap);
314
315                 if (all && pdev->subordinate)
316                         pnv_ioda_reserve_m64_pe(pdev->subordinate,
317                                                 pe_bitmap, all);
318         }
319 }
320
321 static struct pnv_ioda_pe *pnv_ioda_pick_m64_pe(struct pci_bus *bus, bool all)
322 {
323         struct pci_controller *hose = pci_bus_to_host(bus);
324         struct pnv_phb *phb = hose->private_data;
325         struct pnv_ioda_pe *master_pe, *pe;
326         unsigned long size, *pe_alloc;
327         int i;
328
329         /* Root bus shouldn't use M64 */
330         if (pci_is_root_bus(bus))
331                 return NULL;
332
333         /* Allocate bitmap */
334         size = _ALIGN_UP(phb->ioda.total_pe_num / 8, sizeof(unsigned long));
335         pe_alloc = kzalloc(size, GFP_KERNEL);
336         if (!pe_alloc) {
337                 pr_warn("%s: Out of memory !\n",
338                         __func__);
339                 return NULL;
340         }
341
342         /* Figure out reserved PE numbers by the PE */
343         pnv_ioda_reserve_m64_pe(bus, pe_alloc, all);
344
345         /*
346          * the current bus might not own M64 window and that's all
347          * contributed by its child buses. For the case, we needn't
348          * pick M64 dependent PE#.
349          */
350         if (bitmap_empty(pe_alloc, phb->ioda.total_pe_num)) {
351                 kfree(pe_alloc);
352                 return NULL;
353         }
354
355         /*
356          * Figure out the master PE and put all slave PEs to master
357          * PE's list to form compound PE.
358          */
359         master_pe = NULL;
360         i = -1;
361         while ((i = find_next_bit(pe_alloc, phb->ioda.total_pe_num, i + 1)) <
362                 phb->ioda.total_pe_num) {
363                 pe = &phb->ioda.pe_array[i];
364
365                 phb->ioda.m64_segmap[pe->pe_number] = pe->pe_number;
366                 if (!master_pe) {
367                         pe->flags |= PNV_IODA_PE_MASTER;
368                         INIT_LIST_HEAD(&pe->slaves);
369                         master_pe = pe;
370                 } else {
371                         pe->flags |= PNV_IODA_PE_SLAVE;
372                         pe->master = master_pe;
373                         list_add_tail(&pe->list, &master_pe->slaves);
374                 }
375
376                 /*
377                  * P7IOC supports M64DT, which helps mapping M64 segment
378                  * to one particular PE#. However, PHB3 has fixed mapping
379                  * between M64 segment and PE#. In order to have same logic
380                  * for P7IOC and PHB3, we enforce fixed mapping between M64
381                  * segment and PE# on P7IOC.
382                  */
383                 if (phb->type == PNV_PHB_IODA1) {
384                         int64_t rc;
385
386                         rc = opal_pci_map_pe_mmio_window(phb->opal_id,
387                                         pe->pe_number, OPAL_M64_WINDOW_TYPE,
388                                         pe->pe_number / PNV_IODA1_M64_SEGS,
389                                         pe->pe_number % PNV_IODA1_M64_SEGS);
390                         if (rc != OPAL_SUCCESS)
391                                 pr_warn("%s: Error %lld mapping M64 for PHB#%d-PE#%d\n",
392                                         __func__, rc, phb->hose->global_number,
393                                         pe->pe_number);
394                 }
395         }
396
397         kfree(pe_alloc);
398         return master_pe;
399 }
400
401 static void __init pnv_ioda_parse_m64_window(struct pnv_phb *phb)
402 {
403         struct pci_controller *hose = phb->hose;
404         struct device_node *dn = hose->dn;
405         struct resource *res;
406         const u32 *r;
407         u64 pci_addr;
408
409         if (phb->type != PNV_PHB_IODA1 && phb->type != PNV_PHB_IODA2) {
410                 pr_info("  Not support M64 window\n");
411                 return;
412         }
413
414         if (!firmware_has_feature(FW_FEATURE_OPAL)) {
415                 pr_info("  Firmware too old to support M64 window\n");
416                 return;
417         }
418
419         r = of_get_property(dn, "ibm,opal-m64-window", NULL);
420         if (!r) {
421                 pr_info("  No <ibm,opal-m64-window> on %s\n",
422                         dn->full_name);
423                 return;
424         }
425
426         res = &hose->mem_resources[1];
427         res->name = dn->full_name;
428         res->start = of_translate_address(dn, r + 2);
429         res->end = res->start + of_read_number(r + 4, 2) - 1;
430         res->flags = (IORESOURCE_MEM | IORESOURCE_MEM_64 | IORESOURCE_PREFETCH);
431         pci_addr = of_read_number(r, 2);
432         hose->mem_offset[1] = res->start - pci_addr;
433
434         phb->ioda.m64_size = resource_size(res);
435         phb->ioda.m64_segsize = phb->ioda.m64_size / phb->ioda.total_pe_num;
436         phb->ioda.m64_base = pci_addr;
437
438         pr_info(" MEM64 0x%016llx..0x%016llx -> 0x%016llx\n",
439                         res->start, res->end, pci_addr);
440
441         /* Use last M64 BAR to cover M64 window */
442         phb->ioda.m64_bar_idx = 15;
443         if (phb->type == PNV_PHB_IODA1)
444                 phb->init_m64 = pnv_ioda1_init_m64;
445         else
446                 phb->init_m64 = pnv_ioda2_init_m64;
447         phb->reserve_m64_pe = pnv_ioda_reserve_m64_pe;
448         phb->pick_m64_pe = pnv_ioda_pick_m64_pe;
449 }
450
451 static void pnv_ioda_freeze_pe(struct pnv_phb *phb, int pe_no)
452 {
453         struct pnv_ioda_pe *pe = &phb->ioda.pe_array[pe_no];
454         struct pnv_ioda_pe *slave;
455         s64 rc;
456
457         /* Fetch master PE */
458         if (pe->flags & PNV_IODA_PE_SLAVE) {
459                 pe = pe->master;
460                 if (WARN_ON(!pe || !(pe->flags & PNV_IODA_PE_MASTER)))
461                         return;
462
463                 pe_no = pe->pe_number;
464         }
465
466         /* Freeze master PE */
467         rc = opal_pci_eeh_freeze_set(phb->opal_id,
468                                      pe_no,
469                                      OPAL_EEH_ACTION_SET_FREEZE_ALL);
470         if (rc != OPAL_SUCCESS) {
471                 pr_warn("%s: Failure %lld freezing PHB#%x-PE#%x\n",
472                         __func__, rc, phb->hose->global_number, pe_no);
473                 return;
474         }
475
476         /* Freeze slave PEs */
477         if (!(pe->flags & PNV_IODA_PE_MASTER))
478                 return;
479
480         list_for_each_entry(slave, &pe->slaves, list) {
481                 rc = opal_pci_eeh_freeze_set(phb->opal_id,
482                                              slave->pe_number,
483                                              OPAL_EEH_ACTION_SET_FREEZE_ALL);
484                 if (rc != OPAL_SUCCESS)
485                         pr_warn("%s: Failure %lld freezing PHB#%x-PE#%x\n",
486                                 __func__, rc, phb->hose->global_number,
487                                 slave->pe_number);
488         }
489 }
490
491 static int pnv_ioda_unfreeze_pe(struct pnv_phb *phb, int pe_no, int opt)
492 {
493         struct pnv_ioda_pe *pe, *slave;
494         s64 rc;
495
496         /* Find master PE */
497         pe = &phb->ioda.pe_array[pe_no];
498         if (pe->flags & PNV_IODA_PE_SLAVE) {
499                 pe = pe->master;
500                 WARN_ON(!pe || !(pe->flags & PNV_IODA_PE_MASTER));
501                 pe_no = pe->pe_number;
502         }
503
504         /* Clear frozen state for master PE */
505         rc = opal_pci_eeh_freeze_clear(phb->opal_id, pe_no, opt);
506         if (rc != OPAL_SUCCESS) {
507                 pr_warn("%s: Failure %lld clear %d on PHB#%x-PE#%x\n",
508                         __func__, rc, opt, phb->hose->global_number, pe_no);
509                 return -EIO;
510         }
511
512         if (!(pe->flags & PNV_IODA_PE_MASTER))
513                 return 0;
514
515         /* Clear frozen state for slave PEs */
516         list_for_each_entry(slave, &pe->slaves, list) {
517                 rc = opal_pci_eeh_freeze_clear(phb->opal_id,
518                                              slave->pe_number,
519                                              opt);
520                 if (rc != OPAL_SUCCESS) {
521                         pr_warn("%s: Failure %lld clear %d on PHB#%x-PE#%x\n",
522                                 __func__, rc, opt, phb->hose->global_number,
523                                 slave->pe_number);
524                         return -EIO;
525                 }
526         }
527
528         return 0;
529 }
530
531 static int pnv_ioda_get_pe_state(struct pnv_phb *phb, int pe_no)
532 {
533         struct pnv_ioda_pe *slave, *pe;
534         u8 fstate, state;
535         __be16 pcierr;
536         s64 rc;
537
538         /* Sanity check on PE number */
539         if (pe_no < 0 || pe_no >= phb->ioda.total_pe_num)
540                 return OPAL_EEH_STOPPED_PERM_UNAVAIL;
541
542         /*
543          * Fetch the master PE and the PE instance might be
544          * not initialized yet.
545          */
546         pe = &phb->ioda.pe_array[pe_no];
547         if (pe->flags & PNV_IODA_PE_SLAVE) {
548                 pe = pe->master;
549                 WARN_ON(!pe || !(pe->flags & PNV_IODA_PE_MASTER));
550                 pe_no = pe->pe_number;
551         }
552
553         /* Check the master PE */
554         rc = opal_pci_eeh_freeze_status(phb->opal_id, pe_no,
555                                         &state, &pcierr, NULL);
556         if (rc != OPAL_SUCCESS) {
557                 pr_warn("%s: Failure %lld getting "
558                         "PHB#%x-PE#%x state\n",
559                         __func__, rc,
560                         phb->hose->global_number, pe_no);
561                 return OPAL_EEH_STOPPED_TEMP_UNAVAIL;
562         }
563
564         /* Check the slave PE */
565         if (!(pe->flags & PNV_IODA_PE_MASTER))
566                 return state;
567
568         list_for_each_entry(slave, &pe->slaves, list) {
569                 rc = opal_pci_eeh_freeze_status(phb->opal_id,
570                                                 slave->pe_number,
571                                                 &fstate,
572                                                 &pcierr,
573                                                 NULL);
574                 if (rc != OPAL_SUCCESS) {
575                         pr_warn("%s: Failure %lld getting "
576                                 "PHB#%x-PE#%x state\n",
577                                 __func__, rc,
578                                 phb->hose->global_number, slave->pe_number);
579                         return OPAL_EEH_STOPPED_TEMP_UNAVAIL;
580                 }
581
582                 /*
583                  * Override the result based on the ascending
584                  * priority.
585                  */
586                 if (fstate > state)
587                         state = fstate;
588         }
589
590         return state;
591 }
592
593 /* Currently those 2 are only used when MSIs are enabled, this will change
594  * but in the meantime, we need to protect them to avoid warnings
595  */
596 #ifdef CONFIG_PCI_MSI
597 static struct pnv_ioda_pe *pnv_ioda_get_pe(struct pci_dev *dev)
598 {
599         struct pci_controller *hose = pci_bus_to_host(dev->bus);
600         struct pnv_phb *phb = hose->private_data;
601         struct pci_dn *pdn = pci_get_pdn(dev);
602
603         if (!pdn)
604                 return NULL;
605         if (pdn->pe_number == IODA_INVALID_PE)
606                 return NULL;
607         return &phb->ioda.pe_array[pdn->pe_number];
608 }
609 #endif /* CONFIG_PCI_MSI */
610
611 static int pnv_ioda_set_one_peltv(struct pnv_phb *phb,
612                                   struct pnv_ioda_pe *parent,
613                                   struct pnv_ioda_pe *child,
614                                   bool is_add)
615 {
616         const char *desc = is_add ? "adding" : "removing";
617         uint8_t op = is_add ? OPAL_ADD_PE_TO_DOMAIN :
618                               OPAL_REMOVE_PE_FROM_DOMAIN;
619         struct pnv_ioda_pe *slave;
620         long rc;
621
622         /* Parent PE affects child PE */
623         rc = opal_pci_set_peltv(phb->opal_id, parent->pe_number,
624                                 child->pe_number, op);
625         if (rc != OPAL_SUCCESS) {
626                 pe_warn(child, "OPAL error %ld %s to parent PELTV\n",
627                         rc, desc);
628                 return -ENXIO;
629         }
630
631         if (!(child->flags & PNV_IODA_PE_MASTER))
632                 return 0;
633
634         /* Compound case: parent PE affects slave PEs */
635         list_for_each_entry(slave, &child->slaves, list) {
636                 rc = opal_pci_set_peltv(phb->opal_id, parent->pe_number,
637                                         slave->pe_number, op);
638                 if (rc != OPAL_SUCCESS) {
639                         pe_warn(slave, "OPAL error %ld %s to parent PELTV\n",
640                                 rc, desc);
641                         return -ENXIO;
642                 }
643         }
644
645         return 0;
646 }
647
648 static int pnv_ioda_set_peltv(struct pnv_phb *phb,
649                               struct pnv_ioda_pe *pe,
650                               bool is_add)
651 {
652         struct pnv_ioda_pe *slave;
653         struct pci_dev *pdev = NULL;
654         int ret;
655
656         /*
657          * Clear PE frozen state. If it's master PE, we need
658          * clear slave PE frozen state as well.
659          */
660         if (is_add) {
661                 opal_pci_eeh_freeze_clear(phb->opal_id, pe->pe_number,
662                                           OPAL_EEH_ACTION_CLEAR_FREEZE_ALL);
663                 if (pe->flags & PNV_IODA_PE_MASTER) {
664                         list_for_each_entry(slave, &pe->slaves, list)
665                                 opal_pci_eeh_freeze_clear(phb->opal_id,
666                                                           slave->pe_number,
667                                                           OPAL_EEH_ACTION_CLEAR_FREEZE_ALL);
668                 }
669         }
670
671         /*
672          * Associate PE in PELT. We need add the PE into the
673          * corresponding PELT-V as well. Otherwise, the error
674          * originated from the PE might contribute to other
675          * PEs.
676          */
677         ret = pnv_ioda_set_one_peltv(phb, pe, pe, is_add);
678         if (ret)
679                 return ret;
680
681         /* For compound PEs, any one affects all of them */
682         if (pe->flags & PNV_IODA_PE_MASTER) {
683                 list_for_each_entry(slave, &pe->slaves, list) {
684                         ret = pnv_ioda_set_one_peltv(phb, slave, pe, is_add);
685                         if (ret)
686                                 return ret;
687                 }
688         }
689
690         if (pe->flags & (PNV_IODA_PE_BUS_ALL | PNV_IODA_PE_BUS))
691                 pdev = pe->pbus->self;
692         else if (pe->flags & PNV_IODA_PE_DEV)
693                 pdev = pe->pdev->bus->self;
694 #ifdef CONFIG_PCI_IOV
695         else if (pe->flags & PNV_IODA_PE_VF)
696                 pdev = pe->parent_dev;
697 #endif /* CONFIG_PCI_IOV */
698         while (pdev) {
699                 struct pci_dn *pdn = pci_get_pdn(pdev);
700                 struct pnv_ioda_pe *parent;
701
702                 if (pdn && pdn->pe_number != IODA_INVALID_PE) {
703                         parent = &phb->ioda.pe_array[pdn->pe_number];
704                         ret = pnv_ioda_set_one_peltv(phb, parent, pe, is_add);
705                         if (ret)
706                                 return ret;
707                 }
708
709                 pdev = pdev->bus->self;
710         }
711
712         return 0;
713 }
714
715 #ifdef CONFIG_PCI_IOV
716 static int pnv_ioda_deconfigure_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe)
717 {
718         struct pci_dev *parent;
719         uint8_t bcomp, dcomp, fcomp;
720         int64_t rc;
721         long rid_end, rid;
722
723         /* Currently, we just deconfigure VF PE. Bus PE will always there.*/
724         if (pe->pbus) {
725                 int count;
726
727                 dcomp = OPAL_IGNORE_RID_DEVICE_NUMBER;
728                 fcomp = OPAL_IGNORE_RID_FUNCTION_NUMBER;
729                 parent = pe->pbus->self;
730                 if (pe->flags & PNV_IODA_PE_BUS_ALL)
731                         count = pe->pbus->busn_res.end - pe->pbus->busn_res.start + 1;
732                 else
733                         count = 1;
734
735                 switch(count) {
736                 case  1: bcomp = OpalPciBusAll;         break;
737                 case  2: bcomp = OpalPciBus7Bits;       break;
738                 case  4: bcomp = OpalPciBus6Bits;       break;
739                 case  8: bcomp = OpalPciBus5Bits;       break;
740                 case 16: bcomp = OpalPciBus4Bits;       break;
741                 case 32: bcomp = OpalPciBus3Bits;       break;
742                 default:
743                         dev_err(&pe->pbus->dev, "Number of subordinate buses %d unsupported\n",
744                                 count);
745                         /* Do an exact match only */
746                         bcomp = OpalPciBusAll;
747                 }
748                 rid_end = pe->rid + (count << 8);
749         } else {
750                 if (pe->flags & PNV_IODA_PE_VF)
751                         parent = pe->parent_dev;
752                 else
753                         parent = pe->pdev->bus->self;
754                 bcomp = OpalPciBusAll;
755                 dcomp = OPAL_COMPARE_RID_DEVICE_NUMBER;
756                 fcomp = OPAL_COMPARE_RID_FUNCTION_NUMBER;
757                 rid_end = pe->rid + 1;
758         }
759
760         /* Clear the reverse map */
761         for (rid = pe->rid; rid < rid_end; rid++)
762                 phb->ioda.pe_rmap[rid] = IODA_INVALID_PE;
763
764         /* Release from all parents PELT-V */
765         while (parent) {
766                 struct pci_dn *pdn = pci_get_pdn(parent);
767                 if (pdn && pdn->pe_number != IODA_INVALID_PE) {
768                         rc = opal_pci_set_peltv(phb->opal_id, pdn->pe_number,
769                                                 pe->pe_number, OPAL_REMOVE_PE_FROM_DOMAIN);
770                         /* XXX What to do in case of error ? */
771                 }
772                 parent = parent->bus->self;
773         }
774
775         opal_pci_eeh_freeze_clear(phb->opal_id, pe->pe_number,
776                                   OPAL_EEH_ACTION_CLEAR_FREEZE_ALL);
777
778         /* Disassociate PE in PELT */
779         rc = opal_pci_set_peltv(phb->opal_id, pe->pe_number,
780                                 pe->pe_number, OPAL_REMOVE_PE_FROM_DOMAIN);
781         if (rc)
782                 pe_warn(pe, "OPAL error %ld remove self from PELTV\n", rc);
783         rc = opal_pci_set_pe(phb->opal_id, pe->pe_number, pe->rid,
784                              bcomp, dcomp, fcomp, OPAL_UNMAP_PE);
785         if (rc)
786                 pe_err(pe, "OPAL error %ld trying to setup PELT table\n", rc);
787
788         pe->pbus = NULL;
789         pe->pdev = NULL;
790         pe->parent_dev = NULL;
791
792         return 0;
793 }
794 #endif /* CONFIG_PCI_IOV */
795
796 static int pnv_ioda_configure_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe)
797 {
798         struct pci_dev *parent;
799         uint8_t bcomp, dcomp, fcomp;
800         long rc, rid_end, rid;
801
802         /* Bus validation ? */
803         if (pe->pbus) {
804                 int count;
805
806                 dcomp = OPAL_IGNORE_RID_DEVICE_NUMBER;
807                 fcomp = OPAL_IGNORE_RID_FUNCTION_NUMBER;
808                 parent = pe->pbus->self;
809                 if (pe->flags & PNV_IODA_PE_BUS_ALL)
810                         count = pe->pbus->busn_res.end - pe->pbus->busn_res.start + 1;
811                 else
812                         count = 1;
813
814                 switch(count) {
815                 case  1: bcomp = OpalPciBusAll;         break;
816                 case  2: bcomp = OpalPciBus7Bits;       break;
817                 case  4: bcomp = OpalPciBus6Bits;       break;
818                 case  8: bcomp = OpalPciBus5Bits;       break;
819                 case 16: bcomp = OpalPciBus4Bits;       break;
820                 case 32: bcomp = OpalPciBus3Bits;       break;
821                 default:
822                         dev_err(&pe->pbus->dev, "Number of subordinate buses %d unsupported\n",
823                                 count);
824                         /* Do an exact match only */
825                         bcomp = OpalPciBusAll;
826                 }
827                 rid_end = pe->rid + (count << 8);
828         } else {
829 #ifdef CONFIG_PCI_IOV
830                 if (pe->flags & PNV_IODA_PE_VF)
831                         parent = pe->parent_dev;
832                 else
833 #endif /* CONFIG_PCI_IOV */
834                         parent = pe->pdev->bus->self;
835                 bcomp = OpalPciBusAll;
836                 dcomp = OPAL_COMPARE_RID_DEVICE_NUMBER;
837                 fcomp = OPAL_COMPARE_RID_FUNCTION_NUMBER;
838                 rid_end = pe->rid + 1;
839         }
840
841         /*
842          * Associate PE in PELT. We need add the PE into the
843          * corresponding PELT-V as well. Otherwise, the error
844          * originated from the PE might contribute to other
845          * PEs.
846          */
847         rc = opal_pci_set_pe(phb->opal_id, pe->pe_number, pe->rid,
848                              bcomp, dcomp, fcomp, OPAL_MAP_PE);
849         if (rc) {
850                 pe_err(pe, "OPAL error %ld trying to setup PELT table\n", rc);
851                 return -ENXIO;
852         }
853
854         /*
855          * Configure PELTV. NPUs don't have a PELTV table so skip
856          * configuration on them.
857          */
858         if (phb->type != PNV_PHB_NPU)
859                 pnv_ioda_set_peltv(phb, pe, true);
860
861         /* Setup reverse map */
862         for (rid = pe->rid; rid < rid_end; rid++)
863                 phb->ioda.pe_rmap[rid] = pe->pe_number;
864
865         /* Setup one MVTs on IODA1 */
866         if (phb->type != PNV_PHB_IODA1) {
867                 pe->mve_number = 0;
868                 goto out;
869         }
870
871         pe->mve_number = pe->pe_number;
872         rc = opal_pci_set_mve(phb->opal_id, pe->mve_number, pe->pe_number);
873         if (rc != OPAL_SUCCESS) {
874                 pe_err(pe, "OPAL error %ld setting up MVE %d\n",
875                        rc, pe->mve_number);
876                 pe->mve_number = -1;
877         } else {
878                 rc = opal_pci_set_mve_enable(phb->opal_id,
879                                              pe->mve_number, OPAL_ENABLE_MVE);
880                 if (rc) {
881                         pe_err(pe, "OPAL error %ld enabling MVE %d\n",
882                                rc, pe->mve_number);
883                         pe->mve_number = -1;
884                 }
885         }
886
887 out:
888         return 0;
889 }
890
891 #ifdef CONFIG_PCI_IOV
892 static int pnv_pci_vf_resource_shift(struct pci_dev *dev, int offset)
893 {
894         struct pci_dn *pdn = pci_get_pdn(dev);
895         int i;
896         struct resource *res, res2;
897         resource_size_t size;
898         u16 num_vfs;
899
900         if (!dev->is_physfn)
901                 return -EINVAL;
902
903         /*
904          * "offset" is in VFs.  The M64 windows are sized so that when they
905          * are segmented, each segment is the same size as the IOV BAR.
906          * Each segment is in a separate PE, and the high order bits of the
907          * address are the PE number.  Therefore, each VF's BAR is in a
908          * separate PE, and changing the IOV BAR start address changes the
909          * range of PEs the VFs are in.
910          */
911         num_vfs = pdn->num_vfs;
912         for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
913                 res = &dev->resource[i + PCI_IOV_RESOURCES];
914                 if (!res->flags || !res->parent)
915                         continue;
916
917                 /*
918                  * The actual IOV BAR range is determined by the start address
919                  * and the actual size for num_vfs VFs BAR.  This check is to
920                  * make sure that after shifting, the range will not overlap
921                  * with another device.
922                  */
923                 size = pci_iov_resource_size(dev, i + PCI_IOV_RESOURCES);
924                 res2.flags = res->flags;
925                 res2.start = res->start + (size * offset);
926                 res2.end = res2.start + (size * num_vfs) - 1;
927
928                 if (res2.end > res->end) {
929                         dev_err(&dev->dev, "VF BAR%d: %pR would extend past %pR (trying to enable %d VFs shifted by %d)\n",
930                                 i, &res2, res, num_vfs, offset);
931                         return -EBUSY;
932                 }
933         }
934
935         /*
936          * After doing so, there would be a "hole" in the /proc/iomem when
937          * offset is a positive value. It looks like the device return some
938          * mmio back to the system, which actually no one could use it.
939          */
940         for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
941                 res = &dev->resource[i + PCI_IOV_RESOURCES];
942                 if (!res->flags || !res->parent)
943                         continue;
944
945                 size = pci_iov_resource_size(dev, i + PCI_IOV_RESOURCES);
946                 res2 = *res;
947                 res->start += size * offset;
948
949                 dev_info(&dev->dev, "VF BAR%d: %pR shifted to %pR (%sabling %d VFs shifted by %d)\n",
950                          i, &res2, res, (offset > 0) ? "En" : "Dis",
951                          num_vfs, offset);
952                 pci_update_resource(dev, i + PCI_IOV_RESOURCES);
953         }
954         return 0;
955 }
956 #endif /* CONFIG_PCI_IOV */
957
958 static struct pnv_ioda_pe *pnv_ioda_setup_dev_PE(struct pci_dev *dev)
959 {
960         struct pci_controller *hose = pci_bus_to_host(dev->bus);
961         struct pnv_phb *phb = hose->private_data;
962         struct pci_dn *pdn = pci_get_pdn(dev);
963         struct pnv_ioda_pe *pe;
964
965         if (!pdn) {
966                 pr_err("%s: Device tree node not associated properly\n",
967                            pci_name(dev));
968                 return NULL;
969         }
970         if (pdn->pe_number != IODA_INVALID_PE)
971                 return NULL;
972
973         pe = pnv_ioda_alloc_pe(phb);
974         if (!pe) {
975                 pr_warning("%s: Not enough PE# available, disabling device\n",
976                            pci_name(dev));
977                 return NULL;
978         }
979
980         /* NOTE: We get only one ref to the pci_dev for the pdn, not for the
981          * pointer in the PE data structure, both should be destroyed at the
982          * same time. However, this needs to be looked at more closely again
983          * once we actually start removing things (Hotplug, SR-IOV, ...)
984          *
985          * At some point we want to remove the PDN completely anyways
986          */
987         pci_dev_get(dev);
988         pdn->pcidev = dev;
989         pdn->pe_number = pe->pe_number;
990         pe->flags = PNV_IODA_PE_DEV;
991         pe->pdev = dev;
992         pe->pbus = NULL;
993         pe->mve_number = -1;
994         pe->rid = dev->bus->number << 8 | pdn->devfn;
995
996         pe_info(pe, "Associated device to PE\n");
997
998         if (pnv_ioda_configure_pe(phb, pe)) {
999                 /* XXX What do we do here ? */
1000                 pnv_ioda_free_pe(pe);
1001                 pdn->pe_number = IODA_INVALID_PE;
1002                 pe->pdev = NULL;
1003                 pci_dev_put(dev);
1004                 return NULL;
1005         }
1006
1007         /* Put PE to the list */
1008         list_add_tail(&pe->list, &phb->ioda.pe_list);
1009
1010         return pe;
1011 }
1012
1013 static void pnv_ioda_setup_same_PE(struct pci_bus *bus, struct pnv_ioda_pe *pe)
1014 {
1015         struct pci_dev *dev;
1016
1017         list_for_each_entry(dev, &bus->devices, bus_list) {
1018                 struct pci_dn *pdn = pci_get_pdn(dev);
1019
1020                 if (pdn == NULL) {
1021                         pr_warn("%s: No device node associated with device !\n",
1022                                 pci_name(dev));
1023                         continue;
1024                 }
1025
1026                 /*
1027                  * In partial hotplug case, the PCI device might be still
1028                  * associated with the PE and needn't attach it to the PE
1029                  * again.
1030                  */
1031                 if (pdn->pe_number != IODA_INVALID_PE)
1032                         continue;
1033
1034                 pdn->pcidev = dev;
1035                 pdn->pe_number = pe->pe_number;
1036                 if ((pe->flags & PNV_IODA_PE_BUS_ALL) && dev->subordinate)
1037                         pnv_ioda_setup_same_PE(dev->subordinate, pe);
1038         }
1039 }
1040
1041 /*
1042  * There're 2 types of PCI bus sensitive PEs: One that is compromised of
1043  * single PCI bus. Another one that contains the primary PCI bus and its
1044  * subordinate PCI devices and buses. The second type of PE is normally
1045  * orgiriated by PCIe-to-PCI bridge or PLX switch downstream ports.
1046  */
1047 static struct pnv_ioda_pe *pnv_ioda_setup_bus_PE(struct pci_bus *bus, bool all)
1048 {
1049         struct pci_controller *hose = pci_bus_to_host(bus);
1050         struct pnv_phb *phb = hose->private_data;
1051         struct pnv_ioda_pe *pe = NULL;
1052         unsigned int pe_num;
1053
1054         /*
1055          * In partial hotplug case, the PE instance might be still alive.
1056          * We should reuse it instead of allocating a new one.
1057          */
1058         pe_num = phb->ioda.pe_rmap[bus->number << 8];
1059         if (pe_num != IODA_INVALID_PE) {
1060                 pe = &phb->ioda.pe_array[pe_num];
1061                 pnv_ioda_setup_same_PE(bus, pe);
1062                 return NULL;
1063         }
1064
1065         /* PE number for root bus should have been reserved */
1066         if (pci_is_root_bus(bus) &&
1067             phb->ioda.root_pe_idx != IODA_INVALID_PE)
1068                 pe = &phb->ioda.pe_array[phb->ioda.root_pe_idx];
1069
1070         /* Check if PE is determined by M64 */
1071         if (!pe && phb->pick_m64_pe)
1072                 pe = phb->pick_m64_pe(bus, all);
1073
1074         /* The PE number isn't pinned by M64 */
1075         if (!pe)
1076                 pe = pnv_ioda_alloc_pe(phb);
1077
1078         if (!pe) {
1079                 pr_warning("%s: Not enough PE# available for PCI bus %04x:%02x\n",
1080                         __func__, pci_domain_nr(bus), bus->number);
1081                 return NULL;
1082         }
1083
1084         pe->flags |= (all ? PNV_IODA_PE_BUS_ALL : PNV_IODA_PE_BUS);
1085         pe->pbus = bus;
1086         pe->pdev = NULL;
1087         pe->mve_number = -1;
1088         pe->rid = bus->busn_res.start << 8;
1089
1090         if (all)
1091                 pe_info(pe, "Secondary bus %d..%d associated with PE#%d\n",
1092                         bus->busn_res.start, bus->busn_res.end, pe->pe_number);
1093         else
1094                 pe_info(pe, "Secondary bus %d associated with PE#%d\n",
1095                         bus->busn_res.start, pe->pe_number);
1096
1097         if (pnv_ioda_configure_pe(phb, pe)) {
1098                 /* XXX What do we do here ? */
1099                 pnv_ioda_free_pe(pe);
1100                 pe->pbus = NULL;
1101                 return NULL;
1102         }
1103
1104         /* Associate it with all child devices */
1105         pnv_ioda_setup_same_PE(bus, pe);
1106
1107         /* Put PE to the list */
1108         list_add_tail(&pe->list, &phb->ioda.pe_list);
1109
1110         return pe;
1111 }
1112
1113 static struct pnv_ioda_pe *pnv_ioda_setup_npu_PE(struct pci_dev *npu_pdev)
1114 {
1115         int pe_num, found_pe = false, rc;
1116         long rid;
1117         struct pnv_ioda_pe *pe;
1118         struct pci_dev *gpu_pdev;
1119         struct pci_dn *npu_pdn;
1120         struct pci_controller *hose = pci_bus_to_host(npu_pdev->bus);
1121         struct pnv_phb *phb = hose->private_data;
1122
1123         /*
1124          * Due to a hardware errata PE#0 on the NPU is reserved for
1125          * error handling. This means we only have three PEs remaining
1126          * which need to be assigned to four links, implying some
1127          * links must share PEs.
1128          *
1129          * To achieve this we assign PEs such that NPUs linking the
1130          * same GPU get assigned the same PE.
1131          */
1132         gpu_pdev = pnv_pci_get_gpu_dev(npu_pdev);
1133         for (pe_num = 0; pe_num < phb->ioda.total_pe_num; pe_num++) {
1134                 pe = &phb->ioda.pe_array[pe_num];
1135                 if (!pe->pdev)
1136                         continue;
1137
1138                 if (pnv_pci_get_gpu_dev(pe->pdev) == gpu_pdev) {
1139                         /*
1140                          * This device has the same peer GPU so should
1141                          * be assigned the same PE as the existing
1142                          * peer NPU.
1143                          */
1144                         dev_info(&npu_pdev->dev,
1145                                 "Associating to existing PE %d\n", pe_num);
1146                         pci_dev_get(npu_pdev);
1147                         npu_pdn = pci_get_pdn(npu_pdev);
1148                         rid = npu_pdev->bus->number << 8 | npu_pdn->devfn;
1149                         npu_pdn->pcidev = npu_pdev;
1150                         npu_pdn->pe_number = pe_num;
1151                         phb->ioda.pe_rmap[rid] = pe->pe_number;
1152
1153                         /* Map the PE to this link */
1154                         rc = opal_pci_set_pe(phb->opal_id, pe_num, rid,
1155                                         OpalPciBusAll,
1156                                         OPAL_COMPARE_RID_DEVICE_NUMBER,
1157                                         OPAL_COMPARE_RID_FUNCTION_NUMBER,
1158                                         OPAL_MAP_PE);
1159                         WARN_ON(rc != OPAL_SUCCESS);
1160                         found_pe = true;
1161                         break;
1162                 }
1163         }
1164
1165         if (!found_pe)
1166                 /*
1167                  * Could not find an existing PE so allocate a new
1168                  * one.
1169                  */
1170                 return pnv_ioda_setup_dev_PE(npu_pdev);
1171         else
1172                 return pe;
1173 }
1174
1175 static void pnv_ioda_setup_npu_PEs(struct pci_bus *bus)
1176 {
1177         struct pci_dev *pdev;
1178
1179         list_for_each_entry(pdev, &bus->devices, bus_list)
1180                 pnv_ioda_setup_npu_PE(pdev);
1181 }
1182
1183 static void pnv_pci_ioda_setup_PEs(void)
1184 {
1185         struct pci_controller *hose, *tmp;
1186         struct pnv_phb *phb;
1187
1188         list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
1189                 phb = hose->private_data;
1190                 if (phb->type == PNV_PHB_NPU) {
1191                         /* PE#0 is needed for error reporting */
1192                         pnv_ioda_reserve_pe(phb, 0);
1193                         pnv_ioda_setup_npu_PEs(hose->bus);
1194                 }
1195         }
1196 }
1197
1198 #ifdef CONFIG_PCI_IOV
1199 static int pnv_pci_vf_release_m64(struct pci_dev *pdev, u16 num_vfs)
1200 {
1201         struct pci_bus        *bus;
1202         struct pci_controller *hose;
1203         struct pnv_phb        *phb;
1204         struct pci_dn         *pdn;
1205         int                    i, j;
1206         int                    m64_bars;
1207
1208         bus = pdev->bus;
1209         hose = pci_bus_to_host(bus);
1210         phb = hose->private_data;
1211         pdn = pci_get_pdn(pdev);
1212
1213         if (pdn->m64_single_mode)
1214                 m64_bars = num_vfs;
1215         else
1216                 m64_bars = 1;
1217
1218         for (i = 0; i < PCI_SRIOV_NUM_BARS; i++)
1219                 for (j = 0; j < m64_bars; j++) {
1220                         if (pdn->m64_map[j][i] == IODA_INVALID_M64)
1221                                 continue;
1222                         opal_pci_phb_mmio_enable(phb->opal_id,
1223                                 OPAL_M64_WINDOW_TYPE, pdn->m64_map[j][i], 0);
1224                         clear_bit(pdn->m64_map[j][i], &phb->ioda.m64_bar_alloc);
1225                         pdn->m64_map[j][i] = IODA_INVALID_M64;
1226                 }
1227
1228         kfree(pdn->m64_map);
1229         return 0;
1230 }
1231
1232 static int pnv_pci_vf_assign_m64(struct pci_dev *pdev, u16 num_vfs)
1233 {
1234         struct pci_bus        *bus;
1235         struct pci_controller *hose;
1236         struct pnv_phb        *phb;
1237         struct pci_dn         *pdn;
1238         unsigned int           win;
1239         struct resource       *res;
1240         int                    i, j;
1241         int64_t                rc;
1242         int                    total_vfs;
1243         resource_size_t        size, start;
1244         int                    pe_num;
1245         int                    m64_bars;
1246
1247         bus = pdev->bus;
1248         hose = pci_bus_to_host(bus);
1249         phb = hose->private_data;
1250         pdn = pci_get_pdn(pdev);
1251         total_vfs = pci_sriov_get_totalvfs(pdev);
1252
1253         if (pdn->m64_single_mode)
1254                 m64_bars = num_vfs;
1255         else
1256                 m64_bars = 1;
1257
1258         pdn->m64_map = kmalloc(sizeof(*pdn->m64_map) * m64_bars, GFP_KERNEL);
1259         if (!pdn->m64_map)
1260                 return -ENOMEM;
1261         /* Initialize the m64_map to IODA_INVALID_M64 */
1262         for (i = 0; i < m64_bars ; i++)
1263                 for (j = 0; j < PCI_SRIOV_NUM_BARS; j++)
1264                         pdn->m64_map[i][j] = IODA_INVALID_M64;
1265
1266
1267         for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
1268                 res = &pdev->resource[i + PCI_IOV_RESOURCES];
1269                 if (!res->flags || !res->parent)
1270                         continue;
1271
1272                 for (j = 0; j < m64_bars; j++) {
1273                         do {
1274                                 win = find_next_zero_bit(&phb->ioda.m64_bar_alloc,
1275                                                 phb->ioda.m64_bar_idx + 1, 0);
1276
1277                                 if (win >= phb->ioda.m64_bar_idx + 1)
1278                                         goto m64_failed;
1279                         } while (test_and_set_bit(win, &phb->ioda.m64_bar_alloc));
1280
1281                         pdn->m64_map[j][i] = win;
1282
1283                         if (pdn->m64_single_mode) {
1284                                 size = pci_iov_resource_size(pdev,
1285                                                         PCI_IOV_RESOURCES + i);
1286                                 start = res->start + size * j;
1287                         } else {
1288                                 size = resource_size(res);
1289                                 start = res->start;
1290                         }
1291
1292                         /* Map the M64 here */
1293                         if (pdn->m64_single_mode) {
1294                                 pe_num = pdn->pe_num_map[j];
1295                                 rc = opal_pci_map_pe_mmio_window(phb->opal_id,
1296                                                 pe_num, OPAL_M64_WINDOW_TYPE,
1297                                                 pdn->m64_map[j][i], 0);
1298                         }
1299
1300                         rc = opal_pci_set_phb_mem_window(phb->opal_id,
1301                                                  OPAL_M64_WINDOW_TYPE,
1302                                                  pdn->m64_map[j][i],
1303                                                  start,
1304                                                  0, /* unused */
1305                                                  size);
1306
1307
1308                         if (rc != OPAL_SUCCESS) {
1309                                 dev_err(&pdev->dev, "Failed to map M64 window #%d: %lld\n",
1310                                         win, rc);
1311                                 goto m64_failed;
1312                         }
1313
1314                         if (pdn->m64_single_mode)
1315                                 rc = opal_pci_phb_mmio_enable(phb->opal_id,
1316                                      OPAL_M64_WINDOW_TYPE, pdn->m64_map[j][i], 2);
1317                         else
1318                                 rc = opal_pci_phb_mmio_enable(phb->opal_id,
1319                                      OPAL_M64_WINDOW_TYPE, pdn->m64_map[j][i], 1);
1320
1321                         if (rc != OPAL_SUCCESS) {
1322                                 dev_err(&pdev->dev, "Failed to enable M64 window #%d: %llx\n",
1323                                         win, rc);
1324                                 goto m64_failed;
1325                         }
1326                 }
1327         }
1328         return 0;
1329
1330 m64_failed:
1331         pnv_pci_vf_release_m64(pdev, num_vfs);
1332         return -EBUSY;
1333 }
1334
1335 static long pnv_pci_ioda2_unset_window(struct iommu_table_group *table_group,
1336                 int num);
1337 static void pnv_pci_ioda2_set_bypass(struct pnv_ioda_pe *pe, bool enable);
1338
1339 static void pnv_pci_ioda2_release_dma_pe(struct pci_dev *dev, struct pnv_ioda_pe *pe)
1340 {
1341         struct iommu_table    *tbl;
1342         int64_t               rc;
1343
1344         tbl = pe->table_group.tables[0];
1345         rc = pnv_pci_ioda2_unset_window(&pe->table_group, 0);
1346         if (rc)
1347                 pe_warn(pe, "OPAL error %ld release DMA window\n", rc);
1348
1349         pnv_pci_ioda2_set_bypass(pe, false);
1350         if (pe->table_group.group) {
1351                 iommu_group_put(pe->table_group.group);
1352                 BUG_ON(pe->table_group.group);
1353         }
1354         pnv_pci_ioda2_table_free_pages(tbl);
1355         iommu_free_table(tbl, of_node_full_name(dev->dev.of_node));
1356 }
1357
1358 static void pnv_ioda_release_vf_PE(struct pci_dev *pdev)
1359 {
1360         struct pci_bus        *bus;
1361         struct pci_controller *hose;
1362         struct pnv_phb        *phb;
1363         struct pnv_ioda_pe    *pe, *pe_n;
1364         struct pci_dn         *pdn;
1365
1366         bus = pdev->bus;
1367         hose = pci_bus_to_host(bus);
1368         phb = hose->private_data;
1369         pdn = pci_get_pdn(pdev);
1370
1371         if (!pdev->is_physfn)
1372                 return;
1373
1374         list_for_each_entry_safe(pe, pe_n, &phb->ioda.pe_list, list) {
1375                 if (pe->parent_dev != pdev)
1376                         continue;
1377
1378                 pnv_pci_ioda2_release_dma_pe(pdev, pe);
1379
1380                 /* Remove from list */
1381                 mutex_lock(&phb->ioda.pe_list_mutex);
1382                 list_del(&pe->list);
1383                 mutex_unlock(&phb->ioda.pe_list_mutex);
1384
1385                 pnv_ioda_deconfigure_pe(phb, pe);
1386
1387                 pnv_ioda_free_pe(pe);
1388         }
1389 }
1390
1391 void pnv_pci_sriov_disable(struct pci_dev *pdev)
1392 {
1393         struct pci_bus        *bus;
1394         struct pci_controller *hose;
1395         struct pnv_phb        *phb;
1396         struct pnv_ioda_pe    *pe;
1397         struct pci_dn         *pdn;
1398         struct pci_sriov      *iov;
1399         u16                    num_vfs, i;
1400
1401         bus = pdev->bus;
1402         hose = pci_bus_to_host(bus);
1403         phb = hose->private_data;
1404         pdn = pci_get_pdn(pdev);
1405         iov = pdev->sriov;
1406         num_vfs = pdn->num_vfs;
1407
1408         /* Release VF PEs */
1409         pnv_ioda_release_vf_PE(pdev);
1410
1411         if (phb->type == PNV_PHB_IODA2) {
1412                 if (!pdn->m64_single_mode)
1413                         pnv_pci_vf_resource_shift(pdev, -*pdn->pe_num_map);
1414
1415                 /* Release M64 windows */
1416                 pnv_pci_vf_release_m64(pdev, num_vfs);
1417
1418                 /* Release PE numbers */
1419                 if (pdn->m64_single_mode) {
1420                         for (i = 0; i < num_vfs; i++) {
1421                                 if (pdn->pe_num_map[i] == IODA_INVALID_PE)
1422                                         continue;
1423
1424                                 pe = &phb->ioda.pe_array[pdn->pe_num_map[i]];
1425                                 pnv_ioda_free_pe(pe);
1426                         }
1427                 } else
1428                         bitmap_clear(phb->ioda.pe_alloc, *pdn->pe_num_map, num_vfs);
1429                 /* Releasing pe_num_map */
1430                 kfree(pdn->pe_num_map);
1431         }
1432 }
1433
1434 static void pnv_pci_ioda2_setup_dma_pe(struct pnv_phb *phb,
1435                                        struct pnv_ioda_pe *pe);
1436 static void pnv_ioda_setup_vf_PE(struct pci_dev *pdev, u16 num_vfs)
1437 {
1438         struct pci_bus        *bus;
1439         struct pci_controller *hose;
1440         struct pnv_phb        *phb;
1441         struct pnv_ioda_pe    *pe;
1442         int                    pe_num;
1443         u16                    vf_index;
1444         struct pci_dn         *pdn;
1445
1446         bus = pdev->bus;
1447         hose = pci_bus_to_host(bus);
1448         phb = hose->private_data;
1449         pdn = pci_get_pdn(pdev);
1450
1451         if (!pdev->is_physfn)
1452                 return;
1453
1454         /* Reserve PE for each VF */
1455         for (vf_index = 0; vf_index < num_vfs; vf_index++) {
1456                 if (pdn->m64_single_mode)
1457                         pe_num = pdn->pe_num_map[vf_index];
1458                 else
1459                         pe_num = *pdn->pe_num_map + vf_index;
1460
1461                 pe = &phb->ioda.pe_array[pe_num];
1462                 pe->pe_number = pe_num;
1463                 pe->phb = phb;
1464                 pe->flags = PNV_IODA_PE_VF;
1465                 pe->pbus = NULL;
1466                 pe->parent_dev = pdev;
1467                 pe->mve_number = -1;
1468                 pe->rid = (pci_iov_virtfn_bus(pdev, vf_index) << 8) |
1469                            pci_iov_virtfn_devfn(pdev, vf_index);
1470
1471                 pe_info(pe, "VF %04d:%02d:%02d.%d associated with PE#%d\n",
1472                         hose->global_number, pdev->bus->number,
1473                         PCI_SLOT(pci_iov_virtfn_devfn(pdev, vf_index)),
1474                         PCI_FUNC(pci_iov_virtfn_devfn(pdev, vf_index)), pe_num);
1475
1476                 if (pnv_ioda_configure_pe(phb, pe)) {
1477                         /* XXX What do we do here ? */
1478                         pnv_ioda_free_pe(pe);
1479                         pe->pdev = NULL;
1480                         continue;
1481                 }
1482
1483                 /* Put PE to the list */
1484                 mutex_lock(&phb->ioda.pe_list_mutex);
1485                 list_add_tail(&pe->list, &phb->ioda.pe_list);
1486                 mutex_unlock(&phb->ioda.pe_list_mutex);
1487
1488                 pnv_pci_ioda2_setup_dma_pe(phb, pe);
1489         }
1490 }
1491
1492 int pnv_pci_sriov_enable(struct pci_dev *pdev, u16 num_vfs)
1493 {
1494         struct pci_bus        *bus;
1495         struct pci_controller *hose;
1496         struct pnv_phb        *phb;
1497         struct pnv_ioda_pe    *pe;
1498         struct pci_dn         *pdn;
1499         int                    ret;
1500         u16                    i;
1501
1502         bus = pdev->bus;
1503         hose = pci_bus_to_host(bus);
1504         phb = hose->private_data;
1505         pdn = pci_get_pdn(pdev);
1506
1507         if (phb->type == PNV_PHB_IODA2) {
1508                 if (!pdn->vfs_expanded) {
1509                         dev_info(&pdev->dev, "don't support this SRIOV device"
1510                                 " with non 64bit-prefetchable IOV BAR\n");
1511                         return -ENOSPC;
1512                 }
1513
1514                 /*
1515                  * When M64 BARs functions in Single PE mode, the number of VFs
1516                  * could be enabled must be less than the number of M64 BARs.
1517                  */
1518                 if (pdn->m64_single_mode && num_vfs > phb->ioda.m64_bar_idx) {
1519                         dev_info(&pdev->dev, "Not enough M64 BAR for VFs\n");
1520                         return -EBUSY;
1521                 }
1522
1523                 /* Allocating pe_num_map */
1524                 if (pdn->m64_single_mode)
1525                         pdn->pe_num_map = kmalloc(sizeof(*pdn->pe_num_map) * num_vfs,
1526                                         GFP_KERNEL);
1527                 else
1528                         pdn->pe_num_map = kmalloc(sizeof(*pdn->pe_num_map), GFP_KERNEL);
1529
1530                 if (!pdn->pe_num_map)
1531                         return -ENOMEM;
1532
1533                 if (pdn->m64_single_mode)
1534                         for (i = 0; i < num_vfs; i++)
1535                                 pdn->pe_num_map[i] = IODA_INVALID_PE;
1536
1537                 /* Calculate available PE for required VFs */
1538                 if (pdn->m64_single_mode) {
1539                         for (i = 0; i < num_vfs; i++) {
1540                                 pe = pnv_ioda_alloc_pe(phb);
1541                                 if (!pe) {
1542                                         ret = -EBUSY;
1543                                         goto m64_failed;
1544                                 }
1545
1546                                 pdn->pe_num_map[i] = pe->pe_number;
1547                         }
1548                 } else {
1549                         mutex_lock(&phb->ioda.pe_alloc_mutex);
1550                         *pdn->pe_num_map = bitmap_find_next_zero_area(
1551                                 phb->ioda.pe_alloc, phb->ioda.total_pe_num,
1552                                 0, num_vfs, 0);
1553                         if (*pdn->pe_num_map >= phb->ioda.total_pe_num) {
1554                                 mutex_unlock(&phb->ioda.pe_alloc_mutex);
1555                                 dev_info(&pdev->dev, "Failed to enable VF%d\n", num_vfs);
1556                                 kfree(pdn->pe_num_map);
1557                                 return -EBUSY;
1558                         }
1559                         bitmap_set(phb->ioda.pe_alloc, *pdn->pe_num_map, num_vfs);
1560                         mutex_unlock(&phb->ioda.pe_alloc_mutex);
1561                 }
1562                 pdn->num_vfs = num_vfs;
1563
1564                 /* Assign M64 window accordingly */
1565                 ret = pnv_pci_vf_assign_m64(pdev, num_vfs);
1566                 if (ret) {
1567                         dev_info(&pdev->dev, "Not enough M64 window resources\n");
1568                         goto m64_failed;
1569                 }
1570
1571                 /*
1572                  * When using one M64 BAR to map one IOV BAR, we need to shift
1573                  * the IOV BAR according to the PE# allocated to the VFs.
1574                  * Otherwise, the PE# for the VF will conflict with others.
1575                  */
1576                 if (!pdn->m64_single_mode) {
1577                         ret = pnv_pci_vf_resource_shift(pdev, *pdn->pe_num_map);
1578                         if (ret)
1579                                 goto m64_failed;
1580                 }
1581         }
1582
1583         /* Setup VF PEs */
1584         pnv_ioda_setup_vf_PE(pdev, num_vfs);
1585
1586         return 0;
1587
1588 m64_failed:
1589         if (pdn->m64_single_mode) {
1590                 for (i = 0; i < num_vfs; i++) {
1591                         if (pdn->pe_num_map[i] == IODA_INVALID_PE)
1592                                 continue;
1593
1594                         pe = &phb->ioda.pe_array[pdn->pe_num_map[i]];
1595                         pnv_ioda_free_pe(pe);
1596                 }
1597         } else
1598                 bitmap_clear(phb->ioda.pe_alloc, *pdn->pe_num_map, num_vfs);
1599
1600         /* Releasing pe_num_map */
1601         kfree(pdn->pe_num_map);
1602
1603         return ret;
1604 }
1605
1606 int pcibios_sriov_disable(struct pci_dev *pdev)
1607 {
1608         pnv_pci_sriov_disable(pdev);
1609
1610         /* Release PCI data */
1611         remove_dev_pci_data(pdev);
1612         return 0;
1613 }
1614
1615 int pcibios_sriov_enable(struct pci_dev *pdev, u16 num_vfs)
1616 {
1617         /* Allocate PCI data */
1618         add_dev_pci_data(pdev);
1619
1620         return pnv_pci_sriov_enable(pdev, num_vfs);
1621 }
1622 #endif /* CONFIG_PCI_IOV */
1623
1624 static void pnv_pci_ioda_dma_dev_setup(struct pnv_phb *phb, struct pci_dev *pdev)
1625 {
1626         struct pci_dn *pdn = pci_get_pdn(pdev);
1627         struct pnv_ioda_pe *pe;
1628
1629         /*
1630          * The function can be called while the PE#
1631          * hasn't been assigned. Do nothing for the
1632          * case.
1633          */
1634         if (!pdn || pdn->pe_number == IODA_INVALID_PE)
1635                 return;
1636
1637         pe = &phb->ioda.pe_array[pdn->pe_number];
1638         WARN_ON(get_dma_ops(&pdev->dev) != &dma_iommu_ops);
1639         set_dma_offset(&pdev->dev, pe->tce_bypass_base);
1640         set_iommu_table_base(&pdev->dev, pe->table_group.tables[0]);
1641         /*
1642          * Note: iommu_add_device() will fail here as
1643          * for physical PE: the device is already added by now;
1644          * for virtual PE: sysfs entries are not ready yet and
1645          * tce_iommu_bus_notifier will add the device to a group later.
1646          */
1647 }
1648
1649 static int pnv_pci_ioda_dma_set_mask(struct pci_dev *pdev, u64 dma_mask)
1650 {
1651         struct pci_controller *hose = pci_bus_to_host(pdev->bus);
1652         struct pnv_phb *phb = hose->private_data;
1653         struct pci_dn *pdn = pci_get_pdn(pdev);
1654         struct pnv_ioda_pe *pe;
1655         uint64_t top;
1656         bool bypass = false;
1657
1658         if (WARN_ON(!pdn || pdn->pe_number == IODA_INVALID_PE))
1659                 return -ENODEV;;
1660
1661         pe = &phb->ioda.pe_array[pdn->pe_number];
1662         if (pe->tce_bypass_enabled) {
1663                 top = pe->tce_bypass_base + memblock_end_of_DRAM() - 1;
1664                 bypass = (dma_mask >= top);
1665         }
1666
1667         if (bypass) {
1668                 dev_info(&pdev->dev, "Using 64-bit DMA iommu bypass\n");
1669                 set_dma_ops(&pdev->dev, &dma_direct_ops);
1670         } else {
1671                 dev_info(&pdev->dev, "Using 32-bit DMA via iommu\n");
1672                 set_dma_ops(&pdev->dev, &dma_iommu_ops);
1673         }
1674         *pdev->dev.dma_mask = dma_mask;
1675
1676         /* Update peer npu devices */
1677         pnv_npu_try_dma_set_bypass(pdev, bypass);
1678
1679         return 0;
1680 }
1681
1682 static u64 pnv_pci_ioda_dma_get_required_mask(struct pci_dev *pdev)
1683 {
1684         struct pci_controller *hose = pci_bus_to_host(pdev->bus);
1685         struct pnv_phb *phb = hose->private_data;
1686         struct pci_dn *pdn = pci_get_pdn(pdev);
1687         struct pnv_ioda_pe *pe;
1688         u64 end, mask;
1689
1690         if (WARN_ON(!pdn || pdn->pe_number == IODA_INVALID_PE))
1691                 return 0;
1692
1693         pe = &phb->ioda.pe_array[pdn->pe_number];
1694         if (!pe->tce_bypass_enabled)
1695                 return __dma_get_required_mask(&pdev->dev);
1696
1697
1698         end = pe->tce_bypass_base + memblock_end_of_DRAM();
1699         mask = 1ULL << (fls64(end) - 1);
1700         mask += mask - 1;
1701
1702         return mask;
1703 }
1704
1705 static void pnv_ioda_setup_bus_dma(struct pnv_ioda_pe *pe,
1706                                    struct pci_bus *bus)
1707 {
1708         struct pci_dev *dev;
1709
1710         list_for_each_entry(dev, &bus->devices, bus_list) {
1711                 set_iommu_table_base(&dev->dev, pe->table_group.tables[0]);
1712                 set_dma_offset(&dev->dev, pe->tce_bypass_base);
1713                 iommu_add_device(&dev->dev);
1714
1715                 if ((pe->flags & PNV_IODA_PE_BUS_ALL) && dev->subordinate)
1716                         pnv_ioda_setup_bus_dma(pe, dev->subordinate);
1717         }
1718 }
1719
1720 static void pnv_pci_ioda1_tce_invalidate(struct iommu_table *tbl,
1721                 unsigned long index, unsigned long npages, bool rm)
1722 {
1723         struct iommu_table_group_link *tgl = list_first_entry_or_null(
1724                         &tbl->it_group_list, struct iommu_table_group_link,
1725                         next);
1726         struct pnv_ioda_pe *pe = container_of(tgl->table_group,
1727                         struct pnv_ioda_pe, table_group);
1728         __be64 __iomem *invalidate = rm ?
1729                 (__be64 __iomem *)pe->phb->ioda.tce_inval_reg_phys :
1730                 pe->phb->ioda.tce_inval_reg;
1731         unsigned long start, end, inc;
1732         const unsigned shift = tbl->it_page_shift;
1733
1734         start = __pa(((__be64 *)tbl->it_base) + index - tbl->it_offset);
1735         end = __pa(((__be64 *)tbl->it_base) + index - tbl->it_offset +
1736                         npages - 1);
1737
1738         /* BML uses this case for p6/p7/galaxy2: Shift addr and put in node */
1739         if (tbl->it_busno) {
1740                 start <<= shift;
1741                 end <<= shift;
1742                 inc = 128ull << shift;
1743                 start |= tbl->it_busno;
1744                 end |= tbl->it_busno;
1745         } else if (tbl->it_type & TCE_PCI_SWINV_PAIR) {
1746                 /* p7ioc-style invalidation, 2 TCEs per write */
1747                 start |= (1ull << 63);
1748                 end |= (1ull << 63);
1749                 inc = 16;
1750         } else {
1751                 /* Default (older HW) */
1752                 inc = 128;
1753         }
1754
1755         end |= inc - 1; /* round up end to be different than start */
1756
1757         mb(); /* Ensure above stores are visible */
1758         while (start <= end) {
1759                 if (rm)
1760                         __raw_rm_writeq(cpu_to_be64(start), invalidate);
1761                 else
1762                         __raw_writeq(cpu_to_be64(start), invalidate);
1763                 start += inc;
1764         }
1765
1766         /*
1767          * The iommu layer will do another mb() for us on build()
1768          * and we don't care on free()
1769          */
1770 }
1771
1772 static int pnv_ioda1_tce_build(struct iommu_table *tbl, long index,
1773                 long npages, unsigned long uaddr,
1774                 enum dma_data_direction direction,
1775                 struct dma_attrs *attrs)
1776 {
1777         int ret = pnv_tce_build(tbl, index, npages, uaddr, direction,
1778                         attrs);
1779
1780         if (!ret && (tbl->it_type & TCE_PCI_SWINV_CREATE))
1781                 pnv_pci_ioda1_tce_invalidate(tbl, index, npages, false);
1782
1783         return ret;
1784 }
1785
1786 #ifdef CONFIG_IOMMU_API
1787 static int pnv_ioda1_tce_xchg(struct iommu_table *tbl, long index,
1788                 unsigned long *hpa, enum dma_data_direction *direction)
1789 {
1790         long ret = pnv_tce_xchg(tbl, index, hpa, direction);
1791
1792         if (!ret && (tbl->it_type &
1793                         (TCE_PCI_SWINV_CREATE | TCE_PCI_SWINV_FREE)))
1794                 pnv_pci_ioda1_tce_invalidate(tbl, index, 1, false);
1795
1796         return ret;
1797 }
1798 #endif
1799
1800 static void pnv_ioda1_tce_free(struct iommu_table *tbl, long index,
1801                 long npages)
1802 {
1803         pnv_tce_free(tbl, index, npages);
1804
1805         if (tbl->it_type & TCE_PCI_SWINV_FREE)
1806                 pnv_pci_ioda1_tce_invalidate(tbl, index, npages, false);
1807 }
1808
1809 static struct iommu_table_ops pnv_ioda1_iommu_ops = {
1810         .set = pnv_ioda1_tce_build,
1811 #ifdef CONFIG_IOMMU_API
1812         .exchange = pnv_ioda1_tce_xchg,
1813 #endif
1814         .clear = pnv_ioda1_tce_free,
1815         .get = pnv_tce_get,
1816 };
1817
1818 #define TCE_KILL_INVAL_ALL  PPC_BIT(0)
1819 #define TCE_KILL_INVAL_PE   PPC_BIT(1)
1820 #define TCE_KILL_INVAL_TCE  PPC_BIT(2)
1821
1822 void pnv_pci_ioda2_tce_invalidate_entire(struct pnv_phb *phb, bool rm)
1823 {
1824         const unsigned long val = TCE_KILL_INVAL_ALL;
1825
1826         mb(); /* Ensure previous TCE table stores are visible */
1827         if (rm)
1828                 __raw_rm_writeq(cpu_to_be64(val),
1829                                 (__be64 __iomem *)
1830                                 phb->ioda.tce_inval_reg_phys);
1831         else
1832                 __raw_writeq(cpu_to_be64(val), phb->ioda.tce_inval_reg);
1833 }
1834
1835 static inline void pnv_pci_ioda2_tce_invalidate_pe(struct pnv_ioda_pe *pe)
1836 {
1837         /* 01xb - invalidate TCEs that match the specified PE# */
1838         unsigned long val = TCE_KILL_INVAL_PE | (pe->pe_number & 0xFF);
1839         struct pnv_phb *phb = pe->phb;
1840
1841         if (!phb->ioda.tce_inval_reg)
1842                 return;
1843
1844         mb(); /* Ensure above stores are visible */
1845         __raw_writeq(cpu_to_be64(val), phb->ioda.tce_inval_reg);
1846 }
1847
1848 static void pnv_pci_ioda2_do_tce_invalidate(unsigned pe_number, bool rm,
1849                 __be64 __iomem *invalidate, unsigned shift,
1850                 unsigned long index, unsigned long npages)
1851 {
1852         unsigned long start, end, inc;
1853
1854         /* We'll invalidate DMA address in PE scope */
1855         start = TCE_KILL_INVAL_TCE;
1856         start |= (pe_number & 0xFF);
1857         end = start;
1858
1859         /* Figure out the start, end and step */
1860         start |= (index << shift);
1861         end |= ((index + npages - 1) << shift);
1862         inc = (0x1ull << shift);
1863         mb();
1864
1865         while (start <= end) {
1866                 if (rm)
1867                         __raw_rm_writeq(cpu_to_be64(start), invalidate);
1868                 else
1869                         __raw_writeq(cpu_to_be64(start), invalidate);
1870                 start += inc;
1871         }
1872 }
1873
1874 static void pnv_pci_ioda2_tce_invalidate(struct iommu_table *tbl,
1875                 unsigned long index, unsigned long npages, bool rm)
1876 {
1877         struct iommu_table_group_link *tgl;
1878
1879         list_for_each_entry_rcu(tgl, &tbl->it_group_list, next) {
1880                 struct pnv_ioda_pe *pe = container_of(tgl->table_group,
1881                                 struct pnv_ioda_pe, table_group);
1882                 __be64 __iomem *invalidate = rm ?
1883                         (__be64 __iomem *)pe->phb->ioda.tce_inval_reg_phys :
1884                         pe->phb->ioda.tce_inval_reg;
1885
1886                 if (pe->phb->type == PNV_PHB_NPU) {
1887                         /*
1888                          * The NVLink hardware does not support TCE kill
1889                          * per TCE entry so we have to invalidate
1890                          * the entire cache for it.
1891                          */
1892                         pnv_pci_ioda2_tce_invalidate_entire(pe->phb, rm);
1893                         continue;
1894                 }
1895                 pnv_pci_ioda2_do_tce_invalidate(pe->pe_number, rm,
1896                         invalidate, tbl->it_page_shift,
1897                         index, npages);
1898         }
1899 }
1900
1901 static int pnv_ioda2_tce_build(struct iommu_table *tbl, long index,
1902                 long npages, unsigned long uaddr,
1903                 enum dma_data_direction direction,
1904                 struct dma_attrs *attrs)
1905 {
1906         int ret = pnv_tce_build(tbl, index, npages, uaddr, direction,
1907                         attrs);
1908
1909         if (!ret && (tbl->it_type & TCE_PCI_SWINV_CREATE))
1910                 pnv_pci_ioda2_tce_invalidate(tbl, index, npages, false);
1911
1912         return ret;
1913 }
1914
1915 #ifdef CONFIG_IOMMU_API
1916 static int pnv_ioda2_tce_xchg(struct iommu_table *tbl, long index,
1917                 unsigned long *hpa, enum dma_data_direction *direction)
1918 {
1919         long ret = pnv_tce_xchg(tbl, index, hpa, direction);
1920
1921         if (!ret && (tbl->it_type &
1922                         (TCE_PCI_SWINV_CREATE | TCE_PCI_SWINV_FREE)))
1923                 pnv_pci_ioda2_tce_invalidate(tbl, index, 1, false);
1924
1925         return ret;
1926 }
1927 #endif
1928
1929 static void pnv_ioda2_tce_free(struct iommu_table *tbl, long index,
1930                 long npages)
1931 {
1932         pnv_tce_free(tbl, index, npages);
1933
1934         if (tbl->it_type & TCE_PCI_SWINV_FREE)
1935                 pnv_pci_ioda2_tce_invalidate(tbl, index, npages, false);
1936 }
1937
1938 static void pnv_ioda2_table_free(struct iommu_table *tbl)
1939 {
1940         pnv_pci_ioda2_table_free_pages(tbl);
1941         iommu_free_table(tbl, "pnv");
1942 }
1943
1944 static struct iommu_table_ops pnv_ioda2_iommu_ops = {
1945         .set = pnv_ioda2_tce_build,
1946 #ifdef CONFIG_IOMMU_API
1947         .exchange = pnv_ioda2_tce_xchg,
1948 #endif
1949         .clear = pnv_ioda2_tce_free,
1950         .get = pnv_tce_get,
1951         .free = pnv_ioda2_table_free,
1952 };
1953
1954 static int pnv_pci_ioda_dev_dma_weight(struct pci_dev *dev, void *data)
1955 {
1956         unsigned int *weight = (unsigned int *)data;
1957
1958         /* This is quite simplistic. The "base" weight of a device
1959          * is 10. 0 means no DMA is to be accounted for it.
1960          */
1961         if (dev->hdr_type != PCI_HEADER_TYPE_NORMAL)
1962                 return 0;
1963
1964         if (dev->class == PCI_CLASS_SERIAL_USB_UHCI ||
1965             dev->class == PCI_CLASS_SERIAL_USB_OHCI ||
1966             dev->class == PCI_CLASS_SERIAL_USB_EHCI)
1967                 *weight += 3;
1968         else if ((dev->class >> 8) == PCI_CLASS_STORAGE_RAID)
1969                 *weight += 15;
1970         else
1971                 *weight += 10;
1972
1973         return 0;
1974 }
1975
1976 static unsigned int pnv_pci_ioda_pe_dma_weight(struct pnv_ioda_pe *pe)
1977 {
1978         unsigned int weight = 0;
1979
1980         /* SRIOV VF has same DMA32 weight as its PF */
1981 #ifdef CONFIG_PCI_IOV
1982         if ((pe->flags & PNV_IODA_PE_VF) && pe->parent_dev) {
1983                 pnv_pci_ioda_dev_dma_weight(pe->parent_dev, &weight);
1984                 return weight;
1985         }
1986 #endif
1987
1988         if ((pe->flags & PNV_IODA_PE_DEV) && pe->pdev) {
1989                 pnv_pci_ioda_dev_dma_weight(pe->pdev, &weight);
1990         } else if ((pe->flags & PNV_IODA_PE_BUS) && pe->pbus) {
1991                 struct pci_dev *pdev;
1992
1993                 list_for_each_entry(pdev, &pe->pbus->devices, bus_list)
1994                         pnv_pci_ioda_dev_dma_weight(pdev, &weight);
1995         } else if ((pe->flags & PNV_IODA_PE_BUS_ALL) && pe->pbus) {
1996                 pci_walk_bus(pe->pbus, pnv_pci_ioda_dev_dma_weight, &weight);
1997         }
1998
1999         return weight;
2000 }
2001
2002 static void pnv_pci_ioda1_setup_dma_pe(struct pnv_phb *phb,
2003                                        struct pnv_ioda_pe *pe)
2004 {
2005
2006         struct page *tce_mem = NULL;
2007         struct iommu_table *tbl;
2008         unsigned int weight, total_weight = 0;
2009         unsigned int tce32_segsz, base, segs, avail, i;
2010         int64_t rc;
2011         void *addr;
2012
2013         /* XXX FIXME: Handle 64-bit only DMA devices */
2014         /* XXX FIXME: Provide 64-bit DMA facilities & non-4K TCE tables etc.. */
2015         /* XXX FIXME: Allocate multi-level tables on PHB3 */
2016         weight = pnv_pci_ioda_pe_dma_weight(pe);
2017         if (!weight)
2018                 return;
2019
2020         pci_walk_bus(phb->hose->bus, pnv_pci_ioda_dev_dma_weight,
2021                      &total_weight);
2022         segs = (weight * phb->ioda.dma32_count) / total_weight;
2023         if (!segs)
2024                 segs = 1;
2025
2026         /*
2027          * Allocate contiguous DMA32 segments. We begin with the expected
2028          * number of segments. With one more attempt, the number of DMA32
2029          * segments to be allocated is decreased by one until one segment
2030          * is allocated successfully.
2031          */
2032         do {
2033                 for (base = 0; base <= phb->ioda.dma32_count - segs; base++) {
2034                         for (avail = 0, i = base; i < base + segs; i++) {
2035                                 if (phb->ioda.dma32_segmap[i] ==
2036                                     IODA_INVALID_PE)
2037                                         avail++;
2038                         }
2039
2040                         if (avail == segs)
2041                                 goto found;
2042                 }
2043         } while (--segs);
2044
2045         if (!segs) {
2046                 pe_warn(pe, "No available DMA32 segments\n");
2047                 return;
2048         }
2049
2050 found:
2051         tbl = pnv_pci_table_alloc(phb->hose->node);
2052         iommu_register_group(&pe->table_group, phb->hose->global_number,
2053                         pe->pe_number);
2054         pnv_pci_link_table_and_group(phb->hose->node, 0, tbl, &pe->table_group);
2055
2056         /* Grab a 32-bit TCE table */
2057         pe_info(pe, "DMA weight %d (%d), assigned (%d) %d DMA32 segments\n",
2058                 weight, total_weight, base, segs);
2059         pe_info(pe, " Setting up 32-bit TCE table at %08x..%08x\n",
2060                 base * PNV_IODA1_DMA32_SEGSIZE,
2061                 (base + segs) * PNV_IODA1_DMA32_SEGSIZE - 1);
2062
2063         /* XXX Currently, we allocate one big contiguous table for the
2064          * TCEs. We only really need one chunk per 256M of TCE space
2065          * (ie per segment) but that's an optimization for later, it
2066          * requires some added smarts with our get/put_tce implementation
2067          *
2068          * Each TCE page is 4KB in size and each TCE entry occupies 8
2069          * bytes
2070          */
2071         tce32_segsz = PNV_IODA1_DMA32_SEGSIZE >> (IOMMU_PAGE_SHIFT_4K - 3);
2072         tce_mem = alloc_pages_node(phb->hose->node, GFP_KERNEL,
2073                                    get_order(tce32_segsz * segs));
2074         if (!tce_mem) {
2075                 pe_err(pe, " Failed to allocate a 32-bit TCE memory\n");
2076                 goto fail;
2077         }
2078         addr = page_address(tce_mem);
2079         memset(addr, 0, tce32_segsz * segs);
2080
2081         /* Configure HW */
2082         for (i = 0; i < segs; i++) {
2083                 rc = opal_pci_map_pe_dma_window(phb->opal_id,
2084                                               pe->pe_number,
2085                                               base + i, 1,
2086                                               __pa(addr) + tce32_segsz * i,
2087                                               tce32_segsz, IOMMU_PAGE_SIZE_4K);
2088                 if (rc) {
2089                         pe_err(pe, " Failed to configure 32-bit TCE table,"
2090                                " err %ld\n", rc);
2091                         goto fail;
2092                 }
2093         }
2094
2095         /* Setup DMA32 segment mapping */
2096         for (i = base; i < base + segs; i++)
2097                 phb->ioda.dma32_segmap[i] = pe->pe_number;
2098
2099         /* Setup linux iommu table */
2100         pnv_pci_setup_iommu_table(tbl, addr, tce32_segsz * segs,
2101                                   base * PNV_IODA1_DMA32_SEGSIZE,
2102                                   IOMMU_PAGE_SHIFT_4K);
2103
2104         /* OPAL variant of P7IOC SW invalidated TCEs */
2105         if (phb->ioda.tce_inval_reg)
2106                 tbl->it_type |= (TCE_PCI_SWINV_CREATE |
2107                                  TCE_PCI_SWINV_FREE   |
2108                                  TCE_PCI_SWINV_PAIR);
2109
2110         tbl->it_ops = &pnv_ioda1_iommu_ops;
2111         pe->table_group.tce32_start = tbl->it_offset << tbl->it_page_shift;
2112         pe->table_group.tce32_size = tbl->it_size << tbl->it_page_shift;
2113         iommu_init_table(tbl, phb->hose->node);
2114
2115         if (pe->flags & PNV_IODA_PE_DEV) {
2116                 /*
2117                  * Setting table base here only for carrying iommu_group
2118                  * further down to let iommu_add_device() do the job.
2119                  * pnv_pci_ioda_dma_dev_setup will override it later anyway.
2120                  */
2121                 set_iommu_table_base(&pe->pdev->dev, tbl);
2122                 iommu_add_device(&pe->pdev->dev);
2123         } else if (pe->flags & (PNV_IODA_PE_BUS | PNV_IODA_PE_BUS_ALL))
2124                 pnv_ioda_setup_bus_dma(pe, pe->pbus);
2125
2126         return;
2127  fail:
2128         /* XXX Failure: Try to fallback to 64-bit only ? */
2129         if (tce_mem)
2130                 __free_pages(tce_mem, get_order(tce32_segsz * segs));
2131         if (tbl) {
2132                 pnv_pci_unlink_table_and_group(tbl, &pe->table_group);
2133                 iommu_free_table(tbl, "pnv");
2134         }
2135 }
2136
2137 static long pnv_pci_ioda2_set_window(struct iommu_table_group *table_group,
2138                 int num, struct iommu_table *tbl)
2139 {
2140         struct pnv_ioda_pe *pe = container_of(table_group, struct pnv_ioda_pe,
2141                         table_group);
2142         struct pnv_phb *phb = pe->phb;
2143         int64_t rc;
2144         const unsigned long size = tbl->it_indirect_levels ?
2145                         tbl->it_level_size : tbl->it_size;
2146         const __u64 start_addr = tbl->it_offset << tbl->it_page_shift;
2147         const __u64 win_size = tbl->it_size << tbl->it_page_shift;
2148
2149         pe_info(pe, "Setting up window#%d %llx..%llx pg=%x\n", num,
2150                         start_addr, start_addr + win_size - 1,
2151                         IOMMU_PAGE_SIZE(tbl));
2152
2153         /*
2154          * Map TCE table through TVT. The TVE index is the PE number
2155          * shifted by 1 bit for 32-bits DMA space.
2156          */
2157         rc = opal_pci_map_pe_dma_window(phb->opal_id,
2158                         pe->pe_number,
2159                         (pe->pe_number << 1) + num,
2160                         tbl->it_indirect_levels + 1,
2161                         __pa(tbl->it_base),
2162                         size << 3,
2163                         IOMMU_PAGE_SIZE(tbl));
2164         if (rc) {
2165                 pe_err(pe, "Failed to configure TCE table, err %ld\n", rc);
2166                 return rc;
2167         }
2168
2169         pnv_pci_link_table_and_group(phb->hose->node, num,
2170                         tbl, &pe->table_group);
2171         pnv_pci_ioda2_tce_invalidate_pe(pe);
2172
2173         return 0;
2174 }
2175
2176 static void pnv_pci_ioda2_set_bypass(struct pnv_ioda_pe *pe, bool enable)
2177 {
2178         uint16_t window_id = (pe->pe_number << 1 ) + 1;
2179         int64_t rc;
2180
2181         pe_info(pe, "%sabling 64-bit DMA bypass\n", enable ? "En" : "Dis");
2182         if (enable) {
2183                 phys_addr_t top = memblock_end_of_DRAM();
2184
2185                 top = roundup_pow_of_two(top);
2186                 rc = opal_pci_map_pe_dma_window_real(pe->phb->opal_id,
2187                                                      pe->pe_number,
2188                                                      window_id,
2189                                                      pe->tce_bypass_base,
2190                                                      top);
2191         } else {
2192                 rc = opal_pci_map_pe_dma_window_real(pe->phb->opal_id,
2193                                                      pe->pe_number,
2194                                                      window_id,
2195                                                      pe->tce_bypass_base,
2196                                                      0);
2197         }
2198         if (rc)
2199                 pe_err(pe, "OPAL error %lld configuring bypass window\n", rc);
2200         else
2201                 pe->tce_bypass_enabled = enable;
2202 }
2203
2204 static long pnv_pci_ioda2_table_alloc_pages(int nid, __u64 bus_offset,
2205                 __u32 page_shift, __u64 window_size, __u32 levels,
2206                 struct iommu_table *tbl);
2207
2208 static long pnv_pci_ioda2_create_table(struct iommu_table_group *table_group,
2209                 int num, __u32 page_shift, __u64 window_size, __u32 levels,
2210                 struct iommu_table **ptbl)
2211 {
2212         struct pnv_ioda_pe *pe = container_of(table_group, struct pnv_ioda_pe,
2213                         table_group);
2214         int nid = pe->phb->hose->node;
2215         __u64 bus_offset = num ? pe->tce_bypass_base : table_group->tce32_start;
2216         long ret;
2217         struct iommu_table *tbl;
2218
2219         tbl = pnv_pci_table_alloc(nid);
2220         if (!tbl)
2221                 return -ENOMEM;
2222
2223         ret = pnv_pci_ioda2_table_alloc_pages(nid,
2224                         bus_offset, page_shift, window_size,
2225                         levels, tbl);
2226         if (ret) {
2227                 iommu_free_table(tbl, "pnv");
2228                 return ret;
2229         }
2230
2231         tbl->it_ops = &pnv_ioda2_iommu_ops;
2232         if (pe->phb->ioda.tce_inval_reg)
2233                 tbl->it_type |= (TCE_PCI_SWINV_CREATE | TCE_PCI_SWINV_FREE);
2234
2235         *ptbl = tbl;
2236
2237         return 0;
2238 }
2239
2240 static long pnv_pci_ioda2_setup_default_config(struct pnv_ioda_pe *pe)
2241 {
2242         struct iommu_table *tbl = NULL;
2243         long rc;
2244
2245         /*
2246          * crashkernel= specifies the kdump kernel's maximum memory at
2247          * some offset and there is no guaranteed the result is a power
2248          * of 2, which will cause errors later.
2249          */
2250         const u64 max_memory = __rounddown_pow_of_two(memory_hotplug_max());
2251
2252         /*
2253          * In memory constrained environments, e.g. kdump kernel, the
2254          * DMA window can be larger than available memory, which will
2255          * cause errors later.
2256          */
2257         const u64 window_size = min((u64)pe->table_group.tce32_size, max_memory);
2258
2259         rc = pnv_pci_ioda2_create_table(&pe->table_group, 0,
2260                         IOMMU_PAGE_SHIFT_4K,
2261                         window_size,
2262                         POWERNV_IOMMU_DEFAULT_LEVELS, &tbl);
2263         if (rc) {
2264                 pe_err(pe, "Failed to create 32-bit TCE table, err %ld",
2265                                 rc);
2266                 return rc;
2267         }
2268
2269         iommu_init_table(tbl, pe->phb->hose->node);
2270
2271         rc = pnv_pci_ioda2_set_window(&pe->table_group, 0, tbl);
2272         if (rc) {
2273                 pe_err(pe, "Failed to configure 32-bit TCE table, err %ld\n",
2274                                 rc);
2275                 pnv_ioda2_table_free(tbl);
2276                 return rc;
2277         }
2278
2279         if (!pnv_iommu_bypass_disabled)
2280                 pnv_pci_ioda2_set_bypass(pe, true);
2281
2282         /* OPAL variant of PHB3 invalidated TCEs */
2283         if (pe->phb->ioda.tce_inval_reg)
2284                 tbl->it_type |= (TCE_PCI_SWINV_CREATE | TCE_PCI_SWINV_FREE);
2285
2286         /*
2287          * Setting table base here only for carrying iommu_group
2288          * further down to let iommu_add_device() do the job.
2289          * pnv_pci_ioda_dma_dev_setup will override it later anyway.
2290          */
2291         if (pe->flags & PNV_IODA_PE_DEV)
2292                 set_iommu_table_base(&pe->pdev->dev, tbl);
2293
2294         return 0;
2295 }
2296
2297 #if defined(CONFIG_IOMMU_API) || defined(CONFIG_PCI_IOV)
2298 static long pnv_pci_ioda2_unset_window(struct iommu_table_group *table_group,
2299                 int num)
2300 {
2301         struct pnv_ioda_pe *pe = container_of(table_group, struct pnv_ioda_pe,
2302                         table_group);
2303         struct pnv_phb *phb = pe->phb;
2304         long ret;
2305
2306         pe_info(pe, "Removing DMA window #%d\n", num);
2307
2308         ret = opal_pci_map_pe_dma_window(phb->opal_id, pe->pe_number,
2309                         (pe->pe_number << 1) + num,
2310                         0/* levels */, 0/* table address */,
2311                         0/* table size */, 0/* page size */);
2312         if (ret)
2313                 pe_warn(pe, "Unmapping failed, ret = %ld\n", ret);
2314         else
2315                 pnv_pci_ioda2_tce_invalidate_pe(pe);
2316
2317         pnv_pci_unlink_table_and_group(table_group->tables[num], table_group);
2318
2319         return ret;
2320 }
2321 #endif
2322
2323 #ifdef CONFIG_IOMMU_API
2324 static unsigned long pnv_pci_ioda2_get_table_size(__u32 page_shift,
2325                 __u64 window_size, __u32 levels)
2326 {
2327         unsigned long bytes = 0;
2328         const unsigned window_shift = ilog2(window_size);
2329         unsigned entries_shift = window_shift - page_shift;
2330         unsigned table_shift = entries_shift + 3;
2331         unsigned long tce_table_size = max(0x1000UL, 1UL << table_shift);
2332         unsigned long direct_table_size;
2333
2334         if (!levels || (levels > POWERNV_IOMMU_MAX_LEVELS) ||
2335                         (window_size > memory_hotplug_max()) ||
2336                         !is_power_of_2(window_size))
2337                 return 0;
2338
2339         /* Calculate a direct table size from window_size and levels */
2340         entries_shift = (entries_shift + levels - 1) / levels;
2341         table_shift = entries_shift + 3;
2342         table_shift = max_t(unsigned, table_shift, PAGE_SHIFT);
2343         direct_table_size =  1UL << table_shift;
2344
2345         for ( ; levels; --levels) {
2346                 bytes += _ALIGN_UP(tce_table_size, direct_table_size);
2347
2348                 tce_table_size /= direct_table_size;
2349                 tce_table_size <<= 3;
2350                 tce_table_size = _ALIGN_UP(tce_table_size, direct_table_size);
2351         }
2352
2353         return bytes;
2354 }
2355
2356 static void pnv_ioda2_take_ownership(struct iommu_table_group *table_group)
2357 {
2358         struct pnv_ioda_pe *pe = container_of(table_group, struct pnv_ioda_pe,
2359                                                 table_group);
2360         /* Store @tbl as pnv_pci_ioda2_unset_window() resets it */
2361         struct iommu_table *tbl = pe->table_group.tables[0];
2362
2363         pnv_pci_ioda2_set_bypass(pe, false);
2364         pnv_pci_ioda2_unset_window(&pe->table_group, 0);
2365         pnv_ioda2_table_free(tbl);
2366 }
2367
2368 static void pnv_ioda2_release_ownership(struct iommu_table_group *table_group)
2369 {
2370         struct pnv_ioda_pe *pe = container_of(table_group, struct pnv_ioda_pe,
2371                                                 table_group);
2372
2373         pnv_pci_ioda2_setup_default_config(pe);
2374 }
2375
2376 static struct iommu_table_group_ops pnv_pci_ioda2_ops = {
2377         .get_table_size = pnv_pci_ioda2_get_table_size,
2378         .create_table = pnv_pci_ioda2_create_table,
2379         .set_window = pnv_pci_ioda2_set_window,
2380         .unset_window = pnv_pci_ioda2_unset_window,
2381         .take_ownership = pnv_ioda2_take_ownership,
2382         .release_ownership = pnv_ioda2_release_ownership,
2383 };
2384
2385 static int gpe_table_group_to_npe_cb(struct device *dev, void *opaque)
2386 {
2387         struct pci_controller *hose;
2388         struct pnv_phb *phb;
2389         struct pnv_ioda_pe **ptmppe = opaque;
2390         struct pci_dev *pdev = container_of(dev, struct pci_dev, dev);
2391         struct pci_dn *pdn = pci_get_pdn(pdev);
2392
2393         if (!pdn || pdn->pe_number == IODA_INVALID_PE)
2394                 return 0;
2395
2396         hose = pci_bus_to_host(pdev->bus);
2397         phb = hose->private_data;
2398         if (phb->type != PNV_PHB_NPU)
2399                 return 0;
2400
2401         *ptmppe = &phb->ioda.pe_array[pdn->pe_number];
2402
2403         return 1;
2404 }
2405
2406 /*
2407  * This returns PE of associated NPU.
2408  * This assumes that NPU is in the same IOMMU group with GPU and there is
2409  * no other PEs.
2410  */
2411 static struct pnv_ioda_pe *gpe_table_group_to_npe(
2412                 struct iommu_table_group *table_group)
2413 {
2414         struct pnv_ioda_pe *npe = NULL;
2415         int ret = iommu_group_for_each_dev(table_group->group, &npe,
2416                         gpe_table_group_to_npe_cb);
2417
2418         BUG_ON(!ret || !npe);
2419
2420         return npe;
2421 }
2422
2423 static long pnv_pci_ioda2_npu_set_window(struct iommu_table_group *table_group,
2424                 int num, struct iommu_table *tbl)
2425 {
2426         long ret = pnv_pci_ioda2_set_window(table_group, num, tbl);
2427
2428         if (ret)
2429                 return ret;
2430
2431         ret = pnv_npu_set_window(gpe_table_group_to_npe(table_group), num, tbl);
2432         if (ret)
2433                 pnv_pci_ioda2_unset_window(table_group, num);
2434
2435         return ret;
2436 }
2437
2438 static long pnv_pci_ioda2_npu_unset_window(
2439                 struct iommu_table_group *table_group,
2440                 int num)
2441 {
2442         long ret = pnv_pci_ioda2_unset_window(table_group, num);
2443
2444         if (ret)
2445                 return ret;
2446
2447         return pnv_npu_unset_window(gpe_table_group_to_npe(table_group), num);
2448 }
2449
2450 static void pnv_ioda2_npu_take_ownership(struct iommu_table_group *table_group)
2451 {
2452         /*
2453          * Detach NPU first as pnv_ioda2_take_ownership() will destroy
2454          * the iommu_table if 32bit DMA is enabled.
2455          */
2456         pnv_npu_take_ownership(gpe_table_group_to_npe(table_group));
2457         pnv_ioda2_take_ownership(table_group);
2458 }
2459
2460 static struct iommu_table_group_ops pnv_pci_ioda2_npu_ops = {
2461         .get_table_size = pnv_pci_ioda2_get_table_size,
2462         .create_table = pnv_pci_ioda2_create_table,
2463         .set_window = pnv_pci_ioda2_npu_set_window,
2464         .unset_window = pnv_pci_ioda2_npu_unset_window,
2465         .take_ownership = pnv_ioda2_npu_take_ownership,
2466         .release_ownership = pnv_ioda2_release_ownership,
2467 };
2468
2469 static void pnv_pci_ioda_setup_iommu_api(void)
2470 {
2471         struct pci_controller *hose, *tmp;
2472         struct pnv_phb *phb;
2473         struct pnv_ioda_pe *pe, *gpe;
2474
2475         /*
2476          * Now we have all PHBs discovered, time to add NPU devices to
2477          * the corresponding IOMMU groups.
2478          */
2479         list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
2480                 phb = hose->private_data;
2481
2482                 if (phb->type != PNV_PHB_NPU)
2483                         continue;
2484
2485                 list_for_each_entry(pe, &phb->ioda.pe_list, list) {
2486                         gpe = pnv_pci_npu_setup_iommu(pe);
2487                         if (gpe)
2488                                 gpe->table_group.ops = &pnv_pci_ioda2_npu_ops;
2489                 }
2490         }
2491 }
2492 #else /* !CONFIG_IOMMU_API */
2493 static void pnv_pci_ioda_setup_iommu_api(void) { };
2494 #endif
2495
2496 static void pnv_pci_ioda_setup_opal_tce_kill(struct pnv_phb *phb)
2497 {
2498         const __be64 *swinvp;
2499
2500         /* OPAL variant of PHB3 invalidated TCEs */
2501         swinvp = of_get_property(phb->hose->dn, "ibm,opal-tce-kill", NULL);
2502         if (!swinvp)
2503                 return;
2504
2505         phb->ioda.tce_inval_reg_phys = be64_to_cpup(swinvp);
2506         phb->ioda.tce_inval_reg = ioremap(phb->ioda.tce_inval_reg_phys, 8);
2507 }
2508
2509 static __be64 *pnv_pci_ioda2_table_do_alloc_pages(int nid, unsigned shift,
2510                 unsigned levels, unsigned long limit,
2511                 unsigned long *current_offset, unsigned long *total_allocated)
2512 {
2513         struct page *tce_mem = NULL;
2514         __be64 *addr, *tmp;
2515         unsigned order = max_t(unsigned, shift, PAGE_SHIFT) - PAGE_SHIFT;
2516         unsigned long allocated = 1UL << (order + PAGE_SHIFT);
2517         unsigned entries = 1UL << (shift - 3);
2518         long i;
2519
2520         tce_mem = alloc_pages_node(nid, GFP_KERNEL, order);
2521         if (!tce_mem) {
2522                 pr_err("Failed to allocate a TCE memory, order=%d\n", order);
2523                 return NULL;
2524         }
2525         addr = page_address(tce_mem);
2526         memset(addr, 0, allocated);
2527         *total_allocated += allocated;
2528
2529         --levels;
2530         if (!levels) {
2531                 *current_offset += allocated;
2532                 return addr;
2533         }
2534
2535         for (i = 0; i < entries; ++i) {
2536                 tmp = pnv_pci_ioda2_table_do_alloc_pages(nid, shift,
2537                                 levels, limit, current_offset, total_allocated);
2538                 if (!tmp)
2539                         break;
2540
2541                 addr[i] = cpu_to_be64(__pa(tmp) |
2542                                 TCE_PCI_READ | TCE_PCI_WRITE);
2543
2544                 if (*current_offset >= limit)
2545                         break;
2546         }
2547
2548         return addr;
2549 }
2550
2551 static void pnv_pci_ioda2_table_do_free_pages(__be64 *addr,
2552                 unsigned long size, unsigned level);
2553
2554 static long pnv_pci_ioda2_table_alloc_pages(int nid, __u64 bus_offset,
2555                 __u32 page_shift, __u64 window_size, __u32 levels,
2556                 struct iommu_table *tbl)
2557 {
2558         void *addr;
2559         unsigned long offset = 0, level_shift, total_allocated = 0;
2560         const unsigned window_shift = ilog2(window_size);
2561         unsigned entries_shift = window_shift - page_shift;
2562         unsigned table_shift = max_t(unsigned, entries_shift + 3, PAGE_SHIFT);
2563         const unsigned long tce_table_size = 1UL << table_shift;
2564
2565         if (!levels || (levels > POWERNV_IOMMU_MAX_LEVELS))
2566                 return -EINVAL;
2567
2568         if ((window_size > memory_hotplug_max()) || !is_power_of_2(window_size))
2569                 return -EINVAL;
2570
2571         /* Adjust direct table size from window_size and levels */
2572         entries_shift = (entries_shift + levels - 1) / levels;
2573         level_shift = entries_shift + 3;
2574         level_shift = max_t(unsigned, level_shift, PAGE_SHIFT);
2575
2576         /* Allocate TCE table */
2577         addr = pnv_pci_ioda2_table_do_alloc_pages(nid, level_shift,
2578                         levels, tce_table_size, &offset, &total_allocated);
2579
2580         /* addr==NULL means that the first level allocation failed */
2581         if (!addr)
2582                 return -ENOMEM;
2583
2584         /*
2585          * First level was allocated but some lower level failed as
2586          * we did not allocate as much as we wanted,
2587          * release partially allocated table.
2588          */
2589         if (offset < tce_table_size) {
2590                 pnv_pci_ioda2_table_do_free_pages(addr,
2591                                 1ULL << (level_shift - 3), levels - 1);
2592                 return -ENOMEM;
2593         }
2594
2595         /* Setup linux iommu table */
2596         pnv_pci_setup_iommu_table(tbl, addr, tce_table_size, bus_offset,
2597                         page_shift);
2598         tbl->it_level_size = 1ULL << (level_shift - 3);
2599         tbl->it_indirect_levels = levels - 1;
2600         tbl->it_allocated_size = total_allocated;
2601
2602         pr_devel("Created TCE table: ws=%08llx ts=%lx @%08llx\n",
2603                         window_size, tce_table_size, bus_offset);
2604
2605         return 0;
2606 }
2607
2608 static void pnv_pci_ioda2_table_do_free_pages(__be64 *addr,
2609                 unsigned long size, unsigned level)
2610 {
2611         const unsigned long addr_ul = (unsigned long) addr &
2612                         ~(TCE_PCI_READ | TCE_PCI_WRITE);
2613
2614         if (level) {
2615                 long i;
2616                 u64 *tmp = (u64 *) addr_ul;
2617
2618                 for (i = 0; i < size; ++i) {
2619                         unsigned long hpa = be64_to_cpu(tmp[i]);
2620
2621                         if (!(hpa & (TCE_PCI_READ | TCE_PCI_WRITE)))
2622                                 continue;
2623
2624                         pnv_pci_ioda2_table_do_free_pages(__va(hpa), size,
2625                                         level - 1);
2626                 }
2627         }
2628
2629         free_pages(addr_ul, get_order(size << 3));
2630 }
2631
2632 static void pnv_pci_ioda2_table_free_pages(struct iommu_table *tbl)
2633 {
2634         const unsigned long size = tbl->it_indirect_levels ?
2635                         tbl->it_level_size : tbl->it_size;
2636
2637         if (!tbl->it_size)
2638                 return;
2639
2640         pnv_pci_ioda2_table_do_free_pages((__be64 *)tbl->it_base, size,
2641                         tbl->it_indirect_levels);
2642 }
2643
2644 static void pnv_pci_ioda2_setup_dma_pe(struct pnv_phb *phb,
2645                                        struct pnv_ioda_pe *pe)
2646 {
2647         int64_t rc;
2648
2649         if (!pnv_pci_ioda_pe_dma_weight(pe))
2650                 return;
2651
2652         /* TVE #1 is selected by PCI address bit 59 */
2653         pe->tce_bypass_base = 1ull << 59;
2654
2655         iommu_register_group(&pe->table_group, phb->hose->global_number,
2656                         pe->pe_number);
2657
2658         /* The PE will reserve all possible 32-bits space */
2659         pe_info(pe, "Setting up 32-bit TCE table at 0..%08x\n",
2660                 phb->ioda.m32_pci_base);
2661
2662         /* Setup linux iommu table */
2663         pe->table_group.tce32_start = 0;
2664         pe->table_group.tce32_size = phb->ioda.m32_pci_base;
2665         pe->table_group.max_dynamic_windows_supported =
2666                         IOMMU_TABLE_GROUP_MAX_TABLES;
2667         pe->table_group.max_levels = POWERNV_IOMMU_MAX_LEVELS;
2668         pe->table_group.pgsizes = SZ_4K | SZ_64K | SZ_16M;
2669 #ifdef CONFIG_IOMMU_API
2670         pe->table_group.ops = &pnv_pci_ioda2_ops;
2671 #endif
2672
2673         rc = pnv_pci_ioda2_setup_default_config(pe);
2674         if (rc)
2675                 return;
2676
2677         if (pe->flags & PNV_IODA_PE_DEV)
2678                 iommu_add_device(&pe->pdev->dev);
2679         else if (pe->flags & (PNV_IODA_PE_BUS | PNV_IODA_PE_BUS_ALL))
2680                 pnv_ioda_setup_bus_dma(pe, pe->pbus);
2681 }
2682
2683 #ifdef CONFIG_PCI_MSI
2684 static void pnv_ioda2_msi_eoi(struct irq_data *d)
2685 {
2686         unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d);
2687         struct irq_chip *chip = irq_data_get_irq_chip(d);
2688         struct pnv_phb *phb = container_of(chip, struct pnv_phb,
2689                                            ioda.irq_chip);
2690         int64_t rc;
2691
2692         rc = opal_pci_msi_eoi(phb->opal_id, hw_irq);
2693         WARN_ON_ONCE(rc);
2694
2695         icp_native_eoi(d);
2696 }
2697
2698
2699 static void set_msi_irq_chip(struct pnv_phb *phb, unsigned int virq)
2700 {
2701         struct irq_data *idata;
2702         struct irq_chip *ichip;
2703
2704         if (phb->type != PNV_PHB_IODA2)
2705                 return;
2706
2707         if (!phb->ioda.irq_chip_init) {
2708                 /*
2709                  * First time we setup an MSI IRQ, we need to setup the
2710                  * corresponding IRQ chip to route correctly.
2711                  */
2712                 idata = irq_get_irq_data(virq);
2713                 ichip = irq_data_get_irq_chip(idata);
2714                 phb->ioda.irq_chip_init = 1;
2715                 phb->ioda.irq_chip = *ichip;
2716                 phb->ioda.irq_chip.irq_eoi = pnv_ioda2_msi_eoi;
2717         }
2718         irq_set_chip(virq, &phb->ioda.irq_chip);
2719 }
2720
2721 #ifdef CONFIG_CXL_BASE
2722
2723 struct device_node *pnv_pci_get_phb_node(struct pci_dev *dev)
2724 {
2725         struct pci_controller *hose = pci_bus_to_host(dev->bus);
2726
2727         return of_node_get(hose->dn);
2728 }
2729 EXPORT_SYMBOL(pnv_pci_get_phb_node);
2730
2731 int pnv_phb_to_cxl_mode(struct pci_dev *dev, uint64_t mode)
2732 {
2733         struct pci_controller *hose = pci_bus_to_host(dev->bus);
2734         struct pnv_phb *phb = hose->private_data;
2735         struct pnv_ioda_pe *pe;
2736         int rc;
2737
2738         pe = pnv_ioda_get_pe(dev);
2739         if (!pe)
2740                 return -ENODEV;
2741
2742         pe_info(pe, "Switching PHB to CXL\n");
2743
2744         rc = opal_pci_set_phb_cxl_mode(phb->opal_id, mode, pe->pe_number);
2745         if (rc == OPAL_UNSUPPORTED)
2746                 dev_err(&dev->dev, "Required cxl mode not supported by firmware - update skiboot\n");
2747         else if (rc)
2748                 dev_err(&dev->dev, "opal_pci_set_phb_cxl_mode failed: %i\n", rc);
2749
2750         return rc;
2751 }
2752 EXPORT_SYMBOL(pnv_phb_to_cxl_mode);
2753
2754 /* Find PHB for cxl dev and allocate MSI hwirqs?
2755  * Returns the absolute hardware IRQ number
2756  */
2757 int pnv_cxl_alloc_hwirqs(struct pci_dev *dev, int num)
2758 {
2759         struct pci_controller *hose = pci_bus_to_host(dev->bus);
2760         struct pnv_phb *phb = hose->private_data;
2761         int hwirq = msi_bitmap_alloc_hwirqs(&phb->msi_bmp, num);
2762
2763         if (hwirq < 0) {
2764                 dev_warn(&dev->dev, "Failed to find a free MSI\n");
2765                 return -ENOSPC;
2766         }
2767
2768         return phb->msi_base + hwirq;
2769 }
2770 EXPORT_SYMBOL(pnv_cxl_alloc_hwirqs);
2771
2772 void pnv_cxl_release_hwirqs(struct pci_dev *dev, int hwirq, int num)
2773 {
2774         struct pci_controller *hose = pci_bus_to_host(dev->bus);
2775         struct pnv_phb *phb = hose->private_data;
2776
2777         msi_bitmap_free_hwirqs(&phb->msi_bmp, hwirq - phb->msi_base, num);
2778 }
2779 EXPORT_SYMBOL(pnv_cxl_release_hwirqs);
2780
2781 void pnv_cxl_release_hwirq_ranges(struct cxl_irq_ranges *irqs,
2782                                   struct pci_dev *dev)
2783 {
2784         struct pci_controller *hose = pci_bus_to_host(dev->bus);
2785         struct pnv_phb *phb = hose->private_data;
2786         int i, hwirq;
2787
2788         for (i = 1; i < CXL_IRQ_RANGES; i++) {
2789                 if (!irqs->range[i])
2790                         continue;
2791                 pr_devel("cxl release irq range 0x%x: offset: 0x%lx  limit: %ld\n",
2792                          i, irqs->offset[i],
2793                          irqs->range[i]);
2794                 hwirq = irqs->offset[i] - phb->msi_base;
2795                 msi_bitmap_free_hwirqs(&phb->msi_bmp, hwirq,
2796                                        irqs->range[i]);
2797         }
2798 }
2799 EXPORT_SYMBOL(pnv_cxl_release_hwirq_ranges);
2800
2801 int pnv_cxl_alloc_hwirq_ranges(struct cxl_irq_ranges *irqs,
2802                                struct pci_dev *dev, int num)
2803 {
2804         struct pci_controller *hose = pci_bus_to_host(dev->bus);
2805         struct pnv_phb *phb = hose->private_data;
2806         int i, hwirq, try;
2807
2808         memset(irqs, 0, sizeof(struct cxl_irq_ranges));
2809
2810         /* 0 is reserved for the multiplexed PSL DSI interrupt */
2811         for (i = 1; i < CXL_IRQ_RANGES && num; i++) {
2812                 try = num;
2813                 while (try) {
2814                         hwirq = msi_bitmap_alloc_hwirqs(&phb->msi_bmp, try);
2815                         if (hwirq >= 0)
2816                                 break;
2817                         try /= 2;
2818                 }
2819                 if (!try)
2820                         goto fail;
2821
2822                 irqs->offset[i] = phb->msi_base + hwirq;
2823                 irqs->range[i] = try;
2824                 pr_devel("cxl alloc irq range 0x%x: offset: 0x%lx  limit: %li\n",
2825                          i, irqs->offset[i], irqs->range[i]);
2826                 num -= try;
2827         }
2828         if (num)
2829                 goto fail;
2830
2831         return 0;
2832 fail:
2833         pnv_cxl_release_hwirq_ranges(irqs, dev);
2834         return -ENOSPC;
2835 }
2836 EXPORT_SYMBOL(pnv_cxl_alloc_hwirq_ranges);
2837
2838 int pnv_cxl_get_irq_count(struct pci_dev *dev)
2839 {
2840         struct pci_controller *hose = pci_bus_to_host(dev->bus);
2841         struct pnv_phb *phb = hose->private_data;
2842
2843         return phb->msi_bmp.irq_count;
2844 }
2845 EXPORT_SYMBOL(pnv_cxl_get_irq_count);
2846
2847 int pnv_cxl_ioda_msi_setup(struct pci_dev *dev, unsigned int hwirq,
2848                            unsigned int virq)
2849 {
2850         struct pci_controller *hose = pci_bus_to_host(dev->bus);
2851         struct pnv_phb *phb = hose->private_data;
2852         unsigned int xive_num = hwirq - phb->msi_base;
2853         struct pnv_ioda_pe *pe;
2854         int rc;
2855
2856         if (!(pe = pnv_ioda_get_pe(dev)))
2857                 return -ENODEV;
2858
2859         /* Assign XIVE to PE */
2860         rc = opal_pci_set_xive_pe(phb->opal_id, pe->pe_number, xive_num);
2861         if (rc) {
2862                 pe_warn(pe, "%s: OPAL error %d setting msi_base 0x%x "
2863                         "hwirq 0x%x XIVE 0x%x PE\n",
2864                         pci_name(dev), rc, phb->msi_base, hwirq, xive_num);
2865                 return -EIO;
2866         }
2867         set_msi_irq_chip(phb, virq);
2868
2869         return 0;
2870 }
2871 EXPORT_SYMBOL(pnv_cxl_ioda_msi_setup);
2872 #endif
2873
2874 static int pnv_pci_ioda_msi_setup(struct pnv_phb *phb, struct pci_dev *dev,
2875                                   unsigned int hwirq, unsigned int virq,
2876                                   unsigned int is_64, struct msi_msg *msg)
2877 {
2878         struct pnv_ioda_pe *pe = pnv_ioda_get_pe(dev);
2879         unsigned int xive_num = hwirq - phb->msi_base;
2880         __be32 data;
2881         int rc;
2882
2883         /* No PE assigned ? bail out ... no MSI for you ! */
2884         if (pe == NULL)
2885                 return -ENXIO;
2886
2887         /* Check if we have an MVE */
2888         if (pe->mve_number < 0)
2889                 return -ENXIO;
2890
2891         /* Force 32-bit MSI on some broken devices */
2892         if (dev->no_64bit_msi)
2893                 is_64 = 0;
2894
2895         /* Assign XIVE to PE */
2896         rc = opal_pci_set_xive_pe(phb->opal_id, pe->pe_number, xive_num);
2897         if (rc) {
2898                 pr_warn("%s: OPAL error %d setting XIVE %d PE\n",
2899                         pci_name(dev), rc, xive_num);
2900                 return -EIO;
2901         }
2902
2903         if (is_64) {
2904                 __be64 addr64;
2905
2906                 rc = opal_get_msi_64(phb->opal_id, pe->mve_number, xive_num, 1,
2907                                      &addr64, &data);
2908                 if (rc) {
2909                         pr_warn("%s: OPAL error %d getting 64-bit MSI data\n",
2910                                 pci_name(dev), rc);
2911                         return -EIO;
2912                 }
2913                 msg->address_hi = be64_to_cpu(addr64) >> 32;
2914                 msg->address_lo = be64_to_cpu(addr64) & 0xfffffffful;
2915         } else {
2916                 __be32 addr32;
2917
2918                 rc = opal_get_msi_32(phb->opal_id, pe->mve_number, xive_num, 1,
2919                                      &addr32, &data);
2920                 if (rc) {
2921                         pr_warn("%s: OPAL error %d getting 32-bit MSI data\n",
2922                                 pci_name(dev), rc);
2923                         return -EIO;
2924                 }
2925                 msg->address_hi = 0;
2926                 msg->address_lo = be32_to_cpu(addr32);
2927         }
2928         msg->data = be32_to_cpu(data);
2929
2930         set_msi_irq_chip(phb, virq);
2931
2932         pr_devel("%s: %s-bit MSI on hwirq %x (xive #%d),"
2933                  " address=%x_%08x data=%x PE# %d\n",
2934                  pci_name(dev), is_64 ? "64" : "32", hwirq, xive_num,
2935                  msg->address_hi, msg->address_lo, data, pe->pe_number);
2936
2937         return 0;
2938 }
2939
2940 static void pnv_pci_init_ioda_msis(struct pnv_phb *phb)
2941 {
2942         unsigned int count;
2943         const __be32 *prop = of_get_property(phb->hose->dn,
2944                                              "ibm,opal-msi-ranges", NULL);
2945         if (!prop) {
2946                 /* BML Fallback */
2947                 prop = of_get_property(phb->hose->dn, "msi-ranges", NULL);
2948         }
2949         if (!prop)
2950                 return;
2951
2952         phb->msi_base = be32_to_cpup(prop);
2953         count = be32_to_cpup(prop + 1);
2954         if (msi_bitmap_alloc(&phb->msi_bmp, count, phb->hose->dn)) {
2955                 pr_err("PCI %d: Failed to allocate MSI bitmap !\n",
2956                        phb->hose->global_number);
2957                 return;
2958         }
2959
2960         phb->msi_setup = pnv_pci_ioda_msi_setup;
2961         phb->msi32_support = 1;
2962         pr_info("  Allocated bitmap for %d MSIs (base IRQ 0x%x)\n",
2963                 count, phb->msi_base);
2964 }
2965 #else
2966 static void pnv_pci_init_ioda_msis(struct pnv_phb *phb) { }
2967 #endif /* CONFIG_PCI_MSI */
2968
2969 #ifdef CONFIG_PCI_IOV
2970 static void pnv_pci_ioda_fixup_iov_resources(struct pci_dev *pdev)
2971 {
2972         struct pci_controller *hose = pci_bus_to_host(pdev->bus);
2973         struct pnv_phb *phb = hose->private_data;
2974         const resource_size_t gate = phb->ioda.m64_segsize >> 2;
2975         struct resource *res;
2976         int i;
2977         resource_size_t size, total_vf_bar_sz;
2978         struct pci_dn *pdn;
2979         int mul, total_vfs;
2980
2981         if (!pdev->is_physfn || pdev->is_added)
2982                 return;
2983
2984         pdn = pci_get_pdn(pdev);
2985         pdn->vfs_expanded = 0;
2986         pdn->m64_single_mode = false;
2987
2988         total_vfs = pci_sriov_get_totalvfs(pdev);
2989         mul = phb->ioda.total_pe_num;
2990         total_vf_bar_sz = 0;
2991
2992         for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
2993                 res = &pdev->resource[i + PCI_IOV_RESOURCES];
2994                 if (!res->flags || res->parent)
2995                         continue;
2996                 if (!pnv_pci_is_mem_pref_64(res->flags)) {
2997                         dev_warn(&pdev->dev, "Don't support SR-IOV with"
2998                                         " non M64 VF BAR%d: %pR. \n",
2999                                  i, res);
3000                         goto truncate_iov;
3001                 }
3002
3003                 total_vf_bar_sz += pci_iov_resource_size(pdev,
3004                                 i + PCI_IOV_RESOURCES);
3005
3006                 /*
3007                  * If bigger than quarter of M64 segment size, just round up
3008                  * power of two.
3009                  *
3010                  * Generally, one M64 BAR maps one IOV BAR. To avoid conflict
3011                  * with other devices, IOV BAR size is expanded to be
3012                  * (total_pe * VF_BAR_size).  When VF_BAR_size is half of M64
3013                  * segment size , the expanded size would equal to half of the
3014                  * whole M64 space size, which will exhaust the M64 Space and
3015                  * limit the system flexibility.  This is a design decision to
3016                  * set the boundary to quarter of the M64 segment size.
3017                  */
3018                 if (total_vf_bar_sz > gate) {
3019                         mul = roundup_pow_of_two(total_vfs);
3020                         dev_info(&pdev->dev,
3021                                 "VF BAR Total IOV size %llx > %llx, roundup to %d VFs\n",
3022                                 total_vf_bar_sz, gate, mul);
3023                         pdn->m64_single_mode = true;
3024                         break;
3025                 }
3026         }
3027
3028         for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
3029                 res = &pdev->resource[i + PCI_IOV_RESOURCES];
3030                 if (!res->flags || res->parent)
3031                         continue;
3032
3033                 size = pci_iov_resource_size(pdev, i + PCI_IOV_RESOURCES);
3034                 /*
3035                  * On PHB3, the minimum size alignment of M64 BAR in single
3036                  * mode is 32MB.
3037                  */
3038                 if (pdn->m64_single_mode && (size < SZ_32M))
3039                         goto truncate_iov;
3040                 dev_dbg(&pdev->dev, " Fixing VF BAR%d: %pR to\n", i, res);
3041                 res->end = res->start + size * mul - 1;
3042                 dev_dbg(&pdev->dev, "                       %pR\n", res);
3043                 dev_info(&pdev->dev, "VF BAR%d: %pR (expanded to %d VFs for PE alignment)",
3044                          i, res, mul);
3045         }
3046         pdn->vfs_expanded = mul;
3047
3048         return;
3049
3050 truncate_iov:
3051         /* To save MMIO space, IOV BAR is truncated. */
3052         for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
3053                 res = &pdev->resource[i + PCI_IOV_RESOURCES];
3054                 res->flags = 0;
3055                 res->end = res->start - 1;
3056         }
3057 }
3058 #endif /* CONFIG_PCI_IOV */
3059
3060 static void pnv_ioda_setup_pe_res(struct pnv_ioda_pe *pe,
3061                                   struct resource *res)
3062 {
3063         struct pnv_phb *phb = pe->phb;
3064         struct pci_bus_region region;
3065         int index;
3066         int64_t rc;
3067
3068         if (!res || !res->flags || res->start > res->end)
3069                 return;
3070
3071         if (res->flags & IORESOURCE_IO) {
3072                 region.start = res->start - phb->ioda.io_pci_base;
3073                 region.end   = res->end - phb->ioda.io_pci_base;
3074                 index = region.start / phb->ioda.io_segsize;
3075
3076                 while (index < phb->ioda.total_pe_num &&
3077                        region.start <= region.end) {
3078                         phb->ioda.io_segmap[index] = pe->pe_number;
3079                         rc = opal_pci_map_pe_mmio_window(phb->opal_id,
3080                                 pe->pe_number, OPAL_IO_WINDOW_TYPE, 0, index);
3081                         if (rc != OPAL_SUCCESS) {
3082                                 pr_err("%s: Error %lld mapping IO segment#%d to PE#%d\n",
3083                                        __func__, rc, index, pe->pe_number);
3084                                 break;
3085                         }
3086
3087                         region.start += phb->ioda.io_segsize;
3088                         index++;
3089                 }
3090         } else if ((res->flags & IORESOURCE_MEM) &&
3091                    !pnv_pci_is_mem_pref_64(res->flags)) {
3092                 region.start = res->start -
3093                                phb->hose->mem_offset[0] -
3094                                phb->ioda.m32_pci_base;
3095                 region.end   = res->end -
3096                                phb->hose->mem_offset[0] -
3097                                phb->ioda.m32_pci_base;
3098                 index = region.start / phb->ioda.m32_segsize;
3099
3100                 while (index < phb->ioda.total_pe_num &&
3101                        region.start <= region.end) {
3102                         phb->ioda.m32_segmap[index] = pe->pe_number;
3103                         rc = opal_pci_map_pe_mmio_window(phb->opal_id,
3104                                 pe->pe_number, OPAL_M32_WINDOW_TYPE, 0, index);
3105                         if (rc != OPAL_SUCCESS) {
3106                                 pr_err("%s: Error %lld mapping M32 segment#%d to PE#%d",
3107                                        __func__, rc, index, pe->pe_number);
3108                                 break;
3109                         }
3110
3111                         region.start += phb->ioda.m32_segsize;
3112                         index++;
3113                 }
3114         }
3115 }
3116
3117 /*
3118  * This function is supposed to be called on basis of PE from top
3119  * to bottom style. So the the I/O or MMIO segment assigned to
3120  * parent PE could be overrided by its child PEs if necessary.
3121  */
3122 static void pnv_ioda_setup_pe_seg(struct pnv_ioda_pe *pe)
3123 {
3124         struct pci_dev *pdev;
3125         int i;
3126
3127         /*
3128          * NOTE: We only care PCI bus based PE for now. For PCI
3129          * device based PE, for example SRIOV sensitive VF should
3130          * be figured out later.
3131          */
3132         BUG_ON(!(pe->flags & (PNV_IODA_PE_BUS | PNV_IODA_PE_BUS_ALL)));
3133
3134         list_for_each_entry(pdev, &pe->pbus->devices, bus_list) {
3135                 for (i = 0; i <= PCI_ROM_RESOURCE; i++)
3136                         pnv_ioda_setup_pe_res(pe, &pdev->resource[i]);
3137
3138                 /*
3139                  * If the PE contains all subordinate PCI buses, the
3140                  * windows of the child bridges should be mapped to
3141                  * the PE as well.
3142                  */
3143                 if (!(pe->flags & PNV_IODA_PE_BUS_ALL) || !pci_is_bridge(pdev))
3144                         continue;
3145                 for (i = 0; i < PCI_BRIDGE_RESOURCE_NUM; i++)
3146                         pnv_ioda_setup_pe_res(pe,
3147                                 &pdev->resource[PCI_BRIDGE_RESOURCES + i]);
3148         }
3149 }
3150
3151 static void pnv_pci_ioda_create_dbgfs(void)
3152 {
3153 #ifdef CONFIG_DEBUG_FS
3154         struct pci_controller *hose, *tmp;
3155         struct pnv_phb *phb;
3156         char name[16];
3157
3158         list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
3159                 phb = hose->private_data;
3160
3161                 /* Notify initialization of PHB done */
3162                 phb->initialized = 1;
3163
3164                 sprintf(name, "PCI%04x", hose->global_number);
3165                 phb->dbgfs = debugfs_create_dir(name, powerpc_debugfs_root);
3166                 if (!phb->dbgfs)
3167                         pr_warning("%s: Error on creating debugfs on PHB#%x\n",
3168                                 __func__, hose->global_number);
3169         }
3170 #endif /* CONFIG_DEBUG_FS */
3171 }
3172
3173 static void pnv_pci_ioda_fixup(void)
3174 {
3175         pnv_pci_ioda_setup_PEs();
3176         pnv_pci_ioda_setup_iommu_api();
3177         pnv_pci_ioda_create_dbgfs();
3178
3179 #ifdef CONFIG_EEH
3180         eeh_init();
3181         eeh_addr_cache_build();
3182 #endif
3183 }
3184
3185 /*
3186  * Returns the alignment for I/O or memory windows for P2P
3187  * bridges. That actually depends on how PEs are segmented.
3188  * For now, we return I/O or M32 segment size for PE sensitive
3189  * P2P bridges. Otherwise, the default values (4KiB for I/O,
3190  * 1MiB for memory) will be returned.
3191  *
3192  * The current PCI bus might be put into one PE, which was
3193  * create against the parent PCI bridge. For that case, we
3194  * needn't enlarge the alignment so that we can save some
3195  * resources.
3196  */
3197 static resource_size_t pnv_pci_window_alignment(struct pci_bus *bus,
3198                                                 unsigned long type)
3199 {
3200         struct pci_dev *bridge;
3201         struct pci_controller *hose = pci_bus_to_host(bus);
3202         struct pnv_phb *phb = hose->private_data;
3203         int num_pci_bridges = 0;
3204
3205         bridge = bus->self;
3206         while (bridge) {
3207                 if (pci_pcie_type(bridge) == PCI_EXP_TYPE_PCI_BRIDGE) {
3208                         num_pci_bridges++;
3209                         if (num_pci_bridges >= 2)
3210                                 return 1;
3211                 }
3212
3213                 bridge = bridge->bus->self;
3214         }
3215
3216         /* We fail back to M32 if M64 isn't supported */
3217         if (phb->ioda.m64_segsize &&
3218             pnv_pci_is_mem_pref_64(type))
3219                 return phb->ioda.m64_segsize;
3220         if (type & IORESOURCE_MEM)
3221                 return phb->ioda.m32_segsize;
3222
3223         return phb->ioda.io_segsize;
3224 }
3225
3226 /*
3227  * We are updating root port or the upstream port of the
3228  * bridge behind the root port with PHB's windows in order
3229  * to accommodate the changes on required resources during
3230  * PCI (slot) hotplug, which is connected to either root
3231  * port or the downstream ports of PCIe switch behind the
3232  * root port.
3233  */
3234 static void pnv_pci_fixup_bridge_resources(struct pci_bus *bus,
3235                                            unsigned long type)
3236 {
3237         struct pci_controller *hose = pci_bus_to_host(bus);
3238         struct pnv_phb *phb = hose->private_data;
3239         struct pci_dev *bridge = bus->self;
3240         struct resource *r, *w;
3241         bool msi_region = false;
3242         int i;
3243
3244         /* Check if we need apply fixup to the bridge's windows */
3245         if (!pci_is_root_bus(bridge->bus) &&
3246             !pci_is_root_bus(bridge->bus->self->bus))
3247                 return;
3248
3249         /* Fixup the resources */
3250         for (i = 0; i < PCI_BRIDGE_RESOURCE_NUM; i++) {
3251                 r = &bridge->resource[PCI_BRIDGE_RESOURCES + i];
3252                 if (!r->flags || !r->parent)
3253                         continue;
3254
3255                 w = NULL;
3256                 if (r->flags & type & IORESOURCE_IO)
3257                         w = &hose->io_resource;
3258                 else if (pnv_pci_is_mem_pref_64(r->flags) &&
3259                          (type & IORESOURCE_PREFETCH) &&
3260                          phb->ioda.m64_segsize)
3261                         w = &hose->mem_resources[1];
3262                 else if (r->flags & type & IORESOURCE_MEM) {
3263                         w = &hose->mem_resources[0];
3264                         msi_region = true;
3265                 }
3266
3267                 r->start = w->start;
3268                 r->end = w->end;
3269
3270                 /* The 64KB 32-bits MSI region shouldn't be included in
3271                  * the 32-bits bridge window. Otherwise, we can see strange
3272                  * issues. One of them is EEH error observed on Garrison.
3273                  *
3274                  * Exclude top 1MB region which is the minimal alignment of
3275                  * 32-bits bridge window.
3276                  */
3277                 if (msi_region) {
3278                         r->end += 0x10000;
3279                         r->end -= 0x100000;
3280                 }
3281         }
3282 }
3283
3284 static void pnv_pci_setup_bridge(struct pci_bus *bus, unsigned long type)
3285 {
3286         struct pci_controller *hose = pci_bus_to_host(bus);
3287         struct pnv_phb *phb = hose->private_data;
3288         struct pci_dev *bridge = bus->self;
3289         struct pnv_ioda_pe *pe;
3290         bool all = (pci_pcie_type(bridge) == PCI_EXP_TYPE_PCI_BRIDGE);
3291
3292         /* Extend bridge's windows if necessary */
3293         pnv_pci_fixup_bridge_resources(bus, type);
3294
3295         /* The PE for root bus should be realized before any one else */
3296         if (!phb->ioda.root_pe_populated) {
3297                 pe = pnv_ioda_setup_bus_PE(phb->hose->bus, false);
3298                 if (pe) {
3299                         phb->ioda.root_pe_idx = pe->pe_number;
3300                         phb->ioda.root_pe_populated = true;
3301                 }
3302         }
3303
3304         /* Don't assign PE to PCI bus, which doesn't have subordinate devices */
3305         if (list_empty(&bus->devices))
3306                 return;
3307
3308         /* Reserve PEs according to used M64 resources */
3309         if (phb->reserve_m64_pe)
3310                 phb->reserve_m64_pe(bus, NULL, all);
3311
3312         /*
3313          * Assign PE. We might run here because of partial hotplug.
3314          * For the case, we just pick up the existing PE and should
3315          * not allocate resources again.
3316          */
3317         pe = pnv_ioda_setup_bus_PE(bus, all);
3318         if (!pe)
3319                 return;
3320
3321         pnv_ioda_setup_pe_seg(pe);
3322         switch (phb->type) {
3323         case PNV_PHB_IODA1:
3324                 pnv_pci_ioda1_setup_dma_pe(phb, pe);
3325                 break;
3326         case PNV_PHB_IODA2:
3327                 pnv_pci_ioda2_setup_dma_pe(phb, pe);
3328                 break;
3329         default:
3330                 pr_warn("%s: No DMA for PHB#%d (type %d)\n",
3331                         __func__, phb->hose->global_number, phb->type);
3332         }
3333 }
3334
3335 #ifdef CONFIG_PCI_IOV
3336 static resource_size_t pnv_pci_iov_resource_alignment(struct pci_dev *pdev,
3337                                                       int resno)
3338 {
3339         struct pci_controller *hose = pci_bus_to_host(pdev->bus);
3340         struct pnv_phb *phb = hose->private_data;
3341         struct pci_dn *pdn = pci_get_pdn(pdev);
3342         resource_size_t align;
3343
3344         /*
3345          * On PowerNV platform, IOV BAR is mapped by M64 BAR to enable the
3346          * SR-IOV. While from hardware perspective, the range mapped by M64
3347          * BAR should be size aligned.
3348          *
3349          * When IOV BAR is mapped with M64 BAR in Single PE mode, the extra
3350          * powernv-specific hardware restriction is gone. But if just use the
3351          * VF BAR size as the alignment, PF BAR / VF BAR may be allocated with
3352          * in one segment of M64 #15, which introduces the PE conflict between
3353          * PF and VF. Based on this, the minimum alignment of an IOV BAR is
3354          * m64_segsize.
3355          *
3356          * This function returns the total IOV BAR size if M64 BAR is in
3357          * Shared PE mode or just VF BAR size if not.
3358          * If the M64 BAR is in Single PE mode, return the VF BAR size or
3359          * M64 segment size if IOV BAR size is less.
3360          */
3361         align = pci_iov_resource_size(pdev, resno);
3362         if (!pdn->vfs_expanded)
3363                 return align;
3364         if (pdn->m64_single_mode)
3365                 return max(align, (resource_size_t)phb->ioda.m64_segsize);
3366
3367         return pdn->vfs_expanded * align;
3368 }
3369 #endif /* CONFIG_PCI_IOV */
3370
3371 /* Prevent enabling devices for which we couldn't properly
3372  * assign a PE
3373  */
3374 static bool pnv_pci_enable_device_hook(struct pci_dev *dev)
3375 {
3376         struct pci_controller *hose = pci_bus_to_host(dev->bus);
3377         struct pnv_phb *phb = hose->private_data;
3378         struct pci_dn *pdn;
3379
3380         /* The function is probably called while the PEs have
3381          * not be created yet. For example, resource reassignment
3382          * during PCI probe period. We just skip the check if
3383          * PEs isn't ready.
3384          */
3385         if (!phb->initialized)
3386                 return true;
3387
3388         pdn = pci_get_pdn(dev);
3389         if (!pdn || pdn->pe_number == IODA_INVALID_PE)
3390                 return false;
3391
3392         return true;
3393 }
3394
3395 static void pnv_pci_ioda_shutdown(struct pci_controller *hose)
3396 {
3397         struct pnv_phb *phb = hose->private_data;
3398
3399         opal_pci_reset(phb->opal_id, OPAL_RESET_PCI_IODA_TABLE,
3400                        OPAL_ASSERT_RESET);
3401 }
3402
3403 static const struct pci_controller_ops pnv_pci_ioda_controller_ops = {
3404         .dma_dev_setup          = pnv_pci_dma_dev_setup,
3405         .dma_bus_setup          = pnv_pci_dma_bus_setup,
3406 #ifdef CONFIG_PCI_MSI
3407         .setup_msi_irqs         = pnv_setup_msi_irqs,
3408         .teardown_msi_irqs      = pnv_teardown_msi_irqs,
3409 #endif
3410         .enable_device_hook     = pnv_pci_enable_device_hook,
3411         .window_alignment       = pnv_pci_window_alignment,
3412         .setup_bridge           = pnv_pci_setup_bridge,
3413         .reset_secondary_bus    = pnv_pci_reset_secondary_bus,
3414         .dma_set_mask           = pnv_pci_ioda_dma_set_mask,
3415         .dma_get_required_mask  = pnv_pci_ioda_dma_get_required_mask,
3416         .shutdown               = pnv_pci_ioda_shutdown,
3417 };
3418
3419 static int pnv_npu_dma_set_mask(struct pci_dev *npdev, u64 dma_mask)
3420 {
3421         dev_err_once(&npdev->dev,
3422                         "%s operation unsupported for NVLink devices\n",
3423                         __func__);
3424         return -EPERM;
3425 }
3426
3427 static const struct pci_controller_ops pnv_npu_ioda_controller_ops = {
3428         .dma_dev_setup          = pnv_pci_dma_dev_setup,
3429 #ifdef CONFIG_PCI_MSI
3430         .setup_msi_irqs         = pnv_setup_msi_irqs,
3431         .teardown_msi_irqs      = pnv_teardown_msi_irqs,
3432 #endif
3433         .enable_device_hook     = pnv_pci_enable_device_hook,
3434         .window_alignment       = pnv_pci_window_alignment,
3435         .reset_secondary_bus    = pnv_pci_reset_secondary_bus,
3436         .dma_set_mask           = pnv_npu_dma_set_mask,
3437         .shutdown               = pnv_pci_ioda_shutdown,
3438 };
3439
3440 static void __init pnv_pci_init_ioda_phb(struct device_node *np,
3441                                          u64 hub_id, int ioda_type)
3442 {
3443         struct pci_controller *hose;
3444         struct pnv_phb *phb;
3445         unsigned long size, m64map_off, m32map_off, pemap_off;
3446         unsigned long iomap_off = 0, dma32map_off = 0;
3447         const __be64 *prop64;
3448         const __be32 *prop32;
3449         int len;
3450         unsigned int segno;
3451         u64 phb_id;
3452         void *aux;
3453         long rc;
3454
3455         pr_info("Initializing IODA%d OPAL PHB %s\n", ioda_type, np->full_name);
3456
3457         prop64 = of_get_property(np, "ibm,opal-phbid", NULL);
3458         if (!prop64) {
3459                 pr_err("  Missing \"ibm,opal-phbid\" property !\n");
3460                 return;
3461         }
3462         phb_id = be64_to_cpup(prop64);
3463         pr_debug("  PHB-ID  : 0x%016llx\n", phb_id);
3464
3465         phb = memblock_virt_alloc(sizeof(struct pnv_phb), 0);
3466
3467         /* Allocate PCI controller */
3468         phb->hose = hose = pcibios_alloc_controller(np);
3469         if (!phb->hose) {
3470                 pr_err("  Can't allocate PCI controller for %s\n",
3471                        np->full_name);
3472                 memblock_free(__pa(phb), sizeof(struct pnv_phb));
3473                 return;
3474         }
3475
3476         spin_lock_init(&phb->lock);
3477         prop32 = of_get_property(np, "bus-range", &len);
3478         if (prop32 && len == 8) {
3479                 hose->first_busno = be32_to_cpu(prop32[0]);
3480                 hose->last_busno = be32_to_cpu(prop32[1]);
3481         } else {
3482                 pr_warn("  Broken <bus-range> on %s\n", np->full_name);
3483                 hose->first_busno = 0;
3484                 hose->last_busno = 0xff;
3485         }
3486         hose->private_data = phb;
3487         phb->hub_id = hub_id;
3488         phb->opal_id = phb_id;
3489         phb->type = ioda_type;
3490         mutex_init(&phb->ioda.pe_alloc_mutex);
3491
3492         /* Detect specific models for error handling */
3493         if (of_device_is_compatible(np, "ibm,p7ioc-pciex"))
3494                 phb->model = PNV_PHB_MODEL_P7IOC;
3495         else if (of_device_is_compatible(np, "ibm,power8-pciex"))
3496                 phb->model = PNV_PHB_MODEL_PHB3;
3497         else if (of_device_is_compatible(np, "ibm,power8-npu-pciex"))
3498                 phb->model = PNV_PHB_MODEL_NPU;
3499         else
3500                 phb->model = PNV_PHB_MODEL_UNKNOWN;
3501
3502         /* Parse 32-bit and IO ranges (if any) */
3503         pci_process_bridge_OF_ranges(hose, np, !hose->global_number);
3504
3505         /* Get registers */
3506         phb->regs = of_iomap(np, 0);
3507         if (phb->regs == NULL)
3508                 pr_err("  Failed to map registers !\n");
3509
3510         /* Initialize TCE kill register */
3511         pnv_pci_ioda_setup_opal_tce_kill(phb);
3512
3513         /* Initialize more IODA stuff */
3514         phb->ioda.total_pe_num = 1;
3515         prop32 = of_get_property(np, "ibm,opal-num-pes", NULL);
3516         if (prop32)
3517                 phb->ioda.total_pe_num = be32_to_cpup(prop32);
3518         prop32 = of_get_property(np, "ibm,opal-reserved-pe", NULL);
3519         if (prop32)
3520                 phb->ioda.reserved_pe_idx = be32_to_cpup(prop32);
3521
3522         /* Invalidate RID to PE# mapping */
3523         for (segno = 0; segno < ARRAY_SIZE(phb->ioda.pe_rmap); segno++)
3524                 phb->ioda.pe_rmap[segno] = IODA_INVALID_PE;
3525
3526         /* Parse 64-bit MMIO range */
3527         pnv_ioda_parse_m64_window(phb);
3528
3529         phb->ioda.m32_size = resource_size(&hose->mem_resources[0]);
3530         /* FW Has already off top 64k of M32 space (MSI space) */
3531         phb->ioda.m32_size += 0x10000;
3532
3533         phb->ioda.m32_segsize = phb->ioda.m32_size / phb->ioda.total_pe_num;
3534         phb->ioda.m32_pci_base = hose->mem_resources[0].start - hose->mem_offset[0];
3535         phb->ioda.io_size = hose->pci_io_size;
3536         phb->ioda.io_segsize = phb->ioda.io_size / phb->ioda.total_pe_num;
3537         phb->ioda.io_pci_base = 0; /* XXX calculate this ? */
3538
3539         /* Calculate how many 32-bit TCE segments we have */
3540         phb->ioda.dma32_count = phb->ioda.m32_pci_base /
3541                                 PNV_IODA1_DMA32_SEGSIZE;
3542
3543         /* Allocate aux data & arrays. We don't have IO ports on PHB3 */
3544         size = _ALIGN_UP(max_t(unsigned, phb->ioda.total_pe_num, 8) / 8,
3545                         sizeof(unsigned long));
3546         m64map_off = size;
3547         size += phb->ioda.total_pe_num * sizeof(phb->ioda.m64_segmap[0]);
3548         m32map_off = size;
3549         size += phb->ioda.total_pe_num * sizeof(phb->ioda.m32_segmap[0]);
3550         if (phb->type == PNV_PHB_IODA1) {
3551                 iomap_off = size;
3552                 size += phb->ioda.total_pe_num * sizeof(phb->ioda.io_segmap[0]);
3553                 dma32map_off = size;
3554                 size += phb->ioda.dma32_count *
3555                         sizeof(phb->ioda.dma32_segmap[0]);
3556         }
3557         pemap_off = size;
3558         size += phb->ioda.total_pe_num * sizeof(struct pnv_ioda_pe);
3559         aux = memblock_virt_alloc(size, 0);
3560         phb->ioda.pe_alloc = aux;
3561         phb->ioda.m64_segmap = aux + m64map_off;
3562         phb->ioda.m32_segmap = aux + m32map_off;
3563         for (segno = 0; segno < phb->ioda.total_pe_num; segno++) {
3564                 phb->ioda.m64_segmap[segno] = IODA_INVALID_PE;
3565                 phb->ioda.m32_segmap[segno] = IODA_INVALID_PE;
3566         }
3567         if (phb->type == PNV_PHB_IODA1) {
3568                 phb->ioda.io_segmap = aux + iomap_off;
3569                 for (segno = 0; segno < phb->ioda.total_pe_num; segno++)
3570                         phb->ioda.io_segmap[segno] = IODA_INVALID_PE;
3571
3572                 phb->ioda.dma32_segmap = aux + dma32map_off;
3573                 for (segno = 0; segno < phb->ioda.dma32_count; segno++)
3574                         phb->ioda.dma32_segmap[segno] = IODA_INVALID_PE;
3575         }
3576         phb->ioda.pe_array = aux + pemap_off;
3577
3578         /*
3579          * Choose PE number for root bus, which shouldn't have
3580          * M64 resources consumed by its child devices. To pick
3581          * the PE number adjacent to the reserved one if possible.
3582          */
3583         pnv_ioda_reserve_pe(phb, phb->ioda.reserved_pe_idx);
3584         if (phb->ioda.reserved_pe_idx == 0) {
3585                 phb->ioda.root_pe_idx = 1;
3586                 pnv_ioda_reserve_pe(phb, phb->ioda.root_pe_idx);
3587         } else if (phb->ioda.reserved_pe_idx == (phb->ioda.total_pe_num - 1)) {
3588                 phb->ioda.root_pe_idx = phb->ioda.reserved_pe_idx - 1;
3589                 pnv_ioda_reserve_pe(phb, phb->ioda.root_pe_idx);
3590         } else {
3591                 phb->ioda.root_pe_idx = IODA_INVALID_PE;
3592         }
3593
3594         INIT_LIST_HEAD(&phb->ioda.pe_list);
3595         mutex_init(&phb->ioda.pe_list_mutex);
3596
3597         /* Calculate how many 32-bit TCE segments we have */
3598         phb->ioda.dma32_count = phb->ioda.m32_pci_base /
3599                                 PNV_IODA1_DMA32_SEGSIZE;
3600
3601 #if 0 /* We should really do that ... */
3602         rc = opal_pci_set_phb_mem_window(opal->phb_id,
3603                                          window_type,
3604                                          window_num,
3605                                          starting_real_address,
3606                                          starting_pci_address,
3607                                          segment_size);
3608 #endif
3609
3610         pr_info("  %03d (%03d) PE's M32: 0x%x [segment=0x%x]\n",
3611                 phb->ioda.total_pe_num, phb->ioda.reserved_pe_idx,
3612                 phb->ioda.m32_size, phb->ioda.m32_segsize);
3613         if (phb->ioda.m64_size)
3614                 pr_info("                 M64: 0x%lx [segment=0x%lx]\n",
3615                         phb->ioda.m64_size, phb->ioda.m64_segsize);
3616         if (phb->ioda.io_size)
3617                 pr_info("                  IO: 0x%x [segment=0x%x]\n",
3618                         phb->ioda.io_size, phb->ioda.io_segsize);
3619
3620
3621         phb->hose->ops = &pnv_pci_ops;
3622         phb->get_pe_state = pnv_ioda_get_pe_state;
3623         phb->freeze_pe = pnv_ioda_freeze_pe;
3624         phb->unfreeze_pe = pnv_ioda_unfreeze_pe;
3625
3626         /* Setup MSI support */
3627         pnv_pci_init_ioda_msis(phb);
3628
3629         /*
3630          * We pass the PCI probe flag PCI_REASSIGN_ALL_RSRC here
3631          * to let the PCI core do resource assignment. It's supposed
3632          * that the PCI core will do correct I/O and MMIO alignment
3633          * for the P2P bridge bars so that each PCI bus (excluding
3634          * the child P2P bridges) can form individual PE.
3635          */
3636         ppc_md.pcibios_fixup = pnv_pci_ioda_fixup;
3637
3638         if (phb->type == PNV_PHB_NPU) {
3639                 hose->controller_ops = pnv_npu_ioda_controller_ops;
3640         } else {
3641                 phb->dma_dev_setup = pnv_pci_ioda_dma_dev_setup;
3642                 hose->controller_ops = pnv_pci_ioda_controller_ops;
3643         }
3644
3645 #ifdef CONFIG_PCI_IOV
3646         ppc_md.pcibios_fixup_sriov = pnv_pci_ioda_fixup_iov_resources;
3647         ppc_md.pcibios_iov_resource_alignment = pnv_pci_iov_resource_alignment;
3648 #endif
3649
3650         pci_add_flags(PCI_REASSIGN_ALL_RSRC);
3651
3652         /* Reset IODA tables to a clean state */
3653         rc = opal_pci_reset(phb_id, OPAL_RESET_PCI_IODA_TABLE, OPAL_ASSERT_RESET);
3654         if (rc)
3655                 pr_warning("  OPAL Error %ld performing IODA table reset !\n", rc);
3656
3657         /* If we're running in kdump kerenl, the previous kerenl never
3658          * shutdown PCI devices correctly. We already got IODA table
3659          * cleaned out. So we have to issue PHB reset to stop all PCI
3660          * transactions from previous kerenl.
3661          */
3662         if (is_kdump_kernel()) {
3663                 pr_info("  Issue PHB reset ...\n");
3664                 pnv_eeh_phb_reset(hose, EEH_RESET_FUNDAMENTAL);
3665                 pnv_eeh_phb_reset(hose, EEH_RESET_DEACTIVATE);
3666         }
3667
3668         /* Remove M64 resource if we can't configure it successfully */
3669         if (!phb->init_m64 || phb->init_m64(phb))
3670                 hose->mem_resources[1].flags = 0;
3671 }
3672
3673 void __init pnv_pci_init_ioda2_phb(struct device_node *np)
3674 {
3675         pnv_pci_init_ioda_phb(np, 0, PNV_PHB_IODA2);
3676 }
3677
3678 void __init pnv_pci_init_npu_phb(struct device_node *np)
3679 {
3680         pnv_pci_init_ioda_phb(np, 0, PNV_PHB_NPU);
3681 }
3682
3683 void __init pnv_pci_init_ioda_hub(struct device_node *np)
3684 {
3685         struct device_node *phbn;
3686         const __be64 *prop64;
3687         u64 hub_id;
3688
3689         pr_info("Probing IODA IO-Hub %s\n", np->full_name);
3690
3691         prop64 = of_get_property(np, "ibm,opal-hubid", NULL);
3692         if (!prop64) {
3693                 pr_err(" Missing \"ibm,opal-hubid\" property !\n");
3694                 return;
3695         }
3696         hub_id = be64_to_cpup(prop64);
3697         pr_devel(" HUB-ID : 0x%016llx\n", hub_id);
3698
3699         /* Count child PHBs */
3700         for_each_child_of_node(np, phbn) {
3701                 /* Look for IODA1 PHBs */
3702                 if (of_device_is_compatible(phbn, "ibm,ioda-phb"))
3703                         pnv_pci_init_ioda_phb(phbn, hub_id, PNV_PHB_IODA1);
3704         }
3705 }