xref: /linux/drivers/cxl/core/region.c (revision 9f153b7fb5ae45c7d426851f896487927f40e501)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright(c) 2022 Intel Corporation. All rights reserved. */
3 #include <linux/memregion.h>
4 #include <linux/genalloc.h>
5 #include <linux/device.h>
6 #include <linux/module.h>
7 #include <linux/memory.h>
8 #include <linux/slab.h>
9 #include <linux/uuid.h>
10 #include <linux/sort.h>
11 #include <linux/idr.h>
12 #include <linux/memory-tiers.h>
13 #include <cxlmem.h>
14 #include <cxl.h>
15 #include "core.h"
16 
17 /**
18  * DOC: cxl core region
19  *
20  * CXL Regions represent mapped memory capacity in system physical address
21  * space. Whereas the CXL Root Decoders identify the bounds of potential CXL
22  * Memory ranges, Regions represent the active mapped capacity by the HDM
23  * Decoder Capability structures throughout the Host Bridges, Switches, and
24  * Endpoints in the topology.
25  *
26  * Region configuration has ordering constraints. UUID may be set at any time
27  * but is only visible for persistent regions.
28  * 1. Interleave granularity
29  * 2. Interleave size
30  * 3. Decoder targets
31  */
32 
33 static struct cxl_region *to_cxl_region(struct device *dev);
34 
35 #define __ACCESS_ATTR_RO(_level, _name) {				\
36 	.attr	= { .name = __stringify(_name), .mode = 0444 },		\
37 	.show	= _name##_access##_level##_show,			\
38 }
39 
40 #define ACCESS_DEVICE_ATTR_RO(level, name)	\
41 	struct device_attribute dev_attr_access##level##_##name = __ACCESS_ATTR_RO(level, name)
42 
43 #define ACCESS_ATTR_RO(level, attrib)					      \
44 static ssize_t attrib##_access##level##_show(struct device *dev,	      \
45 					  struct device_attribute *attr,      \
46 					  char *buf)			      \
47 {									      \
48 	struct cxl_region *cxlr = to_cxl_region(dev);			      \
49 									      \
50 	if (cxlr->coord[level].attrib == 0)				      \
51 		return -ENOENT;						      \
52 									      \
53 	return sysfs_emit(buf, "%u\n", cxlr->coord[level].attrib);	      \
54 }									      \
55 static ACCESS_DEVICE_ATTR_RO(level, attrib)
56 
57 ACCESS_ATTR_RO(0, read_bandwidth);
58 ACCESS_ATTR_RO(0, read_latency);
59 ACCESS_ATTR_RO(0, write_bandwidth);
60 ACCESS_ATTR_RO(0, write_latency);
61 
62 #define ACCESS_ATTR_DECLARE(level, attrib)	\
63 	(&dev_attr_access##level##_##attrib.attr)
64 
65 static struct attribute *access0_coordinate_attrs[] = {
66 	ACCESS_ATTR_DECLARE(0, read_bandwidth),
67 	ACCESS_ATTR_DECLARE(0, write_bandwidth),
68 	ACCESS_ATTR_DECLARE(0, read_latency),
69 	ACCESS_ATTR_DECLARE(0, write_latency),
70 	NULL
71 };
72 
73 ACCESS_ATTR_RO(1, read_bandwidth);
74 ACCESS_ATTR_RO(1, read_latency);
75 ACCESS_ATTR_RO(1, write_bandwidth);
76 ACCESS_ATTR_RO(1, write_latency);
77 
78 static struct attribute *access1_coordinate_attrs[] = {
79 	ACCESS_ATTR_DECLARE(1, read_bandwidth),
80 	ACCESS_ATTR_DECLARE(1, write_bandwidth),
81 	ACCESS_ATTR_DECLARE(1, read_latency),
82 	ACCESS_ATTR_DECLARE(1, write_latency),
83 	NULL
84 };
85 
86 #define ACCESS_VISIBLE(level)						\
87 static umode_t cxl_region_access##level##_coordinate_visible(		\
88 		struct kobject *kobj, struct attribute *a, int n)	\
89 {									\
90 	struct device *dev = kobj_to_dev(kobj);				\
91 	struct cxl_region *cxlr = to_cxl_region(dev);			\
92 									\
93 	if (a == &dev_attr_access##level##_read_latency.attr &&		\
94 	    cxlr->coord[level].read_latency == 0)			\
95 		return 0;						\
96 									\
97 	if (a == &dev_attr_access##level##_write_latency.attr &&	\
98 	    cxlr->coord[level].write_latency == 0)			\
99 		return 0;						\
100 									\
101 	if (a == &dev_attr_access##level##_read_bandwidth.attr &&	\
102 	    cxlr->coord[level].read_bandwidth == 0)			\
103 		return 0;						\
104 									\
105 	if (a == &dev_attr_access##level##_write_bandwidth.attr &&	\
106 	    cxlr->coord[level].write_bandwidth == 0)			\
107 		return 0;						\
108 									\
109 	return a->mode;							\
110 }
111 
112 ACCESS_VISIBLE(0);
113 ACCESS_VISIBLE(1);
114 
115 static const struct attribute_group cxl_region_access0_coordinate_group = {
116 	.name = "access0",
117 	.attrs = access0_coordinate_attrs,
118 	.is_visible = cxl_region_access0_coordinate_visible,
119 };
120 
121 static const struct attribute_group *get_cxl_region_access0_group(void)
122 {
123 	return &cxl_region_access0_coordinate_group;
124 }
125 
126 static const struct attribute_group cxl_region_access1_coordinate_group = {
127 	.name = "access1",
128 	.attrs = access1_coordinate_attrs,
129 	.is_visible = cxl_region_access1_coordinate_visible,
130 };
131 
132 static const struct attribute_group *get_cxl_region_access1_group(void)
133 {
134 	return &cxl_region_access1_coordinate_group;
135 }
136 
137 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
138 			 char *buf)
139 {
140 	struct cxl_region *cxlr = to_cxl_region(dev);
141 	struct cxl_region_params *p = &cxlr->params;
142 	ssize_t rc;
143 
144 	rc = down_read_interruptible(&cxl_region_rwsem);
145 	if (rc)
146 		return rc;
147 	if (cxlr->mode != CXL_PARTMODE_PMEM)
148 		rc = sysfs_emit(buf, "\n");
149 	else
150 		rc = sysfs_emit(buf, "%pUb\n", &p->uuid);
151 	up_read(&cxl_region_rwsem);
152 
153 	return rc;
154 }
155 
156 static int is_dup(struct device *match, void *data)
157 {
158 	struct cxl_region_params *p;
159 	struct cxl_region *cxlr;
160 	uuid_t *uuid = data;
161 
162 	if (!is_cxl_region(match))
163 		return 0;
164 
165 	lockdep_assert_held(&cxl_region_rwsem);
166 	cxlr = to_cxl_region(match);
167 	p = &cxlr->params;
168 
169 	if (uuid_equal(&p->uuid, uuid)) {
170 		dev_dbg(match, "already has uuid: %pUb\n", uuid);
171 		return -EBUSY;
172 	}
173 
174 	return 0;
175 }
176 
177 static ssize_t uuid_store(struct device *dev, struct device_attribute *attr,
178 			  const char *buf, size_t len)
179 {
180 	struct cxl_region *cxlr = to_cxl_region(dev);
181 	struct cxl_region_params *p = &cxlr->params;
182 	uuid_t temp;
183 	ssize_t rc;
184 
185 	if (len != UUID_STRING_LEN + 1)
186 		return -EINVAL;
187 
188 	rc = uuid_parse(buf, &temp);
189 	if (rc)
190 		return rc;
191 
192 	if (uuid_is_null(&temp))
193 		return -EINVAL;
194 
195 	rc = down_write_killable(&cxl_region_rwsem);
196 	if (rc)
197 		return rc;
198 
199 	if (uuid_equal(&p->uuid, &temp))
200 		goto out;
201 
202 	rc = -EBUSY;
203 	if (p->state >= CXL_CONFIG_ACTIVE)
204 		goto out;
205 
206 	rc = bus_for_each_dev(&cxl_bus_type, NULL, &temp, is_dup);
207 	if (rc < 0)
208 		goto out;
209 
210 	uuid_copy(&p->uuid, &temp);
211 out:
212 	up_write(&cxl_region_rwsem);
213 
214 	if (rc)
215 		return rc;
216 	return len;
217 }
218 static DEVICE_ATTR_RW(uuid);
219 
220 static struct cxl_region_ref *cxl_rr_load(struct cxl_port *port,
221 					  struct cxl_region *cxlr)
222 {
223 	return xa_load(&port->regions, (unsigned long)cxlr);
224 }
225 
226 static int cxl_region_invalidate_memregion(struct cxl_region *cxlr)
227 {
228 	if (!cpu_cache_has_invalidate_memregion()) {
229 		if (IS_ENABLED(CONFIG_CXL_REGION_INVALIDATION_TEST)) {
230 			dev_info_once(
231 				&cxlr->dev,
232 				"Bypassing cpu_cache_invalidate_memregion() for testing!\n");
233 			return 0;
234 		}
235 		dev_WARN(&cxlr->dev,
236 			"Failed to synchronize CPU cache state\n");
237 		return -ENXIO;
238 	}
239 
240 	cpu_cache_invalidate_memregion(IORES_DESC_CXL);
241 	return 0;
242 }
243 
244 static void cxl_region_decode_reset(struct cxl_region *cxlr, int count)
245 {
246 	struct cxl_region_params *p = &cxlr->params;
247 	int i;
248 
249 	/*
250 	 * Before region teardown attempt to flush, evict any data cached for
251 	 * this region, or scream loudly about missing arch / platform support
252 	 * for CXL teardown.
253 	 */
254 	cxl_region_invalidate_memregion(cxlr);
255 
256 	for (i = count - 1; i >= 0; i--) {
257 		struct cxl_endpoint_decoder *cxled = p->targets[i];
258 		struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
259 		struct cxl_port *iter = cxled_to_port(cxled);
260 		struct cxl_dev_state *cxlds = cxlmd->cxlds;
261 		struct cxl_ep *ep;
262 
263 		if (cxlds->rcd)
264 			goto endpoint_reset;
265 
266 		while (!is_cxl_root(to_cxl_port(iter->dev.parent)))
267 			iter = to_cxl_port(iter->dev.parent);
268 
269 		for (ep = cxl_ep_load(iter, cxlmd); iter;
270 		     iter = ep->next, ep = cxl_ep_load(iter, cxlmd)) {
271 			struct cxl_region_ref *cxl_rr;
272 			struct cxl_decoder *cxld;
273 
274 			cxl_rr = cxl_rr_load(iter, cxlr);
275 			cxld = cxl_rr->decoder;
276 			if (cxld->reset)
277 				cxld->reset(cxld);
278 			set_bit(CXL_REGION_F_NEEDS_RESET, &cxlr->flags);
279 		}
280 
281 endpoint_reset:
282 		cxled->cxld.reset(&cxled->cxld);
283 		set_bit(CXL_REGION_F_NEEDS_RESET, &cxlr->flags);
284 	}
285 
286 	/* all decoders associated with this region have been torn down */
287 	clear_bit(CXL_REGION_F_NEEDS_RESET, &cxlr->flags);
288 }
289 
290 static int commit_decoder(struct cxl_decoder *cxld)
291 {
292 	struct cxl_switch_decoder *cxlsd = NULL;
293 
294 	if (cxld->commit)
295 		return cxld->commit(cxld);
296 
297 	if (is_switch_decoder(&cxld->dev))
298 		cxlsd = to_cxl_switch_decoder(&cxld->dev);
299 
300 	if (dev_WARN_ONCE(&cxld->dev, !cxlsd || cxlsd->nr_targets > 1,
301 			  "->commit() is required\n"))
302 		return -ENXIO;
303 	return 0;
304 }
305 
306 static int cxl_region_decode_commit(struct cxl_region *cxlr)
307 {
308 	struct cxl_region_params *p = &cxlr->params;
309 	int i, rc = 0;
310 
311 	for (i = 0; i < p->nr_targets; i++) {
312 		struct cxl_endpoint_decoder *cxled = p->targets[i];
313 		struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
314 		struct cxl_region_ref *cxl_rr;
315 		struct cxl_decoder *cxld;
316 		struct cxl_port *iter;
317 		struct cxl_ep *ep;
318 
319 		/* commit bottom up */
320 		for (iter = cxled_to_port(cxled); !is_cxl_root(iter);
321 		     iter = to_cxl_port(iter->dev.parent)) {
322 			cxl_rr = cxl_rr_load(iter, cxlr);
323 			cxld = cxl_rr->decoder;
324 			rc = commit_decoder(cxld);
325 			if (rc)
326 				break;
327 		}
328 
329 		if (rc) {
330 			/* programming @iter failed, teardown */
331 			for (ep = cxl_ep_load(iter, cxlmd); ep && iter;
332 			     iter = ep->next, ep = cxl_ep_load(iter, cxlmd)) {
333 				cxl_rr = cxl_rr_load(iter, cxlr);
334 				cxld = cxl_rr->decoder;
335 				if (cxld->reset)
336 					cxld->reset(cxld);
337 			}
338 
339 			cxled->cxld.reset(&cxled->cxld);
340 			goto err;
341 		}
342 	}
343 
344 	return 0;
345 
346 err:
347 	/* undo the targets that were successfully committed */
348 	cxl_region_decode_reset(cxlr, i);
349 	return rc;
350 }
351 
352 static ssize_t commit_store(struct device *dev, struct device_attribute *attr,
353 			    const char *buf, size_t len)
354 {
355 	struct cxl_region *cxlr = to_cxl_region(dev);
356 	struct cxl_region_params *p = &cxlr->params;
357 	bool commit;
358 	ssize_t rc;
359 
360 	rc = kstrtobool(buf, &commit);
361 	if (rc)
362 		return rc;
363 
364 	rc = down_write_killable(&cxl_region_rwsem);
365 	if (rc)
366 		return rc;
367 
368 	/* Already in the requested state? */
369 	if (commit && p->state >= CXL_CONFIG_COMMIT)
370 		goto out;
371 	if (!commit && p->state < CXL_CONFIG_COMMIT)
372 		goto out;
373 
374 	/* Not ready to commit? */
375 	if (commit && p->state < CXL_CONFIG_ACTIVE) {
376 		rc = -ENXIO;
377 		goto out;
378 	}
379 
380 	/*
381 	 * Invalidate caches before region setup to drop any speculative
382 	 * consumption of this address space
383 	 */
384 	rc = cxl_region_invalidate_memregion(cxlr);
385 	if (rc)
386 		goto out;
387 
388 	if (commit) {
389 		rc = cxl_region_decode_commit(cxlr);
390 		if (rc == 0)
391 			p->state = CXL_CONFIG_COMMIT;
392 	} else {
393 		p->state = CXL_CONFIG_RESET_PENDING;
394 		up_write(&cxl_region_rwsem);
395 		device_release_driver(&cxlr->dev);
396 		down_write(&cxl_region_rwsem);
397 
398 		/*
399 		 * The lock was dropped, so need to revalidate that the reset is
400 		 * still pending.
401 		 */
402 		if (p->state == CXL_CONFIG_RESET_PENDING) {
403 			cxl_region_decode_reset(cxlr, p->interleave_ways);
404 			p->state = CXL_CONFIG_ACTIVE;
405 		}
406 	}
407 
408 out:
409 	up_write(&cxl_region_rwsem);
410 
411 	if (rc)
412 		return rc;
413 	return len;
414 }
415 
416 static ssize_t commit_show(struct device *dev, struct device_attribute *attr,
417 			   char *buf)
418 {
419 	struct cxl_region *cxlr = to_cxl_region(dev);
420 	struct cxl_region_params *p = &cxlr->params;
421 	ssize_t rc;
422 
423 	rc = down_read_interruptible(&cxl_region_rwsem);
424 	if (rc)
425 		return rc;
426 	rc = sysfs_emit(buf, "%d\n", p->state >= CXL_CONFIG_COMMIT);
427 	up_read(&cxl_region_rwsem);
428 
429 	return rc;
430 }
431 static DEVICE_ATTR_RW(commit);
432 
433 static umode_t cxl_region_visible(struct kobject *kobj, struct attribute *a,
434 				  int n)
435 {
436 	struct device *dev = kobj_to_dev(kobj);
437 	struct cxl_region *cxlr = to_cxl_region(dev);
438 
439 	/*
440 	 * Support tooling that expects to find a 'uuid' attribute for all
441 	 * regions regardless of mode.
442 	 */
443 	if (a == &dev_attr_uuid.attr && cxlr->mode != CXL_PARTMODE_PMEM)
444 		return 0444;
445 	return a->mode;
446 }
447 
448 static ssize_t interleave_ways_show(struct device *dev,
449 				    struct device_attribute *attr, char *buf)
450 {
451 	struct cxl_region *cxlr = to_cxl_region(dev);
452 	struct cxl_region_params *p = &cxlr->params;
453 	ssize_t rc;
454 
455 	rc = down_read_interruptible(&cxl_region_rwsem);
456 	if (rc)
457 		return rc;
458 	rc = sysfs_emit(buf, "%d\n", p->interleave_ways);
459 	up_read(&cxl_region_rwsem);
460 
461 	return rc;
462 }
463 
464 static const struct attribute_group *get_cxl_region_target_group(void);
465 
466 static ssize_t interleave_ways_store(struct device *dev,
467 				     struct device_attribute *attr,
468 				     const char *buf, size_t len)
469 {
470 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev->parent);
471 	struct cxl_decoder *cxld = &cxlrd->cxlsd.cxld;
472 	struct cxl_region *cxlr = to_cxl_region(dev);
473 	struct cxl_region_params *p = &cxlr->params;
474 	unsigned int val, save;
475 	int rc;
476 	u8 iw;
477 
478 	rc = kstrtouint(buf, 0, &val);
479 	if (rc)
480 		return rc;
481 
482 	rc = ways_to_eiw(val, &iw);
483 	if (rc)
484 		return rc;
485 
486 	/*
487 	 * Even for x3, x6, and x12 interleaves the region interleave must be a
488 	 * power of 2 multiple of the host bridge interleave.
489 	 */
490 	if (!is_power_of_2(val / cxld->interleave_ways) ||
491 	    (val % cxld->interleave_ways)) {
492 		dev_dbg(&cxlr->dev, "invalid interleave: %d\n", val);
493 		return -EINVAL;
494 	}
495 
496 	rc = down_write_killable(&cxl_region_rwsem);
497 	if (rc)
498 		return rc;
499 	if (p->state >= CXL_CONFIG_INTERLEAVE_ACTIVE) {
500 		rc = -EBUSY;
501 		goto out;
502 	}
503 
504 	save = p->interleave_ways;
505 	p->interleave_ways = val;
506 	rc = sysfs_update_group(&cxlr->dev.kobj, get_cxl_region_target_group());
507 	if (rc)
508 		p->interleave_ways = save;
509 out:
510 	up_write(&cxl_region_rwsem);
511 	if (rc)
512 		return rc;
513 	return len;
514 }
515 static DEVICE_ATTR_RW(interleave_ways);
516 
517 static ssize_t interleave_granularity_show(struct device *dev,
518 					   struct device_attribute *attr,
519 					   char *buf)
520 {
521 	struct cxl_region *cxlr = to_cxl_region(dev);
522 	struct cxl_region_params *p = &cxlr->params;
523 	ssize_t rc;
524 
525 	rc = down_read_interruptible(&cxl_region_rwsem);
526 	if (rc)
527 		return rc;
528 	rc = sysfs_emit(buf, "%d\n", p->interleave_granularity);
529 	up_read(&cxl_region_rwsem);
530 
531 	return rc;
532 }
533 
534 static ssize_t interleave_granularity_store(struct device *dev,
535 					    struct device_attribute *attr,
536 					    const char *buf, size_t len)
537 {
538 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev->parent);
539 	struct cxl_decoder *cxld = &cxlrd->cxlsd.cxld;
540 	struct cxl_region *cxlr = to_cxl_region(dev);
541 	struct cxl_region_params *p = &cxlr->params;
542 	int rc, val;
543 	u16 ig;
544 
545 	rc = kstrtoint(buf, 0, &val);
546 	if (rc)
547 		return rc;
548 
549 	rc = granularity_to_eig(val, &ig);
550 	if (rc)
551 		return rc;
552 
553 	/*
554 	 * When the host-bridge is interleaved, disallow region granularity !=
555 	 * root granularity. Regions with a granularity less than the root
556 	 * interleave result in needing multiple endpoints to support a single
557 	 * slot in the interleave (possible to support in the future). Regions
558 	 * with a granularity greater than the root interleave result in invalid
559 	 * DPA translations (invalid to support).
560 	 */
561 	if (cxld->interleave_ways > 1 && val != cxld->interleave_granularity)
562 		return -EINVAL;
563 
564 	rc = down_write_killable(&cxl_region_rwsem);
565 	if (rc)
566 		return rc;
567 	if (p->state >= CXL_CONFIG_INTERLEAVE_ACTIVE) {
568 		rc = -EBUSY;
569 		goto out;
570 	}
571 
572 	p->interleave_granularity = val;
573 out:
574 	up_write(&cxl_region_rwsem);
575 	if (rc)
576 		return rc;
577 	return len;
578 }
579 static DEVICE_ATTR_RW(interleave_granularity);
580 
581 static ssize_t resource_show(struct device *dev, struct device_attribute *attr,
582 			     char *buf)
583 {
584 	struct cxl_region *cxlr = to_cxl_region(dev);
585 	struct cxl_region_params *p = &cxlr->params;
586 	u64 resource = -1ULL;
587 	ssize_t rc;
588 
589 	rc = down_read_interruptible(&cxl_region_rwsem);
590 	if (rc)
591 		return rc;
592 	if (p->res)
593 		resource = p->res->start;
594 	rc = sysfs_emit(buf, "%#llx\n", resource);
595 	up_read(&cxl_region_rwsem);
596 
597 	return rc;
598 }
599 static DEVICE_ATTR_RO(resource);
600 
601 static ssize_t mode_show(struct device *dev, struct device_attribute *attr,
602 			 char *buf)
603 {
604 	struct cxl_region *cxlr = to_cxl_region(dev);
605 	const char *desc;
606 
607 	if (cxlr->mode == CXL_PARTMODE_RAM)
608 		desc = "ram";
609 	else if (cxlr->mode == CXL_PARTMODE_PMEM)
610 		desc = "pmem";
611 	else
612 		desc = "";
613 
614 	return sysfs_emit(buf, "%s\n", desc);
615 }
616 static DEVICE_ATTR_RO(mode);
617 
618 static int alloc_hpa(struct cxl_region *cxlr, resource_size_t size)
619 {
620 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(cxlr->dev.parent);
621 	struct cxl_region_params *p = &cxlr->params;
622 	struct resource *res;
623 	u64 remainder = 0;
624 
625 	lockdep_assert_held_write(&cxl_region_rwsem);
626 
627 	/* Nothing to do... */
628 	if (p->res && resource_size(p->res) == size)
629 		return 0;
630 
631 	/* To change size the old size must be freed first */
632 	if (p->res)
633 		return -EBUSY;
634 
635 	if (p->state >= CXL_CONFIG_INTERLEAVE_ACTIVE)
636 		return -EBUSY;
637 
638 	/* ways, granularity and uuid (if PMEM) need to be set before HPA */
639 	if (!p->interleave_ways || !p->interleave_granularity ||
640 	    (cxlr->mode == CXL_PARTMODE_PMEM && uuid_is_null(&p->uuid)))
641 		return -ENXIO;
642 
643 	div64_u64_rem(size, (u64)SZ_256M * p->interleave_ways, &remainder);
644 	if (remainder)
645 		return -EINVAL;
646 
647 	res = alloc_free_mem_region(cxlrd->res, size, SZ_256M,
648 				    dev_name(&cxlr->dev));
649 	if (IS_ERR(res)) {
650 		dev_dbg(&cxlr->dev,
651 			"HPA allocation error (%ld) for size:%pap in %s %pr\n",
652 			PTR_ERR(res), &size, cxlrd->res->name, cxlrd->res);
653 		return PTR_ERR(res);
654 	}
655 
656 	p->res = res;
657 	p->state = CXL_CONFIG_INTERLEAVE_ACTIVE;
658 
659 	return 0;
660 }
661 
662 static void cxl_region_iomem_release(struct cxl_region *cxlr)
663 {
664 	struct cxl_region_params *p = &cxlr->params;
665 
666 	if (device_is_registered(&cxlr->dev))
667 		lockdep_assert_held_write(&cxl_region_rwsem);
668 	if (p->res) {
669 		/*
670 		 * Autodiscovered regions may not have been able to insert their
671 		 * resource.
672 		 */
673 		if (p->res->parent)
674 			remove_resource(p->res);
675 		kfree(p->res);
676 		p->res = NULL;
677 	}
678 }
679 
680 static int free_hpa(struct cxl_region *cxlr)
681 {
682 	struct cxl_region_params *p = &cxlr->params;
683 
684 	lockdep_assert_held_write(&cxl_region_rwsem);
685 
686 	if (!p->res)
687 		return 0;
688 
689 	if (p->state >= CXL_CONFIG_ACTIVE)
690 		return -EBUSY;
691 
692 	cxl_region_iomem_release(cxlr);
693 	p->state = CXL_CONFIG_IDLE;
694 	return 0;
695 }
696 
697 static ssize_t size_store(struct device *dev, struct device_attribute *attr,
698 			  const char *buf, size_t len)
699 {
700 	struct cxl_region *cxlr = to_cxl_region(dev);
701 	u64 val;
702 	int rc;
703 
704 	rc = kstrtou64(buf, 0, &val);
705 	if (rc)
706 		return rc;
707 
708 	rc = down_write_killable(&cxl_region_rwsem);
709 	if (rc)
710 		return rc;
711 
712 	if (val)
713 		rc = alloc_hpa(cxlr, val);
714 	else
715 		rc = free_hpa(cxlr);
716 	up_write(&cxl_region_rwsem);
717 
718 	if (rc)
719 		return rc;
720 
721 	return len;
722 }
723 
724 static ssize_t size_show(struct device *dev, struct device_attribute *attr,
725 			 char *buf)
726 {
727 	struct cxl_region *cxlr = to_cxl_region(dev);
728 	struct cxl_region_params *p = &cxlr->params;
729 	u64 size = 0;
730 	ssize_t rc;
731 
732 	rc = down_read_interruptible(&cxl_region_rwsem);
733 	if (rc)
734 		return rc;
735 	if (p->res)
736 		size = resource_size(p->res);
737 	rc = sysfs_emit(buf, "%#llx\n", size);
738 	up_read(&cxl_region_rwsem);
739 
740 	return rc;
741 }
742 static DEVICE_ATTR_RW(size);
743 
744 static struct attribute *cxl_region_attrs[] = {
745 	&dev_attr_uuid.attr,
746 	&dev_attr_commit.attr,
747 	&dev_attr_interleave_ways.attr,
748 	&dev_attr_interleave_granularity.attr,
749 	&dev_attr_resource.attr,
750 	&dev_attr_size.attr,
751 	&dev_attr_mode.attr,
752 	NULL,
753 };
754 
755 static const struct attribute_group cxl_region_group = {
756 	.attrs = cxl_region_attrs,
757 	.is_visible = cxl_region_visible,
758 };
759 
760 static size_t show_targetN(struct cxl_region *cxlr, char *buf, int pos)
761 {
762 	struct cxl_region_params *p = &cxlr->params;
763 	struct cxl_endpoint_decoder *cxled;
764 	int rc;
765 
766 	rc = down_read_interruptible(&cxl_region_rwsem);
767 	if (rc)
768 		return rc;
769 
770 	if (pos >= p->interleave_ways) {
771 		dev_dbg(&cxlr->dev, "position %d out of range %d\n", pos,
772 			p->interleave_ways);
773 		rc = -ENXIO;
774 		goto out;
775 	}
776 
777 	cxled = p->targets[pos];
778 	if (!cxled)
779 		rc = sysfs_emit(buf, "\n");
780 	else
781 		rc = sysfs_emit(buf, "%s\n", dev_name(&cxled->cxld.dev));
782 out:
783 	up_read(&cxl_region_rwsem);
784 
785 	return rc;
786 }
787 
788 static int check_commit_order(struct device *dev, void *data)
789 {
790 	struct cxl_decoder *cxld = to_cxl_decoder(dev);
791 
792 	/*
793 	 * if port->commit_end is not the only free decoder, then out of
794 	 * order shutdown has occurred, block further allocations until
795 	 * that is resolved
796 	 */
797 	if (((cxld->flags & CXL_DECODER_F_ENABLE) == 0))
798 		return -EBUSY;
799 	return 0;
800 }
801 
802 static int match_free_decoder(struct device *dev, const void *data)
803 {
804 	struct cxl_port *port = to_cxl_port(dev->parent);
805 	struct cxl_decoder *cxld;
806 	int rc;
807 
808 	if (!is_switch_decoder(dev))
809 		return 0;
810 
811 	cxld = to_cxl_decoder(dev);
812 
813 	if (cxld->id != port->commit_end + 1)
814 		return 0;
815 
816 	if (cxld->region) {
817 		dev_dbg(dev->parent,
818 			"next decoder to commit (%s) is already reserved (%s)\n",
819 			dev_name(dev), dev_name(&cxld->region->dev));
820 		return 0;
821 	}
822 
823 	rc = device_for_each_child_reverse_from(dev->parent, dev, NULL,
824 						check_commit_order);
825 	if (rc) {
826 		dev_dbg(dev->parent,
827 			"unable to allocate %s due to out of order shutdown\n",
828 			dev_name(dev));
829 		return 0;
830 	}
831 	return 1;
832 }
833 
834 static bool region_res_match_cxl_range(const struct cxl_region_params *p,
835 				       struct range *range)
836 {
837 	if (!p->res)
838 		return false;
839 
840 	/*
841 	 * If an extended linear cache region then the CXL range is assumed
842 	 * to be fronted by the DRAM range in current known implementation.
843 	 * This assumption will be made until a variant implementation exists.
844 	 */
845 	return p->res->start + p->cache_size == range->start &&
846 		p->res->end == range->end;
847 }
848 
849 static int match_auto_decoder(struct device *dev, const void *data)
850 {
851 	const struct cxl_region_params *p = data;
852 	struct cxl_decoder *cxld;
853 	struct range *r;
854 
855 	if (!is_switch_decoder(dev))
856 		return 0;
857 
858 	cxld = to_cxl_decoder(dev);
859 	r = &cxld->hpa_range;
860 
861 	if (region_res_match_cxl_range(p, r))
862 		return 1;
863 
864 	return 0;
865 }
866 
867 /**
868  * cxl_port_pick_region_decoder() - assign or lookup a decoder for a region
869  * @port: a port in the ancestry of the endpoint implied by @cxled
870  * @cxled: endpoint decoder to be, or currently, mapped by @port
871  * @cxlr: region to establish, or validate, decode @port
872  *
873  * In the region creation path cxl_port_pick_region_decoder() is an
874  * allocator to find a free port. In the region assembly path, it is
875  * recalling the decoder that platform firmware picked for validation
876  * purposes.
877  *
878  * The result is recorded in a 'struct cxl_region_ref' in @port.
879  */
880 static struct cxl_decoder *
881 cxl_port_pick_region_decoder(struct cxl_port *port,
882 			     struct cxl_endpoint_decoder *cxled,
883 			     struct cxl_region *cxlr)
884 {
885 	struct device *dev;
886 
887 	if (port == cxled_to_port(cxled))
888 		return &cxled->cxld;
889 
890 	if (test_bit(CXL_REGION_F_AUTO, &cxlr->flags))
891 		dev = device_find_child(&port->dev, &cxlr->params,
892 					match_auto_decoder);
893 	else
894 		dev = device_find_child(&port->dev, NULL, match_free_decoder);
895 	if (!dev)
896 		return NULL;
897 	/*
898 	 * This decoder is pinned registered as long as the endpoint decoder is
899 	 * registered, and endpoint decoder unregistration holds the
900 	 * cxl_region_rwsem over unregister events, so no need to hold on to
901 	 * this extra reference.
902 	 */
903 	put_device(dev);
904 	return to_cxl_decoder(dev);
905 }
906 
907 static bool auto_order_ok(struct cxl_port *port, struct cxl_region *cxlr_iter,
908 			  struct cxl_decoder *cxld)
909 {
910 	struct cxl_region_ref *rr = cxl_rr_load(port, cxlr_iter);
911 	struct cxl_decoder *cxld_iter = rr->decoder;
912 
913 	/*
914 	 * Allow the out of order assembly of auto-discovered regions.
915 	 * Per CXL Spec 3.1 8.2.4.20.12 software must commit decoders
916 	 * in HPA order. Confirm that the decoder with the lesser HPA
917 	 * starting address has the lesser id.
918 	 */
919 	dev_dbg(&cxld->dev, "check for HPA violation %s:%d < %s:%d\n",
920 		dev_name(&cxld->dev), cxld->id,
921 		dev_name(&cxld_iter->dev), cxld_iter->id);
922 
923 	if (cxld_iter->id > cxld->id)
924 		return true;
925 
926 	return false;
927 }
928 
929 static struct cxl_region_ref *
930 alloc_region_ref(struct cxl_port *port, struct cxl_region *cxlr,
931 		 struct cxl_endpoint_decoder *cxled,
932 		 struct cxl_decoder *cxld)
933 {
934 	struct cxl_region_params *p = &cxlr->params;
935 	struct cxl_region_ref *cxl_rr, *iter;
936 	unsigned long index;
937 	int rc;
938 
939 	xa_for_each(&port->regions, index, iter) {
940 		struct cxl_region_params *ip = &iter->region->params;
941 
942 		if (!ip->res || ip->res->start < p->res->start)
943 			continue;
944 
945 		if (test_bit(CXL_REGION_F_AUTO, &cxlr->flags)) {
946 			if (auto_order_ok(port, iter->region, cxld))
947 				continue;
948 		}
949 		dev_dbg(&cxlr->dev, "%s: HPA order violation %s:%pr vs %pr\n",
950 			dev_name(&port->dev),
951 			dev_name(&iter->region->dev), ip->res, p->res);
952 
953 		return ERR_PTR(-EBUSY);
954 	}
955 
956 	cxl_rr = kzalloc(sizeof(*cxl_rr), GFP_KERNEL);
957 	if (!cxl_rr)
958 		return ERR_PTR(-ENOMEM);
959 	cxl_rr->port = port;
960 	cxl_rr->region = cxlr;
961 	cxl_rr->nr_targets = 1;
962 	xa_init(&cxl_rr->endpoints);
963 
964 	rc = xa_insert(&port->regions, (unsigned long)cxlr, cxl_rr, GFP_KERNEL);
965 	if (rc) {
966 		dev_dbg(&cxlr->dev,
967 			"%s: failed to track region reference: %d\n",
968 			dev_name(&port->dev), rc);
969 		kfree(cxl_rr);
970 		return ERR_PTR(rc);
971 	}
972 
973 	return cxl_rr;
974 }
975 
976 static void cxl_rr_free_decoder(struct cxl_region_ref *cxl_rr)
977 {
978 	struct cxl_region *cxlr = cxl_rr->region;
979 	struct cxl_decoder *cxld = cxl_rr->decoder;
980 
981 	if (!cxld)
982 		return;
983 
984 	dev_WARN_ONCE(&cxlr->dev, cxld->region != cxlr, "region mismatch\n");
985 	if (cxld->region == cxlr) {
986 		cxld->region = NULL;
987 		put_device(&cxlr->dev);
988 	}
989 }
990 
991 static void free_region_ref(struct cxl_region_ref *cxl_rr)
992 {
993 	struct cxl_port *port = cxl_rr->port;
994 	struct cxl_region *cxlr = cxl_rr->region;
995 
996 	cxl_rr_free_decoder(cxl_rr);
997 	xa_erase(&port->regions, (unsigned long)cxlr);
998 	xa_destroy(&cxl_rr->endpoints);
999 	kfree(cxl_rr);
1000 }
1001 
1002 static int cxl_rr_ep_add(struct cxl_region_ref *cxl_rr,
1003 			 struct cxl_endpoint_decoder *cxled)
1004 {
1005 	int rc;
1006 	struct cxl_port *port = cxl_rr->port;
1007 	struct cxl_region *cxlr = cxl_rr->region;
1008 	struct cxl_decoder *cxld = cxl_rr->decoder;
1009 	struct cxl_ep *ep = cxl_ep_load(port, cxled_to_memdev(cxled));
1010 
1011 	if (ep) {
1012 		rc = xa_insert(&cxl_rr->endpoints, (unsigned long)cxled, ep,
1013 			       GFP_KERNEL);
1014 		if (rc)
1015 			return rc;
1016 	}
1017 	cxl_rr->nr_eps++;
1018 
1019 	if (!cxld->region) {
1020 		cxld->region = cxlr;
1021 		get_device(&cxlr->dev);
1022 	}
1023 
1024 	return 0;
1025 }
1026 
1027 static int cxl_rr_assign_decoder(struct cxl_port *port, struct cxl_region *cxlr,
1028 				 struct cxl_endpoint_decoder *cxled,
1029 				 struct cxl_region_ref *cxl_rr,
1030 				 struct cxl_decoder *cxld)
1031 {
1032 	if (cxld->region) {
1033 		dev_dbg(&cxlr->dev, "%s: %s already attached to %s\n",
1034 			dev_name(&port->dev), dev_name(&cxld->dev),
1035 			dev_name(&cxld->region->dev));
1036 		return -EBUSY;
1037 	}
1038 
1039 	/*
1040 	 * Endpoints should already match the region type, but backstop that
1041 	 * assumption with an assertion. Switch-decoders change mapping-type
1042 	 * based on what is mapped when they are assigned to a region.
1043 	 */
1044 	dev_WARN_ONCE(&cxlr->dev,
1045 		      port == cxled_to_port(cxled) &&
1046 			      cxld->target_type != cxlr->type,
1047 		      "%s:%s mismatch decoder type %d -> %d\n",
1048 		      dev_name(&cxled_to_memdev(cxled)->dev),
1049 		      dev_name(&cxld->dev), cxld->target_type, cxlr->type);
1050 	cxld->target_type = cxlr->type;
1051 	cxl_rr->decoder = cxld;
1052 	return 0;
1053 }
1054 
1055 /**
1056  * cxl_port_attach_region() - track a region's interest in a port by endpoint
1057  * @port: port to add a new region reference 'struct cxl_region_ref'
1058  * @cxlr: region to attach to @port
1059  * @cxled: endpoint decoder used to create or further pin a region reference
1060  * @pos: interleave position of @cxled in @cxlr
1061  *
1062  * The attach event is an opportunity to validate CXL decode setup
1063  * constraints and record metadata needed for programming HDM decoders,
1064  * in particular decoder target lists.
1065  *
1066  * The steps are:
1067  *
1068  * - validate that there are no other regions with a higher HPA already
1069  *   associated with @port
1070  * - establish a region reference if one is not already present
1071  *
1072  *   - additionally allocate a decoder instance that will host @cxlr on
1073  *     @port
1074  *
1075  * - pin the region reference by the endpoint
1076  * - account for how many entries in @port's target list are needed to
1077  *   cover all of the added endpoints.
1078  */
1079 static int cxl_port_attach_region(struct cxl_port *port,
1080 				  struct cxl_region *cxlr,
1081 				  struct cxl_endpoint_decoder *cxled, int pos)
1082 {
1083 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1084 	struct cxl_ep *ep = cxl_ep_load(port, cxlmd);
1085 	struct cxl_region_ref *cxl_rr;
1086 	bool nr_targets_inc = false;
1087 	struct cxl_decoder *cxld;
1088 	unsigned long index;
1089 	int rc = -EBUSY;
1090 
1091 	lockdep_assert_held_write(&cxl_region_rwsem);
1092 
1093 	cxl_rr = cxl_rr_load(port, cxlr);
1094 	if (cxl_rr) {
1095 		struct cxl_ep *ep_iter;
1096 		int found = 0;
1097 
1098 		/*
1099 		 * Walk the existing endpoints that have been attached to
1100 		 * @cxlr at @port and see if they share the same 'next' port
1101 		 * in the downstream direction. I.e. endpoints that share common
1102 		 * upstream switch.
1103 		 */
1104 		xa_for_each(&cxl_rr->endpoints, index, ep_iter) {
1105 			if (ep_iter == ep)
1106 				continue;
1107 			if (ep_iter->next == ep->next) {
1108 				found++;
1109 				break;
1110 			}
1111 		}
1112 
1113 		/*
1114 		 * New target port, or @port is an endpoint port that always
1115 		 * accounts its own local decode as a target.
1116 		 */
1117 		if (!found || !ep->next) {
1118 			cxl_rr->nr_targets++;
1119 			nr_targets_inc = true;
1120 		}
1121 	} else {
1122 		struct cxl_decoder *cxld;
1123 
1124 		cxld = cxl_port_pick_region_decoder(port, cxled, cxlr);
1125 		if (!cxld) {
1126 			dev_dbg(&cxlr->dev, "%s: no decoder available\n",
1127 				dev_name(&port->dev));
1128 			return -EBUSY;
1129 		}
1130 
1131 		cxl_rr = alloc_region_ref(port, cxlr, cxled, cxld);
1132 		if (IS_ERR(cxl_rr)) {
1133 			dev_dbg(&cxlr->dev,
1134 				"%s: failed to allocate region reference\n",
1135 				dev_name(&port->dev));
1136 			return PTR_ERR(cxl_rr);
1137 		}
1138 		nr_targets_inc = true;
1139 
1140 		rc = cxl_rr_assign_decoder(port, cxlr, cxled, cxl_rr, cxld);
1141 		if (rc)
1142 			goto out_erase;
1143 	}
1144 	cxld = cxl_rr->decoder;
1145 
1146 	/*
1147 	 * the number of targets should not exceed the target_count
1148 	 * of the decoder
1149 	 */
1150 	if (is_switch_decoder(&cxld->dev)) {
1151 		struct cxl_switch_decoder *cxlsd;
1152 
1153 		cxlsd = to_cxl_switch_decoder(&cxld->dev);
1154 		if (cxl_rr->nr_targets > cxlsd->nr_targets) {
1155 			dev_dbg(&cxlr->dev,
1156 				"%s:%s %s add: %s:%s @ %d overflows targets: %d\n",
1157 				dev_name(port->uport_dev), dev_name(&port->dev),
1158 				dev_name(&cxld->dev), dev_name(&cxlmd->dev),
1159 				dev_name(&cxled->cxld.dev), pos,
1160 				cxlsd->nr_targets);
1161 			rc = -ENXIO;
1162 			goto out_erase;
1163 		}
1164 	}
1165 
1166 	rc = cxl_rr_ep_add(cxl_rr, cxled);
1167 	if (rc) {
1168 		dev_dbg(&cxlr->dev,
1169 			"%s: failed to track endpoint %s:%s reference\n",
1170 			dev_name(&port->dev), dev_name(&cxlmd->dev),
1171 			dev_name(&cxld->dev));
1172 		goto out_erase;
1173 	}
1174 
1175 	dev_dbg(&cxlr->dev,
1176 		"%s:%s %s add: %s:%s @ %d next: %s nr_eps: %d nr_targets: %d\n",
1177 		dev_name(port->uport_dev), dev_name(&port->dev),
1178 		dev_name(&cxld->dev), dev_name(&cxlmd->dev),
1179 		dev_name(&cxled->cxld.dev), pos,
1180 		ep ? ep->next ? dev_name(ep->next->uport_dev) :
1181 				      dev_name(&cxlmd->dev) :
1182 			   "none",
1183 		cxl_rr->nr_eps, cxl_rr->nr_targets);
1184 
1185 	return 0;
1186 out_erase:
1187 	if (nr_targets_inc)
1188 		cxl_rr->nr_targets--;
1189 	if (cxl_rr->nr_eps == 0)
1190 		free_region_ref(cxl_rr);
1191 	return rc;
1192 }
1193 
1194 static void cxl_port_detach_region(struct cxl_port *port,
1195 				   struct cxl_region *cxlr,
1196 				   struct cxl_endpoint_decoder *cxled)
1197 {
1198 	struct cxl_region_ref *cxl_rr;
1199 	struct cxl_ep *ep = NULL;
1200 
1201 	lockdep_assert_held_write(&cxl_region_rwsem);
1202 
1203 	cxl_rr = cxl_rr_load(port, cxlr);
1204 	if (!cxl_rr)
1205 		return;
1206 
1207 	/*
1208 	 * Endpoint ports do not carry cxl_ep references, and they
1209 	 * never target more than one endpoint by definition
1210 	 */
1211 	if (cxl_rr->decoder == &cxled->cxld)
1212 		cxl_rr->nr_eps--;
1213 	else
1214 		ep = xa_erase(&cxl_rr->endpoints, (unsigned long)cxled);
1215 	if (ep) {
1216 		struct cxl_ep *ep_iter;
1217 		unsigned long index;
1218 		int found = 0;
1219 
1220 		cxl_rr->nr_eps--;
1221 		xa_for_each(&cxl_rr->endpoints, index, ep_iter) {
1222 			if (ep_iter->next == ep->next) {
1223 				found++;
1224 				break;
1225 			}
1226 		}
1227 		if (!found)
1228 			cxl_rr->nr_targets--;
1229 	}
1230 
1231 	if (cxl_rr->nr_eps == 0)
1232 		free_region_ref(cxl_rr);
1233 }
1234 
1235 static int check_last_peer(struct cxl_endpoint_decoder *cxled,
1236 			   struct cxl_ep *ep, struct cxl_region_ref *cxl_rr,
1237 			   int distance)
1238 {
1239 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1240 	struct cxl_region *cxlr = cxl_rr->region;
1241 	struct cxl_region_params *p = &cxlr->params;
1242 	struct cxl_endpoint_decoder *cxled_peer;
1243 	struct cxl_port *port = cxl_rr->port;
1244 	struct cxl_memdev *cxlmd_peer;
1245 	struct cxl_ep *ep_peer;
1246 	int pos = cxled->pos;
1247 
1248 	/*
1249 	 * If this position wants to share a dport with the last endpoint mapped
1250 	 * then that endpoint, at index 'position - distance', must also be
1251 	 * mapped by this dport.
1252 	 */
1253 	if (pos < distance) {
1254 		dev_dbg(&cxlr->dev, "%s:%s: cannot host %s:%s at %d\n",
1255 			dev_name(port->uport_dev), dev_name(&port->dev),
1256 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev), pos);
1257 		return -ENXIO;
1258 	}
1259 	cxled_peer = p->targets[pos - distance];
1260 	cxlmd_peer = cxled_to_memdev(cxled_peer);
1261 	ep_peer = cxl_ep_load(port, cxlmd_peer);
1262 	if (ep->dport != ep_peer->dport) {
1263 		dev_dbg(&cxlr->dev,
1264 			"%s:%s: %s:%s pos %d mismatched peer %s:%s\n",
1265 			dev_name(port->uport_dev), dev_name(&port->dev),
1266 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev), pos,
1267 			dev_name(&cxlmd_peer->dev),
1268 			dev_name(&cxled_peer->cxld.dev));
1269 		return -ENXIO;
1270 	}
1271 
1272 	return 0;
1273 }
1274 
1275 static int check_interleave_cap(struct cxl_decoder *cxld, int iw, int ig)
1276 {
1277 	struct cxl_port *port = to_cxl_port(cxld->dev.parent);
1278 	struct cxl_hdm *cxlhdm = dev_get_drvdata(&port->dev);
1279 	unsigned int interleave_mask;
1280 	u8 eiw;
1281 	u16 eig;
1282 	int high_pos, low_pos;
1283 
1284 	if (!test_bit(iw, &cxlhdm->iw_cap_mask))
1285 		return -ENXIO;
1286 	/*
1287 	 * Per CXL specification r3.1(8.2.4.20.13 Decoder Protection),
1288 	 * if eiw < 8:
1289 	 *   DPAOFFSET[51: eig + 8] = HPAOFFSET[51: eig + 8 + eiw]
1290 	 *   DPAOFFSET[eig + 7: 0]  = HPAOFFSET[eig + 7: 0]
1291 	 *
1292 	 *   when the eiw is 0, all the bits of HPAOFFSET[51: 0] are used, the
1293 	 *   interleave bits are none.
1294 	 *
1295 	 * if eiw >= 8:
1296 	 *   DPAOFFSET[51: eig + 8] = HPAOFFSET[51: eig + eiw] / 3
1297 	 *   DPAOFFSET[eig + 7: 0]  = HPAOFFSET[eig + 7: 0]
1298 	 *
1299 	 *   when the eiw is 8, all the bits of HPAOFFSET[51: 0] are used, the
1300 	 *   interleave bits are none.
1301 	 */
1302 	ways_to_eiw(iw, &eiw);
1303 	if (eiw == 0 || eiw == 8)
1304 		return 0;
1305 
1306 	granularity_to_eig(ig, &eig);
1307 	if (eiw > 8)
1308 		high_pos = eiw + eig - 1;
1309 	else
1310 		high_pos = eiw + eig + 7;
1311 	low_pos = eig + 8;
1312 	interleave_mask = GENMASK(high_pos, low_pos);
1313 	if (interleave_mask & ~cxlhdm->interleave_mask)
1314 		return -ENXIO;
1315 
1316 	return 0;
1317 }
1318 
1319 static int cxl_port_setup_targets(struct cxl_port *port,
1320 				  struct cxl_region *cxlr,
1321 				  struct cxl_endpoint_decoder *cxled)
1322 {
1323 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(cxlr->dev.parent);
1324 	int parent_iw, parent_ig, ig, iw, rc, inc = 0, pos = cxled->pos;
1325 	struct cxl_port *parent_port = to_cxl_port(port->dev.parent);
1326 	struct cxl_region_ref *cxl_rr = cxl_rr_load(port, cxlr);
1327 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1328 	struct cxl_ep *ep = cxl_ep_load(port, cxlmd);
1329 	struct cxl_region_params *p = &cxlr->params;
1330 	struct cxl_decoder *cxld = cxl_rr->decoder;
1331 	struct cxl_switch_decoder *cxlsd;
1332 	struct cxl_port *iter = port;
1333 	u16 eig, peig;
1334 	u8 eiw, peiw;
1335 
1336 	/*
1337 	 * While root level decoders support x3, x6, x12, switch level
1338 	 * decoders only support powers of 2 up to x16.
1339 	 */
1340 	if (!is_power_of_2(cxl_rr->nr_targets)) {
1341 		dev_dbg(&cxlr->dev, "%s:%s: invalid target count %d\n",
1342 			dev_name(port->uport_dev), dev_name(&port->dev),
1343 			cxl_rr->nr_targets);
1344 		return -EINVAL;
1345 	}
1346 
1347 	cxlsd = to_cxl_switch_decoder(&cxld->dev);
1348 	if (cxl_rr->nr_targets_set) {
1349 		int i, distance = 1;
1350 		struct cxl_region_ref *cxl_rr_iter;
1351 
1352 		/*
1353 		 * The "distance" between peer downstream ports represents which
1354 		 * endpoint positions in the region interleave a given port can
1355 		 * host.
1356 		 *
1357 		 * For example, at the root of a hierarchy the distance is
1358 		 * always 1 as every index targets a different host-bridge. At
1359 		 * each subsequent switch level those ports map every Nth region
1360 		 * position where N is the width of the switch == distance.
1361 		 */
1362 		do {
1363 			cxl_rr_iter = cxl_rr_load(iter, cxlr);
1364 			distance *= cxl_rr_iter->nr_targets;
1365 			iter = to_cxl_port(iter->dev.parent);
1366 		} while (!is_cxl_root(iter));
1367 		distance *= cxlrd->cxlsd.cxld.interleave_ways;
1368 
1369 		for (i = 0; i < cxl_rr->nr_targets_set; i++)
1370 			if (ep->dport == cxlsd->target[i]) {
1371 				rc = check_last_peer(cxled, ep, cxl_rr,
1372 						     distance);
1373 				if (rc)
1374 					return rc;
1375 				goto out_target_set;
1376 			}
1377 		goto add_target;
1378 	}
1379 
1380 	if (is_cxl_root(parent_port)) {
1381 		/*
1382 		 * Root decoder IG is always set to value in CFMWS which
1383 		 * may be different than this region's IG.  We can use the
1384 		 * region's IG here since interleave_granularity_store()
1385 		 * does not allow interleaved host-bridges with
1386 		 * root IG != region IG.
1387 		 */
1388 		parent_ig = p->interleave_granularity;
1389 		parent_iw = cxlrd->cxlsd.cxld.interleave_ways;
1390 		/*
1391 		 * For purposes of address bit routing, use power-of-2 math for
1392 		 * switch ports.
1393 		 */
1394 		if (!is_power_of_2(parent_iw))
1395 			parent_iw /= 3;
1396 	} else {
1397 		struct cxl_region_ref *parent_rr;
1398 		struct cxl_decoder *parent_cxld;
1399 
1400 		parent_rr = cxl_rr_load(parent_port, cxlr);
1401 		parent_cxld = parent_rr->decoder;
1402 		parent_ig = parent_cxld->interleave_granularity;
1403 		parent_iw = parent_cxld->interleave_ways;
1404 	}
1405 
1406 	rc = granularity_to_eig(parent_ig, &peig);
1407 	if (rc) {
1408 		dev_dbg(&cxlr->dev, "%s:%s: invalid parent granularity: %d\n",
1409 			dev_name(parent_port->uport_dev),
1410 			dev_name(&parent_port->dev), parent_ig);
1411 		return rc;
1412 	}
1413 
1414 	rc = ways_to_eiw(parent_iw, &peiw);
1415 	if (rc) {
1416 		dev_dbg(&cxlr->dev, "%s:%s: invalid parent interleave: %d\n",
1417 			dev_name(parent_port->uport_dev),
1418 			dev_name(&parent_port->dev), parent_iw);
1419 		return rc;
1420 	}
1421 
1422 	iw = cxl_rr->nr_targets;
1423 	rc = ways_to_eiw(iw, &eiw);
1424 	if (rc) {
1425 		dev_dbg(&cxlr->dev, "%s:%s: invalid port interleave: %d\n",
1426 			dev_name(port->uport_dev), dev_name(&port->dev), iw);
1427 		return rc;
1428 	}
1429 
1430 	/*
1431 	 * Interleave granularity is a multiple of @parent_port granularity.
1432 	 * Multiplier is the parent port interleave ways.
1433 	 */
1434 	rc = granularity_to_eig(parent_ig * parent_iw, &eig);
1435 	if (rc) {
1436 		dev_dbg(&cxlr->dev,
1437 			"%s: invalid granularity calculation (%d * %d)\n",
1438 			dev_name(&parent_port->dev), parent_ig, parent_iw);
1439 		return rc;
1440 	}
1441 
1442 	rc = eig_to_granularity(eig, &ig);
1443 	if (rc) {
1444 		dev_dbg(&cxlr->dev, "%s:%s: invalid interleave: %d\n",
1445 			dev_name(port->uport_dev), dev_name(&port->dev),
1446 			256 << eig);
1447 		return rc;
1448 	}
1449 
1450 	if (iw > 8 || iw > cxlsd->nr_targets) {
1451 		dev_dbg(&cxlr->dev,
1452 			"%s:%s:%s: ways: %d overflows targets: %d\n",
1453 			dev_name(port->uport_dev), dev_name(&port->dev),
1454 			dev_name(&cxld->dev), iw, cxlsd->nr_targets);
1455 		return -ENXIO;
1456 	}
1457 
1458 	if (test_bit(CXL_REGION_F_AUTO, &cxlr->flags)) {
1459 		if (cxld->interleave_ways != iw ||
1460 		    (iw > 1 && cxld->interleave_granularity != ig) ||
1461 		    !region_res_match_cxl_range(p, &cxld->hpa_range) ||
1462 		    ((cxld->flags & CXL_DECODER_F_ENABLE) == 0)) {
1463 			dev_err(&cxlr->dev,
1464 				"%s:%s %s expected iw: %d ig: %d %pr\n",
1465 				dev_name(port->uport_dev), dev_name(&port->dev),
1466 				__func__, iw, ig, p->res);
1467 			dev_err(&cxlr->dev,
1468 				"%s:%s %s got iw: %d ig: %d state: %s %#llx:%#llx\n",
1469 				dev_name(port->uport_dev), dev_name(&port->dev),
1470 				__func__, cxld->interleave_ways,
1471 				cxld->interleave_granularity,
1472 				(cxld->flags & CXL_DECODER_F_ENABLE) ?
1473 					"enabled" :
1474 					"disabled",
1475 				cxld->hpa_range.start, cxld->hpa_range.end);
1476 			return -ENXIO;
1477 		}
1478 	} else {
1479 		rc = check_interleave_cap(cxld, iw, ig);
1480 		if (rc) {
1481 			dev_dbg(&cxlr->dev,
1482 				"%s:%s iw: %d ig: %d is not supported\n",
1483 				dev_name(port->uport_dev),
1484 				dev_name(&port->dev), iw, ig);
1485 			return rc;
1486 		}
1487 
1488 		cxld->interleave_ways = iw;
1489 		cxld->interleave_granularity = ig;
1490 		cxld->hpa_range = (struct range) {
1491 			.start = p->res->start,
1492 			.end = p->res->end,
1493 		};
1494 	}
1495 	dev_dbg(&cxlr->dev, "%s:%s iw: %d ig: %d\n", dev_name(port->uport_dev),
1496 		dev_name(&port->dev), iw, ig);
1497 add_target:
1498 	if (cxl_rr->nr_targets_set == cxl_rr->nr_targets) {
1499 		dev_dbg(&cxlr->dev,
1500 			"%s:%s: targets full trying to add %s:%s at %d\n",
1501 			dev_name(port->uport_dev), dev_name(&port->dev),
1502 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev), pos);
1503 		return -ENXIO;
1504 	}
1505 	if (test_bit(CXL_REGION_F_AUTO, &cxlr->flags)) {
1506 		if (cxlsd->target[cxl_rr->nr_targets_set] != ep->dport) {
1507 			dev_dbg(&cxlr->dev, "%s:%s: %s expected %s at %d\n",
1508 				dev_name(port->uport_dev), dev_name(&port->dev),
1509 				dev_name(&cxlsd->cxld.dev),
1510 				dev_name(ep->dport->dport_dev),
1511 				cxl_rr->nr_targets_set);
1512 			return -ENXIO;
1513 		}
1514 	} else
1515 		cxlsd->target[cxl_rr->nr_targets_set] = ep->dport;
1516 	inc = 1;
1517 out_target_set:
1518 	cxl_rr->nr_targets_set += inc;
1519 	dev_dbg(&cxlr->dev, "%s:%s target[%d] = %s for %s:%s @ %d\n",
1520 		dev_name(port->uport_dev), dev_name(&port->dev),
1521 		cxl_rr->nr_targets_set - 1, dev_name(ep->dport->dport_dev),
1522 		dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev), pos);
1523 
1524 	return 0;
1525 }
1526 
1527 static void cxl_port_reset_targets(struct cxl_port *port,
1528 				   struct cxl_region *cxlr)
1529 {
1530 	struct cxl_region_ref *cxl_rr = cxl_rr_load(port, cxlr);
1531 	struct cxl_decoder *cxld;
1532 
1533 	/*
1534 	 * After the last endpoint has been detached the entire cxl_rr may now
1535 	 * be gone.
1536 	 */
1537 	if (!cxl_rr)
1538 		return;
1539 	cxl_rr->nr_targets_set = 0;
1540 
1541 	cxld = cxl_rr->decoder;
1542 	cxld->hpa_range = (struct range) {
1543 		.start = 0,
1544 		.end = -1,
1545 	};
1546 }
1547 
1548 static void cxl_region_teardown_targets(struct cxl_region *cxlr)
1549 {
1550 	struct cxl_region_params *p = &cxlr->params;
1551 	struct cxl_endpoint_decoder *cxled;
1552 	struct cxl_dev_state *cxlds;
1553 	struct cxl_memdev *cxlmd;
1554 	struct cxl_port *iter;
1555 	struct cxl_ep *ep;
1556 	int i;
1557 
1558 	/*
1559 	 * In the auto-discovery case skip automatic teardown since the
1560 	 * address space is already active
1561 	 */
1562 	if (test_bit(CXL_REGION_F_AUTO, &cxlr->flags))
1563 		return;
1564 
1565 	for (i = 0; i < p->nr_targets; i++) {
1566 		cxled = p->targets[i];
1567 		cxlmd = cxled_to_memdev(cxled);
1568 		cxlds = cxlmd->cxlds;
1569 
1570 		if (cxlds->rcd)
1571 			continue;
1572 
1573 		iter = cxled_to_port(cxled);
1574 		while (!is_cxl_root(to_cxl_port(iter->dev.parent)))
1575 			iter = to_cxl_port(iter->dev.parent);
1576 
1577 		for (ep = cxl_ep_load(iter, cxlmd); iter;
1578 		     iter = ep->next, ep = cxl_ep_load(iter, cxlmd))
1579 			cxl_port_reset_targets(iter, cxlr);
1580 	}
1581 }
1582 
1583 static int cxl_region_setup_targets(struct cxl_region *cxlr)
1584 {
1585 	struct cxl_region_params *p = &cxlr->params;
1586 	struct cxl_endpoint_decoder *cxled;
1587 	struct cxl_dev_state *cxlds;
1588 	int i, rc, rch = 0, vh = 0;
1589 	struct cxl_memdev *cxlmd;
1590 	struct cxl_port *iter;
1591 	struct cxl_ep *ep;
1592 
1593 	for (i = 0; i < p->nr_targets; i++) {
1594 		cxled = p->targets[i];
1595 		cxlmd = cxled_to_memdev(cxled);
1596 		cxlds = cxlmd->cxlds;
1597 
1598 		/* validate that all targets agree on topology */
1599 		if (!cxlds->rcd) {
1600 			vh++;
1601 		} else {
1602 			rch++;
1603 			continue;
1604 		}
1605 
1606 		iter = cxled_to_port(cxled);
1607 		while (!is_cxl_root(to_cxl_port(iter->dev.parent)))
1608 			iter = to_cxl_port(iter->dev.parent);
1609 
1610 		/*
1611 		 * Descend the topology tree programming / validating
1612 		 * targets while looking for conflicts.
1613 		 */
1614 		for (ep = cxl_ep_load(iter, cxlmd); iter;
1615 		     iter = ep->next, ep = cxl_ep_load(iter, cxlmd)) {
1616 			rc = cxl_port_setup_targets(iter, cxlr, cxled);
1617 			if (rc) {
1618 				cxl_region_teardown_targets(cxlr);
1619 				return rc;
1620 			}
1621 		}
1622 	}
1623 
1624 	if (rch && vh) {
1625 		dev_err(&cxlr->dev, "mismatched CXL topologies detected\n");
1626 		cxl_region_teardown_targets(cxlr);
1627 		return -ENXIO;
1628 	}
1629 
1630 	return 0;
1631 }
1632 
1633 static int cxl_region_validate_position(struct cxl_region *cxlr,
1634 					struct cxl_endpoint_decoder *cxled,
1635 					int pos)
1636 {
1637 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1638 	struct cxl_region_params *p = &cxlr->params;
1639 	int i;
1640 
1641 	if (pos < 0 || pos >= p->interleave_ways) {
1642 		dev_dbg(&cxlr->dev, "position %d out of range %d\n", pos,
1643 			p->interleave_ways);
1644 		return -ENXIO;
1645 	}
1646 
1647 	if (p->targets[pos] == cxled)
1648 		return 0;
1649 
1650 	if (p->targets[pos]) {
1651 		struct cxl_endpoint_decoder *cxled_target = p->targets[pos];
1652 		struct cxl_memdev *cxlmd_target = cxled_to_memdev(cxled_target);
1653 
1654 		dev_dbg(&cxlr->dev, "position %d already assigned to %s:%s\n",
1655 			pos, dev_name(&cxlmd_target->dev),
1656 			dev_name(&cxled_target->cxld.dev));
1657 		return -EBUSY;
1658 	}
1659 
1660 	for (i = 0; i < p->interleave_ways; i++) {
1661 		struct cxl_endpoint_decoder *cxled_target;
1662 		struct cxl_memdev *cxlmd_target;
1663 
1664 		cxled_target = p->targets[i];
1665 		if (!cxled_target)
1666 			continue;
1667 
1668 		cxlmd_target = cxled_to_memdev(cxled_target);
1669 		if (cxlmd_target == cxlmd) {
1670 			dev_dbg(&cxlr->dev,
1671 				"%s already specified at position %d via: %s\n",
1672 				dev_name(&cxlmd->dev), pos,
1673 				dev_name(&cxled_target->cxld.dev));
1674 			return -EBUSY;
1675 		}
1676 	}
1677 
1678 	return 0;
1679 }
1680 
1681 static int cxl_region_attach_position(struct cxl_region *cxlr,
1682 				      struct cxl_root_decoder *cxlrd,
1683 				      struct cxl_endpoint_decoder *cxled,
1684 				      const struct cxl_dport *dport, int pos)
1685 {
1686 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1687 	struct cxl_switch_decoder *cxlsd = &cxlrd->cxlsd;
1688 	struct cxl_decoder *cxld = &cxlsd->cxld;
1689 	int iw = cxld->interleave_ways;
1690 	struct cxl_port *iter;
1691 	int rc;
1692 
1693 	if (dport != cxlrd->cxlsd.target[pos % iw]) {
1694 		dev_dbg(&cxlr->dev, "%s:%s invalid target position for %s\n",
1695 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
1696 			dev_name(&cxlrd->cxlsd.cxld.dev));
1697 		return -ENXIO;
1698 	}
1699 
1700 	for (iter = cxled_to_port(cxled); !is_cxl_root(iter);
1701 	     iter = to_cxl_port(iter->dev.parent)) {
1702 		rc = cxl_port_attach_region(iter, cxlr, cxled, pos);
1703 		if (rc)
1704 			goto err;
1705 	}
1706 
1707 	return 0;
1708 
1709 err:
1710 	for (iter = cxled_to_port(cxled); !is_cxl_root(iter);
1711 	     iter = to_cxl_port(iter->dev.parent))
1712 		cxl_port_detach_region(iter, cxlr, cxled);
1713 	return rc;
1714 }
1715 
1716 static int cxl_region_attach_auto(struct cxl_region *cxlr,
1717 				  struct cxl_endpoint_decoder *cxled, int pos)
1718 {
1719 	struct cxl_region_params *p = &cxlr->params;
1720 
1721 	if (cxled->state != CXL_DECODER_STATE_AUTO) {
1722 		dev_err(&cxlr->dev,
1723 			"%s: unable to add decoder to autodetected region\n",
1724 			dev_name(&cxled->cxld.dev));
1725 		return -EINVAL;
1726 	}
1727 
1728 	if (pos >= 0) {
1729 		dev_dbg(&cxlr->dev, "%s: expected auto position, not %d\n",
1730 			dev_name(&cxled->cxld.dev), pos);
1731 		return -EINVAL;
1732 	}
1733 
1734 	if (p->nr_targets >= p->interleave_ways) {
1735 		dev_err(&cxlr->dev, "%s: no more target slots available\n",
1736 			dev_name(&cxled->cxld.dev));
1737 		return -ENXIO;
1738 	}
1739 
1740 	/*
1741 	 * Temporarily record the endpoint decoder into the target array. Yes,
1742 	 * this means that userspace can view devices in the wrong position
1743 	 * before the region activates, and must be careful to understand when
1744 	 * it might be racing region autodiscovery.
1745 	 */
1746 	pos = p->nr_targets;
1747 	p->targets[pos] = cxled;
1748 	cxled->pos = pos;
1749 	p->nr_targets++;
1750 
1751 	return 0;
1752 }
1753 
1754 static int cmp_interleave_pos(const void *a, const void *b)
1755 {
1756 	struct cxl_endpoint_decoder *cxled_a = *(typeof(cxled_a) *)a;
1757 	struct cxl_endpoint_decoder *cxled_b = *(typeof(cxled_b) *)b;
1758 
1759 	return cxled_a->pos - cxled_b->pos;
1760 }
1761 
1762 static int match_switch_decoder_by_range(struct device *dev,
1763 					 const void *data)
1764 {
1765 	struct cxl_switch_decoder *cxlsd;
1766 	const struct range *r1, *r2 = data;
1767 
1768 
1769 	if (!is_switch_decoder(dev))
1770 		return 0;
1771 
1772 	cxlsd = to_cxl_switch_decoder(dev);
1773 	r1 = &cxlsd->cxld.hpa_range;
1774 
1775 	if (is_root_decoder(dev))
1776 		return range_contains(r1, r2);
1777 	return (r1->start == r2->start && r1->end == r2->end);
1778 }
1779 
1780 static int find_pos_and_ways(struct cxl_port *port, struct range *range,
1781 			     int *pos, int *ways)
1782 {
1783 	struct cxl_switch_decoder *cxlsd;
1784 	struct cxl_port *parent;
1785 	struct device *dev;
1786 	int rc = -ENXIO;
1787 
1788 	parent = parent_port_of(port);
1789 	if (!parent)
1790 		return rc;
1791 
1792 	dev = device_find_child(&parent->dev, range,
1793 				match_switch_decoder_by_range);
1794 	if (!dev) {
1795 		dev_err(port->uport_dev,
1796 			"failed to find decoder mapping %#llx-%#llx\n",
1797 			range->start, range->end);
1798 		return rc;
1799 	}
1800 	cxlsd = to_cxl_switch_decoder(dev);
1801 	*ways = cxlsd->cxld.interleave_ways;
1802 
1803 	for (int i = 0; i < *ways; i++) {
1804 		if (cxlsd->target[i] == port->parent_dport) {
1805 			*pos = i;
1806 			rc = 0;
1807 			break;
1808 		}
1809 	}
1810 	put_device(dev);
1811 
1812 	if (rc)
1813 		dev_err(port->uport_dev,
1814 			"failed to find %s:%s in target list of %s\n",
1815 			dev_name(&port->dev),
1816 			dev_name(port->parent_dport->dport_dev),
1817 			dev_name(&cxlsd->cxld.dev));
1818 
1819 	return rc;
1820 }
1821 
1822 /**
1823  * cxl_calc_interleave_pos() - calculate an endpoint position in a region
1824  * @cxled: endpoint decoder member of given region
1825  *
1826  * The endpoint position is calculated by traversing the topology from
1827  * the endpoint to the root decoder and iteratively applying this
1828  * calculation:
1829  *
1830  *    position = position * parent_ways + parent_pos;
1831  *
1832  * ...where @position is inferred from switch and root decoder target lists.
1833  *
1834  * Return: position >= 0 on success
1835  *	   -ENXIO on failure
1836  */
1837 static int cxl_calc_interleave_pos(struct cxl_endpoint_decoder *cxled)
1838 {
1839 	struct cxl_port *iter, *port = cxled_to_port(cxled);
1840 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1841 	struct range *range = &cxled->cxld.hpa_range;
1842 	int parent_ways = 0, parent_pos = 0, pos = 0;
1843 	int rc;
1844 
1845 	/*
1846 	 * Example: the expected interleave order of the 4-way region shown
1847 	 * below is: mem0, mem2, mem1, mem3
1848 	 *
1849 	 *		  root_port
1850 	 *                 /      \
1851 	 *      host_bridge_0    host_bridge_1
1852 	 *        |    |           |    |
1853 	 *       mem0 mem1        mem2 mem3
1854 	 *
1855 	 * In the example the calculator will iterate twice. The first iteration
1856 	 * uses the mem position in the host-bridge and the ways of the host-
1857 	 * bridge to generate the first, or local, position. The second
1858 	 * iteration uses the host-bridge position in the root_port and the ways
1859 	 * of the root_port to refine the position.
1860 	 *
1861 	 * A trace of the calculation per endpoint looks like this:
1862 	 * mem0: pos = 0 * 2 + 0    mem2: pos = 0 * 2 + 0
1863 	 *       pos = 0 * 2 + 0          pos = 0 * 2 + 1
1864 	 *       pos: 0                   pos: 1
1865 	 *
1866 	 * mem1: pos = 0 * 2 + 1    mem3: pos = 0 * 2 + 1
1867 	 *       pos = 1 * 2 + 0          pos = 1 * 2 + 1
1868 	 *       pos: 2                   pos = 3
1869 	 *
1870 	 * Note that while this example is simple, the method applies to more
1871 	 * complex topologies, including those with switches.
1872 	 */
1873 
1874 	/* Iterate from endpoint to root_port refining the position */
1875 	for (iter = port; iter; iter = parent_port_of(iter)) {
1876 		if (is_cxl_root(iter))
1877 			break;
1878 
1879 		rc = find_pos_and_ways(iter, range, &parent_pos, &parent_ways);
1880 		if (rc)
1881 			return rc;
1882 
1883 		pos = pos * parent_ways + parent_pos;
1884 	}
1885 
1886 	dev_dbg(&cxlmd->dev,
1887 		"decoder:%s parent:%s port:%s range:%#llx-%#llx pos:%d\n",
1888 		dev_name(&cxled->cxld.dev), dev_name(cxlmd->dev.parent),
1889 		dev_name(&port->dev), range->start, range->end, pos);
1890 
1891 	return pos;
1892 }
1893 
1894 static int cxl_region_sort_targets(struct cxl_region *cxlr)
1895 {
1896 	struct cxl_region_params *p = &cxlr->params;
1897 	int i, rc = 0;
1898 
1899 	for (i = 0; i < p->nr_targets; i++) {
1900 		struct cxl_endpoint_decoder *cxled = p->targets[i];
1901 
1902 		cxled->pos = cxl_calc_interleave_pos(cxled);
1903 		/*
1904 		 * Record that sorting failed, but still continue to calc
1905 		 * cxled->pos so that follow-on code paths can reliably
1906 		 * do p->targets[cxled->pos] to self-reference their entry.
1907 		 */
1908 		if (cxled->pos < 0)
1909 			rc = -ENXIO;
1910 	}
1911 	/* Keep the cxlr target list in interleave position order */
1912 	sort(p->targets, p->nr_targets, sizeof(p->targets[0]),
1913 	     cmp_interleave_pos, NULL);
1914 
1915 	dev_dbg(&cxlr->dev, "region sort %s\n", rc ? "failed" : "successful");
1916 	return rc;
1917 }
1918 
1919 static int cxl_region_attach(struct cxl_region *cxlr,
1920 			     struct cxl_endpoint_decoder *cxled, int pos)
1921 {
1922 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(cxlr->dev.parent);
1923 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1924 	struct cxl_dev_state *cxlds = cxlmd->cxlds;
1925 	struct cxl_region_params *p = &cxlr->params;
1926 	struct cxl_port *ep_port, *root_port;
1927 	struct cxl_dport *dport;
1928 	int rc = -ENXIO;
1929 
1930 	rc = check_interleave_cap(&cxled->cxld, p->interleave_ways,
1931 				  p->interleave_granularity);
1932 	if (rc) {
1933 		dev_dbg(&cxlr->dev, "%s iw: %d ig: %d is not supported\n",
1934 			dev_name(&cxled->cxld.dev), p->interleave_ways,
1935 			p->interleave_granularity);
1936 		return rc;
1937 	}
1938 
1939 	if (cxled->part < 0) {
1940 		dev_dbg(&cxlr->dev, "%s dead\n", dev_name(&cxled->cxld.dev));
1941 		return -ENODEV;
1942 	}
1943 
1944 	if (cxlds->part[cxled->part].mode != cxlr->mode) {
1945 		dev_dbg(&cxlr->dev, "%s region mode: %d mismatch\n",
1946 			dev_name(&cxled->cxld.dev), cxlr->mode);
1947 		return -EINVAL;
1948 	}
1949 
1950 	/* all full of members, or interleave config not established? */
1951 	if (p->state > CXL_CONFIG_INTERLEAVE_ACTIVE) {
1952 		dev_dbg(&cxlr->dev, "region already active\n");
1953 		return -EBUSY;
1954 	}
1955 
1956 	if (p->state < CXL_CONFIG_INTERLEAVE_ACTIVE) {
1957 		dev_dbg(&cxlr->dev, "interleave config missing\n");
1958 		return -ENXIO;
1959 	}
1960 
1961 	if (p->nr_targets >= p->interleave_ways) {
1962 		dev_dbg(&cxlr->dev, "region already has %d endpoints\n",
1963 			p->nr_targets);
1964 		return -EINVAL;
1965 	}
1966 
1967 	ep_port = cxled_to_port(cxled);
1968 	root_port = cxlrd_to_port(cxlrd);
1969 	dport = cxl_find_dport_by_dev(root_port, ep_port->host_bridge);
1970 	if (!dport) {
1971 		dev_dbg(&cxlr->dev, "%s:%s invalid target for %s\n",
1972 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
1973 			dev_name(cxlr->dev.parent));
1974 		return -ENXIO;
1975 	}
1976 
1977 	if (cxled->cxld.target_type != cxlr->type) {
1978 		dev_dbg(&cxlr->dev, "%s:%s type mismatch: %d vs %d\n",
1979 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
1980 			cxled->cxld.target_type, cxlr->type);
1981 		return -ENXIO;
1982 	}
1983 
1984 	if (!cxled->dpa_res) {
1985 		dev_dbg(&cxlr->dev, "%s:%s: missing DPA allocation.\n",
1986 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev));
1987 		return -ENXIO;
1988 	}
1989 
1990 	if (resource_size(cxled->dpa_res) * p->interleave_ways + p->cache_size !=
1991 	    resource_size(p->res)) {
1992 		dev_dbg(&cxlr->dev,
1993 			"%s:%s-size-%#llx * ways-%d + cache-%#llx != region-size-%#llx\n",
1994 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
1995 			(u64)resource_size(cxled->dpa_res), p->interleave_ways,
1996 			(u64)p->cache_size, (u64)resource_size(p->res));
1997 		return -EINVAL;
1998 	}
1999 
2000 	cxl_region_perf_data_calculate(cxlr, cxled);
2001 
2002 	if (test_bit(CXL_REGION_F_AUTO, &cxlr->flags)) {
2003 		int i;
2004 
2005 		rc = cxl_region_attach_auto(cxlr, cxled, pos);
2006 		if (rc)
2007 			return rc;
2008 
2009 		/* await more targets to arrive... */
2010 		if (p->nr_targets < p->interleave_ways)
2011 			return 0;
2012 
2013 		/*
2014 		 * All targets are here, which implies all PCI enumeration that
2015 		 * affects this region has been completed. Walk the topology to
2016 		 * sort the devices into their relative region decode position.
2017 		 */
2018 		rc = cxl_region_sort_targets(cxlr);
2019 		if (rc)
2020 			return rc;
2021 
2022 		for (i = 0; i < p->nr_targets; i++) {
2023 			cxled = p->targets[i];
2024 			ep_port = cxled_to_port(cxled);
2025 			dport = cxl_find_dport_by_dev(root_port,
2026 						      ep_port->host_bridge);
2027 			rc = cxl_region_attach_position(cxlr, cxlrd, cxled,
2028 							dport, i);
2029 			if (rc)
2030 				return rc;
2031 		}
2032 
2033 		rc = cxl_region_setup_targets(cxlr);
2034 		if (rc)
2035 			return rc;
2036 
2037 		/*
2038 		 * If target setup succeeds in the autodiscovery case
2039 		 * then the region is already committed.
2040 		 */
2041 		p->state = CXL_CONFIG_COMMIT;
2042 		cxl_region_shared_upstream_bandwidth_update(cxlr);
2043 
2044 		return 0;
2045 	}
2046 
2047 	rc = cxl_region_validate_position(cxlr, cxled, pos);
2048 	if (rc)
2049 		return rc;
2050 
2051 	rc = cxl_region_attach_position(cxlr, cxlrd, cxled, dport, pos);
2052 	if (rc)
2053 		return rc;
2054 
2055 	p->targets[pos] = cxled;
2056 	cxled->pos = pos;
2057 	p->nr_targets++;
2058 
2059 	if (p->nr_targets == p->interleave_ways) {
2060 		rc = cxl_region_setup_targets(cxlr);
2061 		if (rc)
2062 			return rc;
2063 		p->state = CXL_CONFIG_ACTIVE;
2064 		cxl_region_shared_upstream_bandwidth_update(cxlr);
2065 	}
2066 
2067 	cxled->cxld.interleave_ways = p->interleave_ways;
2068 	cxled->cxld.interleave_granularity = p->interleave_granularity;
2069 	cxled->cxld.hpa_range = (struct range) {
2070 		.start = p->res->start,
2071 		.end = p->res->end,
2072 	};
2073 
2074 	if (p->nr_targets != p->interleave_ways)
2075 		return 0;
2076 
2077 	/*
2078 	 * Test the auto-discovery position calculator function
2079 	 * against this successfully created user-defined region.
2080 	 * A fail message here means that this interleave config
2081 	 * will fail when presented as CXL_REGION_F_AUTO.
2082 	 */
2083 	for (int i = 0; i < p->nr_targets; i++) {
2084 		struct cxl_endpoint_decoder *cxled = p->targets[i];
2085 		int test_pos;
2086 
2087 		test_pos = cxl_calc_interleave_pos(cxled);
2088 		dev_dbg(&cxled->cxld.dev,
2089 			"Test cxl_calc_interleave_pos(): %s test_pos:%d cxled->pos:%d\n",
2090 			(test_pos == cxled->pos) ? "success" : "fail",
2091 			test_pos, cxled->pos);
2092 	}
2093 
2094 	return 0;
2095 }
2096 
2097 static int cxl_region_detach(struct cxl_endpoint_decoder *cxled)
2098 {
2099 	struct cxl_port *iter, *ep_port = cxled_to_port(cxled);
2100 	struct cxl_region *cxlr = cxled->cxld.region;
2101 	struct cxl_region_params *p;
2102 	int rc = 0;
2103 
2104 	lockdep_assert_held_write(&cxl_region_rwsem);
2105 
2106 	if (!cxlr)
2107 		return 0;
2108 
2109 	p = &cxlr->params;
2110 	get_device(&cxlr->dev);
2111 
2112 	if (p->state > CXL_CONFIG_ACTIVE) {
2113 		cxl_region_decode_reset(cxlr, p->interleave_ways);
2114 		p->state = CXL_CONFIG_ACTIVE;
2115 	}
2116 
2117 	for (iter = ep_port; !is_cxl_root(iter);
2118 	     iter = to_cxl_port(iter->dev.parent))
2119 		cxl_port_detach_region(iter, cxlr, cxled);
2120 
2121 	if (cxled->pos < 0 || cxled->pos >= p->interleave_ways ||
2122 	    p->targets[cxled->pos] != cxled) {
2123 		struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
2124 
2125 		dev_WARN_ONCE(&cxlr->dev, 1, "expected %s:%s at position %d\n",
2126 			      dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
2127 			      cxled->pos);
2128 		goto out;
2129 	}
2130 
2131 	if (p->state == CXL_CONFIG_ACTIVE) {
2132 		p->state = CXL_CONFIG_INTERLEAVE_ACTIVE;
2133 		cxl_region_teardown_targets(cxlr);
2134 	}
2135 	p->targets[cxled->pos] = NULL;
2136 	p->nr_targets--;
2137 	cxled->cxld.hpa_range = (struct range) {
2138 		.start = 0,
2139 		.end = -1,
2140 	};
2141 
2142 	/* notify the region driver that one of its targets has departed */
2143 	up_write(&cxl_region_rwsem);
2144 	device_release_driver(&cxlr->dev);
2145 	down_write(&cxl_region_rwsem);
2146 out:
2147 	put_device(&cxlr->dev);
2148 	return rc;
2149 }
2150 
2151 void cxl_decoder_kill_region(struct cxl_endpoint_decoder *cxled)
2152 {
2153 	down_write(&cxl_region_rwsem);
2154 	cxled->part = -1;
2155 	cxl_region_detach(cxled);
2156 	up_write(&cxl_region_rwsem);
2157 }
2158 
2159 static int attach_target(struct cxl_region *cxlr,
2160 			 struct cxl_endpoint_decoder *cxled, int pos,
2161 			 unsigned int state)
2162 {
2163 	int rc = 0;
2164 
2165 	if (state == TASK_INTERRUPTIBLE)
2166 		rc = down_write_killable(&cxl_region_rwsem);
2167 	else
2168 		down_write(&cxl_region_rwsem);
2169 	if (rc)
2170 		return rc;
2171 
2172 	down_read(&cxl_dpa_rwsem);
2173 	rc = cxl_region_attach(cxlr, cxled, pos);
2174 	up_read(&cxl_dpa_rwsem);
2175 	up_write(&cxl_region_rwsem);
2176 
2177 	if (rc)
2178 		dev_warn(cxled->cxld.dev.parent,
2179 			"failed to attach %s to %s: %d\n",
2180 			dev_name(&cxled->cxld.dev), dev_name(&cxlr->dev), rc);
2181 
2182 	return rc;
2183 }
2184 
2185 static int detach_target(struct cxl_region *cxlr, int pos)
2186 {
2187 	struct cxl_region_params *p = &cxlr->params;
2188 	int rc;
2189 
2190 	rc = down_write_killable(&cxl_region_rwsem);
2191 	if (rc)
2192 		return rc;
2193 
2194 	if (pos >= p->interleave_ways) {
2195 		dev_dbg(&cxlr->dev, "position %d out of range %d\n", pos,
2196 			p->interleave_ways);
2197 		rc = -ENXIO;
2198 		goto out;
2199 	}
2200 
2201 	if (!p->targets[pos]) {
2202 		rc = 0;
2203 		goto out;
2204 	}
2205 
2206 	rc = cxl_region_detach(p->targets[pos]);
2207 out:
2208 	up_write(&cxl_region_rwsem);
2209 	return rc;
2210 }
2211 
2212 static size_t store_targetN(struct cxl_region *cxlr, const char *buf, int pos,
2213 			    size_t len)
2214 {
2215 	int rc;
2216 
2217 	if (sysfs_streq(buf, "\n"))
2218 		rc = detach_target(cxlr, pos);
2219 	else {
2220 		struct device *dev;
2221 
2222 		dev = bus_find_device_by_name(&cxl_bus_type, NULL, buf);
2223 		if (!dev)
2224 			return -ENODEV;
2225 
2226 		if (!is_endpoint_decoder(dev)) {
2227 			rc = -EINVAL;
2228 			goto out;
2229 		}
2230 
2231 		rc = attach_target(cxlr, to_cxl_endpoint_decoder(dev), pos,
2232 				   TASK_INTERRUPTIBLE);
2233 out:
2234 		put_device(dev);
2235 	}
2236 
2237 	if (rc < 0)
2238 		return rc;
2239 	return len;
2240 }
2241 
2242 #define TARGET_ATTR_RW(n)                                              \
2243 static ssize_t target##n##_show(                                       \
2244 	struct device *dev, struct device_attribute *attr, char *buf)  \
2245 {                                                                      \
2246 	return show_targetN(to_cxl_region(dev), buf, (n));             \
2247 }                                                                      \
2248 static ssize_t target##n##_store(struct device *dev,                   \
2249 				 struct device_attribute *attr,        \
2250 				 const char *buf, size_t len)          \
2251 {                                                                      \
2252 	return store_targetN(to_cxl_region(dev), buf, (n), len);       \
2253 }                                                                      \
2254 static DEVICE_ATTR_RW(target##n)
2255 
2256 TARGET_ATTR_RW(0);
2257 TARGET_ATTR_RW(1);
2258 TARGET_ATTR_RW(2);
2259 TARGET_ATTR_RW(3);
2260 TARGET_ATTR_RW(4);
2261 TARGET_ATTR_RW(5);
2262 TARGET_ATTR_RW(6);
2263 TARGET_ATTR_RW(7);
2264 TARGET_ATTR_RW(8);
2265 TARGET_ATTR_RW(9);
2266 TARGET_ATTR_RW(10);
2267 TARGET_ATTR_RW(11);
2268 TARGET_ATTR_RW(12);
2269 TARGET_ATTR_RW(13);
2270 TARGET_ATTR_RW(14);
2271 TARGET_ATTR_RW(15);
2272 
2273 static struct attribute *target_attrs[] = {
2274 	&dev_attr_target0.attr,
2275 	&dev_attr_target1.attr,
2276 	&dev_attr_target2.attr,
2277 	&dev_attr_target3.attr,
2278 	&dev_attr_target4.attr,
2279 	&dev_attr_target5.attr,
2280 	&dev_attr_target6.attr,
2281 	&dev_attr_target7.attr,
2282 	&dev_attr_target8.attr,
2283 	&dev_attr_target9.attr,
2284 	&dev_attr_target10.attr,
2285 	&dev_attr_target11.attr,
2286 	&dev_attr_target12.attr,
2287 	&dev_attr_target13.attr,
2288 	&dev_attr_target14.attr,
2289 	&dev_attr_target15.attr,
2290 	NULL,
2291 };
2292 
2293 static umode_t cxl_region_target_visible(struct kobject *kobj,
2294 					 struct attribute *a, int n)
2295 {
2296 	struct device *dev = kobj_to_dev(kobj);
2297 	struct cxl_region *cxlr = to_cxl_region(dev);
2298 	struct cxl_region_params *p = &cxlr->params;
2299 
2300 	if (n < p->interleave_ways)
2301 		return a->mode;
2302 	return 0;
2303 }
2304 
2305 static const struct attribute_group cxl_region_target_group = {
2306 	.attrs = target_attrs,
2307 	.is_visible = cxl_region_target_visible,
2308 };
2309 
2310 static const struct attribute_group *get_cxl_region_target_group(void)
2311 {
2312 	return &cxl_region_target_group;
2313 }
2314 
2315 static const struct attribute_group *region_groups[] = {
2316 	&cxl_base_attribute_group,
2317 	&cxl_region_group,
2318 	&cxl_region_target_group,
2319 	&cxl_region_access0_coordinate_group,
2320 	&cxl_region_access1_coordinate_group,
2321 	NULL,
2322 };
2323 
2324 static void cxl_region_release(struct device *dev)
2325 {
2326 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev->parent);
2327 	struct cxl_region *cxlr = to_cxl_region(dev);
2328 	int id = atomic_read(&cxlrd->region_id);
2329 
2330 	/*
2331 	 * Try to reuse the recently idled id rather than the cached
2332 	 * next id to prevent the region id space from increasing
2333 	 * unnecessarily.
2334 	 */
2335 	if (cxlr->id < id)
2336 		if (atomic_try_cmpxchg(&cxlrd->region_id, &id, cxlr->id)) {
2337 			memregion_free(id);
2338 			goto out;
2339 		}
2340 
2341 	memregion_free(cxlr->id);
2342 out:
2343 	put_device(dev->parent);
2344 	kfree(cxlr);
2345 }
2346 
2347 const struct device_type cxl_region_type = {
2348 	.name = "cxl_region",
2349 	.release = cxl_region_release,
2350 	.groups = region_groups
2351 };
2352 
2353 bool is_cxl_region(struct device *dev)
2354 {
2355 	return dev->type == &cxl_region_type;
2356 }
2357 EXPORT_SYMBOL_NS_GPL(is_cxl_region, "CXL");
2358 
2359 static struct cxl_region *to_cxl_region(struct device *dev)
2360 {
2361 	if (dev_WARN_ONCE(dev, dev->type != &cxl_region_type,
2362 			  "not a cxl_region device\n"))
2363 		return NULL;
2364 
2365 	return container_of(dev, struct cxl_region, dev);
2366 }
2367 
2368 static void unregister_region(void *_cxlr)
2369 {
2370 	struct cxl_region *cxlr = _cxlr;
2371 	struct cxl_region_params *p = &cxlr->params;
2372 	int i;
2373 
2374 	device_del(&cxlr->dev);
2375 
2376 	/*
2377 	 * Now that region sysfs is shutdown, the parameter block is now
2378 	 * read-only, so no need to hold the region rwsem to access the
2379 	 * region parameters.
2380 	 */
2381 	for (i = 0; i < p->interleave_ways; i++)
2382 		detach_target(cxlr, i);
2383 
2384 	cxl_region_iomem_release(cxlr);
2385 	put_device(&cxlr->dev);
2386 }
2387 
2388 static struct lock_class_key cxl_region_key;
2389 
2390 static struct cxl_region *cxl_region_alloc(struct cxl_root_decoder *cxlrd, int id)
2391 {
2392 	struct cxl_region *cxlr;
2393 	struct device *dev;
2394 
2395 	cxlr = kzalloc(sizeof(*cxlr), GFP_KERNEL);
2396 	if (!cxlr) {
2397 		memregion_free(id);
2398 		return ERR_PTR(-ENOMEM);
2399 	}
2400 
2401 	dev = &cxlr->dev;
2402 	device_initialize(dev);
2403 	lockdep_set_class(&dev->mutex, &cxl_region_key);
2404 	dev->parent = &cxlrd->cxlsd.cxld.dev;
2405 	/*
2406 	 * Keep root decoder pinned through cxl_region_release to fixup
2407 	 * region id allocations
2408 	 */
2409 	get_device(dev->parent);
2410 	device_set_pm_not_required(dev);
2411 	dev->bus = &cxl_bus_type;
2412 	dev->type = &cxl_region_type;
2413 	cxlr->id = id;
2414 
2415 	return cxlr;
2416 }
2417 
2418 static bool cxl_region_update_coordinates(struct cxl_region *cxlr, int nid)
2419 {
2420 	int cset = 0;
2421 	int rc;
2422 
2423 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++) {
2424 		if (cxlr->coord[i].read_bandwidth) {
2425 			rc = 0;
2426 			if (cxl_need_node_perf_attrs_update(nid))
2427 				node_set_perf_attrs(nid, &cxlr->coord[i], i);
2428 			else
2429 				rc = cxl_update_hmat_access_coordinates(nid, cxlr, i);
2430 
2431 			if (rc == 0)
2432 				cset++;
2433 		}
2434 	}
2435 
2436 	if (!cset)
2437 		return false;
2438 
2439 	rc = sysfs_update_group(&cxlr->dev.kobj, get_cxl_region_access0_group());
2440 	if (rc)
2441 		dev_dbg(&cxlr->dev, "Failed to update access0 group\n");
2442 
2443 	rc = sysfs_update_group(&cxlr->dev.kobj, get_cxl_region_access1_group());
2444 	if (rc)
2445 		dev_dbg(&cxlr->dev, "Failed to update access1 group\n");
2446 
2447 	return true;
2448 }
2449 
2450 static int cxl_region_perf_attrs_callback(struct notifier_block *nb,
2451 					  unsigned long action, void *arg)
2452 {
2453 	struct cxl_region *cxlr = container_of(nb, struct cxl_region,
2454 					       memory_notifier);
2455 	struct memory_notify *mnb = arg;
2456 	int nid = mnb->status_change_nid;
2457 	int region_nid;
2458 
2459 	if (nid == NUMA_NO_NODE || action != MEM_ONLINE)
2460 		return NOTIFY_DONE;
2461 
2462 	/*
2463 	 * No need to hold cxl_region_rwsem; region parameters are stable
2464 	 * within the cxl_region driver.
2465 	 */
2466 	region_nid = phys_to_target_node(cxlr->params.res->start);
2467 	if (nid != region_nid)
2468 		return NOTIFY_DONE;
2469 
2470 	if (!cxl_region_update_coordinates(cxlr, nid))
2471 		return NOTIFY_DONE;
2472 
2473 	return NOTIFY_OK;
2474 }
2475 
2476 static int cxl_region_calculate_adistance(struct notifier_block *nb,
2477 					  unsigned long nid, void *data)
2478 {
2479 	struct cxl_region *cxlr = container_of(nb, struct cxl_region,
2480 					       adist_notifier);
2481 	struct access_coordinate *perf;
2482 	int *adist = data;
2483 	int region_nid;
2484 
2485 	/*
2486 	 * No need to hold cxl_region_rwsem; region parameters are stable
2487 	 * within the cxl_region driver.
2488 	 */
2489 	region_nid = phys_to_target_node(cxlr->params.res->start);
2490 	if (nid != region_nid)
2491 		return NOTIFY_OK;
2492 
2493 	perf = &cxlr->coord[ACCESS_COORDINATE_CPU];
2494 
2495 	if (mt_perf_to_adistance(perf, adist))
2496 		return NOTIFY_OK;
2497 
2498 	return NOTIFY_STOP;
2499 }
2500 
2501 /**
2502  * devm_cxl_add_region - Adds a region to a decoder
2503  * @cxlrd: root decoder
2504  * @id: memregion id to create, or memregion_free() on failure
2505  * @mode: mode for the endpoint decoders of this region
2506  * @type: select whether this is an expander or accelerator (type-2 or type-3)
2507  *
2508  * This is the second step of region initialization. Regions exist within an
2509  * address space which is mapped by a @cxlrd.
2510  *
2511  * Return: 0 if the region was added to the @cxlrd, else returns negative error
2512  * code. The region will be named "regionZ" where Z is the unique region number.
2513  */
2514 static struct cxl_region *devm_cxl_add_region(struct cxl_root_decoder *cxlrd,
2515 					      int id,
2516 					      enum cxl_partition_mode mode,
2517 					      enum cxl_decoder_type type)
2518 {
2519 	struct cxl_port *port = to_cxl_port(cxlrd->cxlsd.cxld.dev.parent);
2520 	struct cxl_region *cxlr;
2521 	struct device *dev;
2522 	int rc;
2523 
2524 	cxlr = cxl_region_alloc(cxlrd, id);
2525 	if (IS_ERR(cxlr))
2526 		return cxlr;
2527 	cxlr->mode = mode;
2528 	cxlr->type = type;
2529 
2530 	dev = &cxlr->dev;
2531 	rc = dev_set_name(dev, "region%d", id);
2532 	if (rc)
2533 		goto err;
2534 
2535 	rc = device_add(dev);
2536 	if (rc)
2537 		goto err;
2538 
2539 	rc = devm_add_action_or_reset(port->uport_dev, unregister_region, cxlr);
2540 	if (rc)
2541 		return ERR_PTR(rc);
2542 
2543 	dev_dbg(port->uport_dev, "%s: created %s\n",
2544 		dev_name(&cxlrd->cxlsd.cxld.dev), dev_name(dev));
2545 	return cxlr;
2546 
2547 err:
2548 	put_device(dev);
2549 	return ERR_PTR(rc);
2550 }
2551 
2552 static ssize_t __create_region_show(struct cxl_root_decoder *cxlrd, char *buf)
2553 {
2554 	return sysfs_emit(buf, "region%u\n", atomic_read(&cxlrd->region_id));
2555 }
2556 
2557 static ssize_t create_pmem_region_show(struct device *dev,
2558 				       struct device_attribute *attr, char *buf)
2559 {
2560 	return __create_region_show(to_cxl_root_decoder(dev), buf);
2561 }
2562 
2563 static ssize_t create_ram_region_show(struct device *dev,
2564 				      struct device_attribute *attr, char *buf)
2565 {
2566 	return __create_region_show(to_cxl_root_decoder(dev), buf);
2567 }
2568 
2569 static struct cxl_region *__create_region(struct cxl_root_decoder *cxlrd,
2570 					  enum cxl_partition_mode mode, int id)
2571 {
2572 	int rc;
2573 
2574 	switch (mode) {
2575 	case CXL_PARTMODE_RAM:
2576 	case CXL_PARTMODE_PMEM:
2577 		break;
2578 	default:
2579 		dev_err(&cxlrd->cxlsd.cxld.dev, "unsupported mode %d\n", mode);
2580 		return ERR_PTR(-EINVAL);
2581 	}
2582 
2583 	rc = memregion_alloc(GFP_KERNEL);
2584 	if (rc < 0)
2585 		return ERR_PTR(rc);
2586 
2587 	if (atomic_cmpxchg(&cxlrd->region_id, id, rc) != id) {
2588 		memregion_free(rc);
2589 		return ERR_PTR(-EBUSY);
2590 	}
2591 
2592 	return devm_cxl_add_region(cxlrd, id, mode, CXL_DECODER_HOSTONLYMEM);
2593 }
2594 
2595 static ssize_t create_region_store(struct device *dev, const char *buf,
2596 				   size_t len, enum cxl_partition_mode mode)
2597 {
2598 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev);
2599 	struct cxl_region *cxlr;
2600 	int rc, id;
2601 
2602 	rc = sscanf(buf, "region%d\n", &id);
2603 	if (rc != 1)
2604 		return -EINVAL;
2605 
2606 	cxlr = __create_region(cxlrd, mode, id);
2607 	if (IS_ERR(cxlr))
2608 		return PTR_ERR(cxlr);
2609 
2610 	return len;
2611 }
2612 
2613 static ssize_t create_pmem_region_store(struct device *dev,
2614 					struct device_attribute *attr,
2615 					const char *buf, size_t len)
2616 {
2617 	return create_region_store(dev, buf, len, CXL_PARTMODE_PMEM);
2618 }
2619 DEVICE_ATTR_RW(create_pmem_region);
2620 
2621 static ssize_t create_ram_region_store(struct device *dev,
2622 				       struct device_attribute *attr,
2623 				       const char *buf, size_t len)
2624 {
2625 	return create_region_store(dev, buf, len, CXL_PARTMODE_RAM);
2626 }
2627 DEVICE_ATTR_RW(create_ram_region);
2628 
2629 static ssize_t region_show(struct device *dev, struct device_attribute *attr,
2630 			   char *buf)
2631 {
2632 	struct cxl_decoder *cxld = to_cxl_decoder(dev);
2633 	ssize_t rc;
2634 
2635 	rc = down_read_interruptible(&cxl_region_rwsem);
2636 	if (rc)
2637 		return rc;
2638 
2639 	if (cxld->region)
2640 		rc = sysfs_emit(buf, "%s\n", dev_name(&cxld->region->dev));
2641 	else
2642 		rc = sysfs_emit(buf, "\n");
2643 	up_read(&cxl_region_rwsem);
2644 
2645 	return rc;
2646 }
2647 DEVICE_ATTR_RO(region);
2648 
2649 static struct cxl_region *
2650 cxl_find_region_by_name(struct cxl_root_decoder *cxlrd, const char *name)
2651 {
2652 	struct cxl_decoder *cxld = &cxlrd->cxlsd.cxld;
2653 	struct device *region_dev;
2654 
2655 	region_dev = device_find_child_by_name(&cxld->dev, name);
2656 	if (!region_dev)
2657 		return ERR_PTR(-ENODEV);
2658 
2659 	return to_cxl_region(region_dev);
2660 }
2661 
2662 static ssize_t delete_region_store(struct device *dev,
2663 				   struct device_attribute *attr,
2664 				   const char *buf, size_t len)
2665 {
2666 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev);
2667 	struct cxl_port *port = to_cxl_port(dev->parent);
2668 	struct cxl_region *cxlr;
2669 
2670 	cxlr = cxl_find_region_by_name(cxlrd, buf);
2671 	if (IS_ERR(cxlr))
2672 		return PTR_ERR(cxlr);
2673 
2674 	devm_release_action(port->uport_dev, unregister_region, cxlr);
2675 	put_device(&cxlr->dev);
2676 
2677 	return len;
2678 }
2679 DEVICE_ATTR_WO(delete_region);
2680 
2681 static void cxl_pmem_region_release(struct device *dev)
2682 {
2683 	struct cxl_pmem_region *cxlr_pmem = to_cxl_pmem_region(dev);
2684 	int i;
2685 
2686 	for (i = 0; i < cxlr_pmem->nr_mappings; i++) {
2687 		struct cxl_memdev *cxlmd = cxlr_pmem->mapping[i].cxlmd;
2688 
2689 		put_device(&cxlmd->dev);
2690 	}
2691 
2692 	kfree(cxlr_pmem);
2693 }
2694 
2695 static const struct attribute_group *cxl_pmem_region_attribute_groups[] = {
2696 	&cxl_base_attribute_group,
2697 	NULL,
2698 };
2699 
2700 const struct device_type cxl_pmem_region_type = {
2701 	.name = "cxl_pmem_region",
2702 	.release = cxl_pmem_region_release,
2703 	.groups = cxl_pmem_region_attribute_groups,
2704 };
2705 
2706 bool is_cxl_pmem_region(struct device *dev)
2707 {
2708 	return dev->type == &cxl_pmem_region_type;
2709 }
2710 EXPORT_SYMBOL_NS_GPL(is_cxl_pmem_region, "CXL");
2711 
2712 struct cxl_pmem_region *to_cxl_pmem_region(struct device *dev)
2713 {
2714 	if (dev_WARN_ONCE(dev, !is_cxl_pmem_region(dev),
2715 			  "not a cxl_pmem_region device\n"))
2716 		return NULL;
2717 	return container_of(dev, struct cxl_pmem_region, dev);
2718 }
2719 EXPORT_SYMBOL_NS_GPL(to_cxl_pmem_region, "CXL");
2720 
2721 struct cxl_poison_context {
2722 	struct cxl_port *port;
2723 	int part;
2724 	u64 offset;
2725 };
2726 
2727 static int cxl_get_poison_unmapped(struct cxl_memdev *cxlmd,
2728 				   struct cxl_poison_context *ctx)
2729 {
2730 	struct cxl_dev_state *cxlds = cxlmd->cxlds;
2731 	const struct resource *res;
2732 	struct resource *p, *last;
2733 	u64 offset, length;
2734 	int rc = 0;
2735 
2736 	if (ctx->part < 0)
2737 		return 0;
2738 
2739 	/*
2740 	 * Collect poison for the remaining unmapped resources after
2741 	 * poison is collected by committed endpoints decoders.
2742 	 */
2743 	for (int i = ctx->part; i < cxlds->nr_partitions; i++) {
2744 		res = &cxlds->part[i].res;
2745 		for (p = res->child, last = NULL; p; p = p->sibling)
2746 			last = p;
2747 		if (last)
2748 			offset = last->end + 1;
2749 		else
2750 			offset = res->start;
2751 		length = res->end - offset + 1;
2752 		if (!length)
2753 			break;
2754 		rc = cxl_mem_get_poison(cxlmd, offset, length, NULL);
2755 		if (rc == -EFAULT && cxlds->part[i].mode == CXL_PARTMODE_RAM)
2756 			continue;
2757 		if (rc)
2758 			break;
2759 	}
2760 
2761 	return rc;
2762 }
2763 
2764 static int poison_by_decoder(struct device *dev, void *arg)
2765 {
2766 	struct cxl_poison_context *ctx = arg;
2767 	struct cxl_endpoint_decoder *cxled;
2768 	enum cxl_partition_mode mode;
2769 	struct cxl_dev_state *cxlds;
2770 	struct cxl_memdev *cxlmd;
2771 	u64 offset, length;
2772 	int rc = 0;
2773 
2774 	if (!is_endpoint_decoder(dev))
2775 		return rc;
2776 
2777 	cxled = to_cxl_endpoint_decoder(dev);
2778 	if (!cxled->dpa_res)
2779 		return rc;
2780 
2781 	cxlmd = cxled_to_memdev(cxled);
2782 	cxlds = cxlmd->cxlds;
2783 	mode = cxlds->part[cxled->part].mode;
2784 
2785 	if (cxled->skip) {
2786 		offset = cxled->dpa_res->start - cxled->skip;
2787 		length = cxled->skip;
2788 		rc = cxl_mem_get_poison(cxlmd, offset, length, NULL);
2789 		if (rc == -EFAULT && mode == CXL_PARTMODE_RAM)
2790 			rc = 0;
2791 		if (rc)
2792 			return rc;
2793 	}
2794 
2795 	offset = cxled->dpa_res->start;
2796 	length = cxled->dpa_res->end - offset + 1;
2797 	rc = cxl_mem_get_poison(cxlmd, offset, length, cxled->cxld.region);
2798 	if (rc == -EFAULT && mode == CXL_PARTMODE_RAM)
2799 		rc = 0;
2800 	if (rc)
2801 		return rc;
2802 
2803 	/* Iterate until commit_end is reached */
2804 	if (cxled->cxld.id == ctx->port->commit_end) {
2805 		ctx->offset = cxled->dpa_res->end + 1;
2806 		ctx->part = cxled->part;
2807 		return 1;
2808 	}
2809 
2810 	return 0;
2811 }
2812 
2813 int cxl_get_poison_by_endpoint(struct cxl_port *port)
2814 {
2815 	struct cxl_poison_context ctx;
2816 	int rc = 0;
2817 
2818 	ctx = (struct cxl_poison_context) {
2819 		.port = port,
2820 		.part = -1,
2821 	};
2822 
2823 	rc = device_for_each_child(&port->dev, &ctx, poison_by_decoder);
2824 	if (rc == 1)
2825 		rc = cxl_get_poison_unmapped(to_cxl_memdev(port->uport_dev),
2826 					     &ctx);
2827 
2828 	return rc;
2829 }
2830 
2831 struct cxl_dpa_to_region_context {
2832 	struct cxl_region *cxlr;
2833 	u64 dpa;
2834 };
2835 
2836 static int __cxl_dpa_to_region(struct device *dev, void *arg)
2837 {
2838 	struct cxl_dpa_to_region_context *ctx = arg;
2839 	struct cxl_endpoint_decoder *cxled;
2840 	struct cxl_region *cxlr;
2841 	u64 dpa = ctx->dpa;
2842 
2843 	if (!is_endpoint_decoder(dev))
2844 		return 0;
2845 
2846 	cxled = to_cxl_endpoint_decoder(dev);
2847 	if (!cxled || !cxled->dpa_res || !resource_size(cxled->dpa_res))
2848 		return 0;
2849 
2850 	if (dpa > cxled->dpa_res->end || dpa < cxled->dpa_res->start)
2851 		return 0;
2852 
2853 	/*
2854 	 * Stop the region search (return 1) when an endpoint mapping is
2855 	 * found. The region may not be fully constructed so offering
2856 	 * the cxlr in the context structure is not guaranteed.
2857 	 */
2858 	cxlr = cxled->cxld.region;
2859 	if (cxlr)
2860 		dev_dbg(dev, "dpa:0x%llx mapped in region:%s\n", dpa,
2861 			dev_name(&cxlr->dev));
2862 	else
2863 		dev_dbg(dev, "dpa:0x%llx mapped in endpoint:%s\n", dpa,
2864 			dev_name(dev));
2865 
2866 	ctx->cxlr = cxlr;
2867 
2868 	return 1;
2869 }
2870 
2871 struct cxl_region *cxl_dpa_to_region(const struct cxl_memdev *cxlmd, u64 dpa)
2872 {
2873 	struct cxl_dpa_to_region_context ctx;
2874 	struct cxl_port *port;
2875 
2876 	ctx = (struct cxl_dpa_to_region_context) {
2877 		.dpa = dpa,
2878 	};
2879 	port = cxlmd->endpoint;
2880 	if (port && is_cxl_endpoint(port) && cxl_num_decoders_committed(port))
2881 		device_for_each_child(&port->dev, &ctx, __cxl_dpa_to_region);
2882 
2883 	return ctx.cxlr;
2884 }
2885 
2886 static bool cxl_is_hpa_in_chunk(u64 hpa, struct cxl_region *cxlr, int pos)
2887 {
2888 	struct cxl_region_params *p = &cxlr->params;
2889 	int gran = p->interleave_granularity;
2890 	int ways = p->interleave_ways;
2891 	u64 offset;
2892 
2893 	/* Is the hpa in an expected chunk for its pos(-ition) */
2894 	offset = hpa - p->res->start;
2895 	offset = do_div(offset, gran * ways);
2896 	if ((offset >= pos * gran) && (offset < (pos + 1) * gran))
2897 		return true;
2898 
2899 	dev_dbg(&cxlr->dev,
2900 		"Addr trans fail: hpa 0x%llx not in expected chunk\n", hpa);
2901 
2902 	return false;
2903 }
2904 
2905 u64 cxl_dpa_to_hpa(struct cxl_region *cxlr, const struct cxl_memdev *cxlmd,
2906 		   u64 dpa)
2907 {
2908 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(cxlr->dev.parent);
2909 	u64 dpa_offset, hpa_offset, bits_upper, mask_upper, hpa;
2910 	struct cxl_region_params *p = &cxlr->params;
2911 	struct cxl_endpoint_decoder *cxled = NULL;
2912 	u16 eig = 0;
2913 	u8 eiw = 0;
2914 	int pos;
2915 
2916 	for (int i = 0; i < p->nr_targets; i++) {
2917 		cxled = p->targets[i];
2918 		if (cxlmd == cxled_to_memdev(cxled))
2919 			break;
2920 	}
2921 	if (!cxled || cxlmd != cxled_to_memdev(cxled))
2922 		return ULLONG_MAX;
2923 
2924 	pos = cxled->pos;
2925 	ways_to_eiw(p->interleave_ways, &eiw);
2926 	granularity_to_eig(p->interleave_granularity, &eig);
2927 
2928 	/*
2929 	 * The device position in the region interleave set was removed
2930 	 * from the offset at HPA->DPA translation. To reconstruct the
2931 	 * HPA, place the 'pos' in the offset.
2932 	 *
2933 	 * The placement of 'pos' in the HPA is determined by interleave
2934 	 * ways and granularity and is defined in the CXL Spec 3.0 Section
2935 	 * 8.2.4.19.13 Implementation Note: Device Decode Logic
2936 	 */
2937 
2938 	/* Remove the dpa base */
2939 	dpa_offset = dpa - cxl_dpa_resource_start(cxled);
2940 
2941 	mask_upper = GENMASK_ULL(51, eig + 8);
2942 
2943 	if (eiw < 8) {
2944 		hpa_offset = (dpa_offset & mask_upper) << eiw;
2945 		hpa_offset |= pos << (eig + 8);
2946 	} else {
2947 		bits_upper = (dpa_offset & mask_upper) >> (eig + 8);
2948 		bits_upper = bits_upper * 3;
2949 		hpa_offset = ((bits_upper << (eiw - 8)) + pos) << (eig + 8);
2950 	}
2951 
2952 	/* The lower bits remain unchanged */
2953 	hpa_offset |= dpa_offset & GENMASK_ULL(eig + 7, 0);
2954 
2955 	/* Apply the hpa_offset to the region base address */
2956 	hpa = hpa_offset + p->res->start + p->cache_size;
2957 
2958 	/* Root decoder translation overrides typical modulo decode */
2959 	if (cxlrd->hpa_to_spa)
2960 		hpa = cxlrd->hpa_to_spa(cxlrd, hpa);
2961 
2962 	if (hpa < p->res->start || hpa > p->res->end) {
2963 		dev_dbg(&cxlr->dev,
2964 			"Addr trans fail: hpa 0x%llx not in region\n", hpa);
2965 		return ULLONG_MAX;
2966 	}
2967 
2968 	/* Simple chunk check, by pos & gran, only applies to modulo decodes */
2969 	if (!cxlrd->hpa_to_spa && (!cxl_is_hpa_in_chunk(hpa, cxlr, pos)))
2970 		return ULLONG_MAX;
2971 
2972 	return hpa;
2973 }
2974 
2975 static struct lock_class_key cxl_pmem_region_key;
2976 
2977 static int cxl_pmem_region_alloc(struct cxl_region *cxlr)
2978 {
2979 	struct cxl_region_params *p = &cxlr->params;
2980 	struct cxl_nvdimm_bridge *cxl_nvb;
2981 	struct device *dev;
2982 	int i;
2983 
2984 	guard(rwsem_read)(&cxl_region_rwsem);
2985 	if (p->state != CXL_CONFIG_COMMIT)
2986 		return -ENXIO;
2987 
2988 	struct cxl_pmem_region *cxlr_pmem __free(kfree) =
2989 		kzalloc(struct_size(cxlr_pmem, mapping, p->nr_targets), GFP_KERNEL);
2990 	if (!cxlr_pmem)
2991 		return -ENOMEM;
2992 
2993 	cxlr_pmem->hpa_range.start = p->res->start;
2994 	cxlr_pmem->hpa_range.end = p->res->end;
2995 
2996 	/* Snapshot the region configuration underneath the cxl_region_rwsem */
2997 	cxlr_pmem->nr_mappings = p->nr_targets;
2998 	for (i = 0; i < p->nr_targets; i++) {
2999 		struct cxl_endpoint_decoder *cxled = p->targets[i];
3000 		struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
3001 		struct cxl_pmem_region_mapping *m = &cxlr_pmem->mapping[i];
3002 
3003 		/*
3004 		 * Regions never span CXL root devices, so by definition the
3005 		 * bridge for one device is the same for all.
3006 		 */
3007 		if (i == 0) {
3008 			cxl_nvb = cxl_find_nvdimm_bridge(cxlmd->endpoint);
3009 			if (!cxl_nvb)
3010 				return -ENODEV;
3011 			cxlr->cxl_nvb = cxl_nvb;
3012 		}
3013 		m->cxlmd = cxlmd;
3014 		get_device(&cxlmd->dev);
3015 		m->start = cxled->dpa_res->start;
3016 		m->size = resource_size(cxled->dpa_res);
3017 		m->position = i;
3018 	}
3019 
3020 	dev = &cxlr_pmem->dev;
3021 	device_initialize(dev);
3022 	lockdep_set_class(&dev->mutex, &cxl_pmem_region_key);
3023 	device_set_pm_not_required(dev);
3024 	dev->parent = &cxlr->dev;
3025 	dev->bus = &cxl_bus_type;
3026 	dev->type = &cxl_pmem_region_type;
3027 	cxlr_pmem->cxlr = cxlr;
3028 	cxlr->cxlr_pmem = no_free_ptr(cxlr_pmem);
3029 
3030 	return 0;
3031 }
3032 
3033 static void cxl_dax_region_release(struct device *dev)
3034 {
3035 	struct cxl_dax_region *cxlr_dax = to_cxl_dax_region(dev);
3036 
3037 	kfree(cxlr_dax);
3038 }
3039 
3040 static const struct attribute_group *cxl_dax_region_attribute_groups[] = {
3041 	&cxl_base_attribute_group,
3042 	NULL,
3043 };
3044 
3045 const struct device_type cxl_dax_region_type = {
3046 	.name = "cxl_dax_region",
3047 	.release = cxl_dax_region_release,
3048 	.groups = cxl_dax_region_attribute_groups,
3049 };
3050 
3051 static bool is_cxl_dax_region(struct device *dev)
3052 {
3053 	return dev->type == &cxl_dax_region_type;
3054 }
3055 
3056 struct cxl_dax_region *to_cxl_dax_region(struct device *dev)
3057 {
3058 	if (dev_WARN_ONCE(dev, !is_cxl_dax_region(dev),
3059 			  "not a cxl_dax_region device\n"))
3060 		return NULL;
3061 	return container_of(dev, struct cxl_dax_region, dev);
3062 }
3063 EXPORT_SYMBOL_NS_GPL(to_cxl_dax_region, "CXL");
3064 
3065 static struct lock_class_key cxl_dax_region_key;
3066 
3067 static struct cxl_dax_region *cxl_dax_region_alloc(struct cxl_region *cxlr)
3068 {
3069 	struct cxl_region_params *p = &cxlr->params;
3070 	struct cxl_dax_region *cxlr_dax;
3071 	struct device *dev;
3072 
3073 	guard(rwsem_read)(&cxl_region_rwsem);
3074 	if (p->state != CXL_CONFIG_COMMIT)
3075 		return ERR_PTR(-ENXIO);
3076 
3077 	cxlr_dax = kzalloc(sizeof(*cxlr_dax), GFP_KERNEL);
3078 	if (!cxlr_dax)
3079 		return ERR_PTR(-ENOMEM);
3080 
3081 	cxlr_dax->hpa_range.start = p->res->start;
3082 	cxlr_dax->hpa_range.end = p->res->end;
3083 
3084 	dev = &cxlr_dax->dev;
3085 	cxlr_dax->cxlr = cxlr;
3086 	device_initialize(dev);
3087 	lockdep_set_class(&dev->mutex, &cxl_dax_region_key);
3088 	device_set_pm_not_required(dev);
3089 	dev->parent = &cxlr->dev;
3090 	dev->bus = &cxl_bus_type;
3091 	dev->type = &cxl_dax_region_type;
3092 
3093 	return cxlr_dax;
3094 }
3095 
3096 static void cxlr_pmem_unregister(void *_cxlr_pmem)
3097 {
3098 	struct cxl_pmem_region *cxlr_pmem = _cxlr_pmem;
3099 	struct cxl_region *cxlr = cxlr_pmem->cxlr;
3100 	struct cxl_nvdimm_bridge *cxl_nvb = cxlr->cxl_nvb;
3101 
3102 	/*
3103 	 * Either the bridge is in ->remove() context under the device_lock(),
3104 	 * or cxlr_release_nvdimm() is cancelling the bridge's release action
3105 	 * for @cxlr_pmem and doing it itself (while manually holding the bridge
3106 	 * lock).
3107 	 */
3108 	device_lock_assert(&cxl_nvb->dev);
3109 	cxlr->cxlr_pmem = NULL;
3110 	cxlr_pmem->cxlr = NULL;
3111 	device_unregister(&cxlr_pmem->dev);
3112 }
3113 
3114 static void cxlr_release_nvdimm(void *_cxlr)
3115 {
3116 	struct cxl_region *cxlr = _cxlr;
3117 	struct cxl_nvdimm_bridge *cxl_nvb = cxlr->cxl_nvb;
3118 
3119 	scoped_guard(device, &cxl_nvb->dev) {
3120 		if (cxlr->cxlr_pmem)
3121 			devm_release_action(&cxl_nvb->dev, cxlr_pmem_unregister,
3122 					    cxlr->cxlr_pmem);
3123 	}
3124 	cxlr->cxl_nvb = NULL;
3125 	put_device(&cxl_nvb->dev);
3126 }
3127 
3128 /**
3129  * devm_cxl_add_pmem_region() - add a cxl_region-to-nd_region bridge
3130  * @cxlr: parent CXL region for this pmem region bridge device
3131  *
3132  * Return: 0 on success negative error code on failure.
3133  */
3134 static int devm_cxl_add_pmem_region(struct cxl_region *cxlr)
3135 {
3136 	struct cxl_pmem_region *cxlr_pmem;
3137 	struct cxl_nvdimm_bridge *cxl_nvb;
3138 	struct device *dev;
3139 	int rc;
3140 
3141 	rc = cxl_pmem_region_alloc(cxlr);
3142 	if (rc)
3143 		return rc;
3144 	cxlr_pmem = cxlr->cxlr_pmem;
3145 	cxl_nvb = cxlr->cxl_nvb;
3146 
3147 	dev = &cxlr_pmem->dev;
3148 	rc = dev_set_name(dev, "pmem_region%d", cxlr->id);
3149 	if (rc)
3150 		goto err;
3151 
3152 	rc = device_add(dev);
3153 	if (rc)
3154 		goto err;
3155 
3156 	dev_dbg(&cxlr->dev, "%s: register %s\n", dev_name(dev->parent),
3157 		dev_name(dev));
3158 
3159 	scoped_guard(device, &cxl_nvb->dev) {
3160 		if (cxl_nvb->dev.driver)
3161 			rc = devm_add_action_or_reset(&cxl_nvb->dev,
3162 						      cxlr_pmem_unregister,
3163 						      cxlr_pmem);
3164 		else
3165 			rc = -ENXIO;
3166 	}
3167 
3168 	if (rc)
3169 		goto err_bridge;
3170 
3171 	/* @cxlr carries a reference on @cxl_nvb until cxlr_release_nvdimm */
3172 	return devm_add_action_or_reset(&cxlr->dev, cxlr_release_nvdimm, cxlr);
3173 
3174 err:
3175 	put_device(dev);
3176 err_bridge:
3177 	put_device(&cxl_nvb->dev);
3178 	cxlr->cxl_nvb = NULL;
3179 	return rc;
3180 }
3181 
3182 static void cxlr_dax_unregister(void *_cxlr_dax)
3183 {
3184 	struct cxl_dax_region *cxlr_dax = _cxlr_dax;
3185 
3186 	device_unregister(&cxlr_dax->dev);
3187 }
3188 
3189 static int devm_cxl_add_dax_region(struct cxl_region *cxlr)
3190 {
3191 	struct cxl_dax_region *cxlr_dax;
3192 	struct device *dev;
3193 	int rc;
3194 
3195 	cxlr_dax = cxl_dax_region_alloc(cxlr);
3196 	if (IS_ERR(cxlr_dax))
3197 		return PTR_ERR(cxlr_dax);
3198 
3199 	dev = &cxlr_dax->dev;
3200 	rc = dev_set_name(dev, "dax_region%d", cxlr->id);
3201 	if (rc)
3202 		goto err;
3203 
3204 	rc = device_add(dev);
3205 	if (rc)
3206 		goto err;
3207 
3208 	dev_dbg(&cxlr->dev, "%s: register %s\n", dev_name(dev->parent),
3209 		dev_name(dev));
3210 
3211 	return devm_add_action_or_reset(&cxlr->dev, cxlr_dax_unregister,
3212 					cxlr_dax);
3213 err:
3214 	put_device(dev);
3215 	return rc;
3216 }
3217 
3218 static int match_decoder_by_range(struct device *dev, const void *data)
3219 {
3220 	const struct range *r1, *r2 = data;
3221 	struct cxl_decoder *cxld;
3222 
3223 	if (!is_switch_decoder(dev))
3224 		return 0;
3225 
3226 	cxld = to_cxl_decoder(dev);
3227 	r1 = &cxld->hpa_range;
3228 	return range_contains(r1, r2);
3229 }
3230 
3231 static struct cxl_decoder *
3232 cxl_port_find_switch_decoder(struct cxl_port *port, struct range *hpa)
3233 {
3234 	struct device *cxld_dev = device_find_child(&port->dev, hpa,
3235 						    match_decoder_by_range);
3236 
3237 	return cxld_dev ? to_cxl_decoder(cxld_dev) : NULL;
3238 }
3239 
3240 static struct cxl_root_decoder *
3241 cxl_find_root_decoder(struct cxl_endpoint_decoder *cxled)
3242 {
3243 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
3244 	struct cxl_port *port = cxled_to_port(cxled);
3245 	struct cxl_root *cxl_root __free(put_cxl_root) = find_cxl_root(port);
3246 	struct cxl_decoder *root, *cxld = &cxled->cxld;
3247 	struct range *hpa = &cxld->hpa_range;
3248 
3249 	root = cxl_port_find_switch_decoder(&cxl_root->port, hpa);
3250 	if (!root) {
3251 		dev_err(cxlmd->dev.parent,
3252 			"%s:%s no CXL window for range %#llx:%#llx\n",
3253 			dev_name(&cxlmd->dev), dev_name(&cxld->dev),
3254 			cxld->hpa_range.start, cxld->hpa_range.end);
3255 		return NULL;
3256 	}
3257 
3258 	return to_cxl_root_decoder(&root->dev);
3259 }
3260 
3261 static int match_region_by_range(struct device *dev, const void *data)
3262 {
3263 	struct cxl_region_params *p;
3264 	struct cxl_region *cxlr;
3265 	const struct range *r = data;
3266 
3267 	if (!is_cxl_region(dev))
3268 		return 0;
3269 
3270 	cxlr = to_cxl_region(dev);
3271 	p = &cxlr->params;
3272 
3273 	guard(rwsem_read)(&cxl_region_rwsem);
3274 	if (p->res && p->res->start == r->start && p->res->end == r->end)
3275 		return 1;
3276 
3277 	return 0;
3278 }
3279 
3280 static int cxl_extended_linear_cache_resize(struct cxl_region *cxlr,
3281 					    struct resource *res)
3282 {
3283 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(cxlr->dev.parent);
3284 	struct cxl_region_params *p = &cxlr->params;
3285 	int nid = phys_to_target_node(res->start);
3286 	resource_size_t size = resource_size(res);
3287 	resource_size_t cache_size, start;
3288 	int rc;
3289 
3290 	rc = cxl_acpi_get_extended_linear_cache_size(res, nid, &cache_size);
3291 	if (rc)
3292 		return rc;
3293 
3294 	if (!cache_size)
3295 		return 0;
3296 
3297 	if (size != cache_size) {
3298 		dev_warn(&cxlr->dev,
3299 			 "Extended Linear Cache size %pa != CXL size %pa. No Support!",
3300 			 &cache_size, &size);
3301 		return -ENXIO;
3302 	}
3303 
3304 	/*
3305 	 * Move the start of the range to where the cache range starts. The
3306 	 * implementation assumes that the cache range is in front of the
3307 	 * CXL range. This is not dictated by the HMAT spec but is how the
3308 	 * current known implementation is configured.
3309 	 *
3310 	 * The cache range is expected to be within the CFMWS. The adjusted
3311 	 * res->start should not be less than cxlrd->res->start.
3312 	 */
3313 	start = res->start - cache_size;
3314 	if (start < cxlrd->res->start)
3315 		return -ENXIO;
3316 
3317 	res->start = start;
3318 	p->cache_size = cache_size;
3319 
3320 	return 0;
3321 }
3322 
3323 static int __construct_region(struct cxl_region *cxlr,
3324 			      struct cxl_root_decoder *cxlrd,
3325 			      struct cxl_endpoint_decoder *cxled)
3326 {
3327 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
3328 	struct range *hpa = &cxled->cxld.hpa_range;
3329 	struct cxl_region_params *p;
3330 	struct resource *res;
3331 	int rc;
3332 
3333 	guard(rwsem_write)(&cxl_region_rwsem);
3334 	p = &cxlr->params;
3335 	if (p->state >= CXL_CONFIG_INTERLEAVE_ACTIVE) {
3336 		dev_err(cxlmd->dev.parent,
3337 			"%s:%s: %s autodiscovery interrupted\n",
3338 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
3339 			__func__);
3340 		return -EBUSY;
3341 	}
3342 
3343 	set_bit(CXL_REGION_F_AUTO, &cxlr->flags);
3344 
3345 	res = kmalloc(sizeof(*res), GFP_KERNEL);
3346 	if (!res)
3347 		return -ENOMEM;
3348 
3349 	*res = DEFINE_RES_MEM_NAMED(hpa->start, range_len(hpa),
3350 				    dev_name(&cxlr->dev));
3351 
3352 	rc = cxl_extended_linear_cache_resize(cxlr, res);
3353 	if (rc && rc != -EOPNOTSUPP) {
3354 		/*
3355 		 * Failing to support extended linear cache region resize does not
3356 		 * prevent the region from functioning. Only causes cxl list showing
3357 		 * incorrect region size.
3358 		 */
3359 		dev_warn(cxlmd->dev.parent,
3360 			 "Extended linear cache calculation failed rc:%d\n", rc);
3361 	}
3362 
3363 	rc = insert_resource(cxlrd->res, res);
3364 	if (rc) {
3365 		/*
3366 		 * Platform-firmware may not have split resources like "System
3367 		 * RAM" on CXL window boundaries see cxl_region_iomem_release()
3368 		 */
3369 		dev_warn(cxlmd->dev.parent,
3370 			 "%s:%s: %s %s cannot insert resource\n",
3371 			 dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
3372 			 __func__, dev_name(&cxlr->dev));
3373 	}
3374 
3375 	p->res = res;
3376 	p->interleave_ways = cxled->cxld.interleave_ways;
3377 	p->interleave_granularity = cxled->cxld.interleave_granularity;
3378 	p->state = CXL_CONFIG_INTERLEAVE_ACTIVE;
3379 
3380 	rc = sysfs_update_group(&cxlr->dev.kobj, get_cxl_region_target_group());
3381 	if (rc)
3382 		return rc;
3383 
3384 	dev_dbg(cxlmd->dev.parent, "%s:%s: %s %s res: %pr iw: %d ig: %d\n",
3385 		dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev), __func__,
3386 		dev_name(&cxlr->dev), p->res, p->interleave_ways,
3387 		p->interleave_granularity);
3388 
3389 	/* ...to match put_device() in cxl_add_to_region() */
3390 	get_device(&cxlr->dev);
3391 
3392 	return 0;
3393 }
3394 
3395 /* Establish an empty region covering the given HPA range */
3396 static struct cxl_region *construct_region(struct cxl_root_decoder *cxlrd,
3397 					   struct cxl_endpoint_decoder *cxled)
3398 {
3399 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
3400 	struct cxl_port *port = cxlrd_to_port(cxlrd);
3401 	struct cxl_dev_state *cxlds = cxlmd->cxlds;
3402 	int rc, part = READ_ONCE(cxled->part);
3403 	struct cxl_region *cxlr;
3404 
3405 	do {
3406 		cxlr = __create_region(cxlrd, cxlds->part[part].mode,
3407 				       atomic_read(&cxlrd->region_id));
3408 	} while (IS_ERR(cxlr) && PTR_ERR(cxlr) == -EBUSY);
3409 
3410 	if (IS_ERR(cxlr)) {
3411 		dev_err(cxlmd->dev.parent,
3412 			"%s:%s: %s failed assign region: %ld\n",
3413 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
3414 			__func__, PTR_ERR(cxlr));
3415 		return cxlr;
3416 	}
3417 
3418 	rc = __construct_region(cxlr, cxlrd, cxled);
3419 	if (rc) {
3420 		devm_release_action(port->uport_dev, unregister_region, cxlr);
3421 		return ERR_PTR(rc);
3422 	}
3423 
3424 	return cxlr;
3425 }
3426 
3427 static struct cxl_region *
3428 cxl_find_region_by_range(struct cxl_root_decoder *cxlrd, struct range *hpa)
3429 {
3430 	struct device *region_dev;
3431 
3432 	region_dev = device_find_child(&cxlrd->cxlsd.cxld.dev, hpa,
3433 				       match_region_by_range);
3434 	if (!region_dev)
3435 		return NULL;
3436 
3437 	return to_cxl_region(region_dev);
3438 }
3439 
3440 int cxl_add_to_region(struct cxl_endpoint_decoder *cxled)
3441 {
3442 	struct range *hpa = &cxled->cxld.hpa_range;
3443 	struct cxl_region_params *p;
3444 	bool attach = false;
3445 	int rc;
3446 
3447 	struct cxl_root_decoder *cxlrd __free(put_cxl_root_decoder) =
3448 		cxl_find_root_decoder(cxled);
3449 	if (!cxlrd)
3450 		return -ENXIO;
3451 
3452 	/*
3453 	 * Ensure that if multiple threads race to construct_region() for @hpa
3454 	 * one does the construction and the others add to that.
3455 	 */
3456 	mutex_lock(&cxlrd->range_lock);
3457 	struct cxl_region *cxlr __free(put_cxl_region) =
3458 		cxl_find_region_by_range(cxlrd, hpa);
3459 	if (!cxlr)
3460 		cxlr = construct_region(cxlrd, cxled);
3461 	mutex_unlock(&cxlrd->range_lock);
3462 
3463 	rc = PTR_ERR_OR_ZERO(cxlr);
3464 	if (rc)
3465 		return rc;
3466 
3467 	attach_target(cxlr, cxled, -1, TASK_UNINTERRUPTIBLE);
3468 
3469 	down_read(&cxl_region_rwsem);
3470 	p = &cxlr->params;
3471 	attach = p->state == CXL_CONFIG_COMMIT;
3472 	up_read(&cxl_region_rwsem);
3473 
3474 	if (attach) {
3475 		/*
3476 		 * If device_attach() fails the range may still be active via
3477 		 * the platform-firmware memory map, otherwise the driver for
3478 		 * regions is local to this file, so driver matching can't fail.
3479 		 */
3480 		if (device_attach(&cxlr->dev) < 0)
3481 			dev_err(&cxlr->dev, "failed to enable, range: %pr\n",
3482 				p->res);
3483 	}
3484 
3485 	return rc;
3486 }
3487 EXPORT_SYMBOL_NS_GPL(cxl_add_to_region, "CXL");
3488 
3489 u64 cxl_port_get_spa_cache_alias(struct cxl_port *endpoint, u64 spa)
3490 {
3491 	struct cxl_region_ref *iter;
3492 	unsigned long index;
3493 
3494 	if (!endpoint)
3495 		return ~0ULL;
3496 
3497 	guard(rwsem_write)(&cxl_region_rwsem);
3498 
3499 	xa_for_each(&endpoint->regions, index, iter) {
3500 		struct cxl_region_params *p = &iter->region->params;
3501 
3502 		if (p->res->start <= spa && spa <= p->res->end) {
3503 			if (!p->cache_size)
3504 				return ~0ULL;
3505 
3506 			if (spa >= p->res->start + p->cache_size)
3507 				return spa - p->cache_size;
3508 
3509 			return spa + p->cache_size;
3510 		}
3511 	}
3512 
3513 	return ~0ULL;
3514 }
3515 EXPORT_SYMBOL_NS_GPL(cxl_port_get_spa_cache_alias, "CXL");
3516 
3517 static int is_system_ram(struct resource *res, void *arg)
3518 {
3519 	struct cxl_region *cxlr = arg;
3520 	struct cxl_region_params *p = &cxlr->params;
3521 
3522 	dev_dbg(&cxlr->dev, "%pr has System RAM: %pr\n", p->res, res);
3523 	return 1;
3524 }
3525 
3526 static void shutdown_notifiers(void *_cxlr)
3527 {
3528 	struct cxl_region *cxlr = _cxlr;
3529 
3530 	unregister_memory_notifier(&cxlr->memory_notifier);
3531 	unregister_mt_adistance_algorithm(&cxlr->adist_notifier);
3532 }
3533 
3534 static int cxl_region_probe(struct device *dev)
3535 {
3536 	struct cxl_region *cxlr = to_cxl_region(dev);
3537 	struct cxl_region_params *p = &cxlr->params;
3538 	int rc;
3539 
3540 	rc = down_read_interruptible(&cxl_region_rwsem);
3541 	if (rc) {
3542 		dev_dbg(&cxlr->dev, "probe interrupted\n");
3543 		return rc;
3544 	}
3545 
3546 	if (p->state < CXL_CONFIG_COMMIT) {
3547 		dev_dbg(&cxlr->dev, "config state: %d\n", p->state);
3548 		rc = -ENXIO;
3549 		goto out;
3550 	}
3551 
3552 	if (test_bit(CXL_REGION_F_NEEDS_RESET, &cxlr->flags)) {
3553 		dev_err(&cxlr->dev,
3554 			"failed to activate, re-commit region and retry\n");
3555 		rc = -ENXIO;
3556 		goto out;
3557 	}
3558 
3559 	/*
3560 	 * From this point on any path that changes the region's state away from
3561 	 * CXL_CONFIG_COMMIT is also responsible for releasing the driver.
3562 	 */
3563 out:
3564 	up_read(&cxl_region_rwsem);
3565 
3566 	if (rc)
3567 		return rc;
3568 
3569 	cxlr->memory_notifier.notifier_call = cxl_region_perf_attrs_callback;
3570 	cxlr->memory_notifier.priority = CXL_CALLBACK_PRI;
3571 	register_memory_notifier(&cxlr->memory_notifier);
3572 
3573 	cxlr->adist_notifier.notifier_call = cxl_region_calculate_adistance;
3574 	cxlr->adist_notifier.priority = 100;
3575 	register_mt_adistance_algorithm(&cxlr->adist_notifier);
3576 
3577 	rc = devm_add_action_or_reset(&cxlr->dev, shutdown_notifiers, cxlr);
3578 	if (rc)
3579 		return rc;
3580 
3581 	switch (cxlr->mode) {
3582 	case CXL_PARTMODE_PMEM:
3583 		rc = devm_cxl_region_edac_register(cxlr);
3584 		if (rc)
3585 			dev_dbg(&cxlr->dev, "CXL EDAC registration for region_id=%d failed\n",
3586 				cxlr->id);
3587 
3588 		return devm_cxl_add_pmem_region(cxlr);
3589 	case CXL_PARTMODE_RAM:
3590 		rc = devm_cxl_region_edac_register(cxlr);
3591 		if (rc)
3592 			dev_dbg(&cxlr->dev, "CXL EDAC registration for region_id=%d failed\n",
3593 				cxlr->id);
3594 
3595 		/*
3596 		 * The region can not be manged by CXL if any portion of
3597 		 * it is already online as 'System RAM'
3598 		 */
3599 		if (walk_iomem_res_desc(IORES_DESC_NONE,
3600 					IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY,
3601 					p->res->start, p->res->end, cxlr,
3602 					is_system_ram) > 0)
3603 			return 0;
3604 		return devm_cxl_add_dax_region(cxlr);
3605 	default:
3606 		dev_dbg(&cxlr->dev, "unsupported region mode: %d\n",
3607 			cxlr->mode);
3608 		return -ENXIO;
3609 	}
3610 }
3611 
3612 static struct cxl_driver cxl_region_driver = {
3613 	.name = "cxl_region",
3614 	.probe = cxl_region_probe,
3615 	.id = CXL_DEVICE_REGION,
3616 };
3617 
3618 int cxl_region_init(void)
3619 {
3620 	return cxl_driver_register(&cxl_region_driver);
3621 }
3622 
3623 void cxl_region_exit(void)
3624 {
3625 	cxl_driver_unregister(&cxl_region_driver);
3626 }
3627 
3628 MODULE_IMPORT_NS("CXL");
3629 MODULE_IMPORT_NS("DEVMEM");
3630 MODULE_ALIAS_CXL(CXL_DEVICE_REGION);
3631