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