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