xref: /openbmc/linux/drivers/cxl/core/region.c (revision aeaefabc59ec3c7edd6d0ca7add7aff2ff6f59d0)
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/slab.h>
8 #include <linux/uuid.h>
9 #include <linux/sort.h>
10 #include <linux/idr.h>
11 #include <cxlmem.h>
12 #include <cxl.h>
13 #include "core.h"
14 
15 /**
16  * DOC: cxl core region
17  *
18  * CXL Regions represent mapped memory capacity in system physical address
19  * space. Whereas the CXL Root Decoders identify the bounds of potential CXL
20  * Memory ranges, Regions represent the active mapped capacity by the HDM
21  * Decoder Capability structures throughout the Host Bridges, Switches, and
22  * Endpoints in the topology.
23  *
24  * Region configuration has ordering constraints. UUID may be set at any time
25  * but is only visible for persistent regions.
26  * 1. Interleave granularity
27  * 2. Interleave size
28  * 3. Decoder targets
29  */
30 
31 /*
32  * All changes to the interleave configuration occur with this lock held
33  * for write.
34  */
35 static DECLARE_RWSEM(cxl_region_rwsem);
36 
37 static struct cxl_region *to_cxl_region(struct device *dev);
38 
39 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
40 			 char *buf)
41 {
42 	struct cxl_region *cxlr = to_cxl_region(dev);
43 	struct cxl_region_params *p = &cxlr->params;
44 	ssize_t rc;
45 
46 	rc = down_read_interruptible(&cxl_region_rwsem);
47 	if (rc)
48 		return rc;
49 	if (cxlr->mode != CXL_DECODER_PMEM)
50 		rc = sysfs_emit(buf, "\n");
51 	else
52 		rc = sysfs_emit(buf, "%pUb\n", &p->uuid);
53 	up_read(&cxl_region_rwsem);
54 
55 	return rc;
56 }
57 
58 static int is_dup(struct device *match, void *data)
59 {
60 	struct cxl_region_params *p;
61 	struct cxl_region *cxlr;
62 	uuid_t *uuid = data;
63 
64 	if (!is_cxl_region(match))
65 		return 0;
66 
67 	lockdep_assert_held(&cxl_region_rwsem);
68 	cxlr = to_cxl_region(match);
69 	p = &cxlr->params;
70 
71 	if (uuid_equal(&p->uuid, uuid)) {
72 		dev_dbg(match, "already has uuid: %pUb\n", uuid);
73 		return -EBUSY;
74 	}
75 
76 	return 0;
77 }
78 
79 static ssize_t uuid_store(struct device *dev, struct device_attribute *attr,
80 			  const char *buf, size_t len)
81 {
82 	struct cxl_region *cxlr = to_cxl_region(dev);
83 	struct cxl_region_params *p = &cxlr->params;
84 	uuid_t temp;
85 	ssize_t rc;
86 
87 	if (len != UUID_STRING_LEN + 1)
88 		return -EINVAL;
89 
90 	rc = uuid_parse(buf, &temp);
91 	if (rc)
92 		return rc;
93 
94 	if (uuid_is_null(&temp))
95 		return -EINVAL;
96 
97 	rc = down_write_killable(&cxl_region_rwsem);
98 	if (rc)
99 		return rc;
100 
101 	if (uuid_equal(&p->uuid, &temp))
102 		goto out;
103 
104 	rc = -EBUSY;
105 	if (p->state >= CXL_CONFIG_ACTIVE)
106 		goto out;
107 
108 	rc = bus_for_each_dev(&cxl_bus_type, NULL, &temp, is_dup);
109 	if (rc < 0)
110 		goto out;
111 
112 	uuid_copy(&p->uuid, &temp);
113 out:
114 	up_write(&cxl_region_rwsem);
115 
116 	if (rc)
117 		return rc;
118 	return len;
119 }
120 static DEVICE_ATTR_RW(uuid);
121 
122 static struct cxl_region_ref *cxl_rr_load(struct cxl_port *port,
123 					  struct cxl_region *cxlr)
124 {
125 	return xa_load(&port->regions, (unsigned long)cxlr);
126 }
127 
128 static int cxl_region_decode_reset(struct cxl_region *cxlr, int count)
129 {
130 	struct cxl_region_params *p = &cxlr->params;
131 	int i;
132 
133 	for (i = count - 1; i >= 0; i--) {
134 		struct cxl_endpoint_decoder *cxled = p->targets[i];
135 		struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
136 		struct cxl_port *iter = cxled_to_port(cxled);
137 		struct cxl_dev_state *cxlds = cxlmd->cxlds;
138 		struct cxl_ep *ep;
139 		int rc = 0;
140 
141 		if (cxlds->rcd)
142 			goto endpoint_reset;
143 
144 		while (!is_cxl_root(to_cxl_port(iter->dev.parent)))
145 			iter = to_cxl_port(iter->dev.parent);
146 
147 		for (ep = cxl_ep_load(iter, cxlmd); iter;
148 		     iter = ep->next, ep = cxl_ep_load(iter, cxlmd)) {
149 			struct cxl_region_ref *cxl_rr;
150 			struct cxl_decoder *cxld;
151 
152 			cxl_rr = cxl_rr_load(iter, cxlr);
153 			cxld = cxl_rr->decoder;
154 			if (cxld->reset)
155 				rc = cxld->reset(cxld);
156 			if (rc)
157 				return rc;
158 		}
159 
160 endpoint_reset:
161 		rc = cxled->cxld.reset(&cxled->cxld);
162 		if (rc)
163 			return rc;
164 	}
165 
166 	return 0;
167 }
168 
169 static int commit_decoder(struct cxl_decoder *cxld)
170 {
171 	struct cxl_switch_decoder *cxlsd = NULL;
172 
173 	if (cxld->commit)
174 		return cxld->commit(cxld);
175 
176 	if (is_switch_decoder(&cxld->dev))
177 		cxlsd = to_cxl_switch_decoder(&cxld->dev);
178 
179 	if (dev_WARN_ONCE(&cxld->dev, !cxlsd || cxlsd->nr_targets > 1,
180 			  "->commit() is required\n"))
181 		return -ENXIO;
182 	return 0;
183 }
184 
185 static int cxl_region_decode_commit(struct cxl_region *cxlr)
186 {
187 	struct cxl_region_params *p = &cxlr->params;
188 	int i, rc = 0;
189 
190 	for (i = 0; i < p->nr_targets; i++) {
191 		struct cxl_endpoint_decoder *cxled = p->targets[i];
192 		struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
193 		struct cxl_region_ref *cxl_rr;
194 		struct cxl_decoder *cxld;
195 		struct cxl_port *iter;
196 		struct cxl_ep *ep;
197 
198 		/* commit bottom up */
199 		for (iter = cxled_to_port(cxled); !is_cxl_root(iter);
200 		     iter = to_cxl_port(iter->dev.parent)) {
201 			cxl_rr = cxl_rr_load(iter, cxlr);
202 			cxld = cxl_rr->decoder;
203 			rc = commit_decoder(cxld);
204 			if (rc)
205 				break;
206 		}
207 
208 		if (rc) {
209 			/* programming @iter failed, teardown */
210 			for (ep = cxl_ep_load(iter, cxlmd); ep && iter;
211 			     iter = ep->next, ep = cxl_ep_load(iter, cxlmd)) {
212 				cxl_rr = cxl_rr_load(iter, cxlr);
213 				cxld = cxl_rr->decoder;
214 				if (cxld->reset)
215 					cxld->reset(cxld);
216 			}
217 
218 			cxled->cxld.reset(&cxled->cxld);
219 			goto err;
220 		}
221 	}
222 
223 	return 0;
224 
225 err:
226 	/* undo the targets that were successfully committed */
227 	cxl_region_decode_reset(cxlr, i);
228 	return rc;
229 }
230 
231 static ssize_t commit_store(struct device *dev, struct device_attribute *attr,
232 			    const char *buf, size_t len)
233 {
234 	struct cxl_region *cxlr = to_cxl_region(dev);
235 	struct cxl_region_params *p = &cxlr->params;
236 	bool commit;
237 	ssize_t rc;
238 
239 	rc = kstrtobool(buf, &commit);
240 	if (rc)
241 		return rc;
242 
243 	rc = down_write_killable(&cxl_region_rwsem);
244 	if (rc)
245 		return rc;
246 
247 	/* Already in the requested state? */
248 	if (commit && p->state >= CXL_CONFIG_COMMIT)
249 		goto out;
250 	if (!commit && p->state < CXL_CONFIG_COMMIT)
251 		goto out;
252 
253 	/* Not ready to commit? */
254 	if (commit && p->state < CXL_CONFIG_ACTIVE) {
255 		rc = -ENXIO;
256 		goto out;
257 	}
258 
259 	if (commit)
260 		rc = cxl_region_decode_commit(cxlr);
261 	else {
262 		p->state = CXL_CONFIG_RESET_PENDING;
263 		up_write(&cxl_region_rwsem);
264 		device_release_driver(&cxlr->dev);
265 		down_write(&cxl_region_rwsem);
266 
267 		/*
268 		 * The lock was dropped, so need to revalidate that the reset is
269 		 * still pending.
270 		 */
271 		if (p->state == CXL_CONFIG_RESET_PENDING)
272 			rc = cxl_region_decode_reset(cxlr, p->interleave_ways);
273 	}
274 
275 	if (rc)
276 		goto out;
277 
278 	if (commit)
279 		p->state = CXL_CONFIG_COMMIT;
280 	else if (p->state == CXL_CONFIG_RESET_PENDING)
281 		p->state = CXL_CONFIG_ACTIVE;
282 
283 out:
284 	up_write(&cxl_region_rwsem);
285 
286 	if (rc)
287 		return rc;
288 	return len;
289 }
290 
291 static ssize_t commit_show(struct device *dev, struct device_attribute *attr,
292 			   char *buf)
293 {
294 	struct cxl_region *cxlr = to_cxl_region(dev);
295 	struct cxl_region_params *p = &cxlr->params;
296 	ssize_t rc;
297 
298 	rc = down_read_interruptible(&cxl_region_rwsem);
299 	if (rc)
300 		return rc;
301 	rc = sysfs_emit(buf, "%d\n", p->state >= CXL_CONFIG_COMMIT);
302 	up_read(&cxl_region_rwsem);
303 
304 	return rc;
305 }
306 static DEVICE_ATTR_RW(commit);
307 
308 static umode_t cxl_region_visible(struct kobject *kobj, struct attribute *a,
309 				  int n)
310 {
311 	struct device *dev = kobj_to_dev(kobj);
312 	struct cxl_region *cxlr = to_cxl_region(dev);
313 
314 	/*
315 	 * Support tooling that expects to find a 'uuid' attribute for all
316 	 * regions regardless of mode.
317 	 */
318 	if (a == &dev_attr_uuid.attr && cxlr->mode != CXL_DECODER_PMEM)
319 		return 0444;
320 	return a->mode;
321 }
322 
323 static ssize_t interleave_ways_show(struct device *dev,
324 				    struct device_attribute *attr, char *buf)
325 {
326 	struct cxl_region *cxlr = to_cxl_region(dev);
327 	struct cxl_region_params *p = &cxlr->params;
328 	ssize_t rc;
329 
330 	rc = down_read_interruptible(&cxl_region_rwsem);
331 	if (rc)
332 		return rc;
333 	rc = sysfs_emit(buf, "%d\n", p->interleave_ways);
334 	up_read(&cxl_region_rwsem);
335 
336 	return rc;
337 }
338 
339 static const struct attribute_group *get_cxl_region_target_group(void);
340 
341 static ssize_t interleave_ways_store(struct device *dev,
342 				     struct device_attribute *attr,
343 				     const char *buf, size_t len)
344 {
345 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev->parent);
346 	struct cxl_decoder *cxld = &cxlrd->cxlsd.cxld;
347 	struct cxl_region *cxlr = to_cxl_region(dev);
348 	struct cxl_region_params *p = &cxlr->params;
349 	unsigned int val, save;
350 	int rc;
351 	u8 iw;
352 
353 	rc = kstrtouint(buf, 0, &val);
354 	if (rc)
355 		return rc;
356 
357 	rc = ways_to_eiw(val, &iw);
358 	if (rc)
359 		return rc;
360 
361 	/*
362 	 * Even for x3, x9, and x12 interleaves the region interleave must be a
363 	 * power of 2 multiple of the host bridge interleave.
364 	 */
365 	if (!is_power_of_2(val / cxld->interleave_ways) ||
366 	    (val % cxld->interleave_ways)) {
367 		dev_dbg(&cxlr->dev, "invalid interleave: %d\n", val);
368 		return -EINVAL;
369 	}
370 
371 	rc = down_write_killable(&cxl_region_rwsem);
372 	if (rc)
373 		return rc;
374 	if (p->state >= CXL_CONFIG_INTERLEAVE_ACTIVE) {
375 		rc = -EBUSY;
376 		goto out;
377 	}
378 
379 	save = p->interleave_ways;
380 	p->interleave_ways = val;
381 	rc = sysfs_update_group(&cxlr->dev.kobj, get_cxl_region_target_group());
382 	if (rc)
383 		p->interleave_ways = save;
384 out:
385 	up_write(&cxl_region_rwsem);
386 	if (rc)
387 		return rc;
388 	return len;
389 }
390 static DEVICE_ATTR_RW(interleave_ways);
391 
392 static ssize_t interleave_granularity_show(struct device *dev,
393 					   struct device_attribute *attr,
394 					   char *buf)
395 {
396 	struct cxl_region *cxlr = to_cxl_region(dev);
397 	struct cxl_region_params *p = &cxlr->params;
398 	ssize_t rc;
399 
400 	rc = down_read_interruptible(&cxl_region_rwsem);
401 	if (rc)
402 		return rc;
403 	rc = sysfs_emit(buf, "%d\n", p->interleave_granularity);
404 	up_read(&cxl_region_rwsem);
405 
406 	return rc;
407 }
408 
409 static ssize_t interleave_granularity_store(struct device *dev,
410 					    struct device_attribute *attr,
411 					    const char *buf, size_t len)
412 {
413 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev->parent);
414 	struct cxl_decoder *cxld = &cxlrd->cxlsd.cxld;
415 	struct cxl_region *cxlr = to_cxl_region(dev);
416 	struct cxl_region_params *p = &cxlr->params;
417 	int rc, val;
418 	u16 ig;
419 
420 	rc = kstrtoint(buf, 0, &val);
421 	if (rc)
422 		return rc;
423 
424 	rc = granularity_to_eig(val, &ig);
425 	if (rc)
426 		return rc;
427 
428 	/*
429 	 * When the host-bridge is interleaved, disallow region granularity !=
430 	 * root granularity. Regions with a granularity less than the root
431 	 * interleave result in needing multiple endpoints to support a single
432 	 * slot in the interleave (possible to support in the future). Regions
433 	 * with a granularity greater than the root interleave result in invalid
434 	 * DPA translations (invalid to support).
435 	 */
436 	if (cxld->interleave_ways > 1 && val != cxld->interleave_granularity)
437 		return -EINVAL;
438 
439 	rc = down_write_killable(&cxl_region_rwsem);
440 	if (rc)
441 		return rc;
442 	if (p->state >= CXL_CONFIG_INTERLEAVE_ACTIVE) {
443 		rc = -EBUSY;
444 		goto out;
445 	}
446 
447 	p->interleave_granularity = val;
448 out:
449 	up_write(&cxl_region_rwsem);
450 	if (rc)
451 		return rc;
452 	return len;
453 }
454 static DEVICE_ATTR_RW(interleave_granularity);
455 
456 static ssize_t resource_show(struct device *dev, struct device_attribute *attr,
457 			     char *buf)
458 {
459 	struct cxl_region *cxlr = to_cxl_region(dev);
460 	struct cxl_region_params *p = &cxlr->params;
461 	u64 resource = -1ULL;
462 	ssize_t rc;
463 
464 	rc = down_read_interruptible(&cxl_region_rwsem);
465 	if (rc)
466 		return rc;
467 	if (p->res)
468 		resource = p->res->start;
469 	rc = sysfs_emit(buf, "%#llx\n", resource);
470 	up_read(&cxl_region_rwsem);
471 
472 	return rc;
473 }
474 static DEVICE_ATTR_RO(resource);
475 
476 static ssize_t mode_show(struct device *dev, struct device_attribute *attr,
477 			 char *buf)
478 {
479 	struct cxl_region *cxlr = to_cxl_region(dev);
480 
481 	return sysfs_emit(buf, "%s\n", cxl_decoder_mode_name(cxlr->mode));
482 }
483 static DEVICE_ATTR_RO(mode);
484 
485 static int alloc_hpa(struct cxl_region *cxlr, resource_size_t size)
486 {
487 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(cxlr->dev.parent);
488 	struct cxl_region_params *p = &cxlr->params;
489 	struct resource *res;
490 	u32 remainder = 0;
491 
492 	lockdep_assert_held_write(&cxl_region_rwsem);
493 
494 	/* Nothing to do... */
495 	if (p->res && resource_size(p->res) == size)
496 		return 0;
497 
498 	/* To change size the old size must be freed first */
499 	if (p->res)
500 		return -EBUSY;
501 
502 	if (p->state >= CXL_CONFIG_INTERLEAVE_ACTIVE)
503 		return -EBUSY;
504 
505 	/* ways, granularity and uuid (if PMEM) need to be set before HPA */
506 	if (!p->interleave_ways || !p->interleave_granularity ||
507 	    (cxlr->mode == CXL_DECODER_PMEM && uuid_is_null(&p->uuid)))
508 		return -ENXIO;
509 
510 	div_u64_rem(size, SZ_256M * p->interleave_ways, &remainder);
511 	if (remainder)
512 		return -EINVAL;
513 
514 	res = alloc_free_mem_region(cxlrd->res, size, SZ_256M,
515 				    dev_name(&cxlr->dev));
516 	if (IS_ERR(res)) {
517 		dev_dbg(&cxlr->dev, "failed to allocate HPA: %ld\n",
518 			PTR_ERR(res));
519 		return PTR_ERR(res);
520 	}
521 
522 	p->res = res;
523 	p->state = CXL_CONFIG_INTERLEAVE_ACTIVE;
524 
525 	return 0;
526 }
527 
528 static void cxl_region_iomem_release(struct cxl_region *cxlr)
529 {
530 	struct cxl_region_params *p = &cxlr->params;
531 
532 	if (device_is_registered(&cxlr->dev))
533 		lockdep_assert_held_write(&cxl_region_rwsem);
534 	if (p->res) {
535 		/*
536 		 * Autodiscovered regions may not have been able to insert their
537 		 * resource.
538 		 */
539 		if (p->res->parent)
540 			remove_resource(p->res);
541 		kfree(p->res);
542 		p->res = NULL;
543 	}
544 }
545 
546 static int free_hpa(struct cxl_region *cxlr)
547 {
548 	struct cxl_region_params *p = &cxlr->params;
549 
550 	lockdep_assert_held_write(&cxl_region_rwsem);
551 
552 	if (!p->res)
553 		return 0;
554 
555 	if (p->state >= CXL_CONFIG_ACTIVE)
556 		return -EBUSY;
557 
558 	cxl_region_iomem_release(cxlr);
559 	p->state = CXL_CONFIG_IDLE;
560 	return 0;
561 }
562 
563 static ssize_t size_store(struct device *dev, struct device_attribute *attr,
564 			  const char *buf, size_t len)
565 {
566 	struct cxl_region *cxlr = to_cxl_region(dev);
567 	u64 val;
568 	int rc;
569 
570 	rc = kstrtou64(buf, 0, &val);
571 	if (rc)
572 		return rc;
573 
574 	rc = down_write_killable(&cxl_region_rwsem);
575 	if (rc)
576 		return rc;
577 
578 	if (val)
579 		rc = alloc_hpa(cxlr, val);
580 	else
581 		rc = free_hpa(cxlr);
582 	up_write(&cxl_region_rwsem);
583 
584 	if (rc)
585 		return rc;
586 
587 	return len;
588 }
589 
590 static ssize_t size_show(struct device *dev, struct device_attribute *attr,
591 			 char *buf)
592 {
593 	struct cxl_region *cxlr = to_cxl_region(dev);
594 	struct cxl_region_params *p = &cxlr->params;
595 	u64 size = 0;
596 	ssize_t rc;
597 
598 	rc = down_read_interruptible(&cxl_region_rwsem);
599 	if (rc)
600 		return rc;
601 	if (p->res)
602 		size = resource_size(p->res);
603 	rc = sysfs_emit(buf, "%#llx\n", size);
604 	up_read(&cxl_region_rwsem);
605 
606 	return rc;
607 }
608 static DEVICE_ATTR_RW(size);
609 
610 static struct attribute *cxl_region_attrs[] = {
611 	&dev_attr_uuid.attr,
612 	&dev_attr_commit.attr,
613 	&dev_attr_interleave_ways.attr,
614 	&dev_attr_interleave_granularity.attr,
615 	&dev_attr_resource.attr,
616 	&dev_attr_size.attr,
617 	&dev_attr_mode.attr,
618 	NULL,
619 };
620 
621 static const struct attribute_group cxl_region_group = {
622 	.attrs = cxl_region_attrs,
623 	.is_visible = cxl_region_visible,
624 };
625 
626 static size_t show_targetN(struct cxl_region *cxlr, char *buf, int pos)
627 {
628 	struct cxl_region_params *p = &cxlr->params;
629 	struct cxl_endpoint_decoder *cxled;
630 	int rc;
631 
632 	rc = down_read_interruptible(&cxl_region_rwsem);
633 	if (rc)
634 		return rc;
635 
636 	if (pos >= p->interleave_ways) {
637 		dev_dbg(&cxlr->dev, "position %d out of range %d\n", pos,
638 			p->interleave_ways);
639 		rc = -ENXIO;
640 		goto out;
641 	}
642 
643 	cxled = p->targets[pos];
644 	if (!cxled)
645 		rc = sysfs_emit(buf, "\n");
646 	else
647 		rc = sysfs_emit(buf, "%s\n", dev_name(&cxled->cxld.dev));
648 out:
649 	up_read(&cxl_region_rwsem);
650 
651 	return rc;
652 }
653 
654 static int match_free_decoder(struct device *dev, void *data)
655 {
656 	struct cxl_decoder *cxld;
657 	int *id = data;
658 
659 	if (!is_switch_decoder(dev))
660 		return 0;
661 
662 	cxld = to_cxl_decoder(dev);
663 
664 	/* enforce ordered allocation */
665 	if (cxld->id != *id)
666 		return 0;
667 
668 	if (!cxld->region)
669 		return 1;
670 
671 	(*id)++;
672 
673 	return 0;
674 }
675 
676 static struct cxl_decoder *cxl_region_find_decoder(struct cxl_port *port,
677 						   struct cxl_region *cxlr)
678 {
679 	struct device *dev;
680 	int id = 0;
681 
682 	dev = device_find_child(&port->dev, &id, match_free_decoder);
683 	if (!dev)
684 		return NULL;
685 	/*
686 	 * This decoder is pinned registered as long as the endpoint decoder is
687 	 * registered, and endpoint decoder unregistration holds the
688 	 * cxl_region_rwsem over unregister events, so no need to hold on to
689 	 * this extra reference.
690 	 */
691 	put_device(dev);
692 	return to_cxl_decoder(dev);
693 }
694 
695 static struct cxl_region_ref *alloc_region_ref(struct cxl_port *port,
696 					       struct cxl_region *cxlr)
697 {
698 	struct cxl_region_params *p = &cxlr->params;
699 	struct cxl_region_ref *cxl_rr, *iter;
700 	unsigned long index;
701 	int rc;
702 
703 	xa_for_each(&port->regions, index, iter) {
704 		struct cxl_region_params *ip = &iter->region->params;
705 
706 		if (!ip->res)
707 			continue;
708 
709 		if (ip->res->start > p->res->start) {
710 			dev_dbg(&cxlr->dev,
711 				"%s: HPA order violation %s:%pr vs %pr\n",
712 				dev_name(&port->dev),
713 				dev_name(&iter->region->dev), ip->res, p->res);
714 			return ERR_PTR(-EBUSY);
715 		}
716 	}
717 
718 	cxl_rr = kzalloc(sizeof(*cxl_rr), GFP_KERNEL);
719 	if (!cxl_rr)
720 		return ERR_PTR(-ENOMEM);
721 	cxl_rr->port = port;
722 	cxl_rr->region = cxlr;
723 	cxl_rr->nr_targets = 1;
724 	xa_init(&cxl_rr->endpoints);
725 
726 	rc = xa_insert(&port->regions, (unsigned long)cxlr, cxl_rr, GFP_KERNEL);
727 	if (rc) {
728 		dev_dbg(&cxlr->dev,
729 			"%s: failed to track region reference: %d\n",
730 			dev_name(&port->dev), rc);
731 		kfree(cxl_rr);
732 		return ERR_PTR(rc);
733 	}
734 
735 	return cxl_rr;
736 }
737 
738 static void cxl_rr_free_decoder(struct cxl_region_ref *cxl_rr)
739 {
740 	struct cxl_region *cxlr = cxl_rr->region;
741 	struct cxl_decoder *cxld = cxl_rr->decoder;
742 
743 	if (!cxld)
744 		return;
745 
746 	dev_WARN_ONCE(&cxlr->dev, cxld->region != cxlr, "region mismatch\n");
747 	if (cxld->region == cxlr) {
748 		cxld->region = NULL;
749 		put_device(&cxlr->dev);
750 	}
751 }
752 
753 static void free_region_ref(struct cxl_region_ref *cxl_rr)
754 {
755 	struct cxl_port *port = cxl_rr->port;
756 	struct cxl_region *cxlr = cxl_rr->region;
757 
758 	cxl_rr_free_decoder(cxl_rr);
759 	xa_erase(&port->regions, (unsigned long)cxlr);
760 	xa_destroy(&cxl_rr->endpoints);
761 	kfree(cxl_rr);
762 }
763 
764 static int cxl_rr_ep_add(struct cxl_region_ref *cxl_rr,
765 			 struct cxl_endpoint_decoder *cxled)
766 {
767 	int rc;
768 	struct cxl_port *port = cxl_rr->port;
769 	struct cxl_region *cxlr = cxl_rr->region;
770 	struct cxl_decoder *cxld = cxl_rr->decoder;
771 	struct cxl_ep *ep = cxl_ep_load(port, cxled_to_memdev(cxled));
772 
773 	if (ep) {
774 		rc = xa_insert(&cxl_rr->endpoints, (unsigned long)cxled, ep,
775 			       GFP_KERNEL);
776 		if (rc)
777 			return rc;
778 	}
779 	cxl_rr->nr_eps++;
780 
781 	if (!cxld->region) {
782 		cxld->region = cxlr;
783 		get_device(&cxlr->dev);
784 	}
785 
786 	return 0;
787 }
788 
789 static int cxl_rr_alloc_decoder(struct cxl_port *port, struct cxl_region *cxlr,
790 				struct cxl_endpoint_decoder *cxled,
791 				struct cxl_region_ref *cxl_rr)
792 {
793 	struct cxl_decoder *cxld;
794 
795 	if (port == cxled_to_port(cxled))
796 		cxld = &cxled->cxld;
797 	else
798 		cxld = cxl_region_find_decoder(port, cxlr);
799 	if (!cxld) {
800 		dev_dbg(&cxlr->dev, "%s: no decoder available\n",
801 			dev_name(&port->dev));
802 		return -EBUSY;
803 	}
804 
805 	if (cxld->region) {
806 		dev_dbg(&cxlr->dev, "%s: %s already attached to %s\n",
807 			dev_name(&port->dev), dev_name(&cxld->dev),
808 			dev_name(&cxld->region->dev));
809 		return -EBUSY;
810 	}
811 
812 	/*
813 	 * Endpoints should already match the region type, but backstop that
814 	 * assumption with an assertion. Switch-decoders change mapping-type
815 	 * based on what is mapped when they are assigned to a region.
816 	 */
817 	dev_WARN_ONCE(&cxlr->dev,
818 		      port == cxled_to_port(cxled) &&
819 			      cxld->target_type != cxlr->type,
820 		      "%s:%s mismatch decoder type %d -> %d\n",
821 		      dev_name(&cxled_to_memdev(cxled)->dev),
822 		      dev_name(&cxld->dev), cxld->target_type, cxlr->type);
823 	cxld->target_type = cxlr->type;
824 	cxl_rr->decoder = cxld;
825 	return 0;
826 }
827 
828 /**
829  * cxl_port_attach_region() - track a region's interest in a port by endpoint
830  * @port: port to add a new region reference 'struct cxl_region_ref'
831  * @cxlr: region to attach to @port
832  * @cxled: endpoint decoder used to create or further pin a region reference
833  * @pos: interleave position of @cxled in @cxlr
834  *
835  * The attach event is an opportunity to validate CXL decode setup
836  * constraints and record metadata needed for programming HDM decoders,
837  * in particular decoder target lists.
838  *
839  * The steps are:
840  *
841  * - validate that there are no other regions with a higher HPA already
842  *   associated with @port
843  * - establish a region reference if one is not already present
844  *
845  *   - additionally allocate a decoder instance that will host @cxlr on
846  *     @port
847  *
848  * - pin the region reference by the endpoint
849  * - account for how many entries in @port's target list are needed to
850  *   cover all of the added endpoints.
851  */
852 static int cxl_port_attach_region(struct cxl_port *port,
853 				  struct cxl_region *cxlr,
854 				  struct cxl_endpoint_decoder *cxled, int pos)
855 {
856 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
857 	struct cxl_ep *ep = cxl_ep_load(port, cxlmd);
858 	struct cxl_region_ref *cxl_rr;
859 	bool nr_targets_inc = false;
860 	struct cxl_decoder *cxld;
861 	unsigned long index;
862 	int rc = -EBUSY;
863 
864 	lockdep_assert_held_write(&cxl_region_rwsem);
865 
866 	cxl_rr = cxl_rr_load(port, cxlr);
867 	if (cxl_rr) {
868 		struct cxl_ep *ep_iter;
869 		int found = 0;
870 
871 		/*
872 		 * Walk the existing endpoints that have been attached to
873 		 * @cxlr at @port and see if they share the same 'next' port
874 		 * in the downstream direction. I.e. endpoints that share common
875 		 * upstream switch.
876 		 */
877 		xa_for_each(&cxl_rr->endpoints, index, ep_iter) {
878 			if (ep_iter == ep)
879 				continue;
880 			if (ep_iter->next == ep->next) {
881 				found++;
882 				break;
883 			}
884 		}
885 
886 		/*
887 		 * New target port, or @port is an endpoint port that always
888 		 * accounts its own local decode as a target.
889 		 */
890 		if (!found || !ep->next) {
891 			cxl_rr->nr_targets++;
892 			nr_targets_inc = true;
893 		}
894 	} else {
895 		cxl_rr = alloc_region_ref(port, cxlr);
896 		if (IS_ERR(cxl_rr)) {
897 			dev_dbg(&cxlr->dev,
898 				"%s: failed to allocate region reference\n",
899 				dev_name(&port->dev));
900 			return PTR_ERR(cxl_rr);
901 		}
902 		nr_targets_inc = true;
903 
904 		rc = cxl_rr_alloc_decoder(port, cxlr, cxled, cxl_rr);
905 		if (rc)
906 			goto out_erase;
907 	}
908 	cxld = cxl_rr->decoder;
909 
910 	rc = cxl_rr_ep_add(cxl_rr, cxled);
911 	if (rc) {
912 		dev_dbg(&cxlr->dev,
913 			"%s: failed to track endpoint %s:%s reference\n",
914 			dev_name(&port->dev), dev_name(&cxlmd->dev),
915 			dev_name(&cxld->dev));
916 		goto out_erase;
917 	}
918 
919 	dev_dbg(&cxlr->dev,
920 		"%s:%s %s add: %s:%s @ %d next: %s nr_eps: %d nr_targets: %d\n",
921 		dev_name(port->uport), dev_name(&port->dev),
922 		dev_name(&cxld->dev), dev_name(&cxlmd->dev),
923 		dev_name(&cxled->cxld.dev), pos,
924 		ep ? ep->next ? dev_name(ep->next->uport) :
925 				      dev_name(&cxlmd->dev) :
926 			   "none",
927 		cxl_rr->nr_eps, cxl_rr->nr_targets);
928 
929 	return 0;
930 out_erase:
931 	if (nr_targets_inc)
932 		cxl_rr->nr_targets--;
933 	if (cxl_rr->nr_eps == 0)
934 		free_region_ref(cxl_rr);
935 	return rc;
936 }
937 
938 static void cxl_port_detach_region(struct cxl_port *port,
939 				   struct cxl_region *cxlr,
940 				   struct cxl_endpoint_decoder *cxled)
941 {
942 	struct cxl_region_ref *cxl_rr;
943 	struct cxl_ep *ep = NULL;
944 
945 	lockdep_assert_held_write(&cxl_region_rwsem);
946 
947 	cxl_rr = cxl_rr_load(port, cxlr);
948 	if (!cxl_rr)
949 		return;
950 
951 	/*
952 	 * Endpoint ports do not carry cxl_ep references, and they
953 	 * never target more than one endpoint by definition
954 	 */
955 	if (cxl_rr->decoder == &cxled->cxld)
956 		cxl_rr->nr_eps--;
957 	else
958 		ep = xa_erase(&cxl_rr->endpoints, (unsigned long)cxled);
959 	if (ep) {
960 		struct cxl_ep *ep_iter;
961 		unsigned long index;
962 		int found = 0;
963 
964 		cxl_rr->nr_eps--;
965 		xa_for_each(&cxl_rr->endpoints, index, ep_iter) {
966 			if (ep_iter->next == ep->next) {
967 				found++;
968 				break;
969 			}
970 		}
971 		if (!found)
972 			cxl_rr->nr_targets--;
973 	}
974 
975 	if (cxl_rr->nr_eps == 0)
976 		free_region_ref(cxl_rr);
977 }
978 
979 static int check_last_peer(struct cxl_endpoint_decoder *cxled,
980 			   struct cxl_ep *ep, struct cxl_region_ref *cxl_rr,
981 			   int distance)
982 {
983 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
984 	struct cxl_region *cxlr = cxl_rr->region;
985 	struct cxl_region_params *p = &cxlr->params;
986 	struct cxl_endpoint_decoder *cxled_peer;
987 	struct cxl_port *port = cxl_rr->port;
988 	struct cxl_memdev *cxlmd_peer;
989 	struct cxl_ep *ep_peer;
990 	int pos = cxled->pos;
991 
992 	/*
993 	 * If this position wants to share a dport with the last endpoint mapped
994 	 * then that endpoint, at index 'position - distance', must also be
995 	 * mapped by this dport.
996 	 */
997 	if (pos < distance) {
998 		dev_dbg(&cxlr->dev, "%s:%s: cannot host %s:%s at %d\n",
999 			dev_name(port->uport), dev_name(&port->dev),
1000 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev), pos);
1001 		return -ENXIO;
1002 	}
1003 	cxled_peer = p->targets[pos - distance];
1004 	cxlmd_peer = cxled_to_memdev(cxled_peer);
1005 	ep_peer = cxl_ep_load(port, cxlmd_peer);
1006 	if (ep->dport != ep_peer->dport) {
1007 		dev_dbg(&cxlr->dev,
1008 			"%s:%s: %s:%s pos %d mismatched peer %s:%s\n",
1009 			dev_name(port->uport), dev_name(&port->dev),
1010 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev), pos,
1011 			dev_name(&cxlmd_peer->dev),
1012 			dev_name(&cxled_peer->cxld.dev));
1013 		return -ENXIO;
1014 	}
1015 
1016 	return 0;
1017 }
1018 
1019 static int cxl_port_setup_targets(struct cxl_port *port,
1020 				  struct cxl_region *cxlr,
1021 				  struct cxl_endpoint_decoder *cxled)
1022 {
1023 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(cxlr->dev.parent);
1024 	int parent_iw, parent_ig, ig, iw, rc, inc = 0, pos = cxled->pos;
1025 	struct cxl_port *parent_port = to_cxl_port(port->dev.parent);
1026 	struct cxl_region_ref *cxl_rr = cxl_rr_load(port, cxlr);
1027 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1028 	struct cxl_ep *ep = cxl_ep_load(port, cxlmd);
1029 	struct cxl_region_params *p = &cxlr->params;
1030 	struct cxl_decoder *cxld = cxl_rr->decoder;
1031 	struct cxl_switch_decoder *cxlsd;
1032 	u16 eig, peig;
1033 	u8 eiw, peiw;
1034 
1035 	/*
1036 	 * While root level decoders support x3, x6, x12, switch level
1037 	 * decoders only support powers of 2 up to x16.
1038 	 */
1039 	if (!is_power_of_2(cxl_rr->nr_targets)) {
1040 		dev_dbg(&cxlr->dev, "%s:%s: invalid target count %d\n",
1041 			dev_name(port->uport), dev_name(&port->dev),
1042 			cxl_rr->nr_targets);
1043 		return -EINVAL;
1044 	}
1045 
1046 	cxlsd = to_cxl_switch_decoder(&cxld->dev);
1047 	if (cxl_rr->nr_targets_set) {
1048 		int i, distance;
1049 
1050 		/*
1051 		 * Passthrough decoders impose no distance requirements between
1052 		 * peers
1053 		 */
1054 		if (cxl_rr->nr_targets == 1)
1055 			distance = 0;
1056 		else
1057 			distance = p->nr_targets / cxl_rr->nr_targets;
1058 		for (i = 0; i < cxl_rr->nr_targets_set; i++)
1059 			if (ep->dport == cxlsd->target[i]) {
1060 				rc = check_last_peer(cxled, ep, cxl_rr,
1061 						     distance);
1062 				if (rc)
1063 					return rc;
1064 				goto out_target_set;
1065 			}
1066 		goto add_target;
1067 	}
1068 
1069 	if (is_cxl_root(parent_port)) {
1070 		parent_ig = cxlrd->cxlsd.cxld.interleave_granularity;
1071 		parent_iw = cxlrd->cxlsd.cxld.interleave_ways;
1072 		/*
1073 		 * For purposes of address bit routing, use power-of-2 math for
1074 		 * switch ports.
1075 		 */
1076 		if (!is_power_of_2(parent_iw))
1077 			parent_iw /= 3;
1078 	} else {
1079 		struct cxl_region_ref *parent_rr;
1080 		struct cxl_decoder *parent_cxld;
1081 
1082 		parent_rr = cxl_rr_load(parent_port, cxlr);
1083 		parent_cxld = parent_rr->decoder;
1084 		parent_ig = parent_cxld->interleave_granularity;
1085 		parent_iw = parent_cxld->interleave_ways;
1086 	}
1087 
1088 	rc = granularity_to_eig(parent_ig, &peig);
1089 	if (rc) {
1090 		dev_dbg(&cxlr->dev, "%s:%s: invalid parent granularity: %d\n",
1091 			dev_name(parent_port->uport),
1092 			dev_name(&parent_port->dev), parent_ig);
1093 		return rc;
1094 	}
1095 
1096 	rc = ways_to_eiw(parent_iw, &peiw);
1097 	if (rc) {
1098 		dev_dbg(&cxlr->dev, "%s:%s: invalid parent interleave: %d\n",
1099 			dev_name(parent_port->uport),
1100 			dev_name(&parent_port->dev), parent_iw);
1101 		return rc;
1102 	}
1103 
1104 	iw = cxl_rr->nr_targets;
1105 	rc = ways_to_eiw(iw, &eiw);
1106 	if (rc) {
1107 		dev_dbg(&cxlr->dev, "%s:%s: invalid port interleave: %d\n",
1108 			dev_name(port->uport), dev_name(&port->dev), iw);
1109 		return rc;
1110 	}
1111 
1112 	/*
1113 	 * If @parent_port is masking address bits, pick the next unused address
1114 	 * bit to route @port's targets.
1115 	 */
1116 	if (parent_iw > 1 && cxl_rr->nr_targets > 1) {
1117 		u32 address_bit = max(peig + peiw, eiw + peig);
1118 
1119 		eig = address_bit - eiw + 1;
1120 	} else {
1121 		eiw = peiw;
1122 		eig = peig;
1123 	}
1124 
1125 	rc = eig_to_granularity(eig, &ig);
1126 	if (rc) {
1127 		dev_dbg(&cxlr->dev, "%s:%s: invalid interleave: %d\n",
1128 			dev_name(port->uport), dev_name(&port->dev),
1129 			256 << eig);
1130 		return rc;
1131 	}
1132 
1133 	if (test_bit(CXL_REGION_F_AUTO, &cxlr->flags)) {
1134 		if (cxld->interleave_ways != iw ||
1135 		    cxld->interleave_granularity != ig ||
1136 		    cxld->hpa_range.start != p->res->start ||
1137 		    cxld->hpa_range.end != p->res->end ||
1138 		    ((cxld->flags & CXL_DECODER_F_ENABLE) == 0)) {
1139 			dev_err(&cxlr->dev,
1140 				"%s:%s %s expected iw: %d ig: %d %pr\n",
1141 				dev_name(port->uport), dev_name(&port->dev),
1142 				__func__, iw, ig, p->res);
1143 			dev_err(&cxlr->dev,
1144 				"%s:%s %s got iw: %d ig: %d state: %s %#llx:%#llx\n",
1145 				dev_name(port->uport), dev_name(&port->dev),
1146 				__func__, cxld->interleave_ways,
1147 				cxld->interleave_granularity,
1148 				(cxld->flags & CXL_DECODER_F_ENABLE) ?
1149 					"enabled" :
1150 					"disabled",
1151 				cxld->hpa_range.start, cxld->hpa_range.end);
1152 			return -ENXIO;
1153 		}
1154 	} else {
1155 		cxld->interleave_ways = iw;
1156 		cxld->interleave_granularity = ig;
1157 		cxld->hpa_range = (struct range) {
1158 			.start = p->res->start,
1159 			.end = p->res->end,
1160 		};
1161 	}
1162 	dev_dbg(&cxlr->dev, "%s:%s iw: %d ig: %d\n", dev_name(port->uport),
1163 		dev_name(&port->dev), iw, ig);
1164 add_target:
1165 	if (cxl_rr->nr_targets_set == cxl_rr->nr_targets) {
1166 		dev_dbg(&cxlr->dev,
1167 			"%s:%s: targets full trying to add %s:%s at %d\n",
1168 			dev_name(port->uport), dev_name(&port->dev),
1169 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev), pos);
1170 		return -ENXIO;
1171 	}
1172 	if (test_bit(CXL_REGION_F_AUTO, &cxlr->flags)) {
1173 		if (cxlsd->target[cxl_rr->nr_targets_set] != ep->dport) {
1174 			dev_dbg(&cxlr->dev, "%s:%s: %s expected %s at %d\n",
1175 				dev_name(port->uport), dev_name(&port->dev),
1176 				dev_name(&cxlsd->cxld.dev),
1177 				dev_name(ep->dport->dport),
1178 				cxl_rr->nr_targets_set);
1179 			return -ENXIO;
1180 		}
1181 	} else
1182 		cxlsd->target[cxl_rr->nr_targets_set] = ep->dport;
1183 	inc = 1;
1184 out_target_set:
1185 	cxl_rr->nr_targets_set += inc;
1186 	dev_dbg(&cxlr->dev, "%s:%s target[%d] = %s for %s:%s @ %d\n",
1187 		dev_name(port->uport), dev_name(&port->dev),
1188 		cxl_rr->nr_targets_set - 1, dev_name(ep->dport->dport),
1189 		dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev), pos);
1190 
1191 	return 0;
1192 }
1193 
1194 static void cxl_port_reset_targets(struct cxl_port *port,
1195 				   struct cxl_region *cxlr)
1196 {
1197 	struct cxl_region_ref *cxl_rr = cxl_rr_load(port, cxlr);
1198 	struct cxl_decoder *cxld;
1199 
1200 	/*
1201 	 * After the last endpoint has been detached the entire cxl_rr may now
1202 	 * be gone.
1203 	 */
1204 	if (!cxl_rr)
1205 		return;
1206 	cxl_rr->nr_targets_set = 0;
1207 
1208 	cxld = cxl_rr->decoder;
1209 	cxld->hpa_range = (struct range) {
1210 		.start = 0,
1211 		.end = -1,
1212 	};
1213 }
1214 
1215 static void cxl_region_teardown_targets(struct cxl_region *cxlr)
1216 {
1217 	struct cxl_region_params *p = &cxlr->params;
1218 	struct cxl_endpoint_decoder *cxled;
1219 	struct cxl_dev_state *cxlds;
1220 	struct cxl_memdev *cxlmd;
1221 	struct cxl_port *iter;
1222 	struct cxl_ep *ep;
1223 	int i;
1224 
1225 	/*
1226 	 * In the auto-discovery case skip automatic teardown since the
1227 	 * address space is already active
1228 	 */
1229 	if (test_bit(CXL_REGION_F_AUTO, &cxlr->flags))
1230 		return;
1231 
1232 	for (i = 0; i < p->nr_targets; i++) {
1233 		cxled = p->targets[i];
1234 		cxlmd = cxled_to_memdev(cxled);
1235 		cxlds = cxlmd->cxlds;
1236 
1237 		if (cxlds->rcd)
1238 			continue;
1239 
1240 		iter = cxled_to_port(cxled);
1241 		while (!is_cxl_root(to_cxl_port(iter->dev.parent)))
1242 			iter = to_cxl_port(iter->dev.parent);
1243 
1244 		for (ep = cxl_ep_load(iter, cxlmd); iter;
1245 		     iter = ep->next, ep = cxl_ep_load(iter, cxlmd))
1246 			cxl_port_reset_targets(iter, cxlr);
1247 	}
1248 }
1249 
1250 static int cxl_region_setup_targets(struct cxl_region *cxlr)
1251 {
1252 	struct cxl_region_params *p = &cxlr->params;
1253 	struct cxl_endpoint_decoder *cxled;
1254 	struct cxl_dev_state *cxlds;
1255 	int i, rc, rch = 0, vh = 0;
1256 	struct cxl_memdev *cxlmd;
1257 	struct cxl_port *iter;
1258 	struct cxl_ep *ep;
1259 
1260 	for (i = 0; i < p->nr_targets; i++) {
1261 		cxled = p->targets[i];
1262 		cxlmd = cxled_to_memdev(cxled);
1263 		cxlds = cxlmd->cxlds;
1264 
1265 		/* validate that all targets agree on topology */
1266 		if (!cxlds->rcd) {
1267 			vh++;
1268 		} else {
1269 			rch++;
1270 			continue;
1271 		}
1272 
1273 		iter = cxled_to_port(cxled);
1274 		while (!is_cxl_root(to_cxl_port(iter->dev.parent)))
1275 			iter = to_cxl_port(iter->dev.parent);
1276 
1277 		/*
1278 		 * Descend the topology tree programming / validating
1279 		 * targets while looking for conflicts.
1280 		 */
1281 		for (ep = cxl_ep_load(iter, cxlmd); iter;
1282 		     iter = ep->next, ep = cxl_ep_load(iter, cxlmd)) {
1283 			rc = cxl_port_setup_targets(iter, cxlr, cxled);
1284 			if (rc) {
1285 				cxl_region_teardown_targets(cxlr);
1286 				return rc;
1287 			}
1288 		}
1289 	}
1290 
1291 	if (rch && vh) {
1292 		dev_err(&cxlr->dev, "mismatched CXL topologies detected\n");
1293 		cxl_region_teardown_targets(cxlr);
1294 		return -ENXIO;
1295 	}
1296 
1297 	return 0;
1298 }
1299 
1300 static int cxl_region_validate_position(struct cxl_region *cxlr,
1301 					struct cxl_endpoint_decoder *cxled,
1302 					int pos)
1303 {
1304 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1305 	struct cxl_region_params *p = &cxlr->params;
1306 	int i;
1307 
1308 	if (pos < 0 || pos >= p->interleave_ways) {
1309 		dev_dbg(&cxlr->dev, "position %d out of range %d\n", pos,
1310 			p->interleave_ways);
1311 		return -ENXIO;
1312 	}
1313 
1314 	if (p->targets[pos] == cxled)
1315 		return 0;
1316 
1317 	if (p->targets[pos]) {
1318 		struct cxl_endpoint_decoder *cxled_target = p->targets[pos];
1319 		struct cxl_memdev *cxlmd_target = cxled_to_memdev(cxled_target);
1320 
1321 		dev_dbg(&cxlr->dev, "position %d already assigned to %s:%s\n",
1322 			pos, dev_name(&cxlmd_target->dev),
1323 			dev_name(&cxled_target->cxld.dev));
1324 		return -EBUSY;
1325 	}
1326 
1327 	for (i = 0; i < p->interleave_ways; i++) {
1328 		struct cxl_endpoint_decoder *cxled_target;
1329 		struct cxl_memdev *cxlmd_target;
1330 
1331 		cxled_target = p->targets[i];
1332 		if (!cxled_target)
1333 			continue;
1334 
1335 		cxlmd_target = cxled_to_memdev(cxled_target);
1336 		if (cxlmd_target == cxlmd) {
1337 			dev_dbg(&cxlr->dev,
1338 				"%s already specified at position %d via: %s\n",
1339 				dev_name(&cxlmd->dev), pos,
1340 				dev_name(&cxled_target->cxld.dev));
1341 			return -EBUSY;
1342 		}
1343 	}
1344 
1345 	return 0;
1346 }
1347 
1348 static int cxl_region_attach_position(struct cxl_region *cxlr,
1349 				      struct cxl_root_decoder *cxlrd,
1350 				      struct cxl_endpoint_decoder *cxled,
1351 				      const struct cxl_dport *dport, int pos)
1352 {
1353 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1354 	struct cxl_port *iter;
1355 	int rc;
1356 
1357 	if (cxlrd->calc_hb(cxlrd, pos) != dport) {
1358 		dev_dbg(&cxlr->dev, "%s:%s invalid target position for %s\n",
1359 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
1360 			dev_name(&cxlrd->cxlsd.cxld.dev));
1361 		return -ENXIO;
1362 	}
1363 
1364 	for (iter = cxled_to_port(cxled); !is_cxl_root(iter);
1365 	     iter = to_cxl_port(iter->dev.parent)) {
1366 		rc = cxl_port_attach_region(iter, cxlr, cxled, pos);
1367 		if (rc)
1368 			goto err;
1369 	}
1370 
1371 	return 0;
1372 
1373 err:
1374 	for (iter = cxled_to_port(cxled); !is_cxl_root(iter);
1375 	     iter = to_cxl_port(iter->dev.parent))
1376 		cxl_port_detach_region(iter, cxlr, cxled);
1377 	return rc;
1378 }
1379 
1380 static int cxl_region_attach_auto(struct cxl_region *cxlr,
1381 				  struct cxl_endpoint_decoder *cxled, int pos)
1382 {
1383 	struct cxl_region_params *p = &cxlr->params;
1384 
1385 	if (cxled->state != CXL_DECODER_STATE_AUTO) {
1386 		dev_err(&cxlr->dev,
1387 			"%s: unable to add decoder to autodetected region\n",
1388 			dev_name(&cxled->cxld.dev));
1389 		return -EINVAL;
1390 	}
1391 
1392 	if (pos >= 0) {
1393 		dev_dbg(&cxlr->dev, "%s: expected auto position, not %d\n",
1394 			dev_name(&cxled->cxld.dev), pos);
1395 		return -EINVAL;
1396 	}
1397 
1398 	if (p->nr_targets >= p->interleave_ways) {
1399 		dev_err(&cxlr->dev, "%s: no more target slots available\n",
1400 			dev_name(&cxled->cxld.dev));
1401 		return -ENXIO;
1402 	}
1403 
1404 	/*
1405 	 * Temporarily record the endpoint decoder into the target array. Yes,
1406 	 * this means that userspace can view devices in the wrong position
1407 	 * before the region activates, and must be careful to understand when
1408 	 * it might be racing region autodiscovery.
1409 	 */
1410 	pos = p->nr_targets;
1411 	p->targets[pos] = cxled;
1412 	cxled->pos = pos;
1413 	p->nr_targets++;
1414 
1415 	return 0;
1416 }
1417 
1418 static struct cxl_port *next_port(struct cxl_port *port)
1419 {
1420 	if (!port->parent_dport)
1421 		return NULL;
1422 	return port->parent_dport->port;
1423 }
1424 
1425 static int decoder_match_range(struct device *dev, void *data)
1426 {
1427 	struct cxl_endpoint_decoder *cxled = data;
1428 	struct cxl_switch_decoder *cxlsd;
1429 
1430 	if (!is_switch_decoder(dev))
1431 		return 0;
1432 
1433 	cxlsd = to_cxl_switch_decoder(dev);
1434 	return range_contains(&cxlsd->cxld.hpa_range, &cxled->cxld.hpa_range);
1435 }
1436 
1437 static void find_positions(const struct cxl_switch_decoder *cxlsd,
1438 			   const struct cxl_port *iter_a,
1439 			   const struct cxl_port *iter_b, int *a_pos,
1440 			   int *b_pos)
1441 {
1442 	int i;
1443 
1444 	for (i = 0, *a_pos = -1, *b_pos = -1; i < cxlsd->nr_targets; i++) {
1445 		if (cxlsd->target[i] == iter_a->parent_dport)
1446 			*a_pos = i;
1447 		else if (cxlsd->target[i] == iter_b->parent_dport)
1448 			*b_pos = i;
1449 		if (*a_pos >= 0 && *b_pos >= 0)
1450 			break;
1451 	}
1452 }
1453 
1454 static int cmp_decode_pos(const void *a, const void *b)
1455 {
1456 	struct cxl_endpoint_decoder *cxled_a = *(typeof(cxled_a) *)a;
1457 	struct cxl_endpoint_decoder *cxled_b = *(typeof(cxled_b) *)b;
1458 	struct cxl_memdev *cxlmd_a = cxled_to_memdev(cxled_a);
1459 	struct cxl_memdev *cxlmd_b = cxled_to_memdev(cxled_b);
1460 	struct cxl_port *port_a = cxled_to_port(cxled_a);
1461 	struct cxl_port *port_b = cxled_to_port(cxled_b);
1462 	struct cxl_port *iter_a, *iter_b, *port = NULL;
1463 	struct cxl_switch_decoder *cxlsd;
1464 	struct device *dev;
1465 	int a_pos, b_pos;
1466 	unsigned int seq;
1467 
1468 	/* Exit early if any prior sorting failed */
1469 	if (cxled_a->pos < 0 || cxled_b->pos < 0)
1470 		return 0;
1471 
1472 	/*
1473 	 * Walk up the hierarchy to find a shared port, find the decoder that
1474 	 * maps the range, compare the relative position of those dport
1475 	 * mappings.
1476 	 */
1477 	for (iter_a = port_a; iter_a; iter_a = next_port(iter_a)) {
1478 		struct cxl_port *next_a, *next_b;
1479 
1480 		next_a = next_port(iter_a);
1481 		if (!next_a)
1482 			break;
1483 
1484 		for (iter_b = port_b; iter_b; iter_b = next_port(iter_b)) {
1485 			next_b = next_port(iter_b);
1486 			if (next_a != next_b)
1487 				continue;
1488 			port = next_a;
1489 			break;
1490 		}
1491 
1492 		if (port)
1493 			break;
1494 	}
1495 
1496 	if (!port) {
1497 		dev_err(cxlmd_a->dev.parent,
1498 			"failed to find shared port with %s\n",
1499 			dev_name(cxlmd_b->dev.parent));
1500 		goto err;
1501 	}
1502 
1503 	dev = device_find_child(&port->dev, cxled_a, decoder_match_range);
1504 	if (!dev) {
1505 		struct range *range = &cxled_a->cxld.hpa_range;
1506 
1507 		dev_err(port->uport,
1508 			"failed to find decoder that maps %#llx-%#llx\n",
1509 			range->start, range->end);
1510 		goto err;
1511 	}
1512 
1513 	cxlsd = to_cxl_switch_decoder(dev);
1514 	do {
1515 		seq = read_seqbegin(&cxlsd->target_lock);
1516 		find_positions(cxlsd, iter_a, iter_b, &a_pos, &b_pos);
1517 	} while (read_seqretry(&cxlsd->target_lock, seq));
1518 
1519 	put_device(dev);
1520 
1521 	if (a_pos < 0 || b_pos < 0) {
1522 		dev_err(port->uport,
1523 			"failed to find shared decoder for %s and %s\n",
1524 			dev_name(cxlmd_a->dev.parent),
1525 			dev_name(cxlmd_b->dev.parent));
1526 		goto err;
1527 	}
1528 
1529 	dev_dbg(port->uport, "%s comes %s %s\n", dev_name(cxlmd_a->dev.parent),
1530 		a_pos - b_pos < 0 ? "before" : "after",
1531 		dev_name(cxlmd_b->dev.parent));
1532 
1533 	return a_pos - b_pos;
1534 err:
1535 	cxled_a->pos = -1;
1536 	return 0;
1537 }
1538 
1539 static int cxl_region_sort_targets(struct cxl_region *cxlr)
1540 {
1541 	struct cxl_region_params *p = &cxlr->params;
1542 	int i, rc = 0;
1543 
1544 	sort(p->targets, p->nr_targets, sizeof(p->targets[0]), cmp_decode_pos,
1545 	     NULL);
1546 
1547 	for (i = 0; i < p->nr_targets; i++) {
1548 		struct cxl_endpoint_decoder *cxled = p->targets[i];
1549 
1550 		/*
1551 		 * Record that sorting failed, but still continue to restore
1552 		 * cxled->pos with its ->targets[] position so that follow-on
1553 		 * code paths can reliably do p->targets[cxled->pos] to
1554 		 * self-reference their entry.
1555 		 */
1556 		if (cxled->pos < 0)
1557 			rc = -ENXIO;
1558 		cxled->pos = i;
1559 	}
1560 
1561 	dev_dbg(&cxlr->dev, "region sort %s\n", rc ? "failed" : "successful");
1562 	return rc;
1563 }
1564 
1565 static int cxl_region_attach(struct cxl_region *cxlr,
1566 			     struct cxl_endpoint_decoder *cxled, int pos)
1567 {
1568 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(cxlr->dev.parent);
1569 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1570 	struct cxl_region_params *p = &cxlr->params;
1571 	struct cxl_port *ep_port, *root_port;
1572 	struct cxl_dport *dport;
1573 	int rc = -ENXIO;
1574 
1575 	if (cxled->mode != cxlr->mode) {
1576 		dev_dbg(&cxlr->dev, "%s region mode: %d mismatch: %d\n",
1577 			dev_name(&cxled->cxld.dev), cxlr->mode, cxled->mode);
1578 		return -EINVAL;
1579 	}
1580 
1581 	if (cxled->mode == CXL_DECODER_DEAD) {
1582 		dev_dbg(&cxlr->dev, "%s dead\n", dev_name(&cxled->cxld.dev));
1583 		return -ENODEV;
1584 	}
1585 
1586 	/* all full of members, or interleave config not established? */
1587 	if (p->state > CXL_CONFIG_INTERLEAVE_ACTIVE) {
1588 		dev_dbg(&cxlr->dev, "region already active\n");
1589 		return -EBUSY;
1590 	} else if (p->state < CXL_CONFIG_INTERLEAVE_ACTIVE) {
1591 		dev_dbg(&cxlr->dev, "interleave config missing\n");
1592 		return -ENXIO;
1593 	}
1594 
1595 	ep_port = cxled_to_port(cxled);
1596 	root_port = cxlrd_to_port(cxlrd);
1597 	dport = cxl_find_dport_by_dev(root_port, ep_port->host_bridge);
1598 	if (!dport) {
1599 		dev_dbg(&cxlr->dev, "%s:%s invalid target for %s\n",
1600 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
1601 			dev_name(cxlr->dev.parent));
1602 		return -ENXIO;
1603 	}
1604 
1605 	if (cxled->cxld.target_type != cxlr->type) {
1606 		dev_dbg(&cxlr->dev, "%s:%s type mismatch: %d vs %d\n",
1607 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
1608 			cxled->cxld.target_type, cxlr->type);
1609 		return -ENXIO;
1610 	}
1611 
1612 	if (!cxled->dpa_res) {
1613 		dev_dbg(&cxlr->dev, "%s:%s: missing DPA allocation.\n",
1614 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev));
1615 		return -ENXIO;
1616 	}
1617 
1618 	if (resource_size(cxled->dpa_res) * p->interleave_ways !=
1619 	    resource_size(p->res)) {
1620 		dev_dbg(&cxlr->dev,
1621 			"%s:%s: decoder-size-%#llx * ways-%d != region-size-%#llx\n",
1622 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
1623 			(u64)resource_size(cxled->dpa_res), p->interleave_ways,
1624 			(u64)resource_size(p->res));
1625 		return -EINVAL;
1626 	}
1627 
1628 	if (test_bit(CXL_REGION_F_AUTO, &cxlr->flags)) {
1629 		int i;
1630 
1631 		rc = cxl_region_attach_auto(cxlr, cxled, pos);
1632 		if (rc)
1633 			return rc;
1634 
1635 		/* await more targets to arrive... */
1636 		if (p->nr_targets < p->interleave_ways)
1637 			return 0;
1638 
1639 		/*
1640 		 * All targets are here, which implies all PCI enumeration that
1641 		 * affects this region has been completed. Walk the topology to
1642 		 * sort the devices into their relative region decode position.
1643 		 */
1644 		rc = cxl_region_sort_targets(cxlr);
1645 		if (rc)
1646 			return rc;
1647 
1648 		for (i = 0; i < p->nr_targets; i++) {
1649 			cxled = p->targets[i];
1650 			ep_port = cxled_to_port(cxled);
1651 			dport = cxl_find_dport_by_dev(root_port,
1652 						      ep_port->host_bridge);
1653 			rc = cxl_region_attach_position(cxlr, cxlrd, cxled,
1654 							dport, i);
1655 			if (rc)
1656 				return rc;
1657 		}
1658 
1659 		rc = cxl_region_setup_targets(cxlr);
1660 		if (rc)
1661 			return rc;
1662 
1663 		/*
1664 		 * If target setup succeeds in the autodiscovery case
1665 		 * then the region is already committed.
1666 		 */
1667 		p->state = CXL_CONFIG_COMMIT;
1668 
1669 		return 0;
1670 	}
1671 
1672 	rc = cxl_region_validate_position(cxlr, cxled, pos);
1673 	if (rc)
1674 		return rc;
1675 
1676 	rc = cxl_region_attach_position(cxlr, cxlrd, cxled, dport, pos);
1677 	if (rc)
1678 		return rc;
1679 
1680 	p->targets[pos] = cxled;
1681 	cxled->pos = pos;
1682 	p->nr_targets++;
1683 
1684 	if (p->nr_targets == p->interleave_ways) {
1685 		rc = cxl_region_setup_targets(cxlr);
1686 		if (rc)
1687 			goto err_decrement;
1688 		p->state = CXL_CONFIG_ACTIVE;
1689 		set_bit(CXL_REGION_F_INCOHERENT, &cxlr->flags);
1690 	}
1691 
1692 	cxled->cxld.interleave_ways = p->interleave_ways;
1693 	cxled->cxld.interleave_granularity = p->interleave_granularity;
1694 	cxled->cxld.hpa_range = (struct range) {
1695 		.start = p->res->start,
1696 		.end = p->res->end,
1697 	};
1698 
1699 	return 0;
1700 
1701 err_decrement:
1702 	p->nr_targets--;
1703 	cxled->pos = -1;
1704 	p->targets[pos] = NULL;
1705 	return rc;
1706 }
1707 
1708 static int cxl_region_detach(struct cxl_endpoint_decoder *cxled)
1709 {
1710 	struct cxl_port *iter, *ep_port = cxled_to_port(cxled);
1711 	struct cxl_region *cxlr = cxled->cxld.region;
1712 	struct cxl_region_params *p;
1713 	int rc = 0;
1714 
1715 	lockdep_assert_held_write(&cxl_region_rwsem);
1716 
1717 	if (!cxlr)
1718 		return 0;
1719 
1720 	p = &cxlr->params;
1721 	get_device(&cxlr->dev);
1722 
1723 	if (p->state > CXL_CONFIG_ACTIVE) {
1724 		/*
1725 		 * TODO: tear down all impacted regions if a device is
1726 		 * removed out of order
1727 		 */
1728 		rc = cxl_region_decode_reset(cxlr, p->interleave_ways);
1729 		if (rc)
1730 			goto out;
1731 		p->state = CXL_CONFIG_ACTIVE;
1732 	}
1733 
1734 	for (iter = ep_port; !is_cxl_root(iter);
1735 	     iter = to_cxl_port(iter->dev.parent))
1736 		cxl_port_detach_region(iter, cxlr, cxled);
1737 
1738 	if (cxled->pos < 0 || cxled->pos >= p->interleave_ways ||
1739 	    p->targets[cxled->pos] != cxled) {
1740 		struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
1741 
1742 		dev_WARN_ONCE(&cxlr->dev, 1, "expected %s:%s at position %d\n",
1743 			      dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
1744 			      cxled->pos);
1745 		goto out;
1746 	}
1747 
1748 	if (p->state == CXL_CONFIG_ACTIVE) {
1749 		p->state = CXL_CONFIG_INTERLEAVE_ACTIVE;
1750 		cxl_region_teardown_targets(cxlr);
1751 	}
1752 	p->targets[cxled->pos] = NULL;
1753 	p->nr_targets--;
1754 	cxled->cxld.hpa_range = (struct range) {
1755 		.start = 0,
1756 		.end = -1,
1757 	};
1758 
1759 	/* notify the region driver that one of its targets has departed */
1760 	up_write(&cxl_region_rwsem);
1761 	device_release_driver(&cxlr->dev);
1762 	down_write(&cxl_region_rwsem);
1763 out:
1764 	put_device(&cxlr->dev);
1765 	return rc;
1766 }
1767 
1768 void cxl_decoder_kill_region(struct cxl_endpoint_decoder *cxled)
1769 {
1770 	down_write(&cxl_region_rwsem);
1771 	cxled->mode = CXL_DECODER_DEAD;
1772 	cxl_region_detach(cxled);
1773 	up_write(&cxl_region_rwsem);
1774 }
1775 
1776 static int attach_target(struct cxl_region *cxlr,
1777 			 struct cxl_endpoint_decoder *cxled, int pos,
1778 			 unsigned int state)
1779 {
1780 	int rc = 0;
1781 
1782 	if (state == TASK_INTERRUPTIBLE)
1783 		rc = down_write_killable(&cxl_region_rwsem);
1784 	else
1785 		down_write(&cxl_region_rwsem);
1786 	if (rc)
1787 		return rc;
1788 
1789 	down_read(&cxl_dpa_rwsem);
1790 	rc = cxl_region_attach(cxlr, cxled, pos);
1791 	up_read(&cxl_dpa_rwsem);
1792 	up_write(&cxl_region_rwsem);
1793 	return rc;
1794 }
1795 
1796 static int detach_target(struct cxl_region *cxlr, int pos)
1797 {
1798 	struct cxl_region_params *p = &cxlr->params;
1799 	int rc;
1800 
1801 	rc = down_write_killable(&cxl_region_rwsem);
1802 	if (rc)
1803 		return rc;
1804 
1805 	if (pos >= p->interleave_ways) {
1806 		dev_dbg(&cxlr->dev, "position %d out of range %d\n", pos,
1807 			p->interleave_ways);
1808 		rc = -ENXIO;
1809 		goto out;
1810 	}
1811 
1812 	if (!p->targets[pos]) {
1813 		rc = 0;
1814 		goto out;
1815 	}
1816 
1817 	rc = cxl_region_detach(p->targets[pos]);
1818 out:
1819 	up_write(&cxl_region_rwsem);
1820 	return rc;
1821 }
1822 
1823 static size_t store_targetN(struct cxl_region *cxlr, const char *buf, int pos,
1824 			    size_t len)
1825 {
1826 	int rc;
1827 
1828 	if (sysfs_streq(buf, "\n"))
1829 		rc = detach_target(cxlr, pos);
1830 	else {
1831 		struct device *dev;
1832 
1833 		dev = bus_find_device_by_name(&cxl_bus_type, NULL, buf);
1834 		if (!dev)
1835 			return -ENODEV;
1836 
1837 		if (!is_endpoint_decoder(dev)) {
1838 			rc = -EINVAL;
1839 			goto out;
1840 		}
1841 
1842 		rc = attach_target(cxlr, to_cxl_endpoint_decoder(dev), pos,
1843 				   TASK_INTERRUPTIBLE);
1844 out:
1845 		put_device(dev);
1846 	}
1847 
1848 	if (rc < 0)
1849 		return rc;
1850 	return len;
1851 }
1852 
1853 #define TARGET_ATTR_RW(n)                                              \
1854 static ssize_t target##n##_show(                                       \
1855 	struct device *dev, struct device_attribute *attr, char *buf)  \
1856 {                                                                      \
1857 	return show_targetN(to_cxl_region(dev), buf, (n));             \
1858 }                                                                      \
1859 static ssize_t target##n##_store(struct device *dev,                   \
1860 				 struct device_attribute *attr,        \
1861 				 const char *buf, size_t len)          \
1862 {                                                                      \
1863 	return store_targetN(to_cxl_region(dev), buf, (n), len);       \
1864 }                                                                      \
1865 static DEVICE_ATTR_RW(target##n)
1866 
1867 TARGET_ATTR_RW(0);
1868 TARGET_ATTR_RW(1);
1869 TARGET_ATTR_RW(2);
1870 TARGET_ATTR_RW(3);
1871 TARGET_ATTR_RW(4);
1872 TARGET_ATTR_RW(5);
1873 TARGET_ATTR_RW(6);
1874 TARGET_ATTR_RW(7);
1875 TARGET_ATTR_RW(8);
1876 TARGET_ATTR_RW(9);
1877 TARGET_ATTR_RW(10);
1878 TARGET_ATTR_RW(11);
1879 TARGET_ATTR_RW(12);
1880 TARGET_ATTR_RW(13);
1881 TARGET_ATTR_RW(14);
1882 TARGET_ATTR_RW(15);
1883 
1884 static struct attribute *target_attrs[] = {
1885 	&dev_attr_target0.attr,
1886 	&dev_attr_target1.attr,
1887 	&dev_attr_target2.attr,
1888 	&dev_attr_target3.attr,
1889 	&dev_attr_target4.attr,
1890 	&dev_attr_target5.attr,
1891 	&dev_attr_target6.attr,
1892 	&dev_attr_target7.attr,
1893 	&dev_attr_target8.attr,
1894 	&dev_attr_target9.attr,
1895 	&dev_attr_target10.attr,
1896 	&dev_attr_target11.attr,
1897 	&dev_attr_target12.attr,
1898 	&dev_attr_target13.attr,
1899 	&dev_attr_target14.attr,
1900 	&dev_attr_target15.attr,
1901 	NULL,
1902 };
1903 
1904 static umode_t cxl_region_target_visible(struct kobject *kobj,
1905 					 struct attribute *a, int n)
1906 {
1907 	struct device *dev = kobj_to_dev(kobj);
1908 	struct cxl_region *cxlr = to_cxl_region(dev);
1909 	struct cxl_region_params *p = &cxlr->params;
1910 
1911 	if (n < p->interleave_ways)
1912 		return a->mode;
1913 	return 0;
1914 }
1915 
1916 static const struct attribute_group cxl_region_target_group = {
1917 	.attrs = target_attrs,
1918 	.is_visible = cxl_region_target_visible,
1919 };
1920 
1921 static const struct attribute_group *get_cxl_region_target_group(void)
1922 {
1923 	return &cxl_region_target_group;
1924 }
1925 
1926 static const struct attribute_group *region_groups[] = {
1927 	&cxl_base_attribute_group,
1928 	&cxl_region_group,
1929 	&cxl_region_target_group,
1930 	NULL,
1931 };
1932 
1933 static void cxl_region_release(struct device *dev)
1934 {
1935 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev->parent);
1936 	struct cxl_region *cxlr = to_cxl_region(dev);
1937 	int id = atomic_read(&cxlrd->region_id);
1938 
1939 	/*
1940 	 * Try to reuse the recently idled id rather than the cached
1941 	 * next id to prevent the region id space from increasing
1942 	 * unnecessarily.
1943 	 */
1944 	if (cxlr->id < id)
1945 		if (atomic_try_cmpxchg(&cxlrd->region_id, &id, cxlr->id)) {
1946 			memregion_free(id);
1947 			goto out;
1948 		}
1949 
1950 	memregion_free(cxlr->id);
1951 out:
1952 	put_device(dev->parent);
1953 	kfree(cxlr);
1954 }
1955 
1956 const struct device_type cxl_region_type = {
1957 	.name = "cxl_region",
1958 	.release = cxl_region_release,
1959 	.groups = region_groups
1960 };
1961 
1962 bool is_cxl_region(struct device *dev)
1963 {
1964 	return dev->type == &cxl_region_type;
1965 }
1966 EXPORT_SYMBOL_NS_GPL(is_cxl_region, CXL);
1967 
1968 static struct cxl_region *to_cxl_region(struct device *dev)
1969 {
1970 	if (dev_WARN_ONCE(dev, dev->type != &cxl_region_type,
1971 			  "not a cxl_region device\n"))
1972 		return NULL;
1973 
1974 	return container_of(dev, struct cxl_region, dev);
1975 }
1976 
1977 static void unregister_region(void *dev)
1978 {
1979 	struct cxl_region *cxlr = to_cxl_region(dev);
1980 	struct cxl_region_params *p = &cxlr->params;
1981 	int i;
1982 
1983 	device_del(dev);
1984 
1985 	/*
1986 	 * Now that region sysfs is shutdown, the parameter block is now
1987 	 * read-only, so no need to hold the region rwsem to access the
1988 	 * region parameters.
1989 	 */
1990 	for (i = 0; i < p->interleave_ways; i++)
1991 		detach_target(cxlr, i);
1992 
1993 	cxl_region_iomem_release(cxlr);
1994 	put_device(dev);
1995 }
1996 
1997 static struct lock_class_key cxl_region_key;
1998 
1999 static struct cxl_region *cxl_region_alloc(struct cxl_root_decoder *cxlrd, int id)
2000 {
2001 	struct cxl_region *cxlr;
2002 	struct device *dev;
2003 
2004 	cxlr = kzalloc(sizeof(*cxlr), GFP_KERNEL);
2005 	if (!cxlr) {
2006 		memregion_free(id);
2007 		return ERR_PTR(-ENOMEM);
2008 	}
2009 
2010 	dev = &cxlr->dev;
2011 	device_initialize(dev);
2012 	lockdep_set_class(&dev->mutex, &cxl_region_key);
2013 	dev->parent = &cxlrd->cxlsd.cxld.dev;
2014 	/*
2015 	 * Keep root decoder pinned through cxl_region_release to fixup
2016 	 * region id allocations
2017 	 */
2018 	get_device(dev->parent);
2019 	device_set_pm_not_required(dev);
2020 	dev->bus = &cxl_bus_type;
2021 	dev->type = &cxl_region_type;
2022 	cxlr->id = id;
2023 
2024 	return cxlr;
2025 }
2026 
2027 /**
2028  * devm_cxl_add_region - Adds a region to a decoder
2029  * @cxlrd: root decoder
2030  * @id: memregion id to create, or memregion_free() on failure
2031  * @mode: mode for the endpoint decoders of this region
2032  * @type: select whether this is an expander or accelerator (type-2 or type-3)
2033  *
2034  * This is the second step of region initialization. Regions exist within an
2035  * address space which is mapped by a @cxlrd.
2036  *
2037  * Return: 0 if the region was added to the @cxlrd, else returns negative error
2038  * code. The region will be named "regionZ" where Z is the unique region number.
2039  */
2040 static struct cxl_region *devm_cxl_add_region(struct cxl_root_decoder *cxlrd,
2041 					      int id,
2042 					      enum cxl_decoder_mode mode,
2043 					      enum cxl_decoder_type type)
2044 {
2045 	struct cxl_port *port = to_cxl_port(cxlrd->cxlsd.cxld.dev.parent);
2046 	struct cxl_region *cxlr;
2047 	struct device *dev;
2048 	int rc;
2049 
2050 	switch (mode) {
2051 	case CXL_DECODER_RAM:
2052 	case CXL_DECODER_PMEM:
2053 		break;
2054 	default:
2055 		dev_err(&cxlrd->cxlsd.cxld.dev, "unsupported mode %d\n", mode);
2056 		return ERR_PTR(-EINVAL);
2057 	}
2058 
2059 	cxlr = cxl_region_alloc(cxlrd, id);
2060 	if (IS_ERR(cxlr))
2061 		return cxlr;
2062 	cxlr->mode = mode;
2063 	cxlr->type = type;
2064 
2065 	dev = &cxlr->dev;
2066 	rc = dev_set_name(dev, "region%d", id);
2067 	if (rc)
2068 		goto err;
2069 
2070 	rc = device_add(dev);
2071 	if (rc)
2072 		goto err;
2073 
2074 	rc = devm_add_action_or_reset(port->uport, unregister_region, cxlr);
2075 	if (rc)
2076 		return ERR_PTR(rc);
2077 
2078 	dev_dbg(port->uport, "%s: created %s\n",
2079 		dev_name(&cxlrd->cxlsd.cxld.dev), dev_name(dev));
2080 	return cxlr;
2081 
2082 err:
2083 	put_device(dev);
2084 	return ERR_PTR(rc);
2085 }
2086 
2087 static ssize_t __create_region_show(struct cxl_root_decoder *cxlrd, char *buf)
2088 {
2089 	return sysfs_emit(buf, "region%u\n", atomic_read(&cxlrd->region_id));
2090 }
2091 
2092 static ssize_t create_pmem_region_show(struct device *dev,
2093 				       struct device_attribute *attr, char *buf)
2094 {
2095 	return __create_region_show(to_cxl_root_decoder(dev), buf);
2096 }
2097 
2098 static ssize_t create_ram_region_show(struct device *dev,
2099 				      struct device_attribute *attr, char *buf)
2100 {
2101 	return __create_region_show(to_cxl_root_decoder(dev), buf);
2102 }
2103 
2104 static struct cxl_region *__create_region(struct cxl_root_decoder *cxlrd,
2105 					  enum cxl_decoder_mode mode, int id)
2106 {
2107 	int rc;
2108 
2109 	rc = memregion_alloc(GFP_KERNEL);
2110 	if (rc < 0)
2111 		return ERR_PTR(rc);
2112 
2113 	if (atomic_cmpxchg(&cxlrd->region_id, id, rc) != id) {
2114 		memregion_free(rc);
2115 		return ERR_PTR(-EBUSY);
2116 	}
2117 
2118 	return devm_cxl_add_region(cxlrd, id, mode, CXL_DECODER_HOSTONLYMEM);
2119 }
2120 
2121 static ssize_t create_pmem_region_store(struct device *dev,
2122 					struct device_attribute *attr,
2123 					const char *buf, size_t len)
2124 {
2125 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev);
2126 	struct cxl_region *cxlr;
2127 	int rc, id;
2128 
2129 	rc = sscanf(buf, "region%d\n", &id);
2130 	if (rc != 1)
2131 		return -EINVAL;
2132 
2133 	cxlr = __create_region(cxlrd, CXL_DECODER_PMEM, id);
2134 	if (IS_ERR(cxlr))
2135 		return PTR_ERR(cxlr);
2136 
2137 	return len;
2138 }
2139 DEVICE_ATTR_RW(create_pmem_region);
2140 
2141 static ssize_t create_ram_region_store(struct device *dev,
2142 				       struct device_attribute *attr,
2143 				       const char *buf, size_t len)
2144 {
2145 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev);
2146 	struct cxl_region *cxlr;
2147 	int rc, id;
2148 
2149 	rc = sscanf(buf, "region%d\n", &id);
2150 	if (rc != 1)
2151 		return -EINVAL;
2152 
2153 	cxlr = __create_region(cxlrd, CXL_DECODER_RAM, id);
2154 	if (IS_ERR(cxlr))
2155 		return PTR_ERR(cxlr);
2156 
2157 	return len;
2158 }
2159 DEVICE_ATTR_RW(create_ram_region);
2160 
2161 static ssize_t region_show(struct device *dev, struct device_attribute *attr,
2162 			   char *buf)
2163 {
2164 	struct cxl_decoder *cxld = to_cxl_decoder(dev);
2165 	ssize_t rc;
2166 
2167 	rc = down_read_interruptible(&cxl_region_rwsem);
2168 	if (rc)
2169 		return rc;
2170 
2171 	if (cxld->region)
2172 		rc = sysfs_emit(buf, "%s\n", dev_name(&cxld->region->dev));
2173 	else
2174 		rc = sysfs_emit(buf, "\n");
2175 	up_read(&cxl_region_rwsem);
2176 
2177 	return rc;
2178 }
2179 DEVICE_ATTR_RO(region);
2180 
2181 static struct cxl_region *
2182 cxl_find_region_by_name(struct cxl_root_decoder *cxlrd, const char *name)
2183 {
2184 	struct cxl_decoder *cxld = &cxlrd->cxlsd.cxld;
2185 	struct device *region_dev;
2186 
2187 	region_dev = device_find_child_by_name(&cxld->dev, name);
2188 	if (!region_dev)
2189 		return ERR_PTR(-ENODEV);
2190 
2191 	return to_cxl_region(region_dev);
2192 }
2193 
2194 static ssize_t delete_region_store(struct device *dev,
2195 				   struct device_attribute *attr,
2196 				   const char *buf, size_t len)
2197 {
2198 	struct cxl_root_decoder *cxlrd = to_cxl_root_decoder(dev);
2199 	struct cxl_port *port = to_cxl_port(dev->parent);
2200 	struct cxl_region *cxlr;
2201 
2202 	cxlr = cxl_find_region_by_name(cxlrd, buf);
2203 	if (IS_ERR(cxlr))
2204 		return PTR_ERR(cxlr);
2205 
2206 	devm_release_action(port->uport, unregister_region, cxlr);
2207 	put_device(&cxlr->dev);
2208 
2209 	return len;
2210 }
2211 DEVICE_ATTR_WO(delete_region);
2212 
2213 static void cxl_pmem_region_release(struct device *dev)
2214 {
2215 	struct cxl_pmem_region *cxlr_pmem = to_cxl_pmem_region(dev);
2216 	int i;
2217 
2218 	for (i = 0; i < cxlr_pmem->nr_mappings; i++) {
2219 		struct cxl_memdev *cxlmd = cxlr_pmem->mapping[i].cxlmd;
2220 
2221 		put_device(&cxlmd->dev);
2222 	}
2223 
2224 	kfree(cxlr_pmem);
2225 }
2226 
2227 static const struct attribute_group *cxl_pmem_region_attribute_groups[] = {
2228 	&cxl_base_attribute_group,
2229 	NULL,
2230 };
2231 
2232 const struct device_type cxl_pmem_region_type = {
2233 	.name = "cxl_pmem_region",
2234 	.release = cxl_pmem_region_release,
2235 	.groups = cxl_pmem_region_attribute_groups,
2236 };
2237 
2238 bool is_cxl_pmem_region(struct device *dev)
2239 {
2240 	return dev->type == &cxl_pmem_region_type;
2241 }
2242 EXPORT_SYMBOL_NS_GPL(is_cxl_pmem_region, CXL);
2243 
2244 struct cxl_pmem_region *to_cxl_pmem_region(struct device *dev)
2245 {
2246 	if (dev_WARN_ONCE(dev, !is_cxl_pmem_region(dev),
2247 			  "not a cxl_pmem_region device\n"))
2248 		return NULL;
2249 	return container_of(dev, struct cxl_pmem_region, dev);
2250 }
2251 EXPORT_SYMBOL_NS_GPL(to_cxl_pmem_region, CXL);
2252 
2253 struct cxl_poison_context {
2254 	struct cxl_port *port;
2255 	enum cxl_decoder_mode mode;
2256 	u64 offset;
2257 };
2258 
2259 static int cxl_get_poison_unmapped(struct cxl_memdev *cxlmd,
2260 				   struct cxl_poison_context *ctx)
2261 {
2262 	struct cxl_dev_state *cxlds = cxlmd->cxlds;
2263 	u64 offset, length;
2264 	int rc = 0;
2265 
2266 	/*
2267 	 * Collect poison for the remaining unmapped resources
2268 	 * after poison is collected by committed endpoints.
2269 	 *
2270 	 * Knowing that PMEM must always follow RAM, get poison
2271 	 * for unmapped resources based on the last decoder's mode:
2272 	 *	ram: scan remains of ram range, then any pmem range
2273 	 *	pmem: scan remains of pmem range
2274 	 */
2275 
2276 	if (ctx->mode == CXL_DECODER_RAM) {
2277 		offset = ctx->offset;
2278 		length = resource_size(&cxlds->ram_res) - offset;
2279 		rc = cxl_mem_get_poison(cxlmd, offset, length, NULL);
2280 		if (rc == -EFAULT)
2281 			rc = 0;
2282 		if (rc)
2283 			return rc;
2284 	}
2285 	if (ctx->mode == CXL_DECODER_PMEM) {
2286 		offset = ctx->offset;
2287 		length = resource_size(&cxlds->dpa_res) - offset;
2288 		if (!length)
2289 			return 0;
2290 	} else if (resource_size(&cxlds->pmem_res)) {
2291 		offset = cxlds->pmem_res.start;
2292 		length = resource_size(&cxlds->pmem_res);
2293 	} else {
2294 		return 0;
2295 	}
2296 
2297 	return cxl_mem_get_poison(cxlmd, offset, length, NULL);
2298 }
2299 
2300 static int poison_by_decoder(struct device *dev, void *arg)
2301 {
2302 	struct cxl_poison_context *ctx = arg;
2303 	struct cxl_endpoint_decoder *cxled;
2304 	struct cxl_memdev *cxlmd;
2305 	u64 offset, length;
2306 	int rc = 0;
2307 
2308 	if (!is_endpoint_decoder(dev))
2309 		return rc;
2310 
2311 	cxled = to_cxl_endpoint_decoder(dev);
2312 	if (!cxled->dpa_res || !resource_size(cxled->dpa_res))
2313 		return rc;
2314 
2315 	/*
2316 	 * Regions are only created with single mode decoders: pmem or ram.
2317 	 * Linux does not support mixed mode decoders. This means that
2318 	 * reading poison per endpoint decoder adheres to the requirement
2319 	 * that poison reads of pmem and ram must be separated.
2320 	 * CXL 3.0 Spec 8.2.9.8.4.1
2321 	 */
2322 	if (cxled->mode == CXL_DECODER_MIXED) {
2323 		dev_dbg(dev, "poison list read unsupported in mixed mode\n");
2324 		return rc;
2325 	}
2326 
2327 	cxlmd = cxled_to_memdev(cxled);
2328 	if (cxled->skip) {
2329 		offset = cxled->dpa_res->start - cxled->skip;
2330 		length = cxled->skip;
2331 		rc = cxl_mem_get_poison(cxlmd, offset, length, NULL);
2332 		if (rc == -EFAULT && cxled->mode == CXL_DECODER_RAM)
2333 			rc = 0;
2334 		if (rc)
2335 			return rc;
2336 	}
2337 
2338 	offset = cxled->dpa_res->start;
2339 	length = cxled->dpa_res->end - offset + 1;
2340 	rc = cxl_mem_get_poison(cxlmd, offset, length, cxled->cxld.region);
2341 	if (rc == -EFAULT && cxled->mode == CXL_DECODER_RAM)
2342 		rc = 0;
2343 	if (rc)
2344 		return rc;
2345 
2346 	/* Iterate until commit_end is reached */
2347 	if (cxled->cxld.id == ctx->port->commit_end) {
2348 		ctx->offset = cxled->dpa_res->end + 1;
2349 		ctx->mode = cxled->mode;
2350 		return 1;
2351 	}
2352 
2353 	return 0;
2354 }
2355 
2356 int cxl_get_poison_by_endpoint(struct cxl_port *port)
2357 {
2358 	struct cxl_poison_context ctx;
2359 	int rc = 0;
2360 
2361 	rc = down_read_interruptible(&cxl_region_rwsem);
2362 	if (rc)
2363 		return rc;
2364 
2365 	ctx = (struct cxl_poison_context) {
2366 		.port = port
2367 	};
2368 
2369 	rc = device_for_each_child(&port->dev, &ctx, poison_by_decoder);
2370 	if (rc == 1)
2371 		rc = cxl_get_poison_unmapped(to_cxl_memdev(port->uport), &ctx);
2372 
2373 	up_read(&cxl_region_rwsem);
2374 	return rc;
2375 }
2376 
2377 static struct lock_class_key cxl_pmem_region_key;
2378 
2379 static struct cxl_pmem_region *cxl_pmem_region_alloc(struct cxl_region *cxlr)
2380 {
2381 	struct cxl_region_params *p = &cxlr->params;
2382 	struct cxl_nvdimm_bridge *cxl_nvb;
2383 	struct cxl_pmem_region *cxlr_pmem;
2384 	struct device *dev;
2385 	int i;
2386 
2387 	down_read(&cxl_region_rwsem);
2388 	if (p->state != CXL_CONFIG_COMMIT) {
2389 		cxlr_pmem = ERR_PTR(-ENXIO);
2390 		goto out;
2391 	}
2392 
2393 	cxlr_pmem = kzalloc(struct_size(cxlr_pmem, mapping, p->nr_targets),
2394 			    GFP_KERNEL);
2395 	if (!cxlr_pmem) {
2396 		cxlr_pmem = ERR_PTR(-ENOMEM);
2397 		goto out;
2398 	}
2399 
2400 	cxlr_pmem->hpa_range.start = p->res->start;
2401 	cxlr_pmem->hpa_range.end = p->res->end;
2402 
2403 	/* Snapshot the region configuration underneath the cxl_region_rwsem */
2404 	cxlr_pmem->nr_mappings = p->nr_targets;
2405 	for (i = 0; i < p->nr_targets; i++) {
2406 		struct cxl_endpoint_decoder *cxled = p->targets[i];
2407 		struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
2408 		struct cxl_pmem_region_mapping *m = &cxlr_pmem->mapping[i];
2409 
2410 		/*
2411 		 * Regions never span CXL root devices, so by definition the
2412 		 * bridge for one device is the same for all.
2413 		 */
2414 		if (i == 0) {
2415 			cxl_nvb = cxl_find_nvdimm_bridge(cxlmd);
2416 			if (!cxl_nvb) {
2417 				cxlr_pmem = ERR_PTR(-ENODEV);
2418 				goto out;
2419 			}
2420 			cxlr->cxl_nvb = cxl_nvb;
2421 		}
2422 		m->cxlmd = cxlmd;
2423 		get_device(&cxlmd->dev);
2424 		m->start = cxled->dpa_res->start;
2425 		m->size = resource_size(cxled->dpa_res);
2426 		m->position = i;
2427 	}
2428 
2429 	dev = &cxlr_pmem->dev;
2430 	cxlr_pmem->cxlr = cxlr;
2431 	cxlr->cxlr_pmem = cxlr_pmem;
2432 	device_initialize(dev);
2433 	lockdep_set_class(&dev->mutex, &cxl_pmem_region_key);
2434 	device_set_pm_not_required(dev);
2435 	dev->parent = &cxlr->dev;
2436 	dev->bus = &cxl_bus_type;
2437 	dev->type = &cxl_pmem_region_type;
2438 out:
2439 	up_read(&cxl_region_rwsem);
2440 
2441 	return cxlr_pmem;
2442 }
2443 
2444 static void cxl_dax_region_release(struct device *dev)
2445 {
2446 	struct cxl_dax_region *cxlr_dax = to_cxl_dax_region(dev);
2447 
2448 	kfree(cxlr_dax);
2449 }
2450 
2451 static const struct attribute_group *cxl_dax_region_attribute_groups[] = {
2452 	&cxl_base_attribute_group,
2453 	NULL,
2454 };
2455 
2456 const struct device_type cxl_dax_region_type = {
2457 	.name = "cxl_dax_region",
2458 	.release = cxl_dax_region_release,
2459 	.groups = cxl_dax_region_attribute_groups,
2460 };
2461 
2462 static bool is_cxl_dax_region(struct device *dev)
2463 {
2464 	return dev->type == &cxl_dax_region_type;
2465 }
2466 
2467 struct cxl_dax_region *to_cxl_dax_region(struct device *dev)
2468 {
2469 	if (dev_WARN_ONCE(dev, !is_cxl_dax_region(dev),
2470 			  "not a cxl_dax_region device\n"))
2471 		return NULL;
2472 	return container_of(dev, struct cxl_dax_region, dev);
2473 }
2474 EXPORT_SYMBOL_NS_GPL(to_cxl_dax_region, CXL);
2475 
2476 static struct lock_class_key cxl_dax_region_key;
2477 
2478 static struct cxl_dax_region *cxl_dax_region_alloc(struct cxl_region *cxlr)
2479 {
2480 	struct cxl_region_params *p = &cxlr->params;
2481 	struct cxl_dax_region *cxlr_dax;
2482 	struct device *dev;
2483 
2484 	down_read(&cxl_region_rwsem);
2485 	if (p->state != CXL_CONFIG_COMMIT) {
2486 		cxlr_dax = ERR_PTR(-ENXIO);
2487 		goto out;
2488 	}
2489 
2490 	cxlr_dax = kzalloc(sizeof(*cxlr_dax), GFP_KERNEL);
2491 	if (!cxlr_dax) {
2492 		cxlr_dax = ERR_PTR(-ENOMEM);
2493 		goto out;
2494 	}
2495 
2496 	cxlr_dax->hpa_range.start = p->res->start;
2497 	cxlr_dax->hpa_range.end = p->res->end;
2498 
2499 	dev = &cxlr_dax->dev;
2500 	cxlr_dax->cxlr = cxlr;
2501 	device_initialize(dev);
2502 	lockdep_set_class(&dev->mutex, &cxl_dax_region_key);
2503 	device_set_pm_not_required(dev);
2504 	dev->parent = &cxlr->dev;
2505 	dev->bus = &cxl_bus_type;
2506 	dev->type = &cxl_dax_region_type;
2507 out:
2508 	up_read(&cxl_region_rwsem);
2509 
2510 	return cxlr_dax;
2511 }
2512 
2513 static void cxlr_pmem_unregister(void *_cxlr_pmem)
2514 {
2515 	struct cxl_pmem_region *cxlr_pmem = _cxlr_pmem;
2516 	struct cxl_region *cxlr = cxlr_pmem->cxlr;
2517 	struct cxl_nvdimm_bridge *cxl_nvb = cxlr->cxl_nvb;
2518 
2519 	/*
2520 	 * Either the bridge is in ->remove() context under the device_lock(),
2521 	 * or cxlr_release_nvdimm() is cancelling the bridge's release action
2522 	 * for @cxlr_pmem and doing it itself (while manually holding the bridge
2523 	 * lock).
2524 	 */
2525 	device_lock_assert(&cxl_nvb->dev);
2526 	cxlr->cxlr_pmem = NULL;
2527 	cxlr_pmem->cxlr = NULL;
2528 	device_unregister(&cxlr_pmem->dev);
2529 }
2530 
2531 static void cxlr_release_nvdimm(void *_cxlr)
2532 {
2533 	struct cxl_region *cxlr = _cxlr;
2534 	struct cxl_nvdimm_bridge *cxl_nvb = cxlr->cxl_nvb;
2535 
2536 	device_lock(&cxl_nvb->dev);
2537 	if (cxlr->cxlr_pmem)
2538 		devm_release_action(&cxl_nvb->dev, cxlr_pmem_unregister,
2539 				    cxlr->cxlr_pmem);
2540 	device_unlock(&cxl_nvb->dev);
2541 	cxlr->cxl_nvb = NULL;
2542 	put_device(&cxl_nvb->dev);
2543 }
2544 
2545 /**
2546  * devm_cxl_add_pmem_region() - add a cxl_region-to-nd_region bridge
2547  * @cxlr: parent CXL region for this pmem region bridge device
2548  *
2549  * Return: 0 on success negative error code on failure.
2550  */
2551 static int devm_cxl_add_pmem_region(struct cxl_region *cxlr)
2552 {
2553 	struct cxl_pmem_region *cxlr_pmem;
2554 	struct cxl_nvdimm_bridge *cxl_nvb;
2555 	struct device *dev;
2556 	int rc;
2557 
2558 	cxlr_pmem = cxl_pmem_region_alloc(cxlr);
2559 	if (IS_ERR(cxlr_pmem))
2560 		return PTR_ERR(cxlr_pmem);
2561 	cxl_nvb = cxlr->cxl_nvb;
2562 
2563 	dev = &cxlr_pmem->dev;
2564 	rc = dev_set_name(dev, "pmem_region%d", cxlr->id);
2565 	if (rc)
2566 		goto err;
2567 
2568 	rc = device_add(dev);
2569 	if (rc)
2570 		goto err;
2571 
2572 	dev_dbg(&cxlr->dev, "%s: register %s\n", dev_name(dev->parent),
2573 		dev_name(dev));
2574 
2575 	device_lock(&cxl_nvb->dev);
2576 	if (cxl_nvb->dev.driver)
2577 		rc = devm_add_action_or_reset(&cxl_nvb->dev,
2578 					      cxlr_pmem_unregister, cxlr_pmem);
2579 	else
2580 		rc = -ENXIO;
2581 	device_unlock(&cxl_nvb->dev);
2582 
2583 	if (rc)
2584 		goto err_bridge;
2585 
2586 	/* @cxlr carries a reference on @cxl_nvb until cxlr_release_nvdimm */
2587 	return devm_add_action_or_reset(&cxlr->dev, cxlr_release_nvdimm, cxlr);
2588 
2589 err:
2590 	put_device(dev);
2591 err_bridge:
2592 	put_device(&cxl_nvb->dev);
2593 	cxlr->cxl_nvb = NULL;
2594 	return rc;
2595 }
2596 
2597 static void cxlr_dax_unregister(void *_cxlr_dax)
2598 {
2599 	struct cxl_dax_region *cxlr_dax = _cxlr_dax;
2600 
2601 	device_unregister(&cxlr_dax->dev);
2602 }
2603 
2604 static int devm_cxl_add_dax_region(struct cxl_region *cxlr)
2605 {
2606 	struct cxl_dax_region *cxlr_dax;
2607 	struct device *dev;
2608 	int rc;
2609 
2610 	cxlr_dax = cxl_dax_region_alloc(cxlr);
2611 	if (IS_ERR(cxlr_dax))
2612 		return PTR_ERR(cxlr_dax);
2613 
2614 	dev = &cxlr_dax->dev;
2615 	rc = dev_set_name(dev, "dax_region%d", cxlr->id);
2616 	if (rc)
2617 		goto err;
2618 
2619 	rc = device_add(dev);
2620 	if (rc)
2621 		goto err;
2622 
2623 	dev_dbg(&cxlr->dev, "%s: register %s\n", dev_name(dev->parent),
2624 		dev_name(dev));
2625 
2626 	return devm_add_action_or_reset(&cxlr->dev, cxlr_dax_unregister,
2627 					cxlr_dax);
2628 err:
2629 	put_device(dev);
2630 	return rc;
2631 }
2632 
2633 static int match_decoder_by_range(struct device *dev, void *data)
2634 {
2635 	struct range *r1, *r2 = data;
2636 	struct cxl_root_decoder *cxlrd;
2637 
2638 	if (!is_root_decoder(dev))
2639 		return 0;
2640 
2641 	cxlrd = to_cxl_root_decoder(dev);
2642 	r1 = &cxlrd->cxlsd.cxld.hpa_range;
2643 	return range_contains(r1, r2);
2644 }
2645 
2646 static int match_region_by_range(struct device *dev, void *data)
2647 {
2648 	struct cxl_region_params *p;
2649 	struct cxl_region *cxlr;
2650 	struct range *r = data;
2651 	int rc = 0;
2652 
2653 	if (!is_cxl_region(dev))
2654 		return 0;
2655 
2656 	cxlr = to_cxl_region(dev);
2657 	p = &cxlr->params;
2658 
2659 	down_read(&cxl_region_rwsem);
2660 	if (p->res && p->res->start == r->start && p->res->end == r->end)
2661 		rc = 1;
2662 	up_read(&cxl_region_rwsem);
2663 
2664 	return rc;
2665 }
2666 
2667 /* Establish an empty region covering the given HPA range */
2668 static struct cxl_region *construct_region(struct cxl_root_decoder *cxlrd,
2669 					   struct cxl_endpoint_decoder *cxled)
2670 {
2671 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
2672 	struct cxl_port *port = cxlrd_to_port(cxlrd);
2673 	struct range *hpa = &cxled->cxld.hpa_range;
2674 	struct cxl_region_params *p;
2675 	struct cxl_region *cxlr;
2676 	struct resource *res;
2677 	int rc;
2678 
2679 	do {
2680 		cxlr = __create_region(cxlrd, cxled->mode,
2681 				       atomic_read(&cxlrd->region_id));
2682 	} while (IS_ERR(cxlr) && PTR_ERR(cxlr) == -EBUSY);
2683 
2684 	if (IS_ERR(cxlr)) {
2685 		dev_err(cxlmd->dev.parent,
2686 			"%s:%s: %s failed assign region: %ld\n",
2687 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
2688 			__func__, PTR_ERR(cxlr));
2689 		return cxlr;
2690 	}
2691 
2692 	down_write(&cxl_region_rwsem);
2693 	p = &cxlr->params;
2694 	if (p->state >= CXL_CONFIG_INTERLEAVE_ACTIVE) {
2695 		dev_err(cxlmd->dev.parent,
2696 			"%s:%s: %s autodiscovery interrupted\n",
2697 			dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
2698 			__func__);
2699 		rc = -EBUSY;
2700 		goto err;
2701 	}
2702 
2703 	set_bit(CXL_REGION_F_AUTO, &cxlr->flags);
2704 
2705 	res = kmalloc(sizeof(*res), GFP_KERNEL);
2706 	if (!res) {
2707 		rc = -ENOMEM;
2708 		goto err;
2709 	}
2710 
2711 	*res = DEFINE_RES_MEM_NAMED(hpa->start, range_len(hpa),
2712 				    dev_name(&cxlr->dev));
2713 	rc = insert_resource(cxlrd->res, res);
2714 	if (rc) {
2715 		/*
2716 		 * Platform-firmware may not have split resources like "System
2717 		 * RAM" on CXL window boundaries see cxl_region_iomem_release()
2718 		 */
2719 		dev_warn(cxlmd->dev.parent,
2720 			 "%s:%s: %s %s cannot insert resource\n",
2721 			 dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev),
2722 			 __func__, dev_name(&cxlr->dev));
2723 	}
2724 
2725 	p->res = res;
2726 	p->interleave_ways = cxled->cxld.interleave_ways;
2727 	p->interleave_granularity = cxled->cxld.interleave_granularity;
2728 	p->state = CXL_CONFIG_INTERLEAVE_ACTIVE;
2729 
2730 	rc = sysfs_update_group(&cxlr->dev.kobj, get_cxl_region_target_group());
2731 	if (rc)
2732 		goto err;
2733 
2734 	dev_dbg(cxlmd->dev.parent, "%s:%s: %s %s res: %pr iw: %d ig: %d\n",
2735 		dev_name(&cxlmd->dev), dev_name(&cxled->cxld.dev), __func__,
2736 		dev_name(&cxlr->dev), p->res, p->interleave_ways,
2737 		p->interleave_granularity);
2738 
2739 	/* ...to match put_device() in cxl_add_to_region() */
2740 	get_device(&cxlr->dev);
2741 	up_write(&cxl_region_rwsem);
2742 
2743 	return cxlr;
2744 
2745 err:
2746 	up_write(&cxl_region_rwsem);
2747 	devm_release_action(port->uport, unregister_region, cxlr);
2748 	return ERR_PTR(rc);
2749 }
2750 
2751 int cxl_add_to_region(struct cxl_port *root, struct cxl_endpoint_decoder *cxled)
2752 {
2753 	struct cxl_memdev *cxlmd = cxled_to_memdev(cxled);
2754 	struct range *hpa = &cxled->cxld.hpa_range;
2755 	struct cxl_decoder *cxld = &cxled->cxld;
2756 	struct device *cxlrd_dev, *region_dev;
2757 	struct cxl_root_decoder *cxlrd;
2758 	struct cxl_region_params *p;
2759 	struct cxl_region *cxlr;
2760 	bool attach = false;
2761 	int rc;
2762 
2763 	cxlrd_dev = device_find_child(&root->dev, &cxld->hpa_range,
2764 				      match_decoder_by_range);
2765 	if (!cxlrd_dev) {
2766 		dev_err(cxlmd->dev.parent,
2767 			"%s:%s no CXL window for range %#llx:%#llx\n",
2768 			dev_name(&cxlmd->dev), dev_name(&cxld->dev),
2769 			cxld->hpa_range.start, cxld->hpa_range.end);
2770 		return -ENXIO;
2771 	}
2772 
2773 	cxlrd = to_cxl_root_decoder(cxlrd_dev);
2774 
2775 	/*
2776 	 * Ensure that if multiple threads race to construct_region() for @hpa
2777 	 * one does the construction and the others add to that.
2778 	 */
2779 	mutex_lock(&cxlrd->range_lock);
2780 	region_dev = device_find_child(&cxlrd->cxlsd.cxld.dev, hpa,
2781 				       match_region_by_range);
2782 	if (!region_dev) {
2783 		cxlr = construct_region(cxlrd, cxled);
2784 		region_dev = &cxlr->dev;
2785 	} else
2786 		cxlr = to_cxl_region(region_dev);
2787 	mutex_unlock(&cxlrd->range_lock);
2788 
2789 	rc = PTR_ERR_OR_ZERO(cxlr);
2790 	if (rc)
2791 		goto out;
2792 
2793 	attach_target(cxlr, cxled, -1, TASK_UNINTERRUPTIBLE);
2794 
2795 	down_read(&cxl_region_rwsem);
2796 	p = &cxlr->params;
2797 	attach = p->state == CXL_CONFIG_COMMIT;
2798 	up_read(&cxl_region_rwsem);
2799 
2800 	if (attach) {
2801 		/*
2802 		 * If device_attach() fails the range may still be active via
2803 		 * the platform-firmware memory map, otherwise the driver for
2804 		 * regions is local to this file, so driver matching can't fail.
2805 		 */
2806 		if (device_attach(&cxlr->dev) < 0)
2807 			dev_err(&cxlr->dev, "failed to enable, range: %pr\n",
2808 				p->res);
2809 	}
2810 
2811 	put_device(region_dev);
2812 out:
2813 	put_device(cxlrd_dev);
2814 	return rc;
2815 }
2816 EXPORT_SYMBOL_NS_GPL(cxl_add_to_region, CXL);
2817 
2818 static int cxl_region_invalidate_memregion(struct cxl_region *cxlr)
2819 {
2820 	if (!test_bit(CXL_REGION_F_INCOHERENT, &cxlr->flags))
2821 		return 0;
2822 
2823 	if (!cpu_cache_has_invalidate_memregion()) {
2824 		if (IS_ENABLED(CONFIG_CXL_REGION_INVALIDATION_TEST)) {
2825 			dev_warn_once(
2826 				&cxlr->dev,
2827 				"Bypassing cpu_cache_invalidate_memregion() for testing!\n");
2828 			clear_bit(CXL_REGION_F_INCOHERENT, &cxlr->flags);
2829 			return 0;
2830 		} else {
2831 			dev_err(&cxlr->dev,
2832 				"Failed to synchronize CPU cache state\n");
2833 			return -ENXIO;
2834 		}
2835 	}
2836 
2837 	cpu_cache_invalidate_memregion(IORES_DESC_CXL);
2838 	clear_bit(CXL_REGION_F_INCOHERENT, &cxlr->flags);
2839 	return 0;
2840 }
2841 
2842 static int is_system_ram(struct resource *res, void *arg)
2843 {
2844 	struct cxl_region *cxlr = arg;
2845 	struct cxl_region_params *p = &cxlr->params;
2846 
2847 	dev_dbg(&cxlr->dev, "%pr has System RAM: %pr\n", p->res, res);
2848 	return 1;
2849 }
2850 
2851 static int cxl_region_probe(struct device *dev)
2852 {
2853 	struct cxl_region *cxlr = to_cxl_region(dev);
2854 	struct cxl_region_params *p = &cxlr->params;
2855 	int rc;
2856 
2857 	rc = down_read_interruptible(&cxl_region_rwsem);
2858 	if (rc) {
2859 		dev_dbg(&cxlr->dev, "probe interrupted\n");
2860 		return rc;
2861 	}
2862 
2863 	if (p->state < CXL_CONFIG_COMMIT) {
2864 		dev_dbg(&cxlr->dev, "config state: %d\n", p->state);
2865 		rc = -ENXIO;
2866 		goto out;
2867 	}
2868 
2869 	rc = cxl_region_invalidate_memregion(cxlr);
2870 
2871 	/*
2872 	 * From this point on any path that changes the region's state away from
2873 	 * CXL_CONFIG_COMMIT is also responsible for releasing the driver.
2874 	 */
2875 out:
2876 	up_read(&cxl_region_rwsem);
2877 
2878 	if (rc)
2879 		return rc;
2880 
2881 	switch (cxlr->mode) {
2882 	case CXL_DECODER_PMEM:
2883 		return devm_cxl_add_pmem_region(cxlr);
2884 	case CXL_DECODER_RAM:
2885 		/*
2886 		 * The region can not be manged by CXL if any portion of
2887 		 * it is already online as 'System RAM'
2888 		 */
2889 		if (walk_iomem_res_desc(IORES_DESC_NONE,
2890 					IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY,
2891 					p->res->start, p->res->end, cxlr,
2892 					is_system_ram) > 0)
2893 			return 0;
2894 		return devm_cxl_add_dax_region(cxlr);
2895 	default:
2896 		dev_dbg(&cxlr->dev, "unsupported region mode: %d\n",
2897 			cxlr->mode);
2898 		return -ENXIO;
2899 	}
2900 }
2901 
2902 static struct cxl_driver cxl_region_driver = {
2903 	.name = "cxl_region",
2904 	.probe = cxl_region_probe,
2905 	.id = CXL_DEVICE_REGION,
2906 };
2907 
2908 int cxl_region_init(void)
2909 {
2910 	return cxl_driver_register(&cxl_region_driver);
2911 }
2912 
2913 void cxl_region_exit(void)
2914 {
2915 	cxl_driver_unregister(&cxl_region_driver);
2916 }
2917 
2918 MODULE_IMPORT_NS(CXL);
2919 MODULE_IMPORT_NS(DEVMEM);
2920 MODULE_ALIAS_CXL(CXL_DEVICE_REGION);
2921