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