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