pci-ioda.c 104.9 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-or-later
2 3 4 5 6 7
/*
 * Support PCI/PCIe on PowerNV platforms
 *
 * Copyright 2011 Benjamin Herrenschmidt, IBM Corp.
 */

8
#undef DEBUG
9 10 11

#include <linux/kernel.h>
#include <linux/pci.h>
12
#include <linux/crash_dump.h>
13 14 15
#include <linux/delay.h>
#include <linux/string.h>
#include <linux/init.h>
M
Mike Rapoport 已提交
16
#include <linux/memblock.h>
17 18 19
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/msi.h>
20
#include <linux/iommu.h>
21
#include <linux/rculist.h>
22
#include <linux/sizes.h>
23 24 25 26 27 28

#include <asm/sections.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/pci-bridge.h>
#include <asm/machdep.h>
29
#include <asm/msi_bitmap.h>
30 31 32 33
#include <asm/ppc-pci.h>
#include <asm/opal.h>
#include <asm/iommu.h>
#include <asm/tce.h>
34
#include <asm/xics.h>
35
#include <asm/debugfs.h>
36
#include <asm/firmware.h>
37
#include <asm/pnv-pci.h>
38
#include <asm/mmzone.h>
39

40
#include <misc/cxl-base.h>
41 42 43

#include "powernv.h"
#include "pci.h"
44
#include "../../../../drivers/pci/pci.h"
45

46 47
#define PNV_IODA1_M64_NUM	16	/* Number of M64 BARs	*/
#define PNV_IODA1_M64_SEGS	8	/* Segments per M64 BAR	*/
48
#define PNV_IODA1_DMA32_SEGSIZE	0x10000000
49

50 51
static const char * const pnv_phb_names[] = { "IODA1", "IODA2", "NPU_NVLINK",
					      "NPU_OCAPI" };
52

53
static void pnv_pci_ioda2_set_bypass(struct pnv_ioda_pe *pe, bool enable);
54
static void pnv_pci_configure_bus(struct pci_bus *bus);
55

56
void pe_level_printk(const struct pnv_ioda_pe *pe, const char *level,
57 58 59 60 61 62 63 64 65 66 67
			    const char *fmt, ...)
{
	struct va_format vaf;
	va_list args;
	char pfix[32];

	va_start(args, fmt);

	vaf.fmt = fmt;
	vaf.va = &args;

68
	if (pe->flags & PNV_IODA_PE_DEV)
69
		strlcpy(pfix, dev_name(&pe->pdev->dev), sizeof(pfix));
70
	else if (pe->flags & (PNV_IODA_PE_BUS | PNV_IODA_PE_BUS_ALL))
71 72
		sprintf(pfix, "%04x:%02x     ",
			pci_domain_nr(pe->pbus), pe->pbus->number);
73 74 75 76 77 78 79
#ifdef CONFIG_PCI_IOV
	else if (pe->flags & PNV_IODA_PE_VF)
		sprintf(pfix, "%04x:%02x:%2x.%d",
			pci_domain_nr(pe->parent_dev->bus),
			(pe->rid & 0xff00) >> 8,
			PCI_SLOT(pe->rid), PCI_FUNC(pe->rid));
#endif /* CONFIG_PCI_IOV*/
80

81
	printk("%spci %s: [PE# %.2x] %pV",
82 83 84 85
	       level, pfix, pe->pe_number, &vaf);

	va_end(args);
}
86

87
static bool pnv_iommu_bypass_disabled __read_mostly;
88
static bool pci_reset_phbs __read_mostly;
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

static int __init iommu_setup(char *str)
{
	if (!str)
		return -EINVAL;

	while (*str) {
		if (!strncmp(str, "nobypass", 8)) {
			pnv_iommu_bypass_disabled = true;
			pr_info("PowerNV: IOMMU bypass window disabled.\n");
			break;
		}
		str += strcspn(str, ",");
		if (*str == ',')
			str++;
	}

	return 0;
}
early_param("iommu", iommu_setup);

110 111 112 113 114 115 116 117
static int __init pci_reset_phbs_setup(char *str)
{
	pci_reset_phbs = true;
	return 0;
}

early_param("ppc_pci_reset_phbs", pci_reset_phbs_setup);

118
static inline bool pnv_pci_is_m64(struct pnv_phb *phb, struct resource *r)
119
{
120 121 122 123 124 125 126 127 128
	/*
	 * WARNING: We cannot rely on the resource flags. The Linux PCI
	 * allocation code sometimes decides to put a 64-bit prefetchable
	 * BAR in the 32-bit window, so we have to compare the addresses.
	 *
	 * For simplicity we only test resource start.
	 */
	return (r->start >= phb->ioda.m64_base &&
		r->start < (phb->ioda.m64_base + phb->ioda.m64_size));
129 130
}

131 132 133 134 135 136 137
static inline bool pnv_pci_is_m64_flags(unsigned long resource_flags)
{
	unsigned long flags = (IORESOURCE_MEM_64 | IORESOURCE_PREFETCH);

	return (resource_flags & flags) == flags;
}

138 139
static struct pnv_ioda_pe *pnv_ioda_init_pe(struct pnv_phb *phb, int pe_no)
{
140 141
	s64 rc;

142 143 144
	phb->ioda.pe_array[pe_no].phb = phb;
	phb->ioda.pe_array[pe_no].pe_number = pe_no;

145 146 147 148 149 150 151
	/*
	 * Clear the PE frozen state as it might be put into frozen state
	 * in the last PCI remove path. It's not harmful to do so when the
	 * PE is already in unfrozen state.
	 */
	rc = opal_pci_eeh_freeze_clear(phb->opal_id, pe_no,
				       OPAL_EEH_ACTION_CLEAR_FREEZE_ALL);
152
	if (rc != OPAL_SUCCESS && rc != OPAL_UNSUPPORTED)
153
		pr_warn("%s: Error %lld unfreezing PHB#%x-PE#%x\n",
154 155
			__func__, rc, phb->hose->global_number, pe_no);

156 157 158
	return &phb->ioda.pe_array[pe_no];
}

159 160
static void pnv_ioda_reserve_pe(struct pnv_phb *phb, int pe_no)
{
161
	if (!(pe_no >= 0 && pe_no < phb->ioda.total_pe_num)) {
162
		pr_warn("%s: Invalid PE %x on PHB#%x\n",
163 164 165 166
			__func__, pe_no, phb->hose->global_number);
		return;
	}

167
	if (test_and_set_bit(pe_no, phb->ioda.pe_alloc))
168
		pr_debug("%s: PE %x was reserved on PHB#%x\n",
169
			 __func__, pe_no, phb->hose->global_number);
170

171
	pnv_ioda_init_pe(phb, pe_no);
172 173
}

174
static struct pnv_ioda_pe *pnv_ioda_alloc_pe(struct pnv_phb *phb)
175
{
176
	long pe;
177

178 179 180 181
	for (pe = phb->ioda.total_pe_num - 1; pe >= 0; pe--) {
		if (!test_and_set_bit(pe, phb->ioda.pe_alloc))
			return pnv_ioda_init_pe(phb, pe);
	}
182

183
	return NULL;
184 185
}

186
static void pnv_ioda_free_pe(struct pnv_ioda_pe *pe)
187
{
188
	struct pnv_phb *phb = pe->phb;
189
	unsigned int pe_num = pe->pe_number;
190 191

	WARN_ON(pe->pdev);
192
	WARN_ON(pe->npucomp); /* NPUs for nvlink are not supposed to be freed */
193
	kfree(pe->npucomp);
194
	memset(pe, 0, sizeof(struct pnv_ioda_pe));
195
	clear_bit(pe_num, phb->ioda.pe_alloc);
196 197
}

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
/* The default M64 BAR is shared by all PEs */
static int pnv_ioda2_init_m64(struct pnv_phb *phb)
{
	const char *desc;
	struct resource *r;
	s64 rc;

	/* Configure the default M64 BAR */
	rc = opal_pci_set_phb_mem_window(phb->opal_id,
					 OPAL_M64_WINDOW_TYPE,
					 phb->ioda.m64_bar_idx,
					 phb->ioda.m64_base,
					 0, /* unused */
					 phb->ioda.m64_size);
	if (rc != OPAL_SUCCESS) {
		desc = "configuring";
		goto fail;
	}

	/* Enable the default M64 BAR */
	rc = opal_pci_phb_mmio_enable(phb->opal_id,
				      OPAL_M64_WINDOW_TYPE,
				      phb->ioda.m64_bar_idx,
				      OPAL_ENABLE_M64_SPLIT);
	if (rc != OPAL_SUCCESS) {
		desc = "enabling";
		goto fail;
	}

	/*
228 229
	 * Exclude the segments for reserved and root bus PE, which
	 * are first or last two PEs.
230 231
	 */
	r = &phb->hose->mem_resources[1];
232
	if (phb->ioda.reserved_pe_idx == 0)
233
		r->start += (2 * phb->ioda.m64_segsize);
234
	else if (phb->ioda.reserved_pe_idx == (phb->ioda.total_pe_num - 1))
235
		r->end -= (2 * phb->ioda.m64_segsize);
236
	else
237
		pr_warn("  Cannot strip M64 segment for reserved PE#%x\n",
238
			phb->ioda.reserved_pe_idx);
239 240 241 242 243 244 245 246 247 248 249 250 251

	return 0;

fail:
	pr_warn("  Failure %lld %s M64 BAR#%d\n",
		rc, desc, phb->ioda.m64_bar_idx);
	opal_pci_phb_mmio_enable(phb->opal_id,
				 OPAL_M64_WINDOW_TYPE,
				 phb->ioda.m64_bar_idx,
				 OPAL_DISABLE_M64);
	return -EIO;
}

252
static void pnv_ioda_reserve_dev_m64_pe(struct pci_dev *pdev,
253
					 unsigned long *pe_bitmap)
254
{
255 256
	struct pci_controller *hose = pci_bus_to_host(pdev->bus);
	struct pnv_phb *phb = hose->private_data;
257
	struct resource *r;
258 259 260 261 262 263 264
	resource_size_t base, sgsz, start, end;
	int segno, i;

	base = phb->ioda.m64_base;
	sgsz = phb->ioda.m64_segsize;
	for (i = 0; i <= PCI_ROM_RESOURCE; i++) {
		r = &pdev->resource[i];
265
		if (!r->parent || !pnv_pci_is_m64(phb, r))
266
			continue;
267

268
		start = ALIGN_DOWN(r->start - base, sgsz);
269
		end = ALIGN(r->end - base, sgsz);
270 271 272 273 274
		for (segno = start / sgsz; segno < end / sgsz; segno++) {
			if (pe_bitmap)
				set_bit(segno, pe_bitmap);
			else
				pnv_ioda_reserve_pe(phb, segno);
275 276 277 278
		}
	}
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
static int pnv_ioda1_init_m64(struct pnv_phb *phb)
{
	struct resource *r;
	int index;

	/*
	 * There are 16 M64 BARs, each of which has 8 segments. So
	 * there are as many M64 segments as the maximum number of
	 * PEs, which is 128.
	 */
	for (index = 0; index < PNV_IODA1_M64_NUM; index++) {
		unsigned long base, segsz = phb->ioda.m64_segsize;
		int64_t rc;

		base = phb->ioda.m64_base +
		       index * PNV_IODA1_M64_SEGS * segsz;
		rc = opal_pci_set_phb_mem_window(phb->opal_id,
				OPAL_M64_WINDOW_TYPE, index, base, 0,
				PNV_IODA1_M64_SEGS * segsz);
		if (rc != OPAL_SUCCESS) {
299
			pr_warn("  Error %lld setting M64 PHB#%x-BAR#%d\n",
300 301 302 303 304 305 306 307
				rc, phb->hose->global_number, index);
			goto fail;
		}

		rc = opal_pci_phb_mmio_enable(phb->opal_id,
				OPAL_M64_WINDOW_TYPE, index,
				OPAL_ENABLE_M64_SPLIT);
		if (rc != OPAL_SUCCESS) {
308
			pr_warn("  Error %lld enabling M64 PHB#%x-BAR#%d\n",
309 310 311 312 313 314
				rc, phb->hose->global_number, index);
			goto fail;
		}
	}

	/*
315 316
	 * Exclude the segments for reserved and root bus PE, which
	 * are first or last two PEs.
317 318 319
	 */
	r = &phb->hose->mem_resources[1];
	if (phb->ioda.reserved_pe_idx == 0)
320
		r->start += (2 * phb->ioda.m64_segsize);
321
	else if (phb->ioda.reserved_pe_idx == (phb->ioda.total_pe_num - 1))
322
		r->end -= (2 * phb->ioda.m64_segsize);
323
	else
324
		WARN(1, "Wrong reserved PE#%x on PHB#%x\n",
325 326 327 328 329 330 331 332 333 334 335 336
		     phb->ioda.reserved_pe_idx, phb->hose->global_number);

	return 0;

fail:
	for ( ; index >= 0; index--)
		opal_pci_phb_mmio_enable(phb->opal_id,
			OPAL_M64_WINDOW_TYPE, index, OPAL_DISABLE_M64);

	return -EIO;
}

337 338 339
static void pnv_ioda_reserve_m64_pe(struct pci_bus *bus,
				    unsigned long *pe_bitmap,
				    bool all)
340 341
{
	struct pci_dev *pdev;
342 343

	list_for_each_entry(pdev, &bus->devices, bus_list) {
344
		pnv_ioda_reserve_dev_m64_pe(pdev, pe_bitmap);
345 346

		if (all && pdev->subordinate)
347 348
			pnv_ioda_reserve_m64_pe(pdev->subordinate,
						pe_bitmap, all);
349 350 351
	}
}

352
static struct pnv_ioda_pe *pnv_ioda_pick_m64_pe(struct pci_bus *bus, bool all)
353
{
354 355
	struct pci_controller *hose = pci_bus_to_host(bus);
	struct pnv_phb *phb = hose->private_data;
356 357
	struct pnv_ioda_pe *master_pe, *pe;
	unsigned long size, *pe_alloc;
358
	int i;
359 360 361

	/* Root bus shouldn't use M64 */
	if (pci_is_root_bus(bus))
362
		return NULL;
363 364

	/* Allocate bitmap */
365
	size = ALIGN(phb->ioda.total_pe_num / 8, sizeof(unsigned long));
366 367 368 369
	pe_alloc = kzalloc(size, GFP_KERNEL);
	if (!pe_alloc) {
		pr_warn("%s: Out of memory !\n",
			__func__);
370
		return NULL;
371 372
	}

373
	/* Figure out reserved PE numbers by the PE */
374
	pnv_ioda_reserve_m64_pe(bus, pe_alloc, all);
375 376 377 378 379 380

	/*
	 * the current bus might not own M64 window and that's all
	 * contributed by its child buses. For the case, we needn't
	 * pick M64 dependent PE#.
	 */
381
	if (bitmap_empty(pe_alloc, phb->ioda.total_pe_num)) {
382
		kfree(pe_alloc);
383
		return NULL;
384 385 386 387 388 389 390 391
	}

	/*
	 * Figure out the master PE and put all slave PEs to master
	 * PE's list to form compound PE.
	 */
	master_pe = NULL;
	i = -1;
392 393
	while ((i = find_next_bit(pe_alloc, phb->ioda.total_pe_num, i + 1)) <
		phb->ioda.total_pe_num) {
394 395
		pe = &phb->ioda.pe_array[i];

396
		phb->ioda.m64_segmap[pe->pe_number] = pe->pe_number;
397 398 399 400 401 402 403 404 405
		if (!master_pe) {
			pe->flags |= PNV_IODA_PE_MASTER;
			INIT_LIST_HEAD(&pe->slaves);
			master_pe = pe;
		} else {
			pe->flags |= PNV_IODA_PE_SLAVE;
			pe->master = master_pe;
			list_add_tail(&pe->list, &master_pe->slaves);
		}
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

		/*
		 * P7IOC supports M64DT, which helps mapping M64 segment
		 * to one particular PE#. However, PHB3 has fixed mapping
		 * between M64 segment and PE#. In order to have same logic
		 * for P7IOC and PHB3, we enforce fixed mapping between M64
		 * segment and PE# on P7IOC.
		 */
		if (phb->type == PNV_PHB_IODA1) {
			int64_t rc;

			rc = opal_pci_map_pe_mmio_window(phb->opal_id,
					pe->pe_number, OPAL_M64_WINDOW_TYPE,
					pe->pe_number / PNV_IODA1_M64_SEGS,
					pe->pe_number % PNV_IODA1_M64_SEGS);
			if (rc != OPAL_SUCCESS)
422
				pr_warn("%s: Error %lld mapping M64 for PHB#%x-PE#%x\n",
423 424 425
					__func__, rc, phb->hose->global_number,
					pe->pe_number);
		}
426 427 428
	}

	kfree(pe_alloc);
429
	return master_pe;
430 431 432 433 434 435 436
}

static void __init pnv_ioda_parse_m64_window(struct pnv_phb *phb)
{
	struct pci_controller *hose = phb->hose;
	struct device_node *dn = hose->dn;
	struct resource *res;
437
	u32 m64_range[2], i;
438
	const __be32 *r;
439 440
	u64 pci_addr;

441
	if (phb->type != PNV_PHB_IODA1 && phb->type != PNV_PHB_IODA2) {
442 443 444 445
		pr_info("  Not support M64 window\n");
		return;
	}

446
	if (!firmware_has_feature(FW_FEATURE_OPAL)) {
447 448 449 450 451 452
		pr_info("  Firmware too old to support M64 window\n");
		return;
	}

	r = of_get_property(dn, "ibm,opal-m64-window", NULL);
	if (!r) {
453 454
		pr_info("  No <ibm,opal-m64-window> on %pOF\n",
			dn);
455 456 457
		return;
	}

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
	/*
	 * Find the available M64 BAR range and pickup the last one for
	 * covering the whole 64-bits space. We support only one range.
	 */
	if (of_property_read_u32_array(dn, "ibm,opal-available-m64-ranges",
				       m64_range, 2)) {
		/* In absence of the property, assume 0..15 */
		m64_range[0] = 0;
		m64_range[1] = 16;
	}
	/* We only support 64 bits in our allocator */
	if (m64_range[1] > 63) {
		pr_warn("%s: Limiting M64 range to 63 (from %d) on PHB#%x\n",
			__func__, m64_range[1], phb->hose->global_number);
		m64_range[1] = 63;
	}
	/* Empty range, no m64 */
	if (m64_range[1] <= m64_range[0]) {
		pr_warn("%s: M64 empty, disabling M64 usage on PHB#%x\n",
			__func__, phb->hose->global_number);
		return;
	}

	/* Configure M64 informations */
482
	res = &hose->mem_resources[1];
483
	res->name = dn->full_name;
484 485 486 487 488 489 490
	res->start = of_translate_address(dn, r + 2);
	res->end = res->start + of_read_number(r + 4, 2) - 1;
	res->flags = (IORESOURCE_MEM | IORESOURCE_MEM_64 | IORESOURCE_PREFETCH);
	pci_addr = of_read_number(r, 2);
	hose->mem_offset[1] = res->start - pci_addr;

	phb->ioda.m64_size = resource_size(res);
491
	phb->ioda.m64_segsize = phb->ioda.m64_size / phb->ioda.total_pe_num;
492 493
	phb->ioda.m64_base = pci_addr;

494 495 496 497 498 499 500
	/* This lines up nicely with the display from processing OF ranges */
	pr_info(" MEM 0x%016llx..0x%016llx -> 0x%016llx (M64 #%d..%d)\n",
		res->start, res->end, pci_addr, m64_range[0],
		m64_range[0] + m64_range[1] - 1);

	/* Mark all M64 used up by default */
	phb->ioda.m64_bar_alloc = (unsigned long)-1;
501

502
	/* Use last M64 BAR to cover M64 window */
503 504 505 506 507 508 509 510 511 512 513 514 515
	m64_range[1]--;
	phb->ioda.m64_bar_idx = m64_range[0] + m64_range[1];

	pr_info(" Using M64 #%d as default window\n", phb->ioda.m64_bar_idx);

	/* Mark remaining ones free */
	for (i = m64_range[0]; i < m64_range[1]; i++)
		clear_bit(i, &phb->ioda.m64_bar_alloc);

	/*
	 * Setup init functions for M64 based on IODA version, IODA3 uses
	 * the IODA2 code.
	 */
516 517 518 519
	if (phb->type == PNV_PHB_IODA1)
		phb->init_m64 = pnv_ioda1_init_m64;
	else
		phb->init_m64 = pnv_ioda2_init_m64;
520 521
}

G
Gavin Shan 已提交
522 523 524 525 526 527 528 529 530
static void pnv_ioda_freeze_pe(struct pnv_phb *phb, int pe_no)
{
	struct pnv_ioda_pe *pe = &phb->ioda.pe_array[pe_no];
	struct pnv_ioda_pe *slave;
	s64 rc;

	/* Fetch master PE */
	if (pe->flags & PNV_IODA_PE_SLAVE) {
		pe = pe->master;
531 532 533
		if (WARN_ON(!pe || !(pe->flags & PNV_IODA_PE_MASTER)))
			return;

G
Gavin Shan 已提交
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
		pe_no = pe->pe_number;
	}

	/* Freeze master PE */
	rc = opal_pci_eeh_freeze_set(phb->opal_id,
				     pe_no,
				     OPAL_EEH_ACTION_SET_FREEZE_ALL);
	if (rc != OPAL_SUCCESS) {
		pr_warn("%s: Failure %lld freezing PHB#%x-PE#%x\n",
			__func__, rc, phb->hose->global_number, pe_no);
		return;
	}

	/* Freeze slave PEs */
	if (!(pe->flags & PNV_IODA_PE_MASTER))
		return;

	list_for_each_entry(slave, &pe->slaves, list) {
		rc = opal_pci_eeh_freeze_set(phb->opal_id,
					     slave->pe_number,
					     OPAL_EEH_ACTION_SET_FREEZE_ALL);
		if (rc != OPAL_SUCCESS)
			pr_warn("%s: Failure %lld freezing PHB#%x-PE#%x\n",
				__func__, rc, phb->hose->global_number,
				slave->pe_number);
	}
}

562
static int pnv_ioda_unfreeze_pe(struct pnv_phb *phb, int pe_no, int opt)
G
Gavin Shan 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
{
	struct pnv_ioda_pe *pe, *slave;
	s64 rc;

	/* Find master PE */
	pe = &phb->ioda.pe_array[pe_no];
	if (pe->flags & PNV_IODA_PE_SLAVE) {
		pe = pe->master;
		WARN_ON(!pe || !(pe->flags & PNV_IODA_PE_MASTER));
		pe_no = pe->pe_number;
	}

	/* Clear frozen state for master PE */
	rc = opal_pci_eeh_freeze_clear(phb->opal_id, pe_no, opt);
	if (rc != OPAL_SUCCESS) {
		pr_warn("%s: Failure %lld clear %d on PHB#%x-PE#%x\n",
			__func__, rc, opt, phb->hose->global_number, pe_no);
		return -EIO;
	}

	if (!(pe->flags & PNV_IODA_PE_MASTER))
		return 0;

	/* Clear frozen state for slave PEs */
	list_for_each_entry(slave, &pe->slaves, list) {
		rc = opal_pci_eeh_freeze_clear(phb->opal_id,
					     slave->pe_number,
					     opt);
		if (rc != OPAL_SUCCESS) {
			pr_warn("%s: Failure %lld clear %d on PHB#%x-PE#%x\n",
				__func__, rc, opt, phb->hose->global_number,
				slave->pe_number);
			return -EIO;
		}
	}

	return 0;
}

static int pnv_ioda_get_pe_state(struct pnv_phb *phb, int pe_no)
{
	struct pnv_ioda_pe *slave, *pe;
605 606
	u8 fstate = 0, state;
	__be16 pcierr = 0;
G
Gavin Shan 已提交
607 608 609
	s64 rc;

	/* Sanity check on PE number */
610
	if (pe_no < 0 || pe_no >= phb->ioda.total_pe_num)
G
Gavin Shan 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
		return OPAL_EEH_STOPPED_PERM_UNAVAIL;

	/*
	 * Fetch the master PE and the PE instance might be
	 * not initialized yet.
	 */
	pe = &phb->ioda.pe_array[pe_no];
	if (pe->flags & PNV_IODA_PE_SLAVE) {
		pe = pe->master;
		WARN_ON(!pe || !(pe->flags & PNV_IODA_PE_MASTER));
		pe_no = pe->pe_number;
	}

	/* Check the master PE */
	rc = opal_pci_eeh_freeze_status(phb->opal_id, pe_no,
					&state, &pcierr, NULL);
	if (rc != OPAL_SUCCESS) {
		pr_warn("%s: Failure %lld getting "
			"PHB#%x-PE#%x state\n",
			__func__, rc,
			phb->hose->global_number, pe_no);
		return OPAL_EEH_STOPPED_TEMP_UNAVAIL;
	}

	/* Check the slave PE */
	if (!(pe->flags & PNV_IODA_PE_MASTER))
		return state;

	list_for_each_entry(slave, &pe->slaves, list) {
		rc = opal_pci_eeh_freeze_status(phb->opal_id,
						slave->pe_number,
						&fstate,
						&pcierr,
						NULL);
		if (rc != OPAL_SUCCESS) {
			pr_warn("%s: Failure %lld getting "
				"PHB#%x-PE#%x state\n",
				__func__, rc,
				phb->hose->global_number, slave->pe_number);
			return OPAL_EEH_STOPPED_TEMP_UNAVAIL;
		}

		/*
		 * Override the result based on the ascending
		 * priority.
		 */
		if (fstate > state)
			state = fstate;
	}

	return state;
}

664 665 666 667 668 669 670 671 672 673
struct pnv_ioda_pe *pnv_pci_bdfn_to_pe(struct pnv_phb *phb, u16 bdfn)
{
	int pe_number = phb->ioda.pe_rmap[bdfn];

	if (pe_number == IODA_INVALID_PE)
		return NULL;

	return &phb->ioda.pe_array[pe_number];
}

674
struct pnv_ioda_pe *pnv_ioda_get_pe(struct pci_dev *dev)
675 676 677
{
	struct pci_controller *hose = pci_bus_to_host(dev->bus);
	struct pnv_phb *phb = hose->private_data;
678
	struct pci_dn *pdn = pci_get_pdn(dev);
679 680 681 682 683 684 685 686

	if (!pdn)
		return NULL;
	if (pdn->pe_number == IODA_INVALID_PE)
		return NULL;
	return &phb->ioda.pe_array[pdn->pe_number];
}

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
static int pnv_ioda_set_one_peltv(struct pnv_phb *phb,
				  struct pnv_ioda_pe *parent,
				  struct pnv_ioda_pe *child,
				  bool is_add)
{
	const char *desc = is_add ? "adding" : "removing";
	uint8_t op = is_add ? OPAL_ADD_PE_TO_DOMAIN :
			      OPAL_REMOVE_PE_FROM_DOMAIN;
	struct pnv_ioda_pe *slave;
	long rc;

	/* Parent PE affects child PE */
	rc = opal_pci_set_peltv(phb->opal_id, parent->pe_number,
				child->pe_number, op);
	if (rc != OPAL_SUCCESS) {
		pe_warn(child, "OPAL error %ld %s to parent PELTV\n",
			rc, desc);
		return -ENXIO;
	}

	if (!(child->flags & PNV_IODA_PE_MASTER))
		return 0;

	/* Compound case: parent PE affects slave PEs */
	list_for_each_entry(slave, &child->slaves, list) {
		rc = opal_pci_set_peltv(phb->opal_id, parent->pe_number,
					slave->pe_number, op);
		if (rc != OPAL_SUCCESS) {
			pe_warn(slave, "OPAL error %ld %s to parent PELTV\n",
				rc, desc);
			return -ENXIO;
		}
	}

	return 0;
}

static int pnv_ioda_set_peltv(struct pnv_phb *phb,
			      struct pnv_ioda_pe *pe,
			      bool is_add)
{
	struct pnv_ioda_pe *slave;
729
	struct pci_dev *pdev = NULL;
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
	int ret;

	/*
	 * Clear PE frozen state. If it's master PE, we need
	 * clear slave PE frozen state as well.
	 */
	if (is_add) {
		opal_pci_eeh_freeze_clear(phb->opal_id, pe->pe_number,
					  OPAL_EEH_ACTION_CLEAR_FREEZE_ALL);
		if (pe->flags & PNV_IODA_PE_MASTER) {
			list_for_each_entry(slave, &pe->slaves, list)
				opal_pci_eeh_freeze_clear(phb->opal_id,
							  slave->pe_number,
							  OPAL_EEH_ACTION_CLEAR_FREEZE_ALL);
		}
	}

	/*
	 * Associate PE in PELT. We need add the PE into the
	 * corresponding PELT-V as well. Otherwise, the error
	 * originated from the PE might contribute to other
	 * PEs.
	 */
	ret = pnv_ioda_set_one_peltv(phb, pe, pe, is_add);
	if (ret)
		return ret;

	/* For compound PEs, any one affects all of them */
	if (pe->flags & PNV_IODA_PE_MASTER) {
		list_for_each_entry(slave, &pe->slaves, list) {
			ret = pnv_ioda_set_one_peltv(phb, slave, pe, is_add);
			if (ret)
				return ret;
		}
	}

	if (pe->flags & (PNV_IODA_PE_BUS_ALL | PNV_IODA_PE_BUS))
		pdev = pe->pbus->self;
768
	else if (pe->flags & PNV_IODA_PE_DEV)
769
		pdev = pe->pdev->bus->self;
770 771
#ifdef CONFIG_PCI_IOV
	else if (pe->flags & PNV_IODA_PE_VF)
772
		pdev = pe->parent_dev;
773
#endif /* CONFIG_PCI_IOV */
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
	while (pdev) {
		struct pci_dn *pdn = pci_get_pdn(pdev);
		struct pnv_ioda_pe *parent;

		if (pdn && pdn->pe_number != IODA_INVALID_PE) {
			parent = &phb->ioda.pe_array[pdn->pe_number];
			ret = pnv_ioda_set_one_peltv(phb, parent, pe, is_add);
			if (ret)
				return ret;
		}

		pdev = pdev->bus->self;
	}

	return 0;
}

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
static void pnv_ioda_unset_peltv(struct pnv_phb *phb,
				 struct pnv_ioda_pe *pe,
				 struct pci_dev *parent)
{
	int64_t rc;

	while (parent) {
		struct pci_dn *pdn = pci_get_pdn(parent);

		if (pdn && pdn->pe_number != IODA_INVALID_PE) {
			rc = opal_pci_set_peltv(phb->opal_id, pdn->pe_number,
						pe->pe_number,
						OPAL_REMOVE_PE_FROM_DOMAIN);
			/* XXX What to do in case of error ? */
		}
		parent = parent->bus->self;
	}

	opal_pci_eeh_freeze_clear(phb->opal_id, pe->pe_number,
				  OPAL_EEH_ACTION_CLEAR_FREEZE_ALL);

	/* Disassociate PE in PELT */
	rc = opal_pci_set_peltv(phb->opal_id, pe->pe_number,
				pe->pe_number, OPAL_REMOVE_PE_FROM_DOMAIN);
	if (rc)
		pe_warn(pe, "OPAL error %lld remove self from PELTV\n", rc);
}

819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
static int pnv_ioda_deconfigure_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe)
{
	struct pci_dev *parent;
	uint8_t bcomp, dcomp, fcomp;
	int64_t rc;
	long rid_end, rid;

	/* Currently, we just deconfigure VF PE. Bus PE will always there.*/
	if (pe->pbus) {
		int count;

		dcomp = OPAL_IGNORE_RID_DEVICE_NUMBER;
		fcomp = OPAL_IGNORE_RID_FUNCTION_NUMBER;
		parent = pe->pbus->self;
		if (pe->flags & PNV_IODA_PE_BUS_ALL)
834
			count = resource_size(&pe->pbus->busn_res);
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
		else
			count = 1;

		switch(count) {
		case  1: bcomp = OpalPciBusAll;         break;
		case  2: bcomp = OpalPciBus7Bits;       break;
		case  4: bcomp = OpalPciBus6Bits;       break;
		case  8: bcomp = OpalPciBus5Bits;       break;
		case 16: bcomp = OpalPciBus4Bits;       break;
		case 32: bcomp = OpalPciBus3Bits;       break;
		default:
			dev_err(&pe->pbus->dev, "Number of subordinate buses %d unsupported\n",
			        count);
			/* Do an exact match only */
			bcomp = OpalPciBusAll;
		}
		rid_end = pe->rid + (count << 8);
	} else {
853
#ifdef CONFIG_PCI_IOV
854 855 856
		if (pe->flags & PNV_IODA_PE_VF)
			parent = pe->parent_dev;
		else
857
#endif
858 859 860 861 862 863 864 865 866
			parent = pe->pdev->bus->self;
		bcomp = OpalPciBusAll;
		dcomp = OPAL_COMPARE_RID_DEVICE_NUMBER;
		fcomp = OPAL_COMPARE_RID_FUNCTION_NUMBER;
		rid_end = pe->rid + 1;
	}

	/* Clear the reverse map */
	for (rid = pe->rid; rid < rid_end; rid++)
867
		phb->ioda.pe_rmap[rid] = IODA_INVALID_PE;
868

869 870 871 872 873 874
	/*
	 * Release from all parents PELT-V. NPUs don't have a PELTV
	 * table
	 */
	if (phb->type != PNV_PHB_NPU_NVLINK && phb->type != PNV_PHB_NPU_OCAPI)
		pnv_ioda_unset_peltv(phb, pe, parent);
875 876 877 878

	rc = opal_pci_set_pe(phb->opal_id, pe->pe_number, pe->rid,
			     bcomp, dcomp, fcomp, OPAL_UNMAP_PE);
	if (rc)
879
		pe_err(pe, "OPAL error %lld trying to setup PELT table\n", rc);
880 881 882

	pe->pbus = NULL;
	pe->pdev = NULL;
883
#ifdef CONFIG_PCI_IOV
884
	pe->parent_dev = NULL;
885
#endif
886 887 888 889

	return 0;
}

890
static int pnv_ioda_configure_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe)
891 892 893 894 895 896 897 898 899 900 901 902
{
	struct pci_dev *parent;
	uint8_t bcomp, dcomp, fcomp;
	long rc, rid_end, rid;

	/* Bus validation ? */
	if (pe->pbus) {
		int count;

		dcomp = OPAL_IGNORE_RID_DEVICE_NUMBER;
		fcomp = OPAL_IGNORE_RID_FUNCTION_NUMBER;
		parent = pe->pbus->self;
903
		if (pe->flags & PNV_IODA_PE_BUS_ALL)
904
			count = resource_size(&pe->pbus->busn_res);
905 906 907
		else
			count = 1;

908 909 910 911 912 913 914 915
		switch(count) {
		case  1: bcomp = OpalPciBusAll;		break;
		case  2: bcomp = OpalPciBus7Bits;	break;
		case  4: bcomp = OpalPciBus6Bits;	break;
		case  8: bcomp = OpalPciBus5Bits;	break;
		case 16: bcomp = OpalPciBus4Bits;	break;
		case 32: bcomp = OpalPciBus3Bits;	break;
		default:
916 917
			dev_err(&pe->pbus->dev, "Number of subordinate buses %d unsupported\n",
			        count);
918 919 920 921 922
			/* Do an exact match only */
			bcomp = OpalPciBusAll;
		}
		rid_end = pe->rid + (count << 8);
	} else {
923 924 925 926 927 928
#ifdef CONFIG_PCI_IOV
		if (pe->flags & PNV_IODA_PE_VF)
			parent = pe->parent_dev;
		else
#endif /* CONFIG_PCI_IOV */
			parent = pe->pdev->bus->self;
929 930 931 932 933 934
		bcomp = OpalPciBusAll;
		dcomp = OPAL_COMPARE_RID_DEVICE_NUMBER;
		fcomp = OPAL_COMPARE_RID_FUNCTION_NUMBER;
		rid_end = pe->rid + 1;
	}

935 936 937 938 939 940
	/*
	 * Associate PE in PELT. We need add the PE into the
	 * corresponding PELT-V as well. Otherwise, the error
	 * originated from the PE might contribute to other
	 * PEs.
	 */
941 942 943 944 945 946
	rc = opal_pci_set_pe(phb->opal_id, pe->pe_number, pe->rid,
			     bcomp, dcomp, fcomp, OPAL_MAP_PE);
	if (rc) {
		pe_err(pe, "OPAL error %ld trying to setup PELT table\n", rc);
		return -ENXIO;
	}
947

948 949 950 951
	/*
	 * Configure PELTV. NPUs don't have a PELTV table so skip
	 * configuration on them.
	 */
952
	if (phb->type != PNV_PHB_NPU_NVLINK && phb->type != PNV_PHB_NPU_OCAPI)
953
		pnv_ioda_set_peltv(phb, pe, true);
954 955 956 957 958 959

	/* Setup reverse map */
	for (rid = pe->rid; rid < rid_end; rid++)
		phb->ioda.pe_rmap[rid] = pe->pe_number;

	/* Setup one MVTs on IODA1 */
960 961 962 963 964 965 966 967
	if (phb->type != PNV_PHB_IODA1) {
		pe->mve_number = 0;
		goto out;
	}

	pe->mve_number = pe->pe_number;
	rc = opal_pci_set_mve(phb->opal_id, pe->mve_number, pe->pe_number);
	if (rc != OPAL_SUCCESS) {
968
		pe_err(pe, "OPAL error %ld setting up MVE %x\n",
969 970 971 972 973
		       rc, pe->mve_number);
		pe->mve_number = -1;
	} else {
		rc = opal_pci_set_mve_enable(phb->opal_id,
					     pe->mve_number, OPAL_ENABLE_MVE);
974
		if (rc) {
975
			pe_err(pe, "OPAL error %ld enabling MVE %x\n",
976 977 978
			       rc, pe->mve_number);
			pe->mve_number = -1;
		}
979
	}
980

981
out:
982 983 984
	return 0;
}

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
#ifdef CONFIG_PCI_IOV
static int pnv_pci_vf_resource_shift(struct pci_dev *dev, int offset)
{
	struct pci_dn *pdn = pci_get_pdn(dev);
	int i;
	struct resource *res, res2;
	resource_size_t size;
	u16 num_vfs;

	if (!dev->is_physfn)
		return -EINVAL;

	/*
	 * "offset" is in VFs.  The M64 windows are sized so that when they
	 * are segmented, each segment is the same size as the IOV BAR.
	 * Each segment is in a separate PE, and the high order bits of the
	 * address are the PE number.  Therefore, each VF's BAR is in a
	 * separate PE, and changing the IOV BAR start address changes the
	 * range of PEs the VFs are in.
	 */
	num_vfs = pdn->num_vfs;
	for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
		res = &dev->resource[i + PCI_IOV_RESOURCES];
		if (!res->flags || !res->parent)
			continue;

		/*
		 * The actual IOV BAR range is determined by the start address
		 * and the actual size for num_vfs VFs BAR.  This check is to
		 * make sure that after shifting, the range will not overlap
		 * with another device.
		 */
		size = pci_iov_resource_size(dev, i + PCI_IOV_RESOURCES);
		res2.flags = res->flags;
		res2.start = res->start + (size * offset);
		res2.end = res2.start + (size * num_vfs) - 1;

		if (res2.end > res->end) {
			dev_err(&dev->dev, "VF BAR%d: %pR would extend past %pR (trying to enable %d VFs shifted by %d)\n",
				i, &res2, res, num_vfs, offset);
			return -EBUSY;
		}
	}

	/*
1030 1031 1032 1033 1034 1035
	 * Since M64 BAR shares segments among all possible 256 PEs,
	 * we have to shift the beginning of PF IOV BAR to make it start from
	 * the segment which belongs to the PE number assigned to the first VF.
	 * This creates a "hole" in the /proc/iomem which could be used for
	 * allocating other resources so we reserve this area below and
	 * release when IOV is released.
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
	 */
	for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
		res = &dev->resource[i + PCI_IOV_RESOURCES];
		if (!res->flags || !res->parent)
			continue;

		size = pci_iov_resource_size(dev, i + PCI_IOV_RESOURCES);
		res2 = *res;
		res->start += size * offset;

1046 1047 1048
		dev_info(&dev->dev, "VF BAR%d: %pR shifted to %pR (%sabling %d VFs shifted by %d)\n",
			 i, &res2, res, (offset > 0) ? "En" : "Dis",
			 num_vfs, offset);
1049 1050 1051 1052 1053 1054

		if (offset < 0) {
			devm_release_resource(&dev->dev, &pdn->holes[i]);
			memset(&pdn->holes[i], 0, sizeof(pdn->holes[i]));
		}

1055
		pci_update_resource(dev, i + PCI_IOV_RESOURCES);
1056 1057 1058 1059 1060 1061 1062 1063 1064

		if (offset > 0) {
			pdn->holes[i].start = res2.start;
			pdn->holes[i].end = res2.start + size * offset - 1;
			pdn->holes[i].flags = IORESOURCE_BUS;
			pdn->holes[i].name = "pnv_iov_reserved";
			devm_request_resource(&dev->dev, res->parent,
					&pdn->holes[i]);
		}
1065 1066 1067 1068 1069
	}
	return 0;
}
#endif /* CONFIG_PCI_IOV */

1070
static struct pnv_ioda_pe *pnv_ioda_setup_dev_PE(struct pci_dev *dev)
1071 1072 1073
{
	struct pci_controller *hose = pci_bus_to_host(dev->bus);
	struct pnv_phb *phb = hose->private_data;
1074
	struct pci_dn *pdn = pci_get_pdn(dev);
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
	struct pnv_ioda_pe *pe;

	if (!pdn) {
		pr_err("%s: Device tree node not associated properly\n",
			   pci_name(dev));
		return NULL;
	}
	if (pdn->pe_number != IODA_INVALID_PE)
		return NULL;

1085 1086
	pe = pnv_ioda_alloc_pe(phb);
	if (!pe) {
1087 1088
		pr_warn("%s: Not enough PE# available, disabling device\n",
			pci_name(dev));
1089 1090 1091
		return NULL;
	}

1092 1093 1094 1095
	/* NOTE: We don't get a reference for the pointer in the PE
	 * data structure, both the device and PE structures should be
	 * destroyed at the same time. However, removing nvlink
	 * devices will need some work.
1096 1097 1098
	 *
	 * At some point we want to remove the PDN completely anyways
	 */
1099
	pdn->pe_number = pe->pe_number;
1100
	pe->flags = PNV_IODA_PE_DEV;
1101 1102 1103 1104
	pe->pdev = dev;
	pe->pbus = NULL;
	pe->mve_number = -1;
	pe->rid = dev->bus->number << 8 | pdn->devfn;
1105
	pe->device_count++;
1106 1107 1108 1109 1110

	pe_info(pe, "Associated device to PE\n");

	if (pnv_ioda_configure_pe(phb, pe)) {
		/* XXX What do we do here ? */
1111
		pnv_ioda_free_pe(pe);
1112 1113 1114 1115 1116
		pdn->pe_number = IODA_INVALID_PE;
		pe->pdev = NULL;
		return NULL;
	}

1117
	/* Put PE to the list */
1118
	mutex_lock(&phb->ioda.pe_list_mutex);
1119
	list_add_tail(&pe->list, &phb->ioda.pe_list);
1120
	mutex_unlock(&phb->ioda.pe_list_mutex);
1121 1122 1123
	return pe;
}

1124 1125 1126 1127 1128 1129
/*
 * There're 2 types of PCI bus sensitive PEs: One that is compromised of
 * single PCI bus. Another one that contains the primary PCI bus and its
 * subordinate PCI devices and buses. The second type of PE is normally
 * orgiriated by PCIe-to-PCI bridge or PLX switch downstream ports.
 */
1130
static struct pnv_ioda_pe *pnv_ioda_setup_bus_PE(struct pci_bus *bus, bool all)
1131
{
1132
	struct pci_controller *hose = pci_bus_to_host(bus);
1133
	struct pnv_phb *phb = hose->private_data;
1134
	struct pnv_ioda_pe *pe = NULL;
1135 1136 1137 1138 1139 1140 1141
	unsigned int pe_num;

	/*
	 * In partial hotplug case, the PE instance might be still alive.
	 * We should reuse it instead of allocating a new one.
	 */
	pe_num = phb->ioda.pe_rmap[bus->number << 8];
1142
	if (WARN_ON(pe_num != IODA_INVALID_PE)) {
1143 1144 1145
		pe = &phb->ioda.pe_array[pe_num];
		return NULL;
	}
1146

1147
	/* PE number for root bus should have been reserved */
1148
	if (pci_is_root_bus(bus))
1149 1150
		pe = &phb->ioda.pe_array[phb->ioda.root_pe_idx];

1151
	/* Check if PE is determined by M64 */
1152 1153
	if (!pe)
		pe = pnv_ioda_pick_m64_pe(bus, all);
1154 1155

	/* The PE number isn't pinned by M64 */
1156 1157
	if (!pe)
		pe = pnv_ioda_alloc_pe(phb);
1158

1159
	if (!pe) {
1160
		pr_warn("%s: Not enough PE# available for PCI bus %04x:%02x\n",
1161
			__func__, pci_domain_nr(bus), bus->number);
1162
		return NULL;
1163 1164
	}

1165
	pe->flags |= (all ? PNV_IODA_PE_BUS_ALL : PNV_IODA_PE_BUS);
1166 1167 1168
	pe->pbus = bus;
	pe->pdev = NULL;
	pe->mve_number = -1;
1169
	pe->rid = bus->busn_res.start << 8;
1170

1171
	if (all)
1172 1173 1174
		pe_info(pe, "Secondary bus %pad..%pad associated with PE#%x\n",
			&bus->busn_res.start, &bus->busn_res.end,
			pe->pe_number);
1175
	else
1176 1177
		pe_info(pe, "Secondary bus %pad associated with PE#%x\n",
			&bus->busn_res.start, pe->pe_number);
1178 1179 1180

	if (pnv_ioda_configure_pe(phb, pe)) {
		/* XXX What do we do here ? */
1181
		pnv_ioda_free_pe(pe);
1182
		pe->pbus = NULL;
1183
		return NULL;
1184 1185
	}

1186 1187
	/* Put PE to the list */
	list_add_tail(&pe->list, &phb->ioda.pe_list);
1188 1189

	return pe;
1190 1191
}

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
static struct pnv_ioda_pe *pnv_ioda_setup_npu_PE(struct pci_dev *npu_pdev)
{
	int pe_num, found_pe = false, rc;
	long rid;
	struct pnv_ioda_pe *pe;
	struct pci_dev *gpu_pdev;
	struct pci_dn *npu_pdn;
	struct pci_controller *hose = pci_bus_to_host(npu_pdev->bus);
	struct pnv_phb *phb = hose->private_data;

1202 1203 1204 1205 1206 1207 1208 1209
	/*
	 * Intentionally leak a reference on the npu device (for
	 * nvlink only; this is not an opencapi path) to make sure it
	 * never goes away, as it's been the case all along and some
	 * work is needed otherwise.
	 */
	pci_dev_get(npu_pdev);

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
	/*
	 * Due to a hardware errata PE#0 on the NPU is reserved for
	 * error handling. This means we only have three PEs remaining
	 * which need to be assigned to four links, implying some
	 * links must share PEs.
	 *
	 * To achieve this we assign PEs such that NPUs linking the
	 * same GPU get assigned the same PE.
	 */
	gpu_pdev = pnv_pci_get_gpu_dev(npu_pdev);
1220
	for (pe_num = 0; pe_num < phb->ioda.total_pe_num; pe_num++) {
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
		pe = &phb->ioda.pe_array[pe_num];
		if (!pe->pdev)
			continue;

		if (pnv_pci_get_gpu_dev(pe->pdev) == gpu_pdev) {
			/*
			 * This device has the same peer GPU so should
			 * be assigned the same PE as the existing
			 * peer NPU.
			 */
			dev_info(&npu_pdev->dev,
1232
				"Associating to existing PE %x\n", pe_num);
1233 1234 1235 1236
			npu_pdn = pci_get_pdn(npu_pdev);
			rid = npu_pdev->bus->number << 8 | npu_pdn->devfn;
			npu_pdn->pe_number = pe_num;
			phb->ioda.pe_rmap[rid] = pe->pe_number;
1237
			pe->device_count++;
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261

			/* Map the PE to this link */
			rc = opal_pci_set_pe(phb->opal_id, pe_num, rid,
					OpalPciBusAll,
					OPAL_COMPARE_RID_DEVICE_NUMBER,
					OPAL_COMPARE_RID_FUNCTION_NUMBER,
					OPAL_MAP_PE);
			WARN_ON(rc != OPAL_SUCCESS);
			found_pe = true;
			break;
		}
	}

	if (!found_pe)
		/*
		 * Could not find an existing PE so allocate a new
		 * one.
		 */
		return pnv_ioda_setup_dev_PE(npu_pdev);
	else
		return pe;
}

static void pnv_ioda_setup_npu_PEs(struct pci_bus *bus)
1262 1263 1264 1265
{
	struct pci_dev *pdev;

	list_for_each_entry(pdev, &bus->devices, bus_list)
1266
		pnv_ioda_setup_npu_PE(pdev);
1267 1268
}

1269
static void pnv_pci_ioda_setup_nvlink(void)
1270
{
1271
	struct pci_controller *hose;
1272
	struct pnv_phb *phb;
1273
	struct pnv_ioda_pe *pe;
1274

1275
	list_for_each_entry(hose, &hose_list, list_node) {
1276
		phb = hose->private_data;
1277
		if (phb->type == PNV_PHB_NPU_NVLINK) {
1278 1279
			/* PE#0 is needed for error reporting */
			pnv_ioda_reserve_pe(phb, 0);
1280
			pnv_ioda_setup_npu_PEs(hose->bus);
1281
			if (phb->model == PNV_PHB_MODEL_NPU2)
1282
				WARN_ON_ONCE(pnv_npu2_init(hose));
1283
		}
1284
	}
1285 1286 1287 1288 1289 1290 1291 1292
	list_for_each_entry(hose, &hose_list, list_node) {
		phb = hose->private_data;
		if (phb->type != PNV_PHB_IODA2)
			continue;

		list_for_each_entry(pe, &phb->ioda.pe_list, list)
			pnv_npu2_map_lpar(pe, MSR_DR | MSR_PR | MSR_HV);
	}
1293 1294 1295 1296 1297

#ifdef CONFIG_IOMMU_API
	/* setup iommu groups so we can do nvlink pass-thru */
	pnv_pci_npu_setup_iommu_groups();
#endif
1298 1299
}

G
Gavin Shan 已提交
1300
#ifdef CONFIG_PCI_IOV
1301
static int pnv_pci_vf_release_m64(struct pci_dev *pdev, u16 num_vfs)
1302 1303 1304 1305 1306
{
	struct pci_bus        *bus;
	struct pci_controller *hose;
	struct pnv_phb        *phb;
	struct pci_dn         *pdn;
1307
	int                    i, j;
1308
	int                    m64_bars;
1309 1310 1311 1312 1313 1314

	bus = pdev->bus;
	hose = pci_bus_to_host(bus);
	phb = hose->private_data;
	pdn = pci_get_pdn(pdev);

1315 1316 1317 1318 1319
	if (pdn->m64_single_mode)
		m64_bars = num_vfs;
	else
		m64_bars = 1;

1320
	for (i = 0; i < PCI_SRIOV_NUM_BARS; i++)
1321 1322
		for (j = 0; j < m64_bars; j++) {
			if (pdn->m64_map[j][i] == IODA_INVALID_M64)
1323 1324
				continue;
			opal_pci_phb_mmio_enable(phb->opal_id,
1325 1326 1327
				OPAL_M64_WINDOW_TYPE, pdn->m64_map[j][i], 0);
			clear_bit(pdn->m64_map[j][i], &phb->ioda.m64_bar_alloc);
			pdn->m64_map[j][i] = IODA_INVALID_M64;
1328
		}
1329

1330
	kfree(pdn->m64_map);
1331 1332 1333
	return 0;
}

1334
static int pnv_pci_vf_assign_m64(struct pci_dev *pdev, u16 num_vfs)
1335 1336 1337 1338 1339 1340 1341
{
	struct pci_bus        *bus;
	struct pci_controller *hose;
	struct pnv_phb        *phb;
	struct pci_dn         *pdn;
	unsigned int           win;
	struct resource       *res;
1342
	int                    i, j;
1343
	int64_t                rc;
1344 1345 1346
	int                    total_vfs;
	resource_size_t        size, start;
	int                    pe_num;
1347
	int                    m64_bars;
1348 1349 1350 1351 1352

	bus = pdev->bus;
	hose = pci_bus_to_host(bus);
	phb = hose->private_data;
	pdn = pci_get_pdn(pdev);
1353
	total_vfs = pci_sriov_get_totalvfs(pdev);
1354

1355 1356 1357 1358 1359
	if (pdn->m64_single_mode)
		m64_bars = num_vfs;
	else
		m64_bars = 1;

1360 1361 1362
	pdn->m64_map = kmalloc_array(m64_bars,
				     sizeof(*pdn->m64_map),
				     GFP_KERNEL);
1363 1364 1365 1366 1367 1368
	if (!pdn->m64_map)
		return -ENOMEM;
	/* Initialize the m64_map to IODA_INVALID_M64 */
	for (i = 0; i < m64_bars ; i++)
		for (j = 0; j < PCI_SRIOV_NUM_BARS; j++)
			pdn->m64_map[i][j] = IODA_INVALID_M64;
1369

1370 1371 1372 1373 1374 1375

	for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
		res = &pdev->resource[i + PCI_IOV_RESOURCES];
		if (!res->flags || !res->parent)
			continue;

1376
		for (j = 0; j < m64_bars; j++) {
1377 1378 1379 1380 1381 1382 1383 1384
			do {
				win = find_next_zero_bit(&phb->ioda.m64_bar_alloc,
						phb->ioda.m64_bar_idx + 1, 0);

				if (win >= phb->ioda.m64_bar_idx + 1)
					goto m64_failed;
			} while (test_and_set_bit(win, &phb->ioda.m64_bar_alloc));

1385
			pdn->m64_map[j][i] = win;
1386

1387
			if (pdn->m64_single_mode) {
1388 1389 1390 1391 1392 1393 1394 1395 1396
				size = pci_iov_resource_size(pdev,
							PCI_IOV_RESOURCES + i);
				start = res->start + size * j;
			} else {
				size = resource_size(res);
				start = res->start;
			}

			/* Map the M64 here */
1397
			if (pdn->m64_single_mode) {
1398
				pe_num = pdn->pe_num_map[j];
1399 1400
				rc = opal_pci_map_pe_mmio_window(phb->opal_id,
						pe_num, OPAL_M64_WINDOW_TYPE,
1401
						pdn->m64_map[j][i], 0);
1402 1403 1404 1405
			}

			rc = opal_pci_set_phb_mem_window(phb->opal_id,
						 OPAL_M64_WINDOW_TYPE,
1406
						 pdn->m64_map[j][i],
1407 1408 1409
						 start,
						 0, /* unused */
						 size);
1410 1411


1412 1413 1414 1415 1416
			if (rc != OPAL_SUCCESS) {
				dev_err(&pdev->dev, "Failed to map M64 window #%d: %lld\n",
					win, rc);
				goto m64_failed;
			}
1417

1418
			if (pdn->m64_single_mode)
1419
				rc = opal_pci_phb_mmio_enable(phb->opal_id,
1420
				     OPAL_M64_WINDOW_TYPE, pdn->m64_map[j][i], 2);
1421 1422
			else
				rc = opal_pci_phb_mmio_enable(phb->opal_id,
1423
				     OPAL_M64_WINDOW_TYPE, pdn->m64_map[j][i], 1);
1424

1425 1426 1427 1428 1429
			if (rc != OPAL_SUCCESS) {
				dev_err(&pdev->dev, "Failed to enable M64 window #%d: %llx\n",
					win, rc);
				goto m64_failed;
			}
1430 1431 1432 1433 1434
		}
	}
	return 0;

m64_failed:
1435
	pnv_pci_vf_release_m64(pdev, num_vfs);
1436 1437 1438
	return -EBUSY;
}

1439 1440 1441
static long pnv_pci_ioda2_unset_window(struct iommu_table_group *table_group,
		int num);

1442 1443 1444 1445 1446
static void pnv_pci_ioda2_release_dma_pe(struct pci_dev *dev, struct pnv_ioda_pe *pe)
{
	struct iommu_table    *tbl;
	int64_t               rc;

1447
	tbl = pe->table_group.tables[0];
1448
	rc = pnv_pci_ioda2_unset_window(&pe->table_group, 0);
1449
	if (rc)
1450
		pe_warn(pe, "OPAL error %lld release DMA window\n", rc);
1451

1452
	pnv_pci_ioda2_set_bypass(pe, false);
1453 1454 1455
	if (pe->table_group.group) {
		iommu_group_put(pe->table_group.group);
		BUG_ON(pe->table_group.group);
1456
	}
1457
	iommu_tce_table_put(tbl);
1458 1459
}

1460
static void pnv_ioda_release_vf_PE(struct pci_dev *pdev)
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
{
	struct pci_bus        *bus;
	struct pci_controller *hose;
	struct pnv_phb        *phb;
	struct pnv_ioda_pe    *pe, *pe_n;
	struct pci_dn         *pdn;

	bus = pdev->bus;
	hose = pci_bus_to_host(bus);
	phb = hose->private_data;
1471
	pdn = pci_get_pdn(pdev);
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488

	if (!pdev->is_physfn)
		return;

	list_for_each_entry_safe(pe, pe_n, &phb->ioda.pe_list, list) {
		if (pe->parent_dev != pdev)
			continue;

		pnv_pci_ioda2_release_dma_pe(pdev, pe);

		/* Remove from list */
		mutex_lock(&phb->ioda.pe_list_mutex);
		list_del(&pe->list);
		mutex_unlock(&phb->ioda.pe_list_mutex);

		pnv_ioda_deconfigure_pe(phb, pe);

1489
		pnv_ioda_free_pe(pe);
1490 1491 1492 1493 1494 1495 1496 1497
	}
}

void pnv_pci_sriov_disable(struct pci_dev *pdev)
{
	struct pci_bus        *bus;
	struct pci_controller *hose;
	struct pnv_phb        *phb;
1498
	struct pnv_ioda_pe    *pe;
1499
	struct pci_dn         *pdn;
1500
	u16                    num_vfs, i;
1501 1502 1503 1504 1505 1506 1507 1508

	bus = pdev->bus;
	hose = pci_bus_to_host(bus);
	phb = hose->private_data;
	pdn = pci_get_pdn(pdev);
	num_vfs = pdn->num_vfs;

	/* Release VF PEs */
1509
	pnv_ioda_release_vf_PE(pdev);
1510 1511

	if (phb->type == PNV_PHB_IODA2) {
1512
		if (!pdn->m64_single_mode)
1513
			pnv_pci_vf_resource_shift(pdev, -*pdn->pe_num_map);
1514 1515

		/* Release M64 windows */
1516
		pnv_pci_vf_release_m64(pdev, num_vfs);
1517 1518

		/* Release PE numbers */
1519 1520
		if (pdn->m64_single_mode) {
			for (i = 0; i < num_vfs; i++) {
1521 1522 1523 1524 1525
				if (pdn->pe_num_map[i] == IODA_INVALID_PE)
					continue;

				pe = &phb->ioda.pe_array[pdn->pe_num_map[i]];
				pnv_ioda_free_pe(pe);
1526 1527 1528 1529 1530
			}
		} else
			bitmap_clear(phb->ioda.pe_alloc, *pdn->pe_num_map, num_vfs);
		/* Releasing pe_num_map */
		kfree(pdn->pe_num_map);
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
	}
}

static void pnv_pci_ioda2_setup_dma_pe(struct pnv_phb *phb,
				       struct pnv_ioda_pe *pe);
static void pnv_ioda_setup_vf_PE(struct pci_dev *pdev, u16 num_vfs)
{
	struct pci_bus        *bus;
	struct pci_controller *hose;
	struct pnv_phb        *phb;
	struct pnv_ioda_pe    *pe;
	int                    pe_num;
	u16                    vf_index;
	struct pci_dn         *pdn;

	bus = pdev->bus;
	hose = pci_bus_to_host(bus);
	phb = hose->private_data;
	pdn = pci_get_pdn(pdev);

	if (!pdev->is_physfn)
		return;

	/* Reserve PE for each VF */
	for (vf_index = 0; vf_index < num_vfs; vf_index++) {
1556 1557 1558 1559
		int vf_devfn = pci_iov_virtfn_devfn(pdev, vf_index);
		int vf_bus = pci_iov_virtfn_bus(pdev, vf_index);
		struct pci_dn *vf_pdn;

1560 1561 1562 1563
		if (pdn->m64_single_mode)
			pe_num = pdn->pe_num_map[vf_index];
		else
			pe_num = *pdn->pe_num_map + vf_index;
1564 1565 1566 1567 1568 1569 1570 1571

		pe = &phb->ioda.pe_array[pe_num];
		pe->pe_number = pe_num;
		pe->phb = phb;
		pe->flags = PNV_IODA_PE_VF;
		pe->pbus = NULL;
		pe->parent_dev = pdev;
		pe->mve_number = -1;
1572
		pe->rid = (vf_bus << 8) | vf_devfn;
1573

1574
		pe_info(pe, "VF %04d:%02d:%02d.%d associated with PE#%x\n",
1575
			hose->global_number, pdev->bus->number,
1576
			PCI_SLOT(vf_devfn), PCI_FUNC(vf_devfn), pe_num);
1577 1578 1579

		if (pnv_ioda_configure_pe(phb, pe)) {
			/* XXX What do we do here ? */
1580
			pnv_ioda_free_pe(pe);
1581 1582 1583 1584 1585 1586 1587 1588 1589
			pe->pdev = NULL;
			continue;
		}

		/* Put PE to the list */
		mutex_lock(&phb->ioda.pe_list_mutex);
		list_add_tail(&pe->list, &phb->ioda.pe_list);
		mutex_unlock(&phb->ioda.pe_list_mutex);

1590 1591 1592 1593 1594 1595 1596 1597 1598
		/* associate this pe to it's pdn */
		list_for_each_entry(vf_pdn, &pdn->parent->child_list, list) {
			if (vf_pdn->busno == vf_bus &&
			    vf_pdn->devfn == vf_devfn) {
				vf_pdn->pe_number = pe_num;
				break;
			}
		}

1599 1600 1601 1602 1603 1604 1605 1606 1607
		pnv_pci_ioda2_setup_dma_pe(phb, pe);
	}
}

int pnv_pci_sriov_enable(struct pci_dev *pdev, u16 num_vfs)
{
	struct pci_bus        *bus;
	struct pci_controller *hose;
	struct pnv_phb        *phb;
1608
	struct pnv_ioda_pe    *pe;
1609 1610
	struct pci_dn         *pdn;
	int                    ret;
1611
	u16                    i;
1612 1613 1614 1615 1616 1617 1618

	bus = pdev->bus;
	hose = pci_bus_to_host(bus);
	phb = hose->private_data;
	pdn = pci_get_pdn(pdev);

	if (phb->type == PNV_PHB_IODA2) {
1619 1620 1621 1622 1623 1624
		if (!pdn->vfs_expanded) {
			dev_info(&pdev->dev, "don't support this SRIOV device"
				" with non 64bit-prefetchable IOV BAR\n");
			return -ENOSPC;
		}

1625 1626 1627 1628 1629 1630 1631 1632 1633
		/*
		 * When M64 BARs functions in Single PE mode, the number of VFs
		 * could be enabled must be less than the number of M64 BARs.
		 */
		if (pdn->m64_single_mode && num_vfs > phb->ioda.m64_bar_idx) {
			dev_info(&pdev->dev, "Not enough M64 BAR for VFs\n");
			return -EBUSY;
		}

1634 1635
		/* Allocating pe_num_map */
		if (pdn->m64_single_mode)
1636 1637 1638
			pdn->pe_num_map = kmalloc_array(num_vfs,
							sizeof(*pdn->pe_num_map),
							GFP_KERNEL);
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
		else
			pdn->pe_num_map = kmalloc(sizeof(*pdn->pe_num_map), GFP_KERNEL);

		if (!pdn->pe_num_map)
			return -ENOMEM;

		if (pdn->m64_single_mode)
			for (i = 0; i < num_vfs; i++)
				pdn->pe_num_map[i] = IODA_INVALID_PE;

1649
		/* Calculate available PE for required VFs */
1650 1651
		if (pdn->m64_single_mode) {
			for (i = 0; i < num_vfs; i++) {
1652 1653
				pe = pnv_ioda_alloc_pe(phb);
				if (!pe) {
1654 1655 1656
					ret = -EBUSY;
					goto m64_failed;
				}
1657 1658

				pdn->pe_num_map[i] = pe->pe_number;
1659 1660 1661 1662
			}
		} else {
			mutex_lock(&phb->ioda.pe_alloc_mutex);
			*pdn->pe_num_map = bitmap_find_next_zero_area(
1663
				phb->ioda.pe_alloc, phb->ioda.total_pe_num,
1664
				0, num_vfs, 0);
1665
			if (*pdn->pe_num_map >= phb->ioda.total_pe_num) {
1666 1667 1668 1669 1670 1671
				mutex_unlock(&phb->ioda.pe_alloc_mutex);
				dev_info(&pdev->dev, "Failed to enable VF%d\n", num_vfs);
				kfree(pdn->pe_num_map);
				return -EBUSY;
			}
			bitmap_set(phb->ioda.pe_alloc, *pdn->pe_num_map, num_vfs);
1672 1673 1674 1675 1676
			mutex_unlock(&phb->ioda.pe_alloc_mutex);
		}
		pdn->num_vfs = num_vfs;

		/* Assign M64 window accordingly */
1677
		ret = pnv_pci_vf_assign_m64(pdev, num_vfs);
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
		if (ret) {
			dev_info(&pdev->dev, "Not enough M64 window resources\n");
			goto m64_failed;
		}

		/*
		 * When using one M64 BAR to map one IOV BAR, we need to shift
		 * the IOV BAR according to the PE# allocated to the VFs.
		 * Otherwise, the PE# for the VF will conflict with others.
		 */
1688
		if (!pdn->m64_single_mode) {
1689
			ret = pnv_pci_vf_resource_shift(pdev, *pdn->pe_num_map);
1690 1691 1692
			if (ret)
				goto m64_failed;
		}
1693 1694 1695 1696 1697 1698 1699 1700
	}

	/* Setup VF PEs */
	pnv_ioda_setup_vf_PE(pdev, num_vfs);

	return 0;

m64_failed:
1701 1702
	if (pdn->m64_single_mode) {
		for (i = 0; i < num_vfs; i++) {
1703 1704 1705 1706 1707
			if (pdn->pe_num_map[i] == IODA_INVALID_PE)
				continue;

			pe = &phb->ioda.pe_array[pdn->pe_num_map[i]];
			pnv_ioda_free_pe(pe);
1708 1709 1710 1711 1712 1713
		}
	} else
		bitmap_clear(phb->ioda.pe_alloc, *pdn->pe_num_map, num_vfs);

	/* Releasing pe_num_map */
	kfree(pdn->pe_num_map);
1714 1715 1716 1717

	return ret;
}

B
Bryant G. Ly 已提交
1718
int pnv_pcibios_sriov_disable(struct pci_dev *pdev)
G
Gavin Shan 已提交
1719
{
1720 1721
	pnv_pci_sriov_disable(pdev);

G
Gavin Shan 已提交
1722
	/* Release PCI data */
1723
	remove_sriov_vf_pdns(pdev);
G
Gavin Shan 已提交
1724 1725 1726
	return 0;
}

B
Bryant G. Ly 已提交
1727
int pnv_pcibios_sriov_enable(struct pci_dev *pdev, u16 num_vfs)
G
Gavin Shan 已提交
1728 1729
{
	/* Allocate PCI data */
1730
	add_sriov_vf_pdns(pdev);
1731

1732
	return pnv_pci_sriov_enable(pdev, num_vfs);
G
Gavin Shan 已提交
1733 1734 1735
}
#endif /* CONFIG_PCI_IOV */

1736
static void pnv_pci_ioda_dma_dev_setup(struct pci_dev *pdev)
1737
{
1738 1739
	struct pci_controller *hose = pci_bus_to_host(pdev->bus);
	struct pnv_phb *phb = hose->private_data;
1740
	struct pci_dn *pdn = pci_get_pdn(pdev);
1741
	struct pnv_ioda_pe *pe;
1742

1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
	/* Check if the BDFN for this device is associated with a PE yet */
	pe = pnv_pci_bdfn_to_pe(phb, pdev->devfn | (pdev->bus->number << 8));
	if (!pe) {
		/* VF PEs should be pre-configured in pnv_pci_sriov_enable() */
		if (WARN_ON(pdev->is_virtfn))
			return;

		pnv_pci_configure_bus(pdev->bus);
		pe = pnv_pci_bdfn_to_pe(phb, pdev->devfn | (pdev->bus->number << 8));
		pci_info(pdev, "Configured PE#%x\n", pe ? pe->pe_number : 0xfffff);


		/*
		 * If we can't setup the IODA PE something has gone horribly
		 * wrong and we can't enable DMA for the device.
		 */
		if (WARN_ON(!pe))
			return;
	} else {
		pci_info(pdev, "Added to existing PE#%x\n", pe->pe_number);
	}

	if (pdn)
		pdn->pe_number = pe->pe_number;
	pe->device_count++;
1768

1769
	WARN_ON(get_dma_ops(&pdev->dev) != &dma_iommu_ops);
1770
	pdev->dev.archdata.dma_offset = pe->tce_bypass_base;
1771
	set_iommu_table_base(&pdev->dev, pe->table_group.tables[0]);
1772 1773 1774 1775

	/* PEs with a DMA weight of zero won't have a group */
	if (pe->table_group.group)
		iommu_add_device(&pe->table_group, &pdev->dev);
1776 1777
}

1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
/*
 * Reconfigure TVE#0 to be usable as 64-bit DMA space.
 *
 * The first 4GB of virtual memory for a PE is reserved for 32-bit accesses.
 * Devices can only access more than that if bit 59 of the PCI address is set
 * by hardware, which indicates TVE#1 should be used instead of TVE#0.
 * Many PCI devices are not capable of addressing that many bits, and as a
 * result are limited to the 4GB of virtual memory made available to 32-bit
 * devices in TVE#0.
 *
 * In order to work around this, reconfigure TVE#0 to be suitable for 64-bit
 * devices by configuring the virtual memory past the first 4GB inaccessible
 * by 64-bit DMAs.  This should only be used by devices that want more than
 * 4GB, and only on PEs that have no 32-bit devices.
 *
 * Currently this will only work on PHB3 (POWER8).
 */
static int pnv_pci_ioda_dma_64bit_bypass(struct pnv_ioda_pe *pe)
{
	u64 window_size, table_size, tce_count, addr;
	struct page *table_pages;
	u64 tce_order = 28; /* 256MB TCEs */
	__be64 *tces;
	s64 rc;

	/*
	 * Window size needs to be a power of two, but needs to account for
	 * shifting memory by the 4GB offset required to skip 32bit space.
	 */
	window_size = roundup_pow_of_two(memory_hotplug_max() + (1ULL << 32));
	tce_count = window_size >> tce_order;
	table_size = tce_count << 3;

	if (table_size < PAGE_SIZE)
		table_size = PAGE_SIZE;

	table_pages = alloc_pages_node(pe->phb->hose->node, GFP_KERNEL,
				       get_order(table_size));
	if (!table_pages)
		goto err;

	tces = page_address(table_pages);
	if (!tces)
		goto err;

	memset(tces, 0, table_size);

	for (addr = 0; addr < memory_hotplug_max(); addr += (1 << tce_order)) {
		tces[(addr + (1ULL << 32)) >> tce_order] =
			cpu_to_be64(addr | TCE_PCI_READ | TCE_PCI_WRITE);
	}

	rc = opal_pci_map_pe_dma_window(pe->phb->opal_id,
					pe->pe_number,
					/* reconfigure window 0 */
					(pe->pe_number << 1) + 0,
					1,
					__pa(tces),
					table_size,
					1 << tce_order);
	if (rc == OPAL_SUCCESS) {
		pe_info(pe, "Using 64-bit DMA iommu bypass (through TVE#0)\n");
		return 0;
	}
err:
	pe_err(pe, "Error configuring 64-bit DMA bypass\n");
	return -EIO;
}

1847 1848
static bool pnv_pci_ioda_iommu_bypass_supported(struct pci_dev *pdev,
		u64 dma_mask)
1849
{
1850 1851
	struct pci_controller *hose = pci_bus_to_host(pdev->bus);
	struct pnv_phb *phb = hose->private_data;
1852 1853 1854 1855
	struct pci_dn *pdn = pci_get_pdn(pdev);
	struct pnv_ioda_pe *pe;

	if (WARN_ON(!pdn || pdn->pe_number == IODA_INVALID_PE))
1856
		return false;
1857 1858 1859

	pe = &phb->ioda.pe_array[pdn->pe_number];
	if (pe->tce_bypass_enabled) {
1860 1861 1862
		u64 top = pe->tce_bypass_base + memblock_end_of_DRAM() - 1;
		if (dma_mask >= top)
			return true;
1863 1864
	}

1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
	/*
	 * If the device can't set the TCE bypass bit but still wants
	 * to access 4GB or more, on PHB3 we can reconfigure TVE#0 to
	 * bypass the 32-bit region and be usable for 64-bit DMAs.
	 * The device needs to be able to address all of this space.
	 */
	if (dma_mask >> 32 &&
	    dma_mask > (memory_hotplug_max() + (1ULL << 32)) &&
	    /* pe->pdev should be set if it's a single device, pe->pbus if not */
	    (pe->device_count == 1 || !pe->pbus) &&
	    phb->model == PNV_PHB_MODEL_PHB3) {
		/* Configure the bypass mode */
		s64 rc = pnv_pci_ioda_dma_64bit_bypass(pe);
		if (rc)
1879
			return false;
1880
		/* 4GB offset bypasses 32-bit space */
1881
		pdev->dev.archdata.dma_offset = (1ULL << 32);
1882
		return true;
1883
	}
1884

1885
	return false;
1886 1887
}

1888
static void pnv_ioda_setup_bus_dma(struct pnv_ioda_pe *pe, struct pci_bus *bus)
1889 1890 1891 1892
{
	struct pci_dev *dev;

	list_for_each_entry(dev, &bus->devices, bus_list) {
1893
		set_iommu_table_base(&dev->dev, pe->table_group.tables[0]);
1894
		dev->dev.archdata.dma_offset = pe->tce_bypass_base;
1895

1896
		if ((pe->flags & PNV_IODA_PE_BUS_ALL) && dev->subordinate)
1897
			pnv_ioda_setup_bus_dma(pe, dev->subordinate);
1898 1899 1900
	}
}

1901 1902 1903 1904 1905 1906 1907
static inline __be64 __iomem *pnv_ioda_get_inval_reg(struct pnv_phb *phb,
						     bool real_mode)
{
	return real_mode ? (__be64 __iomem *)(phb->regs_phys + 0x210) :
		(phb->regs + 0x210);
}

1908
static void pnv_pci_p7ioc_tce_invalidate(struct iommu_table *tbl,
1909
		unsigned long index, unsigned long npages, bool rm)
1910
{
1911 1912 1913 1914
	struct iommu_table_group_link *tgl = list_first_entry_or_null(
			&tbl->it_group_list, struct iommu_table_group_link,
			next);
	struct pnv_ioda_pe *pe = container_of(tgl->table_group,
1915
			struct pnv_ioda_pe, table_group);
1916
	__be64 __iomem *invalidate = pnv_ioda_get_inval_reg(pe->phb, rm);
1917 1918
	unsigned long start, end, inc;

1919 1920 1921
	start = __pa(((__be64 *)tbl->it_base) + index - tbl->it_offset);
	end = __pa(((__be64 *)tbl->it_base) + index - tbl->it_offset +
			npages - 1);
1922

1923 1924 1925 1926
	/* p7ioc-style invalidation, 2 TCEs per write */
	start |= (1ull << 63);
	end |= (1ull << 63);
	inc = 16;
1927 1928 1929 1930
        end |= inc - 1;	/* round up end to be different than start */

        mb(); /* Ensure above stores are visible */
        while (start <= end) {
1931
		if (rm)
1932
			__raw_rm_writeq_be(start, invalidate);
1933
		else
1934 1935
			__raw_writeq_be(start, invalidate);

1936 1937 1938 1939 1940 1941 1942 1943 1944
                start += inc;
        }

	/*
	 * The iommu layer will do another mb() for us on build()
	 * and we don't care on free()
	 */
}

1945 1946 1947
static int pnv_ioda1_tce_build(struct iommu_table *tbl, long index,
		long npages, unsigned long uaddr,
		enum dma_data_direction direction,
1948
		unsigned long attrs)
1949 1950 1951 1952
{
	int ret = pnv_tce_build(tbl, index, npages, uaddr, direction,
			attrs);

1953
	if (!ret)
1954
		pnv_pci_p7ioc_tce_invalidate(tbl, index, npages, false);
1955 1956 1957 1958

	return ret;
}

1959
#ifdef CONFIG_IOMMU_API
1960 1961 1962 1963
/* Common for IODA1 and IODA2 */
static int pnv_ioda_tce_xchg_no_kill(struct iommu_table *tbl, long index,
		unsigned long *hpa, enum dma_data_direction *direction,
		bool realmode)
1964
{
1965
	return pnv_tce_xchg(tbl, index, hpa, direction, !realmode);
1966
}
1967 1968
#endif

1969 1970 1971 1972 1973
static void pnv_ioda1_tce_free(struct iommu_table *tbl, long index,
		long npages)
{
	pnv_tce_free(tbl, index, npages);

1974
	pnv_pci_p7ioc_tce_invalidate(tbl, index, npages, false);
1975 1976
}

1977
static struct iommu_table_ops pnv_ioda1_iommu_ops = {
1978
	.set = pnv_ioda1_tce_build,
1979
#ifdef CONFIG_IOMMU_API
1980 1981
	.xchg_no_kill = pnv_ioda_tce_xchg_no_kill,
	.tce_kill = pnv_pci_p7ioc_tce_invalidate,
1982
	.useraddrptr = pnv_tce_useraddrptr,
1983
#endif
1984
	.clear = pnv_ioda1_tce_free,
1985 1986 1987
	.get = pnv_tce_get,
};

1988 1989 1990
#define PHB3_TCE_KILL_INVAL_ALL		PPC_BIT(0)
#define PHB3_TCE_KILL_INVAL_PE		PPC_BIT(1)
#define PHB3_TCE_KILL_INVAL_ONE		PPC_BIT(2)
1991

1992
static void pnv_pci_phb3_tce_invalidate_entire(struct pnv_phb *phb, bool rm)
1993
{
1994
	__be64 __iomem *invalidate = pnv_ioda_get_inval_reg(phb, rm);
1995
	const unsigned long val = PHB3_TCE_KILL_INVAL_ALL;
1996 1997 1998

	mb(); /* Ensure previous TCE table stores are visible */
	if (rm)
1999
		__raw_rm_writeq_be(val, invalidate);
2000
	else
2001
		__raw_writeq_be(val, invalidate);
2002 2003
}

2004
static inline void pnv_pci_phb3_tce_invalidate_pe(struct pnv_ioda_pe *pe)
2005 2006
{
	/* 01xb - invalidate TCEs that match the specified PE# */
2007
	__be64 __iomem *invalidate = pnv_ioda_get_inval_reg(pe->phb, false);
2008
	unsigned long val = PHB3_TCE_KILL_INVAL_PE | (pe->pe_number & 0xFF);
2009 2010

	mb(); /* Ensure above stores are visible */
2011
	__raw_writeq_be(val, invalidate);
2012 2013
}

2014 2015 2016
static void pnv_pci_phb3_tce_invalidate(struct pnv_ioda_pe *pe, bool rm,
					unsigned shift, unsigned long index,
					unsigned long npages)
2017
{
2018
	__be64 __iomem *invalidate = pnv_ioda_get_inval_reg(pe->phb, rm);
2019 2020 2021
	unsigned long start, end, inc;

	/* We'll invalidate DMA address in PE scope */
2022
	start = PHB3_TCE_KILL_INVAL_ONE;
2023
	start |= (pe->pe_number & 0xFF);
2024 2025 2026
	end = start;

	/* Figure out the start, end and step */
2027 2028
	start |= (index << shift);
	end |= ((index + npages - 1) << shift);
2029
	inc = (0x1ull << shift);
2030 2031 2032
	mb();

	while (start <= end) {
2033
		if (rm)
2034
			__raw_rm_writeq_be(start, invalidate);
2035
		else
2036
			__raw_writeq_be(start, invalidate);
2037 2038 2039 2040
		start += inc;
	}
}

2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
static inline void pnv_pci_ioda2_tce_invalidate_pe(struct pnv_ioda_pe *pe)
{
	struct pnv_phb *phb = pe->phb;

	if (phb->model == PNV_PHB_MODEL_PHB3 && phb->regs)
		pnv_pci_phb3_tce_invalidate_pe(pe);
	else
		opal_pci_tce_kill(phb->opal_id, OPAL_PCI_TCE_KILL_PE,
				  pe->pe_number, 0, 0, 0);
}

2052 2053 2054 2055 2056
static void pnv_pci_ioda2_tce_invalidate(struct iommu_table *tbl,
		unsigned long index, unsigned long npages, bool rm)
{
	struct iommu_table_group_link *tgl;

2057
	list_for_each_entry_lockless(tgl, &tbl->it_group_list, next) {
2058 2059
		struct pnv_ioda_pe *pe = container_of(tgl->table_group,
				struct pnv_ioda_pe, table_group);
2060 2061 2062
		struct pnv_phb *phb = pe->phb;
		unsigned int shift = tbl->it_page_shift;

2063 2064 2065 2066 2067 2068
		/*
		 * NVLink1 can use the TCE kill register directly as
		 * it's the same as PHB3. NVLink2 is different and
		 * should go via the OPAL call.
		 */
		if (phb->model == PNV_PHB_MODEL_NPU) {
2069 2070 2071 2072 2073
			/*
			 * The NVLink hardware does not support TCE kill
			 * per TCE entry so we have to invalidate
			 * the entire cache for it.
			 */
2074
			pnv_pci_phb3_tce_invalidate_entire(phb, rm);
2075 2076
			continue;
		}
2077 2078 2079 2080 2081 2082 2083 2084
		if (phb->model == PNV_PHB_MODEL_PHB3 && phb->regs)
			pnv_pci_phb3_tce_invalidate(pe, rm, shift,
						    index, npages);
		else
			opal_pci_tce_kill(phb->opal_id,
					  OPAL_PCI_TCE_KILL_PAGES,
					  pe->pe_number, 1u << shift,
					  index << shift, npages);
2085 2086 2087
	}
}

2088 2089 2090 2091 2092 2093 2094 2095
void pnv_pci_ioda2_tce_invalidate_entire(struct pnv_phb *phb, bool rm)
{
	if (phb->model == PNV_PHB_MODEL_NPU || phb->model == PNV_PHB_MODEL_PHB3)
		pnv_pci_phb3_tce_invalidate_entire(phb, rm);
	else
		opal_pci_tce_kill(phb->opal_id, OPAL_PCI_TCE_KILL, 0, 0, 0, 0);
}

2096 2097 2098
static int pnv_ioda2_tce_build(struct iommu_table *tbl, long index,
		long npages, unsigned long uaddr,
		enum dma_data_direction direction,
2099
		unsigned long attrs)
2100
{
2101 2102
	int ret = pnv_tce_build(tbl, index, npages, uaddr, direction,
			attrs);
2103

2104
	if (!ret)
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
		pnv_pci_ioda2_tce_invalidate(tbl, index, npages, false);

	return ret;
}

static void pnv_ioda2_tce_free(struct iommu_table *tbl, long index,
		long npages)
{
	pnv_tce_free(tbl, index, npages);

2115
	pnv_pci_ioda2_tce_invalidate(tbl, index, npages, false);
2116 2117
}

2118
static struct iommu_table_ops pnv_ioda2_iommu_ops = {
2119
	.set = pnv_ioda2_tce_build,
2120
#ifdef CONFIG_IOMMU_API
2121 2122
	.xchg_no_kill = pnv_ioda_tce_xchg_no_kill,
	.tce_kill = pnv_pci_ioda2_tce_invalidate,
2123
	.useraddrptr = pnv_tce_useraddrptr,
2124
#endif
2125
	.clear = pnv_ioda2_tce_free,
2126
	.get = pnv_tce_get,
2127
	.free = pnv_pci_ioda2_table_free_pages,
2128 2129
};

2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
static int pnv_pci_ioda_dev_dma_weight(struct pci_dev *dev, void *data)
{
	unsigned int *weight = (unsigned int *)data;

	/* This is quite simplistic. The "base" weight of a device
	 * is 10. 0 means no DMA is to be accounted for it.
	 */
	if (dev->hdr_type != PCI_HEADER_TYPE_NORMAL)
		return 0;

	if (dev->class == PCI_CLASS_SERIAL_USB_UHCI ||
	    dev->class == PCI_CLASS_SERIAL_USB_OHCI ||
	    dev->class == PCI_CLASS_SERIAL_USB_EHCI)
		*weight += 3;
	else if ((dev->class >> 8) == PCI_CLASS_STORAGE_RAID)
		*weight += 15;
	else
		*weight += 10;

	return 0;
}

static unsigned int pnv_pci_ioda_pe_dma_weight(struct pnv_ioda_pe *pe)
{
	unsigned int weight = 0;

	/* SRIOV VF has same DMA32 weight as its PF */
#ifdef CONFIG_PCI_IOV
	if ((pe->flags & PNV_IODA_PE_VF) && pe->parent_dev) {
		pnv_pci_ioda_dev_dma_weight(pe->parent_dev, &weight);
		return weight;
	}
#endif

	if ((pe->flags & PNV_IODA_PE_DEV) && pe->pdev) {
		pnv_pci_ioda_dev_dma_weight(pe->pdev, &weight);
	} else if ((pe->flags & PNV_IODA_PE_BUS) && pe->pbus) {
		struct pci_dev *pdev;

		list_for_each_entry(pdev, &pe->pbus->devices, bus_list)
			pnv_pci_ioda_dev_dma_weight(pdev, &weight);
	} else if ((pe->flags & PNV_IODA_PE_BUS_ALL) && pe->pbus) {
		pci_walk_bus(pe->pbus, pnv_pci_ioda_dev_dma_weight, &weight);
	}

	return weight;
}

2178
static void pnv_pci_ioda1_setup_dma_pe(struct pnv_phb *phb,
2179
				       struct pnv_ioda_pe *pe)
2180 2181 2182 2183
{

	struct page *tce_mem = NULL;
	struct iommu_table *tbl;
2184 2185
	unsigned int weight, total_weight = 0;
	unsigned int tce32_segsz, base, segs, avail, i;
2186 2187 2188 2189 2190 2191
	int64_t rc;
	void *addr;

	/* XXX FIXME: Handle 64-bit only DMA devices */
	/* XXX FIXME: Provide 64-bit DMA facilities & non-4K TCE tables etc.. */
	/* XXX FIXME: Allocate multi-level tables on PHB3 */
2192 2193 2194 2195 2196 2197 2198 2199 2200
	weight = pnv_pci_ioda_pe_dma_weight(pe);
	if (!weight)
		return;

	pci_walk_bus(phb->hose->bus, pnv_pci_ioda_dev_dma_weight,
		     &total_weight);
	segs = (weight * phb->ioda.dma32_count) / total_weight;
	if (!segs)
		segs = 1;
2201

2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
	/*
	 * Allocate contiguous DMA32 segments. We begin with the expected
	 * number of segments. With one more attempt, the number of DMA32
	 * segments to be allocated is decreased by one until one segment
	 * is allocated successfully.
	 */
	do {
		for (base = 0; base <= phb->ioda.dma32_count - segs; base++) {
			for (avail = 0, i = base; i < base + segs; i++) {
				if (phb->ioda.dma32_segmap[i] ==
				    IODA_INVALID_PE)
					avail++;
			}

			if (avail == segs)
				goto found;
		}
	} while (--segs);

	if (!segs) {
		pe_warn(pe, "No available DMA32 segments\n");
		return;
	}

found:
2227
	tbl = pnv_pci_table_alloc(phb->hose->node);
2228 2229 2230
	if (WARN_ON(!tbl))
		return;

2231 2232
	iommu_register_group(&pe->table_group, phb->hose->global_number,
			pe->pe_number);
2233
	pnv_pci_link_table_and_group(phb->hose->node, 0, tbl, &pe->table_group);
2234

2235
	/* Grab a 32-bit TCE table */
2236 2237
	pe_info(pe, "DMA weight %d (%d), assigned (%d) %d DMA32 segments\n",
		weight, total_weight, base, segs);
2238
	pe_info(pe, " Setting up 32-bit TCE table at %08x..%08x\n",
2239 2240
		base * PNV_IODA1_DMA32_SEGSIZE,
		(base + segs) * PNV_IODA1_DMA32_SEGSIZE - 1);
2241 2242 2243 2244 2245

	/* XXX Currently, we allocate one big contiguous table for the
	 * TCEs. We only really need one chunk per 256M of TCE space
	 * (ie per segment) but that's an optimization for later, it
	 * requires some added smarts with our get/put_tce implementation
2246 2247 2248
	 *
	 * Each TCE page is 4KB in size and each TCE entry occupies 8
	 * bytes
2249
	 */
2250
	tce32_segsz = PNV_IODA1_DMA32_SEGSIZE >> (IOMMU_PAGE_SHIFT_4K - 3);
2251
	tce_mem = alloc_pages_node(phb->hose->node, GFP_KERNEL,
2252
				   get_order(tce32_segsz * segs));
2253 2254 2255 2256 2257
	if (!tce_mem) {
		pe_err(pe, " Failed to allocate a 32-bit TCE memory\n");
		goto fail;
	}
	addr = page_address(tce_mem);
2258
	memset(addr, 0, tce32_segsz * segs);
2259 2260 2261 2262 2263 2264

	/* Configure HW */
	for (i = 0; i < segs; i++) {
		rc = opal_pci_map_pe_dma_window(phb->opal_id,
					      pe->pe_number,
					      base + i, 1,
2265 2266
					      __pa(addr) + tce32_segsz * i,
					      tce32_segsz, IOMMU_PAGE_SIZE_4K);
2267
		if (rc) {
2268 2269
			pe_err(pe, " Failed to configure 32-bit TCE table, err %lld\n",
			       rc);
2270 2271 2272 2273
			goto fail;
		}
	}

2274 2275 2276 2277
	/* Setup DMA32 segment mapping */
	for (i = base; i < base + segs; i++)
		phb->ioda.dma32_segmap[i] = pe->pe_number;

2278
	/* Setup linux iommu table */
2279 2280 2281
	pnv_pci_setup_iommu_table(tbl, addr, tce32_segsz * segs,
				  base * PNV_IODA1_DMA32_SEGSIZE,
				  IOMMU_PAGE_SHIFT_4K);
2282

2283
	tbl->it_ops = &pnv_ioda1_iommu_ops;
2284 2285
	pe->table_group.tce32_start = tbl->it_offset << tbl->it_page_shift;
	pe->table_group.tce32_size = tbl->it_size << tbl->it_page_shift;
2286
	iommu_init_table(tbl, phb->hose->node, 0, 0);
2287 2288 2289 2290 2291

	return;
 fail:
	/* XXX Failure: Try to fallback to 64-bit only ? */
	if (tce_mem)
2292
		__free_pages(tce_mem, get_order(tce32_segsz * segs));
2293 2294
	if (tbl) {
		pnv_pci_unlink_table_and_group(tbl, &pe->table_group);
2295
		iommu_tce_table_put(tbl);
2296
	}
2297 2298
}

2299 2300 2301 2302 2303 2304 2305
static long pnv_pci_ioda2_set_window(struct iommu_table_group *table_group,
		int num, struct iommu_table *tbl)
{
	struct pnv_ioda_pe *pe = container_of(table_group, struct pnv_ioda_pe,
			table_group);
	struct pnv_phb *phb = pe->phb;
	int64_t rc;
2306 2307
	const unsigned long size = tbl->it_indirect_levels ?
			tbl->it_level_size : tbl->it_size;
2308 2309 2310
	const __u64 start_addr = tbl->it_offset << tbl->it_page_shift;
	const __u64 win_size = tbl->it_size << tbl->it_page_shift;

2311 2312 2313
	pe_info(pe, "Setting up window#%d %llx..%llx pg=%lx\n",
		num, start_addr, start_addr + win_size - 1,
		IOMMU_PAGE_SIZE(tbl));
2314 2315 2316 2317 2318 2319 2320

	/*
	 * Map TCE table through TVT. The TVE index is the PE number
	 * shifted by 1 bit for 32-bits DMA space.
	 */
	rc = opal_pci_map_pe_dma_window(phb->opal_id,
			pe->pe_number,
2321
			(pe->pe_number << 1) + num,
2322
			tbl->it_indirect_levels + 1,
2323
			__pa(tbl->it_base),
2324
			size << 3,
2325 2326
			IOMMU_PAGE_SIZE(tbl));
	if (rc) {
2327
		pe_err(pe, "Failed to configure TCE table, err %lld\n", rc);
2328 2329 2330 2331 2332
		return rc;
	}

	pnv_pci_link_table_and_group(phb->hose->node, num,
			tbl, &pe->table_group);
2333
	pnv_pci_ioda2_tce_invalidate_pe(pe);
2334 2335 2336 2337

	return 0;
}

2338
static void pnv_pci_ioda2_set_bypass(struct pnv_ioda_pe *pe, bool enable)
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
{
	uint16_t window_id = (pe->pe_number << 1 ) + 1;
	int64_t rc;

	pe_info(pe, "%sabling 64-bit DMA bypass\n", enable ? "En" : "Dis");
	if (enable) {
		phys_addr_t top = memblock_end_of_DRAM();

		top = roundup_pow_of_two(top);
		rc = opal_pci_map_pe_dma_window_real(pe->phb->opal_id,
						     pe->pe_number,
						     window_id,
						     pe->tce_bypass_base,
						     top);
	} else {
		rc = opal_pci_map_pe_dma_window_real(pe->phb->opal_id,
						     pe->pe_number,
						     window_id,
						     pe->tce_bypass_base,
						     0);
	}
	if (rc)
		pe_err(pe, "OPAL error %lld configuring bypass window\n", rc);
	else
		pe->tce_bypass_enabled = enable;
}

2366 2367
static long pnv_pci_ioda2_create_table(struct iommu_table_group *table_group,
		int num, __u32 page_shift, __u64 window_size, __u32 levels,
2368
		bool alloc_userspace_copy, struct iommu_table **ptbl)
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
{
	struct pnv_ioda_pe *pe = container_of(table_group, struct pnv_ioda_pe,
			table_group);
	int nid = pe->phb->hose->node;
	__u64 bus_offset = num ? pe->tce_bypass_base : table_group->tce32_start;
	long ret;
	struct iommu_table *tbl;

	tbl = pnv_pci_table_alloc(nid);
	if (!tbl)
		return -ENOMEM;

2381 2382
	tbl->it_ops = &pnv_ioda2_iommu_ops;

2383 2384
	ret = pnv_pci_ioda2_table_alloc_pages(nid,
			bus_offset, page_shift, window_size,
2385
			levels, alloc_userspace_copy, tbl);
2386
	if (ret) {
2387
		iommu_tce_table_put(tbl);
2388 2389 2390 2391 2392 2393 2394 2395
		return ret;
	}

	*ptbl = tbl;

	return 0;
}

2396 2397 2398 2399
static long pnv_pci_ioda2_setup_default_config(struct pnv_ioda_pe *pe)
{
	struct iommu_table *tbl = NULL;
	long rc;
2400
	unsigned long res_start, res_end;
2401

2402 2403 2404 2405 2406 2407 2408
	/*
	 * crashkernel= specifies the kdump kernel's maximum memory at
	 * some offset and there is no guaranteed the result is a power
	 * of 2, which will cause errors later.
	 */
	const u64 max_memory = __rounddown_pow_of_two(memory_hotplug_max());

2409 2410 2411 2412 2413
	/*
	 * In memory constrained environments, e.g. kdump kernel, the
	 * DMA window can be larger than available memory, which will
	 * cause errors later.
	 */
2414
	const u64 maxblock = 1UL << (PAGE_SHIFT + MAX_ORDER - 1);
2415

2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
	/*
	 * We create the default window as big as we can. The constraint is
	 * the max order of allocation possible. The TCE table is likely to
	 * end up being multilevel and with on-demand allocation in place,
	 * the initial use is not going to be huge as the default window aims
	 * to support crippled devices (i.e. not fully 64bit DMAble) only.
	 */
	/* iommu_table::it_map uses 1 bit per IOMMU page, hence 8 */
	const u64 window_size = min((maxblock * 8) << PAGE_SHIFT, max_memory);
	/* Each TCE level cannot exceed maxblock so go multilevel if needed */
	unsigned long tces_order = ilog2(window_size >> PAGE_SHIFT);
	unsigned long tcelevel_order = ilog2(maxblock >> 3);
	unsigned int levels = tces_order / tcelevel_order;

	if (tces_order % tcelevel_order)
		levels += 1;
	/*
	 * We try to stick to default levels (which is >1 at the moment) in
	 * order to save memory by relying on on-demain TCE level allocation.
	 */
	levels = max_t(unsigned int, levels, POWERNV_IOMMU_DEFAULT_LEVELS);

	rc = pnv_pci_ioda2_create_table(&pe->table_group, 0, PAGE_SHIFT,
			window_size, levels, false, &tbl);
2440 2441 2442 2443 2444 2445
	if (rc) {
		pe_err(pe, "Failed to create 32-bit TCE table, err %ld",
				rc);
		return rc;
	}

2446 2447 2448 2449 2450 2451 2452 2453
	/* We use top part of 32bit space for MMIO so exclude it from DMA */
	res_start = 0;
	res_end = 0;
	if (window_size > pe->phb->ioda.m32_pci_base) {
		res_start = pe->phb->ioda.m32_pci_base >> tbl->it_page_shift;
		res_end = min(window_size, SZ_4G) >> tbl->it_page_shift;
	}
	iommu_init_table(tbl, pe->phb->hose->node, res_start, res_end);
2454 2455 2456 2457 2458

	rc = pnv_pci_ioda2_set_window(&pe->table_group, 0, tbl);
	if (rc) {
		pe_err(pe, "Failed to configure 32-bit TCE table, err %ld\n",
				rc);
2459
		iommu_tce_table_put(tbl);
2460 2461 2462 2463 2464 2465
		return rc;
	}

	if (!pnv_iommu_bypass_disabled)
		pnv_pci_ioda2_set_bypass(pe, true);

2466 2467 2468 2469 2470 2471 2472 2473
	/*
	 * Set table base for the case of IOMMU DMA use. Usually this is done
	 * from dma_dev_setup() which is not called when a device is returned
	 * from VFIO so do it here.
	 */
	if (pe->pdev)
		set_iommu_table_base(&pe->pdev->dev, tbl);

2474 2475 2476
	return 0;
}

2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
#if defined(CONFIG_IOMMU_API) || defined(CONFIG_PCI_IOV)
static long pnv_pci_ioda2_unset_window(struct iommu_table_group *table_group,
		int num)
{
	struct pnv_ioda_pe *pe = container_of(table_group, struct pnv_ioda_pe,
			table_group);
	struct pnv_phb *phb = pe->phb;
	long ret;

	pe_info(pe, "Removing DMA window #%d\n", num);

	ret = opal_pci_map_pe_dma_window(phb->opal_id, pe->pe_number,
			(pe->pe_number << 1) + num,
			0/* levels */, 0/* table address */,
			0/* table size */, 0/* page size */);
	if (ret)
		pe_warn(pe, "Unmapping failed, ret = %ld\n", ret);
	else
2495
		pnv_pci_ioda2_tce_invalidate_pe(pe);
2496 2497 2498 2499 2500 2501 2502

	pnv_pci_unlink_table_and_group(table_group->tables[num], table_group);

	return ret;
}
#endif

2503
#ifdef CONFIG_IOMMU_API
2504
unsigned long pnv_pci_ioda2_get_table_size(__u32 page_shift,
2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
		__u64 window_size, __u32 levels)
{
	unsigned long bytes = 0;
	const unsigned window_shift = ilog2(window_size);
	unsigned entries_shift = window_shift - page_shift;
	unsigned table_shift = entries_shift + 3;
	unsigned long tce_table_size = max(0x1000UL, 1UL << table_shift);
	unsigned long direct_table_size;

	if (!levels || (levels > POWERNV_IOMMU_MAX_LEVELS) ||
			!is_power_of_2(window_size))
		return 0;

	/* Calculate a direct table size from window_size and levels */
	entries_shift = (entries_shift + levels - 1) / levels;
	table_shift = entries_shift + 3;
	table_shift = max_t(unsigned, table_shift, PAGE_SHIFT);
	direct_table_size =  1UL << table_shift;

	for ( ; levels; --levels) {
2525
		bytes += ALIGN(tce_table_size, direct_table_size);
2526 2527 2528

		tce_table_size /= direct_table_size;
		tce_table_size <<= 3;
2529 2530
		tce_table_size = max_t(unsigned long,
				tce_table_size, direct_table_size);
2531 2532
	}

2533 2534 2535 2536 2537 2538 2539 2540
	return bytes + bytes; /* one for HW table, one for userspace copy */
}

static long pnv_pci_ioda2_create_table_userspace(
		struct iommu_table_group *table_group,
		int num, __u32 page_shift, __u64 window_size, __u32 levels,
		struct iommu_table **ptbl)
{
2541
	long ret = pnv_pci_ioda2_create_table(table_group,
2542
			num, page_shift, window_size, levels, true, ptbl);
2543 2544 2545 2546 2547

	if (!ret)
		(*ptbl)->it_allocated_size = pnv_pci_ioda2_get_table_size(
				page_shift, window_size, levels);
	return ret;
2548 2549
}

2550
static void pnv_ioda2_take_ownership(struct iommu_table_group *table_group)
2551
{
2552 2553
	struct pnv_ioda_pe *pe = container_of(table_group, struct pnv_ioda_pe,
						table_group);
2554 2555
	/* Store @tbl as pnv_pci_ioda2_unset_window() resets it */
	struct iommu_table *tbl = pe->table_group.tables[0];
2556

2557
	pnv_pci_ioda2_set_bypass(pe, false);
2558
	pnv_pci_ioda2_unset_window(&pe->table_group, 0);
2559
	if (pe->pbus)
2560
		pnv_ioda_setup_bus_dma(pe, pe->pbus);
2561 2562
	else if (pe->pdev)
		set_iommu_table_base(&pe->pdev->dev, NULL);
2563
	iommu_tce_table_put(tbl);
2564
}
2565

2566 2567 2568 2569 2570
static void pnv_ioda2_release_ownership(struct iommu_table_group *table_group)
{
	struct pnv_ioda_pe *pe = container_of(table_group, struct pnv_ioda_pe,
						table_group);

2571
	pnv_pci_ioda2_setup_default_config(pe);
2572
	if (pe->pbus)
2573
		pnv_ioda_setup_bus_dma(pe, pe->pbus);
2574 2575
}

2576
static struct iommu_table_group_ops pnv_pci_ioda2_ops = {
2577
	.get_table_size = pnv_pci_ioda2_get_table_size,
2578
	.create_table = pnv_pci_ioda2_create_table_userspace,
2579 2580
	.set_window = pnv_pci_ioda2_set_window,
	.unset_window = pnv_pci_ioda2_unset_window,
2581 2582 2583 2584 2585
	.take_ownership = pnv_ioda2_take_ownership,
	.release_ownership = pnv_ioda2_release_ownership,
};
#endif

2586 2587 2588
static void pnv_pci_ioda2_setup_dma_pe(struct pnv_phb *phb,
				       struct pnv_ioda_pe *pe)
{
2589 2590
	int64_t rc;

2591 2592 2593
	if (!pnv_pci_ioda_pe_dma_weight(pe))
		return;

2594 2595 2596
	/* TVE #1 is selected by PCI address bit 59 */
	pe->tce_bypass_base = 1ull << 59;

2597 2598
	/* The PE will reserve all possible 32-bits space */
	pe_info(pe, "Setting up 32-bit TCE table at 0..%08x\n",
2599
		phb->ioda.m32_pci_base);
2600

2601
	/* Setup linux iommu table */
2602 2603 2604 2605 2606
	pe->table_group.tce32_start = 0;
	pe->table_group.tce32_size = phb->ioda.m32_pci_base;
	pe->table_group.max_dynamic_windows_supported =
			IOMMU_TABLE_GROUP_MAX_TABLES;
	pe->table_group.max_levels = POWERNV_IOMMU_MAX_LEVELS;
2607
	pe->table_group.pgsizes = pnv_ioda_parse_tce_sizes(phb);
2608

2609
	rc = pnv_pci_ioda2_setup_default_config(pe);
2610
	if (rc)
2611
		return;
2612

2613 2614 2615 2616 2617
#ifdef CONFIG_IOMMU_API
	pe->table_group.ops = &pnv_pci_ioda2_ops;
	iommu_register_group(&pe->table_group, phb->hose->global_number,
			     pe->pe_number);
#endif
2618 2619
}

2620
int64_t pnv_opal_pci_msi_eoi(struct irq_chip *chip, unsigned int hw_irq)
2621 2622 2623
{
	struct pnv_phb *phb = container_of(chip, struct pnv_phb,
					   ioda.irq_chip);
2624 2625 2626 2627 2628 2629

	return opal_pci_msi_eoi(phb->opal_id, hw_irq);
}

static void pnv_ioda2_msi_eoi(struct irq_data *d)
{
2630
	int64_t rc;
2631 2632
	unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d);
	struct irq_chip *chip = irq_data_get_irq_chip(d);
2633

2634
	rc = pnv_opal_pci_msi_eoi(chip, hw_irq);
2635 2636 2637 2638 2639
	WARN_ON_ONCE(rc);

	icp_native_eoi(d);
}

2640

2641
void pnv_set_msi_irq_chip(struct pnv_phb *phb, unsigned int virq)
2642 2643 2644 2645
{
	struct irq_data *idata;
	struct irq_chip *ichip;

2646 2647
	/* The MSI EOI OPAL call is only needed on PHB3 */
	if (phb->model != PNV_PHB_MODEL_PHB3)
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
		return;

	if (!phb->ioda.irq_chip_init) {
		/*
		 * First time we setup an MSI IRQ, we need to setup the
		 * corresponding IRQ chip to route correctly.
		 */
		idata = irq_get_irq_data(virq);
		ichip = irq_data_get_irq_chip(idata);
		phb->ioda.irq_chip_init = 1;
		phb->ioda.irq_chip = *ichip;
		phb->ioda.irq_chip.irq_eoi = pnv_ioda2_msi_eoi;
	}
	irq_set_chip(virq, &phb->ioda.irq_chip);
}

2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
/*
 * Returns true iff chip is something that we could call
 * pnv_opal_pci_msi_eoi for.
 */
bool is_pnv_opal_msi(struct irq_chip *chip)
{
	return chip->irq_eoi == pnv_ioda2_msi_eoi;
}
EXPORT_SYMBOL_GPL(is_pnv_opal_msi);

2674
static int pnv_pci_ioda_msi_setup(struct pnv_phb *phb, struct pci_dev *dev,
2675 2676
				  unsigned int hwirq, unsigned int virq,
				  unsigned int is_64, struct msi_msg *msg)
2677 2678 2679
{
	struct pnv_ioda_pe *pe = pnv_ioda_get_pe(dev);
	unsigned int xive_num = hwirq - phb->msi_base;
2680
	__be32 data;
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
	int rc;

	/* No PE assigned ? bail out ... no MSI for you ! */
	if (pe == NULL)
		return -ENXIO;

	/* Check if we have an MVE */
	if (pe->mve_number < 0)
		return -ENXIO;

2691
	/* Force 32-bit MSI on some broken devices */
2692
	if (dev->no_64bit_msi)
2693 2694
		is_64 = 0;

2695 2696 2697 2698 2699 2700 2701 2702 2703
	/* Assign XIVE to PE */
	rc = opal_pci_set_xive_pe(phb->opal_id, pe->pe_number, xive_num);
	if (rc) {
		pr_warn("%s: OPAL error %d setting XIVE %d PE\n",
			pci_name(dev), rc, xive_num);
		return -EIO;
	}

	if (is_64) {
2704 2705
		__be64 addr64;

2706 2707 2708 2709 2710 2711 2712
		rc = opal_get_msi_64(phb->opal_id, pe->mve_number, xive_num, 1,
				     &addr64, &data);
		if (rc) {
			pr_warn("%s: OPAL error %d getting 64-bit MSI data\n",
				pci_name(dev), rc);
			return -EIO;
		}
2713 2714
		msg->address_hi = be64_to_cpu(addr64) >> 32;
		msg->address_lo = be64_to_cpu(addr64) & 0xfffffffful;
2715
	} else {
2716 2717
		__be32 addr32;

2718 2719 2720 2721 2722 2723 2724 2725
		rc = opal_get_msi_32(phb->opal_id, pe->mve_number, xive_num, 1,
				     &addr32, &data);
		if (rc) {
			pr_warn("%s: OPAL error %d getting 32-bit MSI data\n",
				pci_name(dev), rc);
			return -EIO;
		}
		msg->address_hi = 0;
2726
		msg->address_lo = be32_to_cpu(addr32);
2727
	}
2728
	msg->data = be32_to_cpu(data);
2729

2730
	pnv_set_msi_irq_chip(phb, virq);
2731

2732
	pr_devel("%s: %s-bit MSI on hwirq %x (xive #%d),"
2733
		 " address=%x_%08x data=%x PE# %x\n",
2734 2735 2736 2737 2738 2739 2740 2741
		 pci_name(dev), is_64 ? "64" : "32", hwirq, xive_num,
		 msg->address_hi, msg->address_lo, data, pe->pe_number);

	return 0;
}

static void pnv_pci_init_ioda_msis(struct pnv_phb *phb)
{
2742
	unsigned int count;
2743 2744 2745 2746 2747 2748 2749 2750 2751 2752
	const __be32 *prop = of_get_property(phb->hose->dn,
					     "ibm,opal-msi-ranges", NULL);
	if (!prop) {
		/* BML Fallback */
		prop = of_get_property(phb->hose->dn, "msi-ranges", NULL);
	}
	if (!prop)
		return;

	phb->msi_base = be32_to_cpup(prop);
2753 2754
	count = be32_to_cpup(prop + 1);
	if (msi_bitmap_alloc(&phb->msi_bmp, count, phb->hose->dn)) {
2755 2756 2757 2758
		pr_err("PCI %d: Failed to allocate MSI bitmap !\n",
		       phb->hose->global_number);
		return;
	}
2759

2760 2761 2762
	phb->msi_setup = pnv_pci_ioda_msi_setup;
	phb->msi32_support = 1;
	pr_info("  Allocated bitmap for %d MSIs (base IRQ 0x%x)\n",
2763
		count, phb->msi_base);
2764 2765
}

2766 2767 2768
#ifdef CONFIG_PCI_IOV
static void pnv_pci_ioda_fixup_iov_resources(struct pci_dev *pdev)
{
2769 2770 2771
	struct pci_controller *hose = pci_bus_to_host(pdev->bus);
	struct pnv_phb *phb = hose->private_data;
	const resource_size_t gate = phb->ioda.m64_segsize >> 2;
2772 2773
	struct resource *res;
	int i;
2774
	resource_size_t size, total_vf_bar_sz;
2775
	struct pci_dn *pdn;
2776
	int mul, total_vfs;
2777 2778 2779

	pdn = pci_get_pdn(pdev);
	pdn->vfs_expanded = 0;
2780
	pdn->m64_single_mode = false;
2781

2782
	total_vfs = pci_sriov_get_totalvfs(pdev);
2783
	mul = phb->ioda.total_pe_num;
2784
	total_vf_bar_sz = 0;
2785 2786 2787 2788 2789

	for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
		res = &pdev->resource[i + PCI_IOV_RESOURCES];
		if (!res->flags || res->parent)
			continue;
2790
		if (!pnv_pci_is_m64_flags(res->flags)) {
2791 2792
			dev_warn(&pdev->dev, "Don't support SR-IOV with"
					" non M64 VF BAR%d: %pR. \n",
2793
				 i, res);
2794
			goto truncate_iov;
2795 2796
		}

2797 2798
		total_vf_bar_sz += pci_iov_resource_size(pdev,
				i + PCI_IOV_RESOURCES);
2799

2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
		/*
		 * If bigger than quarter of M64 segment size, just round up
		 * power of two.
		 *
		 * Generally, one M64 BAR maps one IOV BAR. To avoid conflict
		 * with other devices, IOV BAR size is expanded to be
		 * (total_pe * VF_BAR_size).  When VF_BAR_size is half of M64
		 * segment size , the expanded size would equal to half of the
		 * whole M64 space size, which will exhaust the M64 Space and
		 * limit the system flexibility.  This is a design decision to
		 * set the boundary to quarter of the M64 segment size.
		 */
2812
		if (total_vf_bar_sz > gate) {
2813
			mul = roundup_pow_of_two(total_vfs);
2814 2815 2816
			dev_info(&pdev->dev,
				"VF BAR Total IOV size %llx > %llx, roundup to %d VFs\n",
				total_vf_bar_sz, gate, mul);
2817
			pdn->m64_single_mode = true;
2818 2819 2820 2821
			break;
		}
	}

2822 2823 2824 2825 2826 2827
	for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
		res = &pdev->resource[i + PCI_IOV_RESOURCES];
		if (!res->flags || res->parent)
			continue;

		size = pci_iov_resource_size(pdev, i + PCI_IOV_RESOURCES);
2828 2829 2830 2831 2832 2833 2834
		/*
		 * On PHB3, the minimum size alignment of M64 BAR in single
		 * mode is 32MB.
		 */
		if (pdn->m64_single_mode && (size < SZ_32M))
			goto truncate_iov;
		dev_dbg(&pdev->dev, " Fixing VF BAR%d: %pR to\n", i, res);
2835
		res->end = res->start + size * mul - 1;
2836 2837
		dev_dbg(&pdev->dev, "                       %pR\n", res);
		dev_info(&pdev->dev, "VF BAR%d: %pR (expanded to %d VFs for PE alignment)",
2838
			 i, res, mul);
2839
	}
2840
	pdn->vfs_expanded = mul;
2841 2842 2843 2844 2845 2846 2847 2848 2849 2850

	return;

truncate_iov:
	/* To save MMIO space, IOV BAR is truncated. */
	for (i = 0; i < PCI_SRIOV_NUM_BARS; i++) {
		res = &pdev->resource[i + PCI_IOV_RESOURCES];
		res->flags = 0;
		res->end = res->start - 1;
	}
2851
}
2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875

static void pnv_pci_ioda_fixup_iov(struct pci_dev *pdev)
{
	if (WARN_ON(pci_dev_is_added(pdev)))
		return;

	if (pdev->is_virtfn) {
		struct pnv_ioda_pe *pe = pnv_ioda_get_pe(pdev);

		/*
		 * VF PEs are single-device PEs so their pdev pointer needs to
		 * be set. The pdev doesn't exist when the PE is allocated (in
		 * (pcibios_sriov_enable()) so we fix it up here.
		 */
		pe->pdev = pdev;
		WARN_ON(!(pe->flags & PNV_IODA_PE_VF));
	} else if (pdev->is_physfn) {
		/*
		 * For PFs adjust their allocated IOV resources to match what
		 * the PHB can support using it's M64 BAR table.
		 */
		pnv_pci_ioda_fixup_iov_resources(pdev);
	}
}
2876 2877
#endif /* CONFIG_PCI_IOV */

2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899
static void pnv_ioda_setup_pe_res(struct pnv_ioda_pe *pe,
				  struct resource *res)
{
	struct pnv_phb *phb = pe->phb;
	struct pci_bus_region region;
	int index;
	int64_t rc;

	if (!res || !res->flags || res->start > res->end)
		return;

	if (res->flags & IORESOURCE_IO) {
		region.start = res->start - phb->ioda.io_pci_base;
		region.end   = res->end - phb->ioda.io_pci_base;
		index = region.start / phb->ioda.io_segsize;

		while (index < phb->ioda.total_pe_num &&
		       region.start <= region.end) {
			phb->ioda.io_segmap[index] = pe->pe_number;
			rc = opal_pci_map_pe_mmio_window(phb->opal_id,
				pe->pe_number, OPAL_IO_WINDOW_TYPE, 0, index);
			if (rc != OPAL_SUCCESS) {
2900
				pr_err("%s: Error %lld mapping IO segment#%d to PE#%x\n",
2901 2902 2903 2904 2905 2906 2907 2908
				       __func__, rc, index, pe->pe_number);
				break;
			}

			region.start += phb->ioda.io_segsize;
			index++;
		}
	} else if ((res->flags & IORESOURCE_MEM) &&
2909
		   !pnv_pci_is_m64(phb, res)) {
2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923
		region.start = res->start -
			       phb->hose->mem_offset[0] -
			       phb->ioda.m32_pci_base;
		region.end   = res->end -
			       phb->hose->mem_offset[0] -
			       phb->ioda.m32_pci_base;
		index = region.start / phb->ioda.m32_segsize;

		while (index < phb->ioda.total_pe_num &&
		       region.start <= region.end) {
			phb->ioda.m32_segmap[index] = pe->pe_number;
			rc = opal_pci_map_pe_mmio_window(phb->opal_id,
				pe->pe_number, OPAL_M32_WINDOW_TYPE, 0, index);
			if (rc != OPAL_SUCCESS) {
2924
				pr_err("%s: Error %lld mapping M32 segment#%d to PE#%x",
2925 2926 2927 2928 2929 2930 2931 2932 2933 2934
				       __func__, rc, index, pe->pe_number);
				break;
			}

			region.start += phb->ioda.m32_segsize;
			index++;
		}
	}
}

2935 2936 2937
/*
 * This function is supposed to be called on basis of PE from top
 * to bottom style. So the the I/O or MMIO segment assigned to
2938
 * parent PE could be overridden by its child PEs if necessary.
2939
 */
2940
static void pnv_ioda_setup_pe_seg(struct pnv_ioda_pe *pe)
2941
{
2942
	struct pci_dev *pdev;
2943
	int i;
2944 2945 2946 2947 2948 2949 2950 2951

	/*
	 * NOTE: We only care PCI bus based PE for now. For PCI
	 * device based PE, for example SRIOV sensitive VF should
	 * be figured out later.
	 */
	BUG_ON(!(pe->flags & (PNV_IODA_PE_BUS | PNV_IODA_PE_BUS_ALL)));

2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
	list_for_each_entry(pdev, &pe->pbus->devices, bus_list) {
		for (i = 0; i <= PCI_ROM_RESOURCE; i++)
			pnv_ioda_setup_pe_res(pe, &pdev->resource[i]);

		/*
		 * If the PE contains all subordinate PCI buses, the
		 * windows of the child bridges should be mapped to
		 * the PE as well.
		 */
		if (!(pe->flags & PNV_IODA_PE_BUS_ALL) || !pci_is_bridge(pdev))
			continue;
		for (i = 0; i < PCI_BRIDGE_RESOURCE_NUM; i++)
			pnv_ioda_setup_pe_res(pe,
				&pdev->resource[PCI_BRIDGE_RESOURCES + i]);
	}
2967 2968
}

2969 2970 2971
#ifdef CONFIG_DEBUG_FS
static int pnv_pci_diag_data_set(void *data, u64 val)
{
2972
	struct pnv_phb *phb = data;
2973 2974 2975
	s64 ret;

	/* Retrieve the diag data from firmware */
2976 2977
	ret = opal_pci_get_phb_diag_data2(phb->opal_id, phb->diag_data,
					  phb->diag_data_size);
2978 2979 2980 2981
	if (ret != OPAL_SUCCESS)
		return -EIO;

	/* Print the diag data to the kernel log */
2982
	pnv_pci_dump_phb_diag_data(phb->hose, phb->diag_data);
2983 2984 2985
	return 0;
}

2986 2987
DEFINE_DEBUGFS_ATTRIBUTE(pnv_pci_diag_data_fops, NULL, pnv_pci_diag_data_set,
			 "%llu\n");
2988

2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015
static int pnv_pci_ioda_pe_dump(void *data, u64 val)
{
	struct pnv_phb *phb = data;
	int pe_num;

	for (pe_num = 0; pe_num < phb->ioda.total_pe_num; pe_num++) {
		struct pnv_ioda_pe *pe = &phb->ioda.pe_array[pe_num];

		if (!test_bit(pe_num, phb->ioda.pe_alloc))
			continue;

		pe_warn(pe, "rid: %04x dev count: %2d flags: %s%s%s%s%s%s\n",
			pe->rid, pe->device_count,
			(pe->flags & PNV_IODA_PE_DEV) ? "dev " : "",
			(pe->flags & PNV_IODA_PE_BUS) ? "bus " : "",
			(pe->flags & PNV_IODA_PE_BUS_ALL) ? "all " : "",
			(pe->flags & PNV_IODA_PE_MASTER) ? "master " : "",
			(pe->flags & PNV_IODA_PE_SLAVE) ? "slave " : "",
			(pe->flags & PNV_IODA_PE_VF) ? "vf " : "");
	}

	return 0;
}

DEFINE_DEBUGFS_ATTRIBUTE(pnv_pci_ioda_pe_dump_fops, NULL,
			 pnv_pci_ioda_pe_dump, "%llu\n");

3016 3017
#endif /* CONFIG_DEBUG_FS */

3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
static void pnv_pci_ioda_create_dbgfs(void)
{
#ifdef CONFIG_DEBUG_FS
	struct pci_controller *hose, *tmp;
	struct pnv_phb *phb;
	char name[16];

	list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
		phb = hose->private_data;

3028 3029 3030
		/* Notify initialization of PHB done */
		phb->initialized = 1;

3031 3032
		sprintf(name, "PCI%04x", hose->global_number);
		phb->dbgfs = debugfs_create_dir(name, powerpc_debugfs_root);
3033

3034
		debugfs_create_file_unsafe("dump_diag_regs", 0200, phb->dbgfs,
3035
					   phb, &pnv_pci_diag_data_fops);
3036 3037
		debugfs_create_file_unsafe("dump_ioda_pe_state", 0200, phb->dbgfs,
					   phb, &pnv_pci_ioda_pe_dump_fops);
3038 3039 3040 3041
	}
#endif /* CONFIG_DEBUG_FS */
}

3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076
static void pnv_pci_enable_bridge(struct pci_bus *bus)
{
	struct pci_dev *dev = bus->self;
	struct pci_bus *child;

	/* Empty bus ? bail */
	if (list_empty(&bus->devices))
		return;

	/*
	 * If there's a bridge associated with that bus enable it. This works
	 * around races in the generic code if the enabling is done during
	 * parallel probing. This can be removed once those races have been
	 * fixed.
	 */
	if (dev) {
		int rc = pci_enable_device(dev);
		if (rc)
			pci_err(dev, "Error enabling bridge (%d)\n", rc);
		pci_set_master(dev);
	}

	/* Perform the same to child busses */
	list_for_each_entry(child, &bus->children, node)
		pnv_pci_enable_bridge(child);
}

static void pnv_pci_enable_bridges(void)
{
	struct pci_controller *hose;

	list_for_each_entry(hose, &hose_list, list_node)
		pnv_pci_enable_bridge(hose->bus);
}

3077
static void pnv_pci_ioda_fixup(void)
3078
{
3079
	pnv_pci_ioda_setup_nvlink();
3080 3081
	pnv_pci_ioda_create_dbgfs();

3082 3083
	pnv_pci_enable_bridges();

3084
#ifdef CONFIG_EEH
3085
	pnv_eeh_post_init();
3086
#endif
3087 3088
}

3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
/*
 * Returns the alignment for I/O or memory windows for P2P
 * bridges. That actually depends on how PEs are segmented.
 * For now, we return I/O or M32 segment size for PE sensitive
 * P2P bridges. Otherwise, the default values (4KiB for I/O,
 * 1MiB for memory) will be returned.
 *
 * The current PCI bus might be put into one PE, which was
 * create against the parent PCI bridge. For that case, we
 * needn't enlarge the alignment so that we can save some
 * resources.
 */
static resource_size_t pnv_pci_window_alignment(struct pci_bus *bus,
						unsigned long type)
{
	struct pci_dev *bridge;
	struct pci_controller *hose = pci_bus_to_host(bus);
	struct pnv_phb *phb = hose->private_data;
	int num_pci_bridges = 0;

	bridge = bus->self;
	while (bridge) {
		if (pci_pcie_type(bridge) == PCI_EXP_TYPE_PCI_BRIDGE) {
			num_pci_bridges++;
			if (num_pci_bridges >= 2)
				return 1;
		}

		bridge = bridge->bus->self;
	}

3120 3121 3122 3123 3124
	/*
	 * We fall back to M32 if M64 isn't supported. We enforce the M64
	 * alignment for any 64-bit resource, PCIe doesn't care and
	 * bridges only do 64-bit prefetchable anyway.
	 */
3125
	if (phb->ioda.m64_segsize && pnv_pci_is_m64_flags(type))
3126
		return phb->ioda.m64_segsize;
3127 3128 3129 3130 3131 3132
	if (type & IORESOURCE_MEM)
		return phb->ioda.m32_segsize;

	return phb->ioda.io_segsize;
}

3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164
/*
 * We are updating root port or the upstream port of the
 * bridge behind the root port with PHB's windows in order
 * to accommodate the changes on required resources during
 * PCI (slot) hotplug, which is connected to either root
 * port or the downstream ports of PCIe switch behind the
 * root port.
 */
static void pnv_pci_fixup_bridge_resources(struct pci_bus *bus,
					   unsigned long type)
{
	struct pci_controller *hose = pci_bus_to_host(bus);
	struct pnv_phb *phb = hose->private_data;
	struct pci_dev *bridge = bus->self;
	struct resource *r, *w;
	bool msi_region = false;
	int i;

	/* Check if we need apply fixup to the bridge's windows */
	if (!pci_is_root_bus(bridge->bus) &&
	    !pci_is_root_bus(bridge->bus->self->bus))
		return;

	/* Fixup the resources */
	for (i = 0; i < PCI_BRIDGE_RESOURCE_NUM; i++) {
		r = &bridge->resource[PCI_BRIDGE_RESOURCES + i];
		if (!r->flags || !r->parent)
			continue;

		w = NULL;
		if (r->flags & type & IORESOURCE_IO)
			w = &hose->io_resource;
3165
		else if (pnv_pci_is_m64(phb, r) &&
3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190
			 (type & IORESOURCE_PREFETCH) &&
			 phb->ioda.m64_segsize)
			w = &hose->mem_resources[1];
		else if (r->flags & type & IORESOURCE_MEM) {
			w = &hose->mem_resources[0];
			msi_region = true;
		}

		r->start = w->start;
		r->end = w->end;

		/* The 64KB 32-bits MSI region shouldn't be included in
		 * the 32-bits bridge window. Otherwise, we can see strange
		 * issues. One of them is EEH error observed on Garrison.
		 *
		 * Exclude top 1MB region which is the minimal alignment of
		 * 32-bits bridge window.
		 */
		if (msi_region) {
			r->end += 0x10000;
			r->end -= 0x100000;
		}
	}
}

3191
static void pnv_pci_configure_bus(struct pci_bus *bus)
3192 3193 3194 3195 3196
{
	struct pci_controller *hose = pci_bus_to_host(bus);
	struct pnv_phb *phb = hose->private_data;
	struct pci_dev *bridge = bus->self;
	struct pnv_ioda_pe *pe;
3197
	bool all = (bridge && pci_pcie_type(bridge) == PCI_EXP_TYPE_PCI_BRIDGE);
3198

3199
	dev_info(&bus->dev, "Configuring PE for bus\n");
3200

3201
	/* Don't assign PE to PCI bus, which doesn't have subordinate devices */
3202
	if (WARN_ON(list_empty(&bus->devices)))
3203 3204 3205
		return;

	/* Reserve PEs according to used M64 resources */
3206
	pnv_ioda_reserve_m64_pe(bus, NULL, all);
3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225

	/*
	 * Assign PE. We might run here because of partial hotplug.
	 * For the case, we just pick up the existing PE and should
	 * not allocate resources again.
	 */
	pe = pnv_ioda_setup_bus_PE(bus, all);
	if (!pe)
		return;

	pnv_ioda_setup_pe_seg(pe);
	switch (phb->type) {
	case PNV_PHB_IODA1:
		pnv_pci_ioda1_setup_dma_pe(phb, pe);
		break;
	case PNV_PHB_IODA2:
		pnv_pci_ioda2_setup_dma_pe(phb, pe);
		break;
	default:
3226
		pr_warn("%s: No DMA for PHB#%x (type %d)\n",
3227 3228 3229 3230
			__func__, phb->hose->global_number, phb->type);
	}
}

3231 3232 3233 3234 3235
static resource_size_t pnv_pci_default_alignment(void)
{
	return PAGE_SIZE;
}

3236 3237 3238 3239
#ifdef CONFIG_PCI_IOV
static resource_size_t pnv_pci_iov_resource_alignment(struct pci_dev *pdev,
						      int resno)
{
3240 3241
	struct pci_controller *hose = pci_bus_to_host(pdev->bus);
	struct pnv_phb *phb = hose->private_data;
3242
	struct pci_dn *pdn = pci_get_pdn(pdev);
3243
	resource_size_t align;
3244

3245 3246 3247 3248 3249
	/*
	 * On PowerNV platform, IOV BAR is mapped by M64 BAR to enable the
	 * SR-IOV. While from hardware perspective, the range mapped by M64
	 * BAR should be size aligned.
	 *
3250 3251 3252 3253 3254 3255 3256
	 * When IOV BAR is mapped with M64 BAR in Single PE mode, the extra
	 * powernv-specific hardware restriction is gone. But if just use the
	 * VF BAR size as the alignment, PF BAR / VF BAR may be allocated with
	 * in one segment of M64 #15, which introduces the PE conflict between
	 * PF and VF. Based on this, the minimum alignment of an IOV BAR is
	 * m64_segsize.
	 *
3257 3258
	 * This function returns the total IOV BAR size if M64 BAR is in
	 * Shared PE mode or just VF BAR size if not.
3259 3260
	 * If the M64 BAR is in Single PE mode, return the VF BAR size or
	 * M64 segment size if IOV BAR size is less.
3261
	 */
3262
	align = pci_iov_resource_size(pdev, resno);
3263 3264
	if (!pdn->vfs_expanded)
		return align;
3265 3266
	if (pdn->m64_single_mode)
		return max(align, (resource_size_t)phb->ioda.m64_segsize);
3267

3268
	return pdn->vfs_expanded * align;
3269 3270 3271
}
#endif /* CONFIG_PCI_IOV */

3272 3273 3274
/* Prevent enabling devices for which we couldn't properly
 * assign a PE
 */
3275
static bool pnv_pci_enable_device_hook(struct pci_dev *dev)
3276
{
3277 3278 3279
	struct pci_controller *hose = pci_bus_to_host(dev->bus);
	struct pnv_phb *phb = hose->private_data;
	struct pci_dn *pdn;
3280

3281 3282 3283 3284 3285 3286
	/* The function is probably called while the PEs have
	 * not be created yet. For example, resource reassignment
	 * during PCI probe period. We just skip the check if
	 * PEs isn't ready.
	 */
	if (!phb->initialized)
3287
		return true;
3288

3289
	pdn = pci_get_pdn(dev);
3290
	if (!pdn || pdn->pe_number == IODA_INVALID_PE)
3291
		return false;
3292

3293
	return true;
3294 3295
}

3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
static bool pnv_ocapi_enable_device_hook(struct pci_dev *dev)
{
	struct pci_controller *hose = pci_bus_to_host(dev->bus);
	struct pnv_phb *phb = hose->private_data;
	struct pci_dn *pdn;
	struct pnv_ioda_pe *pe;

	if (!phb->initialized)
		return true;

	pdn = pci_get_pdn(dev);
	if (!pdn)
		return false;

	if (pdn->pe_number == IODA_INVALID_PE) {
		pe = pnv_ioda_setup_dev_PE(dev);
		if (!pe)
			return false;
	}
	return true;
}

3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359
static long pnv_pci_ioda1_unset_window(struct iommu_table_group *table_group,
				       int num)
{
	struct pnv_ioda_pe *pe = container_of(table_group,
					      struct pnv_ioda_pe, table_group);
	struct pnv_phb *phb = pe->phb;
	unsigned int idx;
	long rc;

	pe_info(pe, "Removing DMA window #%d\n", num);
	for (idx = 0; idx < phb->ioda.dma32_count; idx++) {
		if (phb->ioda.dma32_segmap[idx] != pe->pe_number)
			continue;

		rc = opal_pci_map_pe_dma_window(phb->opal_id, pe->pe_number,
						idx, 0, 0ul, 0ul, 0ul);
		if (rc != OPAL_SUCCESS) {
			pe_warn(pe, "Failure %ld unmapping DMA32 segment#%d\n",
				rc, idx);
			return rc;
		}

		phb->ioda.dma32_segmap[idx] = IODA_INVALID_PE;
	}

	pnv_pci_unlink_table_and_group(table_group->tables[num], table_group);
	return OPAL_SUCCESS;
}

static void pnv_pci_ioda1_release_pe_dma(struct pnv_ioda_pe *pe)
{
	unsigned int weight = pnv_pci_ioda_pe_dma_weight(pe);
	struct iommu_table *tbl = pe->table_group.tables[0];
	int64_t rc;

	if (!weight)
		return;

	rc = pnv_pci_ioda1_unset_window(&pe->table_group, 0);
	if (rc != OPAL_SUCCESS)
		return;

3360
	pnv_pci_p7ioc_tce_invalidate(tbl, tbl->it_offset, tbl->it_size, false);
3361 3362 3363 3364 3365 3366
	if (pe->table_group.group) {
		iommu_group_put(pe->table_group.group);
		WARN_ON(pe->table_group.group);
	}

	free_pages(tbl->it_base, get_order(tbl->it_size << 3));
3367
	iommu_tce_table_put(tbl);
3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
}

static void pnv_pci_ioda2_release_pe_dma(struct pnv_ioda_pe *pe)
{
	struct iommu_table *tbl = pe->table_group.tables[0];
	unsigned int weight = pnv_pci_ioda_pe_dma_weight(pe);
#ifdef CONFIG_IOMMU_API
	int64_t rc;
#endif

	if (!weight)
		return;

#ifdef CONFIG_IOMMU_API
	rc = pnv_pci_ioda2_unset_window(&pe->table_group, 0);
	if (rc)
3384
		pe_warn(pe, "OPAL error %lld release DMA window\n", rc);
3385 3386 3387 3388 3389 3390 3391 3392
#endif

	pnv_pci_ioda2_set_bypass(pe, false);
	if (pe->table_group.group) {
		iommu_group_put(pe->table_group.group);
		WARN_ON(pe->table_group.group);
	}

3393
	iommu_tce_table_put(tbl);
3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
}

static void pnv_ioda_free_pe_seg(struct pnv_ioda_pe *pe,
				 unsigned short win,
				 unsigned int *map)
{
	struct pnv_phb *phb = pe->phb;
	int idx;
	int64_t rc;

	for (idx = 0; idx < phb->ioda.total_pe_num; idx++) {
		if (map[idx] != pe->pe_number)
			continue;

		if (win == OPAL_M64_WINDOW_TYPE)
			rc = opal_pci_map_pe_mmio_window(phb->opal_id,
					phb->ioda.reserved_pe_idx, win,
					idx / PNV_IODA1_M64_SEGS,
					idx % PNV_IODA1_M64_SEGS);
		else
			rc = opal_pci_map_pe_mmio_window(phb->opal_id,
					phb->ioda.reserved_pe_idx, win, 0, idx);

		if (rc != OPAL_SUCCESS)
3418
			pe_warn(pe, "Error %lld unmapping (%d) segment#%d\n",
3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446
				rc, win, idx);

		map[idx] = IODA_INVALID_PE;
	}
}

static void pnv_ioda_release_pe_seg(struct pnv_ioda_pe *pe)
{
	struct pnv_phb *phb = pe->phb;

	if (phb->type == PNV_PHB_IODA1) {
		pnv_ioda_free_pe_seg(pe, OPAL_IO_WINDOW_TYPE,
				     phb->ioda.io_segmap);
		pnv_ioda_free_pe_seg(pe, OPAL_M32_WINDOW_TYPE,
				     phb->ioda.m32_segmap);
		pnv_ioda_free_pe_seg(pe, OPAL_M64_WINDOW_TYPE,
				     phb->ioda.m64_segmap);
	} else if (phb->type == PNV_PHB_IODA2) {
		pnv_ioda_free_pe_seg(pe, OPAL_M32_WINDOW_TYPE,
				     phb->ioda.m32_segmap);
	}
}

static void pnv_ioda_release_pe(struct pnv_ioda_pe *pe)
{
	struct pnv_phb *phb = pe->phb;
	struct pnv_ioda_pe *slave, *tmp;

3447 3448
	pe_info(pe, "Releasing PE\n");

3449
	mutex_lock(&phb->ioda.pe_list_mutex);
3450
	list_del(&pe->list);
3451 3452
	mutex_unlock(&phb->ioda.pe_list_mutex);

3453 3454 3455 3456 3457 3458 3459
	switch (phb->type) {
	case PNV_PHB_IODA1:
		pnv_pci_ioda1_release_pe_dma(pe);
		break;
	case PNV_PHB_IODA2:
		pnv_pci_ioda2_release_pe_dma(pe);
		break;
3460 3461
	case PNV_PHB_NPU_OCAPI:
		break;
3462 3463 3464 3465 3466 3467
	default:
		WARN_ON(1);
	}

	pnv_ioda_release_pe_seg(pe);
	pnv_ioda_deconfigure_pe(pe->phb, pe);
3468 3469 3470 3471 3472 3473 3474 3475 3476

	/* Release slave PEs in the compound PE */
	if (pe->flags & PNV_IODA_PE_MASTER) {
		list_for_each_entry_safe(slave, tmp, &pe->slaves, list) {
			list_del(&slave->list);
			pnv_ioda_free_pe(slave);
		}
	}

3477 3478 3479 3480 3481 3482
	/*
	 * The PE for root bus can be removed because of hotplug in EEH
	 * recovery for fenced PHB error. We need to mark the PE dead so
	 * that it can be populated again in PCI hot add path. The PE
	 * shouldn't be destroyed as it's the global reserved resource.
	 */
3483 3484 3485 3486
	if (phb->ioda.root_pe_idx == pe->pe_number)
		return;

	pnv_ioda_free_pe(pe);
3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501
}

static void pnv_pci_release_device(struct pci_dev *pdev)
{
	struct pci_controller *hose = pci_bus_to_host(pdev->bus);
	struct pnv_phb *phb = hose->private_data;
	struct pci_dn *pdn = pci_get_pdn(pdev);
	struct pnv_ioda_pe *pe;

	if (pdev->is_virtfn)
		return;

	if (!pdn || pdn->pe_number == IODA_INVALID_PE)
		return;

3502 3503 3504 3505 3506 3507 3508 3509
	/*
	 * PCI hotplug can happen as part of EEH error recovery. The @pdn
	 * isn't removed and added afterwards in this scenario. We should
	 * set the PE number in @pdn to an invalid one. Otherwise, the PE's
	 * device count is decreased on removing devices while failing to
	 * be increased on adding devices. It leads to unbalanced PE's device
	 * count and eventually make normal PCI hotplug path broken.
	 */
3510
	pe = &phb->ioda.pe_array[pdn->pe_number];
3511 3512
	pdn->pe_number = IODA_INVALID_PE;

3513 3514 3515 3516 3517
	WARN_ON(--pe->device_count < 0);
	if (pe->device_count == 0)
		pnv_ioda_release_pe(pe);
}

3518 3519 3520 3521 3522 3523 3524 3525 3526
static void pnv_npu_disable_device(struct pci_dev *pdev)
{
	struct eeh_dev *edev = pci_dev_to_eeh_dev(pdev);
	struct eeh_pe *eehpe = edev ? edev->pe : NULL;

	if (eehpe && eeh_ops && eeh_ops->reset)
		eeh_ops->reset(eehpe, EEH_RESET_HOT);
}

3527
static void pnv_pci_ioda_shutdown(struct pci_controller *hose)
3528
{
3529 3530
	struct pnv_phb *phb = hose->private_data;

3531
	opal_pci_reset(phb->opal_id, OPAL_RESET_PCI_IODA_TABLE,
3532 3533 3534
		       OPAL_ASSERT_RESET);
}

3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554
static void pnv_pci_ioda_dma_bus_setup(struct pci_bus *bus)
{
	struct pci_controller *hose = bus->sysdata;
	struct pnv_phb *phb = hose->private_data;
	struct pnv_ioda_pe *pe;

	list_for_each_entry(pe, &phb->ioda.pe_list, list) {
		if (!(pe->flags & (PNV_IODA_PE_BUS | PNV_IODA_PE_BUS_ALL)))
			continue;

		if (!pe->pbus)
			continue;

		if (bus->number == ((pe->rid >> 8) & 0xFF)) {
			pe->pbus = bus;
			break;
		}
	}
}

3555
static const struct pci_controller_ops pnv_pci_ioda_controller_ops = {
3556
	.dma_dev_setup		= pnv_pci_ioda_dma_dev_setup,
3557
	.dma_bus_setup		= pnv_pci_ioda_dma_bus_setup,
3558
	.iommu_bypass_supported	= pnv_pci_ioda_iommu_bypass_supported,
3559 3560 3561
	.setup_msi_irqs		= pnv_setup_msi_irqs,
	.teardown_msi_irqs	= pnv_teardown_msi_irqs,
	.enable_device_hook	= pnv_pci_enable_device_hook,
3562
	.release_device		= pnv_pci_release_device,
3563
	.window_alignment	= pnv_pci_window_alignment,
3564
	.setup_bridge		= pnv_pci_fixup_bridge_resources,
3565 3566
	.reset_secondary_bus	= pnv_pci_reset_secondary_bus,
	.shutdown		= pnv_pci_ioda_shutdown,
3567 3568
};

3569
static const struct pci_controller_ops pnv_npu_ioda_controller_ops = {
3570 3571 3572 3573 3574 3575
	.setup_msi_irqs		= pnv_setup_msi_irqs,
	.teardown_msi_irqs	= pnv_teardown_msi_irqs,
	.enable_device_hook	= pnv_pci_enable_device_hook,
	.window_alignment	= pnv_pci_window_alignment,
	.reset_secondary_bus	= pnv_pci_reset_secondary_bus,
	.shutdown		= pnv_pci_ioda_shutdown,
3576
	.disable_device		= pnv_npu_disable_device,
3577 3578
};

3579
static const struct pci_controller_ops pnv_npu_ocapi_ioda_controller_ops = {
3580
	.enable_device_hook	= pnv_ocapi_enable_device_hook,
3581
	.release_device		= pnv_pci_release_device,
3582 3583 3584 3585 3586
	.window_alignment	= pnv_pci_window_alignment,
	.reset_secondary_bus	= pnv_pci_reset_secondary_bus,
	.shutdown		= pnv_pci_ioda_shutdown,
};

3587 3588
static void __init pnv_pci_init_ioda_phb(struct device_node *np,
					 u64 hub_id, int ioda_type)
3589 3590 3591
{
	struct pci_controller *hose;
	struct pnv_phb *phb;
3592 3593
	unsigned long size, m64map_off, m32map_off, pemap_off;
	unsigned long iomap_off = 0, dma32map_off = 0;
3594
	struct pnv_ioda_pe *root_pe;
3595
	struct resource r;
3596
	const __be64 *prop64;
3597
	const __be32 *prop32;
3598
	int len;
3599
	unsigned int segno;
3600 3601 3602 3603
	u64 phb_id;
	void *aux;
	long rc;

3604 3605 3606
	if (!of_device_is_available(np))
		return;

3607
	pr_info("Initializing %s PHB (%pOF)\n",	pnv_phb_names[ioda_type], np);
3608 3609 3610 3611 3612 3613 3614 3615 3616

	prop64 = of_get_property(np, "ibm,opal-phbid", NULL);
	if (!prop64) {
		pr_err("  Missing \"ibm,opal-phbid\" property !\n");
		return;
	}
	phb_id = be64_to_cpup(prop64);
	pr_debug("  PHB-ID  : 0x%016llx\n", phb_id);

3617
	phb = memblock_alloc(sizeof(*phb), SMP_CACHE_BYTES);
3618 3619 3620
	if (!phb)
		panic("%s: Failed to allocate %zu bytes\n", __func__,
		      sizeof(*phb));
3621 3622 3623 3624

	/* Allocate PCI controller */
	phb->hose = hose = pcibios_alloc_controller(np);
	if (!phb->hose) {
3625 3626
		pr_err("  Can't allocate PCI controller for %pOF\n",
		       np);
3627
		memblock_free(__pa(phb), sizeof(struct pnv_phb));
3628 3629 3630 3631
		return;
	}

	spin_lock_init(&phb->lock);
3632 3633
	prop32 = of_get_property(np, "bus-range", &len);
	if (prop32 && len == 8) {
3634 3635
		hose->first_busno = be32_to_cpu(prop32[0]);
		hose->last_busno = be32_to_cpu(prop32[1]);
3636
	} else {
3637
		pr_warn("  Broken <bus-range> on %pOF\n", np);
3638 3639 3640
		hose->first_busno = 0;
		hose->last_busno = 0xff;
	}
3641
	hose->private_data = phb;
3642
	phb->hub_id = hub_id;
3643
	phb->opal_id = phb_id;
G
Gavin Shan 已提交
3644
	phb->type = ioda_type;
3645
	mutex_init(&phb->ioda.pe_alloc_mutex);
3646

3647 3648 3649
	/* Detect specific models for error handling */
	if (of_device_is_compatible(np, "ibm,p7ioc-pciex"))
		phb->model = PNV_PHB_MODEL_P7IOC;
3650
	else if (of_device_is_compatible(np, "ibm,power8-pciex"))
G
Gavin Shan 已提交
3651
		phb->model = PNV_PHB_MODEL_PHB3;
3652 3653
	else if (of_device_is_compatible(np, "ibm,power8-npu-pciex"))
		phb->model = PNV_PHB_MODEL_NPU;
3654 3655
	else if (of_device_is_compatible(np, "ibm,power9-npu-pciex"))
		phb->model = PNV_PHB_MODEL_NPU2;
3656 3657 3658
	else
		phb->model = PNV_PHB_MODEL_UNKNOWN;

3659 3660 3661 3662 3663 3664 3665
	/* Initialize diagnostic data buffer */
	prop32 = of_get_property(np, "ibm,phb-diag-data-size", NULL);
	if (prop32)
		phb->diag_data_size = be32_to_cpup(prop32);
	else
		phb->diag_data_size = PNV_PCI_DIAG_BUF_SIZE;

3666
	phb->diag_data = memblock_alloc(phb->diag_data_size, SMP_CACHE_BYTES);
3667 3668 3669
	if (!phb->diag_data)
		panic("%s: Failed to allocate %u bytes\n", __func__,
		      phb->diag_data_size);
3670

G
Gavin Shan 已提交
3671
	/* Parse 32-bit and IO ranges (if any) */
3672
	pci_process_bridge_OF_ranges(hose, np, !hose->global_number);
3673

G
Gavin Shan 已提交
3674
	/* Get registers */
3675 3676 3677 3678 3679 3680
	if (!of_address_to_resource(np, 0, &r)) {
		phb->regs_phys = r.start;
		phb->regs = ioremap(r.start, resource_size(&r));
		if (phb->regs == NULL)
			pr_err("  Failed to map registers !\n");
	}
3681

3682
	/* Initialize more IODA stuff */
3683
	phb->ioda.total_pe_num = 1;
G
Gavin Shan 已提交
3684
	prop32 = of_get_property(np, "ibm,opal-num-pes", NULL);
3685
	if (prop32)
3686
		phb->ioda.total_pe_num = be32_to_cpup(prop32);
3687 3688
	prop32 = of_get_property(np, "ibm,opal-reserved-pe", NULL);
	if (prop32)
3689
		phb->ioda.reserved_pe_idx = be32_to_cpup(prop32);
3690

3691 3692 3693 3694
	/* Invalidate RID to PE# mapping */
	for (segno = 0; segno < ARRAY_SIZE(phb->ioda.pe_rmap); segno++)
		phb->ioda.pe_rmap[segno] = IODA_INVALID_PE;

3695 3696 3697
	/* Parse 64-bit MMIO range */
	pnv_ioda_parse_m64_window(phb);

3698
	phb->ioda.m32_size = resource_size(&hose->mem_resources[0]);
G
Gavin Shan 已提交
3699
	/* FW Has already off top 64k of M32 space (MSI space) */
3700 3701
	phb->ioda.m32_size += 0x10000;

3702
	phb->ioda.m32_segsize = phb->ioda.m32_size / phb->ioda.total_pe_num;
3703
	phb->ioda.m32_pci_base = hose->mem_resources[0].start - hose->mem_offset[0];
3704
	phb->ioda.io_size = hose->pci_io_size;
3705
	phb->ioda.io_segsize = phb->ioda.io_size / phb->ioda.total_pe_num;
3706 3707
	phb->ioda.io_pci_base = 0; /* XXX calculate this ? */

3708 3709 3710 3711
	/* Calculate how many 32-bit TCE segments we have */
	phb->ioda.dma32_count = phb->ioda.m32_pci_base /
				PNV_IODA1_DMA32_SEGSIZE;

3712
	/* Allocate aux data & arrays. We don't have IO ports on PHB3 */
3713
	size = ALIGN(max_t(unsigned, phb->ioda.total_pe_num, 8) / 8,
3714
			sizeof(unsigned long));
3715 3716
	m64map_off = size;
	size += phb->ioda.total_pe_num * sizeof(phb->ioda.m64_segmap[0]);
3717
	m32map_off = size;
3718
	size += phb->ioda.total_pe_num * sizeof(phb->ioda.m32_segmap[0]);
3719 3720
	if (phb->type == PNV_PHB_IODA1) {
		iomap_off = size;
3721
		size += phb->ioda.total_pe_num * sizeof(phb->ioda.io_segmap[0]);
3722 3723 3724
		dma32map_off = size;
		size += phb->ioda.dma32_count *
			sizeof(phb->ioda.dma32_segmap[0]);
3725
	}
3726
	pemap_off = size;
3727
	size += phb->ioda.total_pe_num * sizeof(struct pnv_ioda_pe);
3728
	aux = memblock_alloc(size, SMP_CACHE_BYTES);
3729 3730
	if (!aux)
		panic("%s: Failed to allocate %lu bytes\n", __func__, size);
3731
	phb->ioda.pe_alloc = aux;
3732
	phb->ioda.m64_segmap = aux + m64map_off;
3733
	phb->ioda.m32_segmap = aux + m32map_off;
3734 3735
	for (segno = 0; segno < phb->ioda.total_pe_num; segno++) {
		phb->ioda.m64_segmap[segno] = IODA_INVALID_PE;
3736
		phb->ioda.m32_segmap[segno] = IODA_INVALID_PE;
3737
	}
3738
	if (phb->type == PNV_PHB_IODA1) {
3739
		phb->ioda.io_segmap = aux + iomap_off;
3740 3741
		for (segno = 0; segno < phb->ioda.total_pe_num; segno++)
			phb->ioda.io_segmap[segno] = IODA_INVALID_PE;
3742 3743 3744 3745

		phb->ioda.dma32_segmap = aux + dma32map_off;
		for (segno = 0; segno < phb->ioda.dma32_count; segno++)
			phb->ioda.dma32_segmap[segno] = IODA_INVALID_PE;
3746
	}
3747
	phb->ioda.pe_array = aux + pemap_off;
3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761

	/*
	 * Choose PE number for root bus, which shouldn't have
	 * M64 resources consumed by its child devices. To pick
	 * the PE number adjacent to the reserved one if possible.
	 */
	pnv_ioda_reserve_pe(phb, phb->ioda.reserved_pe_idx);
	if (phb->ioda.reserved_pe_idx == 0) {
		phb->ioda.root_pe_idx = 1;
		pnv_ioda_reserve_pe(phb, phb->ioda.root_pe_idx);
	} else if (phb->ioda.reserved_pe_idx == (phb->ioda.total_pe_num - 1)) {
		phb->ioda.root_pe_idx = phb->ioda.reserved_pe_idx - 1;
		pnv_ioda_reserve_pe(phb, phb->ioda.root_pe_idx);
	} else {
3762 3763 3764
		/* otherwise just allocate one */
		root_pe = pnv_ioda_alloc_pe(phb);
		phb->ioda.root_pe_idx = root_pe->pe_number;
3765
	}
3766 3767

	INIT_LIST_HEAD(&phb->ioda.pe_list);
3768
	mutex_init(&phb->ioda.pe_list_mutex);
3769 3770

	/* Calculate how many 32-bit TCE segments we have */
3771
	phb->ioda.dma32_count = phb->ioda.m32_pci_base /
3772
				PNV_IODA1_DMA32_SEGSIZE;
3773

G
Gavin Shan 已提交
3774
#if 0 /* We should really do that ... */
3775 3776 3777 3778 3779 3780 3781 3782
	rc = opal_pci_set_phb_mem_window(opal->phb_id,
					 window_type,
					 window_num,
					 starting_real_address,
					 starting_pci_address,
					 segment_size);
#endif

3783
	pr_info("  %03d (%03d) PE's M32: 0x%x [segment=0x%x]\n",
3784
		phb->ioda.total_pe_num, phb->ioda.reserved_pe_idx,
3785 3786 3787 3788 3789 3790 3791 3792
		phb->ioda.m32_size, phb->ioda.m32_segsize);
	if (phb->ioda.m64_size)
		pr_info("                 M64: 0x%lx [segment=0x%lx]\n",
			phb->ioda.m64_size, phb->ioda.m64_segsize);
	if (phb->ioda.io_size)
		pr_info("                  IO: 0x%x [segment=0x%x]\n",
			phb->ioda.io_size, phb->ioda.io_segsize);

3793 3794

	phb->hose->ops = &pnv_pci_ops;
G
Gavin Shan 已提交
3795 3796 3797
	phb->get_pe_state = pnv_ioda_get_pe_state;
	phb->freeze_pe = pnv_ioda_freeze_pe;
	phb->unfreeze_pe = pnv_ioda_unfreeze_pe;
3798 3799 3800 3801

	/* Setup MSI support */
	pnv_pci_init_ioda_msis(phb);

3802 3803 3804 3805 3806 3807
	/*
	 * We pass the PCI probe flag PCI_REASSIGN_ALL_RSRC here
	 * to let the PCI core do resource assignment. It's supposed
	 * that the PCI core will do correct I/O and MMIO alignment
	 * for the P2P bridge bars so that each PCI bus (excluding
	 * the child P2P bridges) can form individual PE.
3808
	 */
3809
	ppc_md.pcibios_fixup = pnv_pci_ioda_fixup;
3810

3811 3812
	switch (phb->type) {
	case PNV_PHB_NPU_NVLINK:
3813
		hose->controller_ops = pnv_npu_ioda_controller_ops;
3814 3815 3816 3817 3818
		break;
	case PNV_PHB_NPU_OCAPI:
		hose->controller_ops = pnv_npu_ocapi_ioda_controller_ops;
		break;
	default:
3819
		hose->controller_ops = pnv_pci_ioda_controller_ops;
3820
	}
3821

3822 3823
	ppc_md.pcibios_default_alignment = pnv_pci_default_alignment;

3824
#ifdef CONFIG_PCI_IOV
3825
	ppc_md.pcibios_fixup_sriov = pnv_pci_ioda_fixup_iov;
3826
	ppc_md.pcibios_iov_resource_alignment = pnv_pci_iov_resource_alignment;
B
Bryant G. Ly 已提交
3827 3828
	ppc_md.pcibios_sriov_enable = pnv_pcibios_sriov_enable;
	ppc_md.pcibios_sriov_disable = pnv_pcibios_sriov_disable;
3829 3830
#endif

3831
	pci_add_flags(PCI_REASSIGN_ALL_RSRC);
3832 3833

	/* Reset IODA tables to a clean state */
3834
	rc = opal_pci_reset(phb_id, OPAL_RESET_PCI_IODA_TABLE, OPAL_ASSERT_RESET);
3835
	if (rc)
3836
		pr_warn("  OPAL Error %ld performing IODA table reset !\n", rc);
3837

3838 3839
	/*
	 * If we're running in kdump kernel, the previous kernel never
3840 3841
	 * shutdown PCI devices correctly. We already got IODA table
	 * cleaned out. So we have to issue PHB reset to stop all PCI
3842
	 * transactions from previous kernel. The ppc_pci_reset_phbs
3843 3844 3845 3846
	 * kernel parameter will force this reset too. Additionally,
	 * if the IODA reset above failed then use a bigger hammer.
	 * This can happen if we get a PHB fatal error in very early
	 * boot.
3847
	 */
3848
	if (is_kdump_kernel() || pci_reset_phbs || rc) {
3849
		pr_info("  Issue PHB reset ...\n");
3850 3851
		pnv_eeh_phb_reset(hose, EEH_RESET_FUNDAMENTAL);
		pnv_eeh_phb_reset(hose, EEH_RESET_DEACTIVATE);
3852
	}
3853

3854 3855
	/* Remove M64 resource if we can't configure it successfully */
	if (!phb->init_m64 || phb->init_m64(phb))
3856
		hose->mem_resources[1].flags = 0;
G
Gavin Shan 已提交
3857 3858
}

3859
void __init pnv_pci_init_ioda2_phb(struct device_node *np)
G
Gavin Shan 已提交
3860
{
3861
	pnv_pci_init_ioda_phb(np, 0, PNV_PHB_IODA2);
3862 3863
}

3864 3865
void __init pnv_pci_init_npu_phb(struct device_node *np)
{
3866 3867 3868 3869 3870 3871
	pnv_pci_init_ioda_phb(np, 0, PNV_PHB_NPU_NVLINK);
}

void __init pnv_pci_init_npu2_opencapi_phb(struct device_node *np)
{
	pnv_pci_init_ioda_phb(np, 0, PNV_PHB_NPU_OCAPI);
3872 3873
}

3874 3875 3876 3877 3878 3879 3880 3881 3882 3883
static void pnv_npu2_opencapi_cfg_size_fixup(struct pci_dev *dev)
{
	struct pci_controller *hose = pci_bus_to_host(dev->bus);
	struct pnv_phb *phb = hose->private_data;

	if (!machine_is(powernv))
		return;

	if (phb->type == PNV_PHB_NPU_OCAPI)
		dev->cfg_size = PCI_CFG_SPACE_EXP_SIZE;
3884
}
3885
DECLARE_PCI_FIXUP_EARLY(PCI_ANY_ID, PCI_ANY_ID, pnv_npu2_opencapi_cfg_size_fixup);
3886

3887 3888 3889
void __init pnv_pci_init_ioda_hub(struct device_node *np)
{
	struct device_node *phbn;
3890
	const __be64 *prop64;
3891 3892
	u64 hub_id;

3893
	pr_info("Probing IODA IO-Hub %pOF\n", np);
3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906

	prop64 = of_get_property(np, "ibm,opal-hubid", NULL);
	if (!prop64) {
		pr_err(" Missing \"ibm,opal-hubid\" property !\n");
		return;
	}
	hub_id = be64_to_cpup(prop64);
	pr_devel(" HUB-ID : 0x%016llx\n", hub_id);

	/* Count child PHBs */
	for_each_child_of_node(np, phbn) {
		/* Look for IODA1 PHBs */
		if (of_device_is_compatible(phbn, "ibm,ioda-phb"))
3907
			pnv_pci_init_ioda_phb(phbn, hub_id, PNV_PHB_IODA1);
3908 3909
	}
}