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