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