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