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