xref: /linux/drivers/cxl/core/cdat.c (revision d304df5f329302fff4658cd6ed8f93aec4b94d27)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright(c) 2023 Intel Corporation. All rights reserved. */
3 #include <linux/acpi.h>
4 #include <linux/xarray.h>
5 #include <linux/fw_table.h>
6 #include <linux/node.h>
7 #include <linux/overflow.h>
8 #include "cxlpci.h"
9 #include "cxlmem.h"
10 #include "core.h"
11 #include "cxl.h"
12 
13 struct dsmas_entry {
14 	struct range dpa_range;
15 	u8 handle;
16 	struct access_coordinate coord[ACCESS_COORDINATE_MAX];
17 	struct access_coordinate cdat_coord[ACCESS_COORDINATE_MAX];
18 	int entries;
19 	int qos_class;
20 	bool shareable;
21 	bool read_only;
22 };
23 
24 static u32 cdat_normalize(u16 entry, u64 base, u8 type)
25 {
26 	u32 value;
27 
28 	/*
29 	 * Check for invalid and overflow values
30 	 */
31 	if (entry == 0xffff || !entry)
32 		return 0;
33 	if (base > (UINT_MAX / (entry)))
34 		return 0;
35 
36 	/*
37 	 * CDAT fields follow the format of HMAT fields. See table 5 Device
38 	 * Scoped Latency and Bandwidth Information Structure in Coherent Device
39 	 * Attribute Table (CDAT) Specification v1.01.
40 	 */
41 	value = entry * base;
42 	switch (type) {
43 	case ACPI_HMAT_ACCESS_LATENCY:
44 	case ACPI_HMAT_READ_LATENCY:
45 	case ACPI_HMAT_WRITE_LATENCY:
46 		value = DIV_ROUND_UP(value, 1000);
47 		break;
48 	default:
49 		break;
50 	}
51 	return value;
52 }
53 
54 static int cdat_dsmas_handler(union acpi_subtable_headers *header, void *arg,
55 			      const unsigned long end)
56 {
57 	struct acpi_cdat_header *hdr = &header->cdat;
58 	struct acpi_cdat_dsmas *dsmas;
59 	int size = sizeof(*hdr) + sizeof(*dsmas);
60 	struct xarray *dsmas_xa = arg;
61 	struct dsmas_entry *dent;
62 	u16 len;
63 	int rc;
64 
65 	len = le16_to_cpu((__force __le16)hdr->length);
66 	if (len != size || (unsigned long)hdr + len > end) {
67 		pr_warn("Malformed DSMAS table length: (%u:%u)\n", size, len);
68 		return -EINVAL;
69 	}
70 
71 	/* Skip common header */
72 	dsmas = (struct acpi_cdat_dsmas *)(hdr + 1);
73 
74 	dent = kzalloc_obj(*dent);
75 	if (!dent)
76 		return -ENOMEM;
77 
78 	/* Stays invalid unless the QTG lookup assigns a class */
79 	dent->qos_class = CXL_QOS_CLASS_INVALID;
80 	dent->handle = dsmas->dsmad_handle;
81 	/* Shareable is CDAT 1.03 and later, DSMAS Flags bit 3 */
82 	dent->shareable = dsmas->flags & ACPI_CDAT_DSMAS_SHAREABLE;
83 	/* Read Only is CDAT 1.04 and later, DSMAS Flags bit 6 */
84 	dent->read_only = dsmas->flags & ACPI_CDAT_DSMAS_READ_ONLY;
85 	dent->dpa_range.start = le64_to_cpu((__force __le64)dsmas->dpa_base_address);
86 	dent->dpa_range.end = le64_to_cpu((__force __le64)dsmas->dpa_base_address) +
87 			      le64_to_cpu((__force __le64)dsmas->dpa_length) - 1;
88 
89 	rc = xa_insert(dsmas_xa, dent->handle, dent, GFP_KERNEL);
90 	if (rc) {
91 		kfree(dent);
92 		return rc;
93 	}
94 
95 	return 0;
96 }
97 
98 static void __cxl_access_coordinate_set(struct access_coordinate *coord,
99 					int access, unsigned int val)
100 {
101 	switch (access) {
102 	case ACPI_HMAT_ACCESS_LATENCY:
103 		coord->read_latency = val;
104 		coord->write_latency = val;
105 		break;
106 	case ACPI_HMAT_READ_LATENCY:
107 		coord->read_latency = val;
108 		break;
109 	case ACPI_HMAT_WRITE_LATENCY:
110 		coord->write_latency = val;
111 		break;
112 	case ACPI_HMAT_ACCESS_BANDWIDTH:
113 		coord->read_bandwidth = val;
114 		coord->write_bandwidth = val;
115 		break;
116 	case ACPI_HMAT_READ_BANDWIDTH:
117 		coord->read_bandwidth = val;
118 		break;
119 	case ACPI_HMAT_WRITE_BANDWIDTH:
120 		coord->write_bandwidth = val;
121 		break;
122 	}
123 }
124 
125 static void cxl_access_coordinate_set(struct access_coordinate *coord,
126 				      int access, unsigned int val)
127 {
128 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++)
129 		__cxl_access_coordinate_set(&coord[i], access, val);
130 }
131 
132 static int cdat_dslbis_handler(union acpi_subtable_headers *header, void *arg,
133 			       const unsigned long end)
134 {
135 	struct acpi_cdat_header *hdr = &header->cdat;
136 	struct acpi_cdat_dslbis *dslbis;
137 	int size = sizeof(*hdr) + sizeof(*dslbis);
138 	struct xarray *dsmas_xa = arg;
139 	struct dsmas_entry *dent;
140 	__le64 le_base;
141 	__le16 le_val;
142 	u64 val;
143 	u16 len;
144 
145 	len = le16_to_cpu((__force __le16)hdr->length);
146 	if (len != size || (unsigned long)hdr + len > end) {
147 		pr_warn("Malformed DSLBIS table length: (%u:%u)\n", size, len);
148 		return -EINVAL;
149 	}
150 
151 	/* Skip common header */
152 	dslbis = (struct acpi_cdat_dslbis *)(hdr + 1);
153 
154 	/* Skip unrecognized data type */
155 	if (dslbis->data_type > ACPI_HMAT_WRITE_BANDWIDTH)
156 		return 0;
157 
158 	/* Not a memory type, skip */
159 	if ((dslbis->flags & ACPI_HMAT_MEMORY_HIERARCHY) != ACPI_HMAT_MEMORY)
160 		return 0;
161 
162 	dent = xa_load(dsmas_xa, dslbis->handle);
163 	if (!dent) {
164 		pr_warn("No matching DSMAS entry for DSLBIS entry.\n");
165 		return 0;
166 	}
167 
168 	le_base = (__force __le64)dslbis->entry_base_unit;
169 	le_val = (__force __le16)dslbis->entry[0];
170 	val = cdat_normalize(le16_to_cpu(le_val), le64_to_cpu(le_base),
171 			     dslbis->data_type);
172 
173 	cxl_access_coordinate_set(dent->cdat_coord, dslbis->data_type, val);
174 
175 	return 0;
176 }
177 
178 static int cdat_table_parse_output(int rc)
179 {
180 	if (rc < 0)
181 		return rc;
182 	if (rc == 0)
183 		return -ENOENT;
184 
185 	return 0;
186 }
187 
188 static int cxl_cdat_endpoint_process(struct cxl_port *port,
189 				     struct xarray *dsmas_xa)
190 {
191 	int rc;
192 
193 	rc = cdat_table_parse(ACPI_CDAT_TYPE_DSMAS, cdat_dsmas_handler,
194 			      dsmas_xa, port->cdat.table, port->cdat.length);
195 	rc = cdat_table_parse_output(rc);
196 	if (rc)
197 		return rc;
198 
199 	/* DSLBIS is optional; zero entries is not an error */
200 	rc = cdat_table_parse(ACPI_CDAT_TYPE_DSLBIS, cdat_dslbis_handler,
201 			      dsmas_xa, port->cdat.table, port->cdat.length);
202 	return rc < 0 ? rc : 0;
203 }
204 
205 static int cxl_port_perf_data_calculate(struct cxl_port *port,
206 					struct xarray *dsmas_xa)
207 {
208 	struct access_coordinate ep_c[ACCESS_COORDINATE_MAX];
209 	struct dsmas_entry *dent;
210 	int valid_entries = 0;
211 	unsigned long index;
212 	int rc;
213 
214 	rc = cxl_endpoint_get_perf_coordinates(port, ep_c);
215 	if (rc) {
216 		dev_dbg(&port->dev, "Failed to retrieve ep perf coordinates.\n");
217 		return rc;
218 	}
219 
220 	struct cxl_root *cxl_root __free(put_cxl_root) = find_cxl_root(port);
221 
222 	if (!cxl_root)
223 		return -ENODEV;
224 
225 	if (!cxl_root->ops.qos_class)
226 		return -EOPNOTSUPP;
227 
228 	xa_for_each(dsmas_xa, index, dent) {
229 		int qos_class;
230 
231 		/* No DSLBIS for this DSMAS; nothing to hand the QTG _DSM */
232 		if (!dent->cdat_coord[ACCESS_COORDINATE_CPU].read_bandwidth &&
233 		    !dent->cdat_coord[ACCESS_COORDINATE_CPU].write_bandwidth &&
234 		    !dent->cdat_coord[ACCESS_COORDINATE_CPU].read_latency &&
235 		    !dent->cdat_coord[ACCESS_COORDINATE_CPU].write_latency)
236 			continue;
237 
238 		cxl_coordinates_combine(dent->coord, dent->cdat_coord, ep_c);
239 		dent->entries = 1;
240 		rc = cxl_root->ops.qos_class(cxl_root,
241 					     &dent->coord[ACCESS_COORDINATE_CPU],
242 					     1, &qos_class);
243 		if (rc != 1)
244 			continue;
245 
246 		valid_entries++;
247 		dent->qos_class = qos_class;
248 	}
249 
250 	if (!valid_entries)
251 		return -ENOENT;
252 
253 	return 0;
254 }
255 
256 static void update_perf_entry(struct device *dev, struct dsmas_entry *dent,
257 			      struct cxl_dpa_perf *dpa_perf)
258 {
259 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++) {
260 		dpa_perf->coord[i] = dent->coord[i];
261 		dpa_perf->cdat_coord[i] = dent->cdat_coord[i];
262 	}
263 	dpa_perf->dpa_range = dent->dpa_range;
264 	dpa_perf->qos_class = dent->qos_class;
265 	dev_dbg(dev,
266 		"DSMAS: dpa: %pra qos: %d read_bw: %d write_bw %d read_lat: %d write_lat: %d\n",
267 		&dent->dpa_range, dpa_perf->qos_class,
268 		dent->coord[ACCESS_COORDINATE_CPU].read_bandwidth,
269 		dent->coord[ACCESS_COORDINATE_CPU].write_bandwidth,
270 		dent->coord[ACCESS_COORDINATE_CPU].read_latency,
271 		dent->coord[ACCESS_COORDINATE_CPU].write_latency);
272 }
273 
274 /*
275  * A DCD shall describe its DC partition in a DSMAS entry (CXL r4.0 9.13.3).
276  * Without one the partition's attributes are unknown, so disable DCD.
277  */
278 static void cxl_dcd_dsmas_missing(struct cxl_dev_state *cxlds, const char *why)
279 {
280 	struct cxl_memdev_state *mds;
281 
282 	if (cxlds->type != CXL_DEVTYPE_CLASSMEM)
283 		return;
284 
285 	mds = to_cxl_memdev_state(cxlds);
286 	if (!cxl_dcd_supported(mds) ||
287 	    !cxl_part_size(cxlds, CXL_PARTMODE_DYNAMIC_RAM))
288 		return;
289 
290 	dev_warn(cxlds->dev, "DC partition has no valid DSMAS entry (%s), disabling DCD\n",
291 		 why);
292 	cxl_disable_dcd(mds);
293 }
294 
295 enum cxl_dsmas_apply {
296 	CXL_DSMAS_APPLY_FLAGS,		/* shareable etc.; no QTG data */
297 	CXL_DSMAS_APPLY_FLAGS_PERF,	/* perf coordinates and qos_class */
298 };
299 
300 /*
301  * DSMAS flags such as shareable are properties of the CDAT entry and are
302  * applied regardless; perf data is applied only if the QTG lookup produced
303  * recommendations.
304  */
305 static void cxl_memdev_apply_dsmas(struct cxl_dev_state *cxlds,
306 				   struct xarray *dsmas_xa,
307 				   enum cxl_dsmas_apply attrs)
308 {
309 	struct device *dev = cxlds->dev;
310 	struct dsmas_entry *dent;
311 	bool dc_matched = false;
312 	unsigned long index;
313 
314 	xa_for_each(dsmas_xa, index, dent) {
315 		bool found = false;
316 
317 		for (int i = 0; i < cxlds->nr_partitions; i++) {
318 			struct cxl_dpa_partition *part = &cxlds->part[i];
319 			struct range range = {
320 				.start = part->res.start,
321 				.end = part->res.end,
322 			};
323 
324 			if (!range_contains(&range, &dent->dpa_range))
325 				continue;
326 
327 			found = true;
328 			/*
329 			 * part->handle is from Get DC Config, dent->handle
330 			 * from the CDAT DSMAS entry.
331 			 */
332 			if (part->mode == CXL_PARTMODE_DYNAMIC_RAM &&
333 			    dent->handle != part->handle) {
334 				dev_warn(dev,
335 					 "DSMAD handle mismatch: %pra has %u, DSMAS %pra has %u\n",
336 					 &range, part->handle,
337 					 &dent->dpa_range, dent->handle);
338 				break;
339 			}
340 
341 			if (attrs == CXL_DSMAS_APPLY_FLAGS_PERF)
342 				update_perf_entry(dev, dent, &part->perf);
343 			if (part->mode == CXL_PARTMODE_DYNAMIC_RAM) {
344 				part->shareable = dent->shareable;
345 				part->read_only = dent->read_only;
346 				dc_matched = true;
347 			}
348 			break;
349 		}
350 
351 		if (!found)
352 			dev_dbg(dev, "no partition for dsmas dpa: %pra\n",
353 				&dent->dpa_range);
354 	}
355 
356 	if (!dc_matched)
357 		cxl_dcd_dsmas_missing(cxlds, "no matching entry");
358 }
359 
360 static int match_cxlrd_qos_class(struct device *dev, void *data)
361 {
362 	int dev_qos_class = *(int *)data;
363 	struct cxl_root_decoder *cxlrd;
364 
365 	if (!is_root_decoder(dev))
366 		return 0;
367 
368 	cxlrd = to_cxl_root_decoder(dev);
369 	if (cxlrd->qos_class == CXL_QOS_CLASS_INVALID)
370 		return 0;
371 
372 	if (cxlrd->qos_class == dev_qos_class)
373 		return 1;
374 
375 	return 0;
376 }
377 
378 static void reset_dpa_perf(struct cxl_dpa_perf *dpa_perf)
379 {
380 	*dpa_perf = (struct cxl_dpa_perf) {
381 		.qos_class = CXL_QOS_CLASS_INVALID,
382 	};
383 }
384 
385 static bool cxl_qos_match(struct cxl_port *root_port,
386 			  struct cxl_dpa_perf *dpa_perf)
387 {
388 	if (dpa_perf->qos_class == CXL_QOS_CLASS_INVALID)
389 		return false;
390 
391 	if (!device_for_each_child(&root_port->dev, &dpa_perf->qos_class,
392 				   match_cxlrd_qos_class))
393 		return false;
394 
395 	return true;
396 }
397 
398 static int match_cxlrd_hb(struct device *dev, void *data)
399 {
400 	struct device *host_bridge = data;
401 	struct cxl_switch_decoder *cxlsd;
402 	struct cxl_root_decoder *cxlrd;
403 
404 	if (!is_root_decoder(dev))
405 		return 0;
406 
407 	cxlrd = to_cxl_root_decoder(dev);
408 	cxlsd = &cxlrd->cxlsd;
409 
410 	guard(rwsem_read)(&cxl_rwsem.region);
411 	for (int i = 0; i < cxlsd->nr_targets; i++) {
412 		if (cxlsd->target[i] && host_bridge == cxlsd->target[i]->dport_dev)
413 			return 1;
414 	}
415 
416 	return 0;
417 }
418 
419 static void cxl_qos_class_verify(struct cxl_memdev *cxlmd)
420 {
421 	struct cxl_dev_state *cxlds = cxlmd->cxlds;
422 	struct cxl_port *root_port;
423 
424 	struct cxl_root *cxl_root __free(put_cxl_root) =
425 		find_cxl_root(cxlmd->endpoint);
426 
427 	/*
428 	 * No need to reset_dpa_perf() here as find_cxl_root() is guaranteed to
429 	 * succeed when called in the cxl_endpoint_port_probe() path.
430 	 */
431 	if (!cxl_root)
432 		return;
433 
434 	root_port = &cxl_root->port;
435 
436 	/*
437 	 * Save userspace from needing to check if a qos class has any matches
438 	 * by hiding qos class info if the memdev is not mapped by a root
439 	 * decoder, or the partition class does not match any root decoder
440 	 * class.
441 	 */
442 	if (!device_for_each_child(&root_port->dev,
443 				   cxlmd->endpoint->host_bridge,
444 				   match_cxlrd_hb)) {
445 		for (int i = 0; i < cxlds->nr_partitions; i++) {
446 			struct cxl_dpa_perf *perf = &cxlds->part[i].perf;
447 
448 			reset_dpa_perf(perf);
449 		}
450 		return;
451 	}
452 
453 	for (int i = 0; i < cxlds->nr_partitions; i++) {
454 		struct cxl_dpa_perf *perf = &cxlds->part[i].perf;
455 
456 		if (!cxl_qos_match(root_port, perf))
457 			reset_dpa_perf(perf);
458 	}
459 }
460 
461 static void discard_dsmas(struct xarray *xa)
462 {
463 	unsigned long index;
464 	void *ent;
465 
466 	xa_for_each(xa, index, ent) {
467 		xa_erase(xa, index);
468 		kfree(ent);
469 	}
470 	xa_destroy(xa);
471 }
472 DEFINE_FREE(dsmas, struct xarray *, if (_T) discard_dsmas(_T))
473 
474 void cxl_endpoint_parse_cdat(struct cxl_port *port)
475 {
476 	struct cxl_memdev *cxlmd = to_cxl_memdev(port->uport_dev);
477 	struct cxl_dev_state *cxlds = cxlmd->cxlds;
478 	struct xarray __dsmas_xa;
479 	struct xarray *dsmas_xa __free(dsmas) = &__dsmas_xa;
480 	int rc;
481 
482 	xa_init(&__dsmas_xa);
483 	if (!port->cdat.table) {
484 		cxl_dcd_dsmas_missing(cxlds, "no CDAT");
485 		return;
486 	}
487 
488 	rc = cxl_cdat_endpoint_process(port, dsmas_xa);
489 	if (rc < 0) {
490 		dev_dbg(&port->dev, "Failed to parse CDAT: %d\n", rc);
491 		cxl_dcd_dsmas_missing(cxlds, "CDAT parse failed");
492 		return;
493 	}
494 
495 	rc = cxl_port_perf_data_calculate(port, dsmas_xa);
496 	if (rc) {
497 		dev_dbg(&port->dev, "Failed to do perf coord calculations.\n");
498 		cxl_memdev_apply_dsmas(cxlds, dsmas_xa, CXL_DSMAS_APPLY_FLAGS);
499 		return;
500 	}
501 
502 	cxl_memdev_apply_dsmas(cxlds, dsmas_xa, CXL_DSMAS_APPLY_FLAGS_PERF);
503 	cxl_qos_class_verify(cxlmd);
504 	cxl_memdev_update_perf(cxlmd);
505 }
506 EXPORT_SYMBOL_NS_GPL(cxl_endpoint_parse_cdat, "CXL");
507 
508 static int cdat_sslbis_handler(union acpi_subtable_headers *header, void *arg,
509 			       const unsigned long end)
510 {
511 	struct acpi_cdat_sslbis_table {
512 		struct acpi_cdat_header header;
513 		struct acpi_cdat_sslbis sslbis_header;
514 		struct acpi_cdat_sslbe entries[];
515 	} *tbl = (struct acpi_cdat_sslbis_table *)header;
516 	int size = sizeof(header->cdat) + sizeof(tbl->sslbis_header);
517 	struct acpi_cdat_sslbis *sslbis;
518 	struct cxl_dport *dport = arg;
519 	struct device *dev = &dport->port->dev;
520 	int remain, entries, i;
521 	u16 len;
522 
523 	len = le16_to_cpu((__force __le16)header->cdat.length);
524 	remain = len - size;
525 	if (!remain || remain % sizeof(tbl->entries[0]) ||
526 	    (unsigned long)header + len > end) {
527 		dev_warn(dev, "Malformed SSLBIS table length: (%u)\n", len);
528 		return -EINVAL;
529 	}
530 
531 	sslbis = &tbl->sslbis_header;
532 	/* Unrecognized data type, we can skip */
533 	if (sslbis->data_type > ACPI_HMAT_WRITE_BANDWIDTH)
534 		return 0;
535 
536 	entries = remain / sizeof(tbl->entries[0]);
537 	if (struct_size(tbl, entries, entries) != len)
538 		return -EINVAL;
539 
540 	for (i = 0; i < entries; i++) {
541 		u16 x = le16_to_cpu((__force __le16)tbl->entries[i].portx_id);
542 		u16 y = le16_to_cpu((__force __le16)tbl->entries[i].porty_id);
543 		__le64 le_base;
544 		__le16 le_val;
545 		u16 dsp_id;
546 		u64 val;
547 
548 		switch (x) {
549 		case ACPI_CDAT_SSLBIS_US_PORT:
550 			dsp_id = y;
551 			break;
552 		case ACPI_CDAT_SSLBIS_ANY_PORT:
553 			switch (y) {
554 			case ACPI_CDAT_SSLBIS_US_PORT:
555 				dsp_id = x;
556 				break;
557 			case ACPI_CDAT_SSLBIS_ANY_PORT:
558 				dsp_id = ACPI_CDAT_SSLBIS_ANY_PORT;
559 				break;
560 			default:
561 				dsp_id = y;
562 				break;
563 			}
564 			break;
565 		default:
566 			dsp_id = x;
567 			break;
568 		}
569 
570 		le_base = (__force __le64)tbl->sslbis_header.entry_base_unit;
571 		le_val = (__force __le16)tbl->entries[i].latency_or_bandwidth;
572 		val = cdat_normalize(le16_to_cpu(le_val), le64_to_cpu(le_base),
573 				     sslbis->data_type);
574 
575 		if (dsp_id == ACPI_CDAT_SSLBIS_ANY_PORT ||
576 		    dsp_id == dport->port_id) {
577 			cxl_access_coordinate_set(dport->coord,
578 						  sslbis->data_type, val);
579 			return 0;
580 		}
581 	}
582 
583 	return 0;
584 }
585 
586 void cxl_switch_parse_cdat(struct cxl_dport *dport)
587 {
588 	struct cxl_port *port = dport->port;
589 	int rc;
590 
591 	if (!port->cdat.table)
592 		return;
593 
594 	rc = cdat_table_parse(ACPI_CDAT_TYPE_SSLBIS, cdat_sslbis_handler,
595 			      dport, port->cdat.table, port->cdat.length);
596 	rc = cdat_table_parse_output(rc);
597 	if (rc)
598 		dev_dbg(&port->dev, "Failed to parse SSLBIS: %d\n", rc);
599 }
600 EXPORT_SYMBOL_NS_GPL(cxl_switch_parse_cdat, "CXL");
601 
602 static void __cxl_coordinates_combine(struct access_coordinate *out,
603 				      struct access_coordinate *c1,
604 				      struct access_coordinate *c2)
605 {
606 		if (c1->write_bandwidth && c2->write_bandwidth)
607 			out->write_bandwidth = min(c1->write_bandwidth,
608 						   c2->write_bandwidth);
609 		out->write_latency = c1->write_latency + c2->write_latency;
610 
611 		if (c1->read_bandwidth && c2->read_bandwidth)
612 			out->read_bandwidth = min(c1->read_bandwidth,
613 						  c2->read_bandwidth);
614 		out->read_latency = c1->read_latency + c2->read_latency;
615 }
616 
617 /**
618  * cxl_coordinates_combine - Combine the two input coordinates
619  *
620  * @out: Output coordinate of c1 and c2 combined
621  * @c1: input coordinates
622  * @c2: input coordinates
623  */
624 void cxl_coordinates_combine(struct access_coordinate *out,
625 			     struct access_coordinate *c1,
626 			     struct access_coordinate *c2)
627 {
628 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++)
629 		__cxl_coordinates_combine(&out[i], &c1[i], &c2[i]);
630 }
631 
632 MODULE_IMPORT_NS("CXL");
633 
634 static void cxl_bandwidth_add(struct access_coordinate *coord,
635 			      struct access_coordinate *c1,
636 			      struct access_coordinate *c2)
637 {
638 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++) {
639 		coord[i].read_bandwidth = c1[i].read_bandwidth +
640 					  c2[i].read_bandwidth;
641 		coord[i].write_bandwidth = c1[i].write_bandwidth +
642 					   c2[i].write_bandwidth;
643 	}
644 }
645 
646 static bool dpa_perf_contains(struct cxl_dpa_perf *perf,
647 			      struct resource *dpa_res)
648 {
649 	struct range dpa = {
650 		.start = dpa_res->start,
651 		.end = dpa_res->end,
652 	};
653 
654 	return range_contains(&perf->dpa_range, &dpa);
655 }
656 
657 static struct cxl_dpa_perf *cxled_get_dpa_perf(struct cxl_endpoint_decoder *cxled)
658 {
659 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
660 	struct cxl_dev_state *cxlds = cxlmd->cxlds;
661 	struct cxl_dpa_perf *perf;
662 
663 	if (cxled->part < 0)
664 		return ERR_PTR(-EINVAL);
665 	perf = &cxlds->part[cxled->part].perf;
666 
667 	if (!perf)
668 		return ERR_PTR(-EINVAL);
669 
670 	if (!dpa_perf_contains(perf, cxled->dpa_res))
671 		return ERR_PTR(-EINVAL);
672 
673 	return perf;
674 }
675 
676 /*
677  * Transient context for containing the current calculation of bandwidth when
678  * doing walking the port hierarchy to deal with shared upstream link.
679  */
680 struct cxl_perf_ctx {
681 	struct access_coordinate coord[ACCESS_COORDINATE_MAX];
682 	struct cxl_port *port;
683 };
684 
685 /**
686  * cxl_endpoint_gather_bandwidth - collect all the endpoint bandwidth in an xarray
687  * @cxlr: CXL region for the bandwidth calculation
688  * @cxled: endpoint decoder to start on
689  * @usp_xa: (output) the xarray that collects all the bandwidth coordinates
690  *          indexed by the upstream device with data of 'struct cxl_perf_ctx'.
691  * @gp_is_root: (output) bool of whether the grandparent is cxl root.
692  *
693  * Return: 0 for success or -errno
694  *
695  * Collects aggregated endpoint bandwidth and store the bandwidth in
696  * an xarray indexed by the upstream device of the switch or the RP
697  * device. Each endpoint consists the minimum of the bandwidth from DSLBIS
698  * from the endpoint CDAT, the endpoint upstream link bandwidth, and the
699  * bandwidth from the SSLBIS of the switch CDAT for the switch upstream port to
700  * the downstream port that's associated with the endpoint. If the
701  * device is directly connected to a RP, then no SSLBIS is involved.
702  */
703 static int cxl_endpoint_gather_bandwidth(struct cxl_region *cxlr,
704 					 struct cxl_endpoint_decoder *cxled,
705 					 struct xarray *usp_xa,
706 					 bool *gp_is_root)
707 {
708 	struct cxl_port *endpoint = to_cxl_port(cxled->cxld.dev.parent);
709 	struct cxl_port *parent_port = to_cxl_port(endpoint->dev.parent);
710 	struct cxl_port *gp_port = to_cxl_port(parent_port->dev.parent);
711 	struct access_coordinate pci_coord[ACCESS_COORDINATE_MAX] = { };
712 	struct access_coordinate sw_coord[ACCESS_COORDINATE_MAX] = { };
713 	struct access_coordinate ep_coord[ACCESS_COORDINATE_MAX] = { };
714 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
715 	struct cxl_dev_state *cxlds = cxlmd->cxlds;
716 	struct pci_dev *pdev = to_pci_dev(cxlds->dev);
717 	struct cxl_perf_ctx *perf_ctx;
718 	struct cxl_dpa_perf *perf;
719 	unsigned long index;
720 	void *ptr;
721 	int rc;
722 
723 	if (!dev_is_pci(cxlds->dev))
724 		return -ENODEV;
725 
726 	if (cxlds->rcd)
727 		return -ENODEV;
728 
729 	perf = cxled_get_dpa_perf(cxled);
730 	if (IS_ERR(perf))
731 		return PTR_ERR(perf);
732 
733 	*gp_is_root = is_cxl_root(gp_port);
734 
735 	/*
736 	 * If the grandparent is cxl root, then index is the root port,
737 	 * otherwise it's the parent switch upstream device.
738 	 */
739 	if (*gp_is_root)
740 		index = (unsigned long)endpoint->parent_dport->dport_dev;
741 	else
742 		index = (unsigned long)parent_port->uport_dev;
743 
744 	perf_ctx = xa_load(usp_xa, index);
745 	if (!perf_ctx) {
746 		struct cxl_perf_ctx *c __free(kfree) =
747 			kzalloc_obj(*perf_ctx);
748 
749 		if (!c)
750 			return -ENOMEM;
751 		ptr = xa_store(usp_xa, index, c, GFP_KERNEL);
752 		if (xa_is_err(ptr))
753 			return xa_err(ptr);
754 		perf_ctx = no_free_ptr(c);
755 		perf_ctx->port = parent_port;
756 	}
757 
758 	/* Direct upstream link from EP bandwidth */
759 	rc = cxl_pci_get_bandwidth(pdev, pci_coord);
760 	if (rc < 0)
761 		return rc;
762 
763 	/*
764 	 * Min of upstream link bandwidth and Endpoint CDAT bandwidth from
765 	 * DSLBIS.
766 	 */
767 	cxl_coordinates_combine(ep_coord, pci_coord, perf->cdat_coord);
768 
769 	/*
770 	 * If grandparent port is root, then there's no switch involved and
771 	 * the endpoint is connected to a root port.
772 	 */
773 	if (!*gp_is_root) {
774 		/*
775 		 * Retrieve the switch SSLBIS for switch downstream port
776 		 * associated with the endpoint bandwidth.
777 		 */
778 		rc = cxl_port_get_switch_dport_bandwidth(endpoint, sw_coord);
779 		if (rc)
780 			return rc;
781 
782 		/*
783 		 * Min of the earlier coordinates with the switch SSLBIS
784 		 * bandwidth
785 		 */
786 		cxl_coordinates_combine(ep_coord, ep_coord, sw_coord);
787 	}
788 
789 	/*
790 	 * Aggregate the computed bandwidth with the current aggregated bandwidth
791 	 * of the endpoints with the same switch upstream device or RP.
792 	 */
793 	cxl_bandwidth_add(perf_ctx->coord, perf_ctx->coord, ep_coord);
794 
795 	return 0;
796 }
797 
798 static void free_perf_xa(struct xarray *xa)
799 {
800 	struct cxl_perf_ctx *ctx;
801 	unsigned long index;
802 
803 	if (!xa)
804 		return;
805 
806 	xa_for_each(xa, index, ctx)
807 		kfree(ctx);
808 	xa_destroy(xa);
809 	kfree(xa);
810 }
811 DEFINE_FREE(free_perf_xa, struct xarray *, if (_T) free_perf_xa(_T))
812 
813 /**
814  * cxl_switch_gather_bandwidth - collect all the bandwidth at switch level in an xarray
815  * @cxlr: The region being operated on
816  * @input_xa: xarray indexed by upstream device of a switch with data of 'struct
817  *	      cxl_perf_ctx'
818  * @gp_is_root: (output) bool of whether the grandparent is cxl root.
819  *
820  * Return: a xarray of resulting cxl_perf_ctx per parent switch or root port
821  *         or ERR_PTR(-errno)
822  *
823  * Iterate through the xarray. Take the minimum of the downstream calculated
824  * bandwidth, the upstream link bandwidth, and the SSLBIS of the upstream
825  * switch if exists. Sum the resulting bandwidth under the switch upstream
826  * device or a RP device. The function can be iterated over multiple switches
827  * if the switches are present.
828  */
829 static struct xarray *cxl_switch_gather_bandwidth(struct cxl_region *cxlr,
830 						  struct xarray *input_xa,
831 						  bool *gp_is_root)
832 {
833 	struct xarray *res_xa __free(free_perf_xa) =
834 		kzalloc_obj(*res_xa);
835 	struct access_coordinate coords[ACCESS_COORDINATE_MAX] = { };
836 	struct cxl_perf_ctx *ctx, *us_ctx;
837 	unsigned long index, us_index;
838 	int dev_count = 0;
839 	int gp_count = 0;
840 	void *ptr;
841 	int rc;
842 
843 	if (!res_xa)
844 		return ERR_PTR(-ENOMEM);
845 	xa_init(res_xa);
846 
847 	xa_for_each(input_xa, index, ctx) {
848 		struct device *dev = (struct device *)index;
849 		struct cxl_port *port = ctx->port;
850 		struct cxl_port *parent_port = to_cxl_port(port->dev.parent);
851 		struct cxl_port *gp_port = to_cxl_port(parent_port->dev.parent);
852 		struct cxl_dport *dport = port->parent_dport;
853 		bool is_root = false;
854 
855 		dev_count++;
856 		if (is_cxl_root(gp_port)) {
857 			is_root = true;
858 			gp_count++;
859 		}
860 
861 		/*
862 		 * If the grandparent is cxl root, then index is the root port,
863 		 * otherwise it's the parent switch upstream device.
864 		 */
865 		if (is_root)
866 			us_index = (unsigned long)port->parent_dport->dport_dev;
867 		else
868 			us_index = (unsigned long)parent_port->uport_dev;
869 
870 		us_ctx = xa_load(res_xa, us_index);
871 		if (!us_ctx) {
872 			struct cxl_perf_ctx *n __free(kfree) =
873 				kzalloc_obj(*n);
874 
875 			if (!n)
876 				return ERR_PTR(-ENOMEM);
877 
878 			ptr = xa_store(res_xa, us_index, n, GFP_KERNEL);
879 			if (xa_is_err(ptr))
880 				return ERR_PTR(xa_err(ptr));
881 			us_ctx = no_free_ptr(n);
882 			us_ctx->port = parent_port;
883 		}
884 
885 		/*
886 		 * If the device isn't an upstream PCIe port, there's something
887 		 * wrong with the topology.
888 		 */
889 		if (!dev_is_pci(dev))
890 			return ERR_PTR(-EINVAL);
891 
892 		/* Retrieve the upstream link bandwidth */
893 		rc = cxl_pci_get_bandwidth(to_pci_dev(dev), coords);
894 		if (rc)
895 			return ERR_PTR(-ENXIO);
896 
897 		/*
898 		 * Take the min of downstream bandwidth and the upstream link
899 		 * bandwidth.
900 		 */
901 		cxl_coordinates_combine(coords, coords, ctx->coord);
902 
903 		/*
904 		 * Take the min of the calculated bandwidth and the upstream
905 		 * switch SSLBIS bandwidth if there's a parent switch
906 		 */
907 		if (!is_root)
908 			cxl_coordinates_combine(coords, coords, dport->coord);
909 
910 		/*
911 		 * Aggregate the calculated bandwidth common to an upstream
912 		 * switch.
913 		 */
914 		cxl_bandwidth_add(us_ctx->coord, us_ctx->coord, coords);
915 	}
916 
917 	/* Asymmetric topology detected. */
918 	if (gp_count) {
919 		if (gp_count != dev_count) {
920 			dev_dbg(&cxlr->dev,
921 				"Asymmetric hierarchy detected, bandwidth not updated\n");
922 			return ERR_PTR(-EOPNOTSUPP);
923 		}
924 		*gp_is_root = true;
925 	}
926 
927 	return no_free_ptr(res_xa);
928 }
929 
930 /**
931  * cxl_rp_gather_bandwidth - handle the root port level bandwidth collection
932  * @xa: the xarray that holds the cxl_perf_ctx that has the bandwidth calculated
933  *      below each root port device.
934  *
935  * Return: xarray that holds cxl_perf_ctx per host bridge or ERR_PTR(-errno)
936  */
937 static struct xarray *cxl_rp_gather_bandwidth(struct xarray *xa)
938 {
939 	struct xarray *hb_xa __free(free_perf_xa) =
940 		kzalloc_obj(*hb_xa);
941 	struct cxl_perf_ctx *ctx;
942 	unsigned long index;
943 
944 	if (!hb_xa)
945 		return ERR_PTR(-ENOMEM);
946 	xa_init(hb_xa);
947 
948 	xa_for_each(xa, index, ctx) {
949 		struct cxl_port *port = ctx->port;
950 		unsigned long hb_index = (unsigned long)port->uport_dev;
951 		struct cxl_perf_ctx *hb_ctx;
952 		void *ptr;
953 
954 		hb_ctx = xa_load(hb_xa, hb_index);
955 		if (!hb_ctx) {
956 			struct cxl_perf_ctx *n __free(kfree) =
957 				kzalloc_obj(*n);
958 
959 			if (!n)
960 				return ERR_PTR(-ENOMEM);
961 			ptr = xa_store(hb_xa, hb_index, n, GFP_KERNEL);
962 			if (xa_is_err(ptr))
963 				return ERR_PTR(xa_err(ptr));
964 			hb_ctx = no_free_ptr(n);
965 			hb_ctx->port = port;
966 		}
967 
968 		cxl_bandwidth_add(hb_ctx->coord, hb_ctx->coord, ctx->coord);
969 	}
970 
971 	return no_free_ptr(hb_xa);
972 }
973 
974 /**
975  * cxl_hb_gather_bandwidth - handle the host bridge level bandwidth collection
976  * @xa: the xarray that holds the cxl_perf_ctx that has the bandwidth calculated
977  *      below each host bridge.
978  *
979  * Return: xarray that holds cxl_perf_ctx per ACPI0017 device or ERR_PTR(-errno)
980  */
981 static struct xarray *cxl_hb_gather_bandwidth(struct xarray *xa)
982 {
983 	struct xarray *mw_xa __free(free_perf_xa) =
984 		kzalloc_obj(*mw_xa);
985 	struct cxl_perf_ctx *ctx;
986 	unsigned long index;
987 
988 	if (!mw_xa)
989 		return ERR_PTR(-ENOMEM);
990 	xa_init(mw_xa);
991 
992 	xa_for_each(xa, index, ctx) {
993 		struct cxl_port *port = ctx->port;
994 		struct cxl_port *parent_port;
995 		struct cxl_perf_ctx *mw_ctx;
996 		struct cxl_dport *dport;
997 		unsigned long mw_index;
998 		void *ptr;
999 
1000 		parent_port = to_cxl_port(port->dev.parent);
1001 		mw_index = (unsigned long)parent_port->uport_dev;
1002 
1003 		mw_ctx = xa_load(mw_xa, mw_index);
1004 		if (!mw_ctx) {
1005 			struct cxl_perf_ctx *n __free(kfree) =
1006 				kzalloc_obj(*n);
1007 
1008 			if (!n)
1009 				return ERR_PTR(-ENOMEM);
1010 			ptr = xa_store(mw_xa, mw_index, n, GFP_KERNEL);
1011 			if (xa_is_err(ptr))
1012 				return ERR_PTR(xa_err(ptr));
1013 			mw_ctx = no_free_ptr(n);
1014 		}
1015 
1016 		dport = port->parent_dport;
1017 		cxl_coordinates_combine(ctx->coord, ctx->coord, dport->coord);
1018 		cxl_bandwidth_add(mw_ctx->coord, mw_ctx->coord, ctx->coord);
1019 	}
1020 
1021 	return no_free_ptr(mw_xa);
1022 }
1023 
1024 /**
1025  * cxl_region_update_bandwidth - Update the bandwidth access coordinates of a region
1026  * @cxlr: The region being operated on
1027  * @input_xa: xarray holds cxl_perf_ctx with calculated bandwidth per ACPI0017 instance
1028  */
1029 static void cxl_region_update_bandwidth(struct cxl_region *cxlr,
1030 					struct xarray *input_xa)
1031 {
1032 	struct access_coordinate coord[ACCESS_COORDINATE_MAX];
1033 	struct cxl_perf_ctx *ctx;
1034 	unsigned long index;
1035 
1036 	memset(coord, 0, sizeof(coord));
1037 	xa_for_each(input_xa, index, ctx)
1038 		cxl_bandwidth_add(coord, coord, ctx->coord);
1039 
1040 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++) {
1041 		cxlr->coord[i].read_bandwidth = coord[i].read_bandwidth;
1042 		cxlr->coord[i].write_bandwidth = coord[i].write_bandwidth;
1043 	}
1044 }
1045 
1046 /**
1047  * cxl_region_shared_upstream_bandwidth_update - Recalculate the bandwidth for
1048  *						 the region
1049  * @cxlr: the cxl region to recalculate
1050  *
1051  * The function walks the topology from bottom up and calculates the bandwidth. It
1052  * starts at the endpoints, processes at the switches if any, processes at the rootport
1053  * level, at the host bridge level, and finally aggregates at the region.
1054  */
1055 void cxl_region_shared_upstream_bandwidth_update(struct cxl_region *cxlr)
1056 {
1057 	struct xarray *working_xa;
1058 	int root_count = 0;
1059 	bool is_root;
1060 	int rc;
1061 
1062 	lockdep_assert_held(&cxl_rwsem.dpa);
1063 
1064 	struct xarray *usp_xa __free(free_perf_xa) =
1065 		kzalloc_obj(*usp_xa);
1066 
1067 	if (!usp_xa)
1068 		return;
1069 
1070 	xa_init(usp_xa);
1071 
1072 	/* Collect bandwidth data from all the endpoints. */
1073 	for (int i = 0; i < cxlr->params.nr_targets; i++) {
1074 		struct cxl_endpoint_decoder *cxled = cxlr->params.targets[i];
1075 
1076 		is_root = false;
1077 		rc = cxl_endpoint_gather_bandwidth(cxlr, cxled, usp_xa, &is_root);
1078 		if (rc)
1079 			return;
1080 		root_count += is_root;
1081 	}
1082 
1083 	/* Detect asymmetric hierarchy with some direct attached endpoints. */
1084 	if (root_count && root_count != cxlr->params.nr_targets) {
1085 		dev_dbg(&cxlr->dev,
1086 			"Asymmetric hierarchy detected, bandwidth not updated\n");
1087 		return;
1088 	}
1089 
1090 	/*
1091 	 * Walk up one or more switches to deal with the bandwidth of the
1092 	 * switches if they exist. Endpoints directly attached to RPs skip
1093 	 * over this part.
1094 	 */
1095 	if (!root_count) {
1096 		do {
1097 			working_xa = cxl_switch_gather_bandwidth(cxlr, usp_xa,
1098 								 &is_root);
1099 			if (IS_ERR(working_xa))
1100 				return;
1101 			free_perf_xa(usp_xa);
1102 			usp_xa = working_xa;
1103 		} while (!is_root);
1104 	}
1105 
1106 	/* Handle the bandwidth at the root port of the hierarchy */
1107 	working_xa = cxl_rp_gather_bandwidth(usp_xa);
1108 	if (IS_ERR(working_xa))
1109 		return;
1110 	free_perf_xa(usp_xa);
1111 	usp_xa = working_xa;
1112 
1113 	/* Handle the bandwidth at the host bridge of the hierarchy */
1114 	working_xa = cxl_hb_gather_bandwidth(usp_xa);
1115 	if (IS_ERR(working_xa))
1116 		return;
1117 	free_perf_xa(usp_xa);
1118 	usp_xa = working_xa;
1119 
1120 	/*
1121 	 * Aggregate all the bandwidth collected per CFMWS (ACPI0017) and
1122 	 * update the region bandwidth with the final calculated values.
1123 	 */
1124 	cxl_region_update_bandwidth(cxlr, usp_xa);
1125 }
1126 
1127 void cxl_region_perf_data_calculate(struct cxl_region *cxlr,
1128 				    struct cxl_endpoint_decoder *cxled)
1129 {
1130 	struct cxl_dpa_perf *perf;
1131 
1132 	lockdep_assert_held(&cxl_rwsem.dpa);
1133 
1134 	perf = cxled_get_dpa_perf(cxled);
1135 	if (IS_ERR(perf))
1136 		return;
1137 
1138 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++) {
1139 		/* Get total bandwidth and the worst latency for the cxl region */
1140 		cxlr->coord[i].read_latency = max_t(unsigned int,
1141 						    cxlr->coord[i].read_latency,
1142 						    perf->coord[i].read_latency);
1143 		cxlr->coord[i].write_latency = max_t(unsigned int,
1144 						     cxlr->coord[i].write_latency,
1145 						     perf->coord[i].write_latency);
1146 		cxlr->coord[i].read_bandwidth += perf->coord[i].read_bandwidth;
1147 		cxlr->coord[i].write_bandwidth += perf->coord[i].write_bandwidth;
1148 	}
1149 }
1150