xref: /linux/drivers/i3c/master.c (revision 26ae421f7f49f8a6a32d15b1d21a782b46a1bad5)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2018 Cadence Design Systems Inc.
4  *
5  * Author: Boris Brezillon <boris.brezillon@bootlin.com>
6  */
7 
8 #include <linux/atomic.h>
9 #include <linux/bitmap.h>
10 #include <linux/bug.h>
11 #include <linux/delay.h>
12 #include <linux/device.h>
13 #include <linux/dma-mapping.h>
14 #include <linux/err.h>
15 #include <linux/export.h>
16 #include <linux/kernel.h>
17 #include <linux/list.h>
18 #include <linux/of.h>
19 #include <linux/pm_runtime.h>
20 #include <linux/slab.h>
21 #include <linux/spinlock.h>
22 #include <linux/workqueue.h>
23 
24 #include "internals.h"
25 
26 static DEFINE_IDR(i3c_bus_idr);
27 static DEFINE_MUTEX(i3c_core_lock);
28 static int __i3c_first_dynamic_bus_num;
29 static BLOCKING_NOTIFIER_HEAD(i3c_bus_notifier);
30 
31 /**
32  * i3c_bus_maintenance_lock - Lock the bus for a maintenance operation
33  * @bus: I3C bus to take the lock on
34  *
35  * This function takes the bus lock so that no other operations can occur on
36  * the bus. This is needed for all kind of bus maintenance operation, like
37  * - enabling/disabling slave events
38  * - re-triggering DAA
39  * - changing the dynamic address of a device
40  * - relinquishing mastership
41  * - ...
42  *
43  * The reason for this kind of locking is that we don't want drivers and core
44  * logic to rely on I3C device information that could be changed behind their
45  * back.
46  */
47 static void i3c_bus_maintenance_lock(struct i3c_bus *bus)
48 {
49 	down_write(&bus->lock);
50 }
51 
52 /**
53  * i3c_bus_maintenance_unlock - Release the bus lock after a maintenance
54  *			      operation
55  * @bus: I3C bus to release the lock on
56  *
57  * Should be called when the bus maintenance operation is done. See
58  * i3c_bus_maintenance_lock() for more details on what these maintenance
59  * operations are.
60  */
61 static void i3c_bus_maintenance_unlock(struct i3c_bus *bus)
62 {
63 	up_write(&bus->lock);
64 }
65 
66 /**
67  * i3c_bus_normaluse_lock - Lock the bus for a normal operation
68  * @bus: I3C bus to take the lock on
69  *
70  * This function takes the bus lock for any operation that is not a maintenance
71  * operation (see i3c_bus_maintenance_lock() for a non-exhaustive list of
72  * maintenance operations). Basically all communications with I3C devices are
73  * normal operations (HDR, SDR transfers or CCC commands that do not change bus
74  * state or I3C dynamic address).
75  *
76  * Note that this lock is not guaranteeing serialization of normal operations.
77  * In other words, transfer requests passed to the I3C master can be submitted
78  * in parallel and I3C master drivers have to use their own locking to make
79  * sure two different communications are not inter-mixed, or access to the
80  * output/input queue is not done while the engine is busy.
81  */
82 void i3c_bus_normaluse_lock(struct i3c_bus *bus)
83 {
84 	down_read(&bus->lock);
85 }
86 
87 /**
88  * i3c_bus_normaluse_unlock - Release the bus lock after a normal operation
89  * @bus: I3C bus to release the lock on
90  *
91  * Should be called when a normal operation is done. See
92  * i3c_bus_normaluse_lock() for more details on what these normal operations
93  * are.
94  */
95 void i3c_bus_normaluse_unlock(struct i3c_bus *bus)
96 {
97 	up_read(&bus->lock);
98 }
99 
100 static struct i3c_master_controller *
101 i3c_bus_to_i3c_master(struct i3c_bus *i3cbus)
102 {
103 	return container_of(i3cbus, struct i3c_master_controller, bus);
104 }
105 
106 static struct i3c_master_controller *dev_to_i3cmaster(struct device *dev)
107 {
108 	return container_of(dev, struct i3c_master_controller, dev);
109 }
110 
111 static int __must_check i3c_master_rpm_get(struct i3c_master_controller *master)
112 {
113 	int ret = master->rpm_allowed ? pm_runtime_resume_and_get(master->dev.parent) : 0;
114 
115 	if (ret < 0) {
116 		dev_err(master->dev.parent, "runtime resume failed, error %d\n", ret);
117 		return ret;
118 	}
119 	return 0;
120 }
121 
122 static void i3c_master_rpm_put(struct i3c_master_controller *master)
123 {
124 	if (master->rpm_allowed)
125 		pm_runtime_put_autosuspend(master->dev.parent);
126 }
127 
128 int i3c_bus_rpm_get(struct i3c_bus *bus)
129 {
130 	return i3c_master_rpm_get(i3c_bus_to_i3c_master(bus));
131 }
132 
133 void i3c_bus_rpm_put(struct i3c_bus *bus)
134 {
135 	i3c_master_rpm_put(i3c_bus_to_i3c_master(bus));
136 }
137 
138 bool i3c_bus_rpm_ibi_allowed(struct i3c_bus *bus)
139 {
140 	return i3c_bus_to_i3c_master(bus)->rpm_ibi_allowed;
141 }
142 
143 static const struct device_type i3c_device_type;
144 
145 static struct i3c_bus *dev_to_i3cbus(struct device *dev)
146 {
147 	struct i3c_master_controller *master;
148 
149 	if (dev->type == &i3c_device_type)
150 		return dev_to_i3cdev(dev)->bus;
151 
152 	master = dev_to_i3cmaster(dev);
153 
154 	return &master->bus;
155 }
156 
157 static struct i3c_dev_desc *dev_to_i3cdesc(struct device *dev)
158 {
159 	struct i3c_master_controller *master;
160 
161 	if (dev->type == &i3c_device_type)
162 		return dev_to_i3cdev(dev)->desc;
163 
164 	master = dev_to_i3cmaster(dev);
165 
166 	return master->this;
167 }
168 
169 static ssize_t bcr_show(struct device *dev,
170 			struct device_attribute *da,
171 			char *buf)
172 {
173 	struct i3c_bus *bus = dev_to_i3cbus(dev);
174 	struct i3c_dev_desc *desc;
175 	ssize_t ret;
176 
177 	i3c_bus_normaluse_lock(bus);
178 	desc = dev_to_i3cdesc(dev);
179 	ret = sysfs_emit(buf, "0x%02x\n", desc->info.bcr);
180 	i3c_bus_normaluse_unlock(bus);
181 
182 	return ret;
183 }
184 static DEVICE_ATTR_RO(bcr);
185 
186 static ssize_t dcr_show(struct device *dev,
187 			struct device_attribute *da,
188 			char *buf)
189 {
190 	struct i3c_bus *bus = dev_to_i3cbus(dev);
191 	struct i3c_dev_desc *desc;
192 	ssize_t ret;
193 
194 	i3c_bus_normaluse_lock(bus);
195 	desc = dev_to_i3cdesc(dev);
196 	ret = sysfs_emit(buf, "0x%02x\n", desc->info.dcr);
197 	i3c_bus_normaluse_unlock(bus);
198 
199 	return ret;
200 }
201 static DEVICE_ATTR_RO(dcr);
202 
203 static ssize_t pid_show(struct device *dev,
204 			struct device_attribute *da,
205 			char *buf)
206 {
207 	struct i3c_bus *bus = dev_to_i3cbus(dev);
208 	struct i3c_dev_desc *desc;
209 	ssize_t ret;
210 
211 	i3c_bus_normaluse_lock(bus);
212 	desc = dev_to_i3cdesc(dev);
213 	ret = sysfs_emit(buf, "%llx\n", desc->info.pid);
214 	i3c_bus_normaluse_unlock(bus);
215 
216 	return ret;
217 }
218 static DEVICE_ATTR_RO(pid);
219 
220 static ssize_t dynamic_address_show(struct device *dev,
221 				    struct device_attribute *da,
222 				    char *buf)
223 {
224 	struct i3c_bus *bus = dev_to_i3cbus(dev);
225 	struct i3c_dev_desc *desc;
226 	ssize_t ret;
227 
228 	i3c_bus_normaluse_lock(bus);
229 	desc = dev_to_i3cdesc(dev);
230 	ret = sysfs_emit(buf, "%02x\n", desc->info.dyn_addr);
231 	i3c_bus_normaluse_unlock(bus);
232 
233 	return ret;
234 }
235 static DEVICE_ATTR_RO(dynamic_address);
236 
237 static const char * const hdrcap_strings[] = {
238 	"hdr-ddr", "hdr-tsp", "hdr-tsl",
239 };
240 
241 static ssize_t hdrcap_show(struct device *dev,
242 			   struct device_attribute *da,
243 			   char *buf)
244 {
245 	struct i3c_bus *bus = dev_to_i3cbus(dev);
246 	struct i3c_dev_desc *desc;
247 	ssize_t offset = 0, ret;
248 	unsigned long caps;
249 	int mode;
250 
251 	i3c_bus_normaluse_lock(bus);
252 	desc = dev_to_i3cdesc(dev);
253 	caps = desc->info.hdr_cap;
254 	for_each_set_bit(mode, &caps, 8) {
255 		if (mode >= ARRAY_SIZE(hdrcap_strings))
256 			break;
257 
258 		if (!hdrcap_strings[mode])
259 			continue;
260 
261 		ret = sysfs_emit_at(buf, offset, offset ? " %s" : "%s",
262 			      hdrcap_strings[mode]);
263 		if (ret < 0)
264 			goto out;
265 
266 		offset += ret;
267 	}
268 
269 	ret = sysfs_emit_at(buf, offset, "\n");
270 	if (ret < 0)
271 		goto out;
272 
273 	ret = offset + ret;
274 
275 out:
276 	i3c_bus_normaluse_unlock(bus);
277 
278 	return ret;
279 }
280 static DEVICE_ATTR_RO(hdrcap);
281 
282 static ssize_t modalias_show(struct device *dev,
283 			     struct device_attribute *da, char *buf)
284 {
285 	struct i3c_device *i3c = dev_to_i3cdev(dev);
286 	struct i3c_device_info devinfo;
287 	u16 manuf, part, ext;
288 
289 	i3c_device_get_info(i3c, &devinfo);
290 	manuf = I3C_PID_MANUF_ID(devinfo.pid);
291 	part = I3C_PID_PART_ID(devinfo.pid);
292 	ext = I3C_PID_EXTRA_INFO(devinfo.pid);
293 
294 	if (I3C_PID_RND_LOWER_32BITS(devinfo.pid))
295 		return sysfs_emit(buf, "i3c:dcr%02Xmanuf%04X\n", devinfo.dcr,
296 			       manuf);
297 
298 	return sysfs_emit(buf, "i3c:dcr%02Xmanuf%04Xpart%04Xext%04X\n",
299 		       devinfo.dcr, manuf, part, ext);
300 }
301 static DEVICE_ATTR_RO(modalias);
302 
303 static struct attribute *i3c_device_attrs[] = {
304 	&dev_attr_bcr.attr,
305 	&dev_attr_dcr.attr,
306 	&dev_attr_pid.attr,
307 	&dev_attr_dynamic_address.attr,
308 	&dev_attr_hdrcap.attr,
309 	&dev_attr_modalias.attr,
310 	NULL,
311 };
312 ATTRIBUTE_GROUPS(i3c_device);
313 
314 static int i3c_device_uevent(const struct device *dev, struct kobj_uevent_env *env)
315 {
316 	const struct i3c_device *i3cdev = dev_to_i3cdev(dev);
317 	struct i3c_device_info devinfo;
318 	u16 manuf, part, ext;
319 
320 	if (i3cdev->desc)
321 		devinfo = i3cdev->desc->info;
322 	manuf = I3C_PID_MANUF_ID(devinfo.pid);
323 	part = I3C_PID_PART_ID(devinfo.pid);
324 	ext = I3C_PID_EXTRA_INFO(devinfo.pid);
325 
326 	if (I3C_PID_RND_LOWER_32BITS(devinfo.pid))
327 		return add_uevent_var(env, "MODALIAS=i3c:dcr%02Xmanuf%04X",
328 				      devinfo.dcr, manuf);
329 
330 	return add_uevent_var(env,
331 			      "MODALIAS=i3c:dcr%02Xmanuf%04Xpart%04Xext%04X",
332 			      devinfo.dcr, manuf, part, ext);
333 }
334 
335 static const struct device_type i3c_device_type = {
336 	.groups	= i3c_device_groups,
337 	.uevent = i3c_device_uevent,
338 };
339 
340 static int i3c_device_match(struct device *dev, const struct device_driver *drv)
341 {
342 	struct i3c_device *i3cdev;
343 	const struct i3c_driver *i3cdrv;
344 
345 	if (dev->type != &i3c_device_type)
346 		return 0;
347 
348 	i3cdev = dev_to_i3cdev(dev);
349 	i3cdrv = drv_to_i3cdrv(drv);
350 	if (i3c_device_match_id(i3cdev, i3cdrv->id_table))
351 		return 1;
352 
353 	return 0;
354 }
355 
356 static int i3c_device_probe(struct device *dev)
357 {
358 	struct i3c_device *i3cdev = dev_to_i3cdev(dev);
359 	struct i3c_driver *driver = drv_to_i3cdrv(dev->driver);
360 
361 	return driver->probe(i3cdev);
362 }
363 
364 static void i3c_device_remove(struct device *dev)
365 {
366 	struct i3c_device *i3cdev = dev_to_i3cdev(dev);
367 	struct i3c_driver *driver = drv_to_i3cdrv(dev->driver);
368 
369 	if (driver->remove)
370 		driver->remove(i3cdev);
371 }
372 
373 static enum i3c_addr_slot_status
374 i3c_bus_get_addr_slot_status_mask(struct i3c_bus *bus, u16 addr, u32 mask)
375 {
376 	unsigned long status;
377 	int bitpos = addr * I3C_ADDR_SLOT_STATUS_BITS;
378 
379 	if (addr > I2C_MAX_ADDR)
380 		return I3C_ADDR_SLOT_RSVD;
381 
382 	status = bus->addrslots[bitpos / BITS_PER_LONG];
383 	status >>= bitpos % BITS_PER_LONG;
384 
385 	return status & mask;
386 }
387 
388 static enum i3c_addr_slot_status
389 i3c_bus_get_addr_slot_status(struct i3c_bus *bus, u16 addr)
390 {
391 	return i3c_bus_get_addr_slot_status_mask(bus, addr, I3C_ADDR_SLOT_STATUS_MASK);
392 }
393 
394 static void i3c_bus_set_addr_slot_status_mask(struct i3c_bus *bus, u16 addr,
395 					      enum i3c_addr_slot_status status, u32 mask)
396 {
397 	int bitpos = addr * I3C_ADDR_SLOT_STATUS_BITS;
398 	unsigned long *ptr;
399 
400 	if (addr > I2C_MAX_ADDR)
401 		return;
402 
403 	ptr = bus->addrslots + (bitpos / BITS_PER_LONG);
404 	*ptr &= ~((unsigned long)mask << (bitpos % BITS_PER_LONG));
405 	*ptr |= ((unsigned long)status & mask) << (bitpos % BITS_PER_LONG);
406 }
407 
408 static void i3c_bus_set_addr_slot_status(struct i3c_bus *bus, u16 addr,
409 					 enum i3c_addr_slot_status status)
410 {
411 	i3c_bus_set_addr_slot_status_mask(bus, addr, status, I3C_ADDR_SLOT_STATUS_MASK);
412 }
413 
414 static bool i3c_bus_dev_addr_is_avail(struct i3c_bus *bus, u8 addr)
415 {
416 	enum i3c_addr_slot_status status;
417 
418 	status = i3c_bus_get_addr_slot_status(bus, addr);
419 
420 	return status == I3C_ADDR_SLOT_FREE;
421 }
422 
423 /*
424  * ┌────┬─────────────┬───┬─────────┬───┐
425  * │S/Sr│ 7'h7E RnW=0 │ACK│ ENTDAA  │ T ├────┐
426  * └────┴─────────────┴───┴─────────┴───┘    │
427  * ┌─────────────────────────────────────────┘
428  * │  ┌──┬─────────────┬───┬─────────────────┬────────────────┬───┬─────────┐
429  * └─►│Sr│7'h7E RnW=1  │ACK│48bit UID BCR DCR│Assign 7bit Addr│PAR│ ACK/NACK430  *    └──┴─────────────┴───┴─────────────────┴────────────────┴───┴─────────┘
431  * Some master controllers (such as HCI) need to prepare the entire above transaction before
432  * sending it out to the I3C bus. This means that a 7-bit dynamic address needs to be allocated
433  * before knowing the target device's UID information.
434  *
435  * However, some I3C targets may request specific addresses (called as "init_dyn_addr"), which is
436  * typically specified by the DT-'s assigned-address property. Lower addresses having higher IBI
437  * priority. If it is available, i3c_bus_get_free_addr() preferably return a free address that is
438  * not in the list of desired addresses (called as "init_dyn_addr"). This allows the device with
439  * the "init_dyn_addr" to switch to its "init_dyn_addr" when it hot-joins the I3C bus. Otherwise,
440  * if the "init_dyn_addr" is already in use by another I3C device, the target device will not be
441  * able to switch to its desired address.
442  *
443  * If the previous step fails, fallback returning one of the remaining unassigned address,
444  * regardless of its state in the desired list.
445  */
446 static int i3c_bus_get_free_addr(struct i3c_bus *bus, u8 start_addr)
447 {
448 	enum i3c_addr_slot_status status;
449 	u8 addr;
450 
451 	for (addr = start_addr; addr < I3C_MAX_ADDR; addr++) {
452 		status = i3c_bus_get_addr_slot_status_mask(bus, addr,
453 							   I3C_ADDR_SLOT_EXT_STATUS_MASK);
454 		if (status == I3C_ADDR_SLOT_FREE)
455 			return addr;
456 	}
457 
458 	for (addr = start_addr; addr < I3C_MAX_ADDR; addr++) {
459 		status = i3c_bus_get_addr_slot_status_mask(bus, addr,
460 							   I3C_ADDR_SLOT_STATUS_MASK);
461 		if (status == I3C_ADDR_SLOT_FREE)
462 			return addr;
463 	}
464 
465 	return -ENOMEM;
466 }
467 
468 static void i3c_bus_init_addrslots(struct i3c_bus *bus)
469 {
470 	int i;
471 
472 	/* Addresses 0 to 7 are reserved. */
473 	for (i = 0; i < 8; i++)
474 		i3c_bus_set_addr_slot_status(bus, i, I3C_ADDR_SLOT_RSVD);
475 
476 	/*
477 	 * Reserve broadcast address and all addresses that might collide
478 	 * with the broadcast address when facing a single bit error.
479 	 */
480 	i3c_bus_set_addr_slot_status(bus, I3C_BROADCAST_ADDR,
481 				     I3C_ADDR_SLOT_RSVD);
482 	for (i = 0; i < 7; i++)
483 		i3c_bus_set_addr_slot_status(bus, I3C_BROADCAST_ADDR ^ BIT(i),
484 					     I3C_ADDR_SLOT_RSVD);
485 }
486 
487 static void i3c_bus_cleanup(struct i3c_bus *i3cbus)
488 {
489 	mutex_lock(&i3c_core_lock);
490 	idr_remove(&i3c_bus_idr, i3cbus->id);
491 	mutex_unlock(&i3c_core_lock);
492 }
493 
494 static int i3c_bus_init(struct i3c_bus *i3cbus, struct device_node *np)
495 {
496 	int ret, start, end, id = -1;
497 
498 	init_rwsem(&i3cbus->lock);
499 	INIT_LIST_HEAD(&i3cbus->devs.i2c);
500 	INIT_LIST_HEAD(&i3cbus->devs.i3c);
501 	i3c_bus_init_addrslots(i3cbus);
502 	i3cbus->mode = I3C_BUS_MODE_PURE;
503 
504 	if (np)
505 		id = of_alias_get_id(np, "i3c");
506 
507 	mutex_lock(&i3c_core_lock);
508 	if (id >= 0) {
509 		start = id;
510 		end = start + 1;
511 	} else {
512 		start = __i3c_first_dynamic_bus_num;
513 		end = 0;
514 	}
515 
516 	ret = idr_alloc(&i3c_bus_idr, i3cbus, start, end, GFP_KERNEL);
517 	mutex_unlock(&i3c_core_lock);
518 
519 	if (ret < 0)
520 		return ret;
521 
522 	i3cbus->id = ret;
523 
524 	return 0;
525 }
526 
527 void i3c_for_each_bus_locked(int (*fn)(struct i3c_bus *bus, void *data),
528 			     void *data)
529 {
530 	struct i3c_bus *bus;
531 	int id;
532 
533 	mutex_lock(&i3c_core_lock);
534 	idr_for_each_entry(&i3c_bus_idr, bus, id)
535 		fn(bus, data);
536 	mutex_unlock(&i3c_core_lock);
537 }
538 EXPORT_SYMBOL_GPL(i3c_for_each_bus_locked);
539 
540 int i3c_register_notifier(struct notifier_block *nb)
541 {
542 	return blocking_notifier_chain_register(&i3c_bus_notifier, nb);
543 }
544 EXPORT_SYMBOL_GPL(i3c_register_notifier);
545 
546 int i3c_unregister_notifier(struct notifier_block *nb)
547 {
548 	return blocking_notifier_chain_unregister(&i3c_bus_notifier, nb);
549 }
550 EXPORT_SYMBOL_GPL(i3c_unregister_notifier);
551 
552 static void i3c_bus_notify(struct i3c_bus *bus, unsigned int action)
553 {
554 	blocking_notifier_call_chain(&i3c_bus_notifier, action, bus);
555 }
556 
557 static const char * const i3c_bus_mode_strings[] = {
558 	[I3C_BUS_MODE_PURE] = "pure",
559 	[I3C_BUS_MODE_MIXED_FAST] = "mixed-fast",
560 	[I3C_BUS_MODE_MIXED_LIMITED] = "mixed-limited",
561 	[I3C_BUS_MODE_MIXED_SLOW] = "mixed-slow",
562 };
563 
564 static ssize_t mode_show(struct device *dev,
565 			 struct device_attribute *da,
566 			 char *buf)
567 {
568 	struct i3c_bus *i3cbus = dev_to_i3cbus(dev);
569 	ssize_t ret;
570 
571 	i3c_bus_normaluse_lock(i3cbus);
572 	if (i3cbus->mode < 0 ||
573 	    i3cbus->mode >= ARRAY_SIZE(i3c_bus_mode_strings) ||
574 	    !i3c_bus_mode_strings[i3cbus->mode])
575 		ret = sysfs_emit(buf, "unknown\n");
576 	else
577 		ret = sysfs_emit(buf, "%s\n", i3c_bus_mode_strings[i3cbus->mode]);
578 	i3c_bus_normaluse_unlock(i3cbus);
579 
580 	return ret;
581 }
582 static DEVICE_ATTR_RO(mode);
583 
584 static ssize_t current_master_show(struct device *dev,
585 				   struct device_attribute *da,
586 				   char *buf)
587 {
588 	struct i3c_bus *i3cbus = dev_to_i3cbus(dev);
589 	ssize_t ret;
590 
591 	i3c_bus_normaluse_lock(i3cbus);
592 	ret = sysfs_emit(buf, "%d-%llx\n", i3cbus->id,
593 		      i3cbus->cur_master->info.pid);
594 	i3c_bus_normaluse_unlock(i3cbus);
595 
596 	return ret;
597 }
598 static DEVICE_ATTR_RO(current_master);
599 
600 static ssize_t i3c_scl_frequency_show(struct device *dev,
601 				      struct device_attribute *da,
602 				      char *buf)
603 {
604 	struct i3c_bus *i3cbus = dev_to_i3cbus(dev);
605 	ssize_t ret;
606 
607 	i3c_bus_normaluse_lock(i3cbus);
608 	ret = sysfs_emit(buf, "%ld\n", i3cbus->scl_rate.i3c);
609 	i3c_bus_normaluse_unlock(i3cbus);
610 
611 	return ret;
612 }
613 static DEVICE_ATTR_RO(i3c_scl_frequency);
614 
615 static ssize_t i2c_scl_frequency_show(struct device *dev,
616 				      struct device_attribute *da,
617 				      char *buf)
618 {
619 	struct i3c_bus *i3cbus = dev_to_i3cbus(dev);
620 	ssize_t ret;
621 
622 	i3c_bus_normaluse_lock(i3cbus);
623 	ret = sysfs_emit(buf, "%ld\n", i3cbus->scl_rate.i2c);
624 	i3c_bus_normaluse_unlock(i3cbus);
625 
626 	return ret;
627 }
628 static DEVICE_ATTR_RO(i2c_scl_frequency);
629 
630 static void i3c_master_hj_work_fn(struct work_struct *work)
631 {
632 	struct i3c_master_controller *master = container_of(work, typeof(*master), hj_work);
633 
634 	if (!master->shutting_down)
635 		i3c_master_do_daa(master);
636 }
637 
638 static int i3c_set_hotjoin(struct i3c_master_controller *master, bool enable)
639 {
640 	int ret;
641 
642 	if (!master || !master->ops)
643 		return -EINVAL;
644 
645 	if (!master->ops->enable_hotjoin || !master->ops->disable_hotjoin)
646 		return -EINVAL;
647 
648 	if (enable || master->rpm_ibi_allowed) {
649 		ret = i3c_master_rpm_get(master);
650 		if (ret)
651 			return ret;
652 	}
653 
654 	i3c_bus_maintenance_lock(&master->bus);
655 
656 	if (master->shutting_down)
657 		ret = -ENODEV;
658 	else if (enable)
659 		ret = master->ops->enable_hotjoin(master);
660 	else
661 		ret = master->ops->disable_hotjoin(master);
662 
663 	if (!ret)
664 		master->hotjoin = enable;
665 
666 	i3c_bus_maintenance_unlock(&master->bus);
667 
668 	if ((enable && ret) || (!enable && !ret) || master->rpm_ibi_allowed)
669 		i3c_master_rpm_put(master);
670 
671 	return ret;
672 }
673 
674 static ssize_t hotjoin_store(struct device *dev, struct device_attribute *attr,
675 			     const char *buf, size_t count)
676 {
677 	struct i3c_bus *i3cbus = dev_to_i3cbus(dev);
678 	int ret;
679 	bool res;
680 
681 	if (!i3cbus->cur_master)
682 		return -EINVAL;
683 
684 	if (kstrtobool(buf, &res))
685 		return -EINVAL;
686 
687 	ret = i3c_set_hotjoin(i3cbus->cur_master->common.master, res);
688 	if (ret)
689 		return ret;
690 
691 	return count;
692 }
693 
694 /*
695  * i3c_master_enable_hotjoin - Enable hotjoin
696  * @master: I3C master object
697  *
698  * Return: a 0 in case of success, an negative error code otherwise.
699  */
700 int i3c_master_enable_hotjoin(struct i3c_master_controller *master)
701 {
702 	return i3c_set_hotjoin(master, true);
703 }
704 EXPORT_SYMBOL_GPL(i3c_master_enable_hotjoin);
705 
706 /*
707  * i3c_master_disable_hotjoin - Disable hotjoin
708  * @master: I3C master object
709  *
710  * Return: a 0 in case of success, an negative error code otherwise.
711  */
712 int i3c_master_disable_hotjoin(struct i3c_master_controller *master)
713 {
714 	return i3c_set_hotjoin(master, false);
715 }
716 EXPORT_SYMBOL_GPL(i3c_master_disable_hotjoin);
717 
718 /**
719  * i3c_master_queue_hotjoin - Queue DAA processing after a Hot-Join event
720  * @master: I3C master object
721  *
722  * Queue the hot-join worker on the master's workqueue.
723  */
724 void i3c_master_queue_hotjoin(struct i3c_master_controller *master)
725 {
726 	queue_work(master->wq, &master->hj_work);
727 }
728 EXPORT_SYMBOL_GPL(i3c_master_queue_hotjoin);
729 
730 static ssize_t hotjoin_show(struct device *dev, struct device_attribute *da, char *buf)
731 {
732 	struct i3c_bus *i3cbus = dev_to_i3cbus(dev);
733 	ssize_t ret;
734 
735 	i3c_bus_normaluse_lock(i3cbus);
736 	ret = sysfs_emit(buf, "%d\n", i3cbus->cur_master->common.master->hotjoin);
737 	i3c_bus_normaluse_unlock(i3cbus);
738 
739 	return ret;
740 }
741 
742 static DEVICE_ATTR_RW(hotjoin);
743 
744 static ssize_t dev_nack_retry_count_show(struct device *dev,
745 					 struct device_attribute *attr, char *buf)
746 {
747 	struct i3c_bus *i3cbus = dev_to_i3cbus(dev);
748 	ssize_t ret;
749 
750 	i3c_bus_normaluse_lock(i3cbus);
751 	ret = sysfs_emit(buf, "%u\n", dev_to_i3cmaster(dev)->dev_nack_retry_count);
752 	i3c_bus_normaluse_unlock(i3cbus);
753 
754 	return ret;
755 }
756 
757 static ssize_t dev_nack_retry_count_store(struct device *dev,
758 					  struct device_attribute *attr,
759 					  const char *buf, size_t count)
760 {
761 	struct i3c_bus *i3cbus = dev_to_i3cbus(dev);
762 	struct i3c_master_controller *master = dev_to_i3cmaster(dev);
763 	unsigned int val;
764 	int ret;
765 
766 	ret = kstrtouint(buf, 0, &val);
767 	if (ret)
768 		return ret;
769 
770 	ret = i3c_master_rpm_get(master);
771 	if (ret)
772 		return ret;
773 
774 	i3c_bus_maintenance_lock(i3cbus);
775 	ret = master->ops->set_dev_nack_retry(master, val);
776 	if (!ret)
777 		master->dev_nack_retry_count = val;
778 	i3c_bus_maintenance_unlock(i3cbus);
779 
780 	i3c_master_rpm_put(master);
781 
782 	return ret ?: count;
783 }
784 
785 static DEVICE_ATTR_RW(dev_nack_retry_count);
786 
787 static ssize_t do_daa_store(struct device *dev,
788 			    struct device_attribute *attr,
789 			    const char *buf, size_t count)
790 {
791 	struct i3c_master_controller *master = dev_to_i3cmaster(dev);
792 	bool val;
793 	int ret;
794 
795 	if (kstrtobool(buf, &val))
796 		return -EINVAL;
797 
798 	if (!val)
799 		return -EINVAL;
800 
801 	if (!master->init_done)
802 		return -EAGAIN;
803 
804 	ret = i3c_master_do_daa(master);
805 	if (ret)
806 		return ret;
807 
808 	return count;
809 }
810 
811 static DEVICE_ATTR_WO(do_daa);
812 
813 static struct attribute *i3c_masterdev_attrs[] = {
814 	&dev_attr_mode.attr,
815 	&dev_attr_current_master.attr,
816 	&dev_attr_i3c_scl_frequency.attr,
817 	&dev_attr_i2c_scl_frequency.attr,
818 	&dev_attr_bcr.attr,
819 	&dev_attr_dcr.attr,
820 	&dev_attr_pid.attr,
821 	&dev_attr_dynamic_address.attr,
822 	&dev_attr_hdrcap.attr,
823 	&dev_attr_hotjoin.attr,
824 	&dev_attr_do_daa.attr,
825 	NULL,
826 };
827 ATTRIBUTE_GROUPS(i3c_masterdev);
828 
829 static void i3c_masterdev_release(struct device *dev)
830 {
831 	struct i3c_master_controller *master = dev_to_i3cmaster(dev);
832 	struct i3c_bus *bus = dev_to_i3cbus(dev);
833 
834 	if (master->wq)
835 		destroy_workqueue(master->wq);
836 
837 	WARN_ON(!list_empty(&bus->devs.i2c) || !list_empty(&bus->devs.i3c));
838 	i3c_bus_cleanup(bus);
839 
840 	of_node_put(dev->of_node);
841 }
842 
843 static const struct device_type i3c_masterdev_type = {
844 	.groups	= i3c_masterdev_groups,
845 };
846 
847 static void i3c_master_shutdown(struct i3c_master_controller *master)
848 {
849 	i3c_bus_maintenance_lock(&master->bus);
850 	master->shutting_down = true;
851 	i3c_bus_maintenance_unlock(&master->bus);
852 
853 	cancel_work_sync(&master->hj_work);
854 	cancel_work_sync(&master->reg_work);
855 }
856 
857 static void i3c_device_shutdown(struct device *dev)
858 {
859 	if (dev->type == &i3c_masterdev_type)
860 		i3c_master_shutdown(dev_to_i3cmaster(dev));
861 }
862 
863 const struct bus_type i3c_bus_type = {
864 	.name = "i3c",
865 	.match = i3c_device_match,
866 	.probe = i3c_device_probe,
867 	.remove = i3c_device_remove,
868 	.shutdown = i3c_device_shutdown,
869 };
870 EXPORT_SYMBOL_GPL(i3c_bus_type);
871 
872 static int i3c_bus_set_mode(struct i3c_bus *i3cbus, enum i3c_bus_mode mode,
873 			    unsigned long max_i2c_scl_rate)
874 {
875 	struct i3c_master_controller *master = i3c_bus_to_i3c_master(i3cbus);
876 
877 	i3cbus->mode = mode;
878 
879 	switch (i3cbus->mode) {
880 	case I3C_BUS_MODE_PURE:
881 		if (!i3cbus->scl_rate.i3c)
882 			i3cbus->scl_rate.i3c = I3C_BUS_I3C_SCL_TYP_RATE;
883 		break;
884 	case I3C_BUS_MODE_MIXED_FAST:
885 	case I3C_BUS_MODE_MIXED_LIMITED:
886 		if (!i3cbus->scl_rate.i3c)
887 			i3cbus->scl_rate.i3c = I3C_BUS_I3C_SCL_TYP_RATE;
888 		if (!i3cbus->scl_rate.i2c)
889 			i3cbus->scl_rate.i2c = max_i2c_scl_rate;
890 		break;
891 	case I3C_BUS_MODE_MIXED_SLOW:
892 		if (!i3cbus->scl_rate.i2c)
893 			i3cbus->scl_rate.i2c = max_i2c_scl_rate;
894 		if (!i3cbus->scl_rate.i3c ||
895 		    i3cbus->scl_rate.i3c > i3cbus->scl_rate.i2c)
896 			i3cbus->scl_rate.i3c = i3cbus->scl_rate.i2c;
897 		break;
898 	default:
899 		return -EINVAL;
900 	}
901 
902 	dev_dbg(&master->dev, "i2c-scl = %ld Hz i3c-scl = %ld Hz\n",
903 		i3cbus->scl_rate.i2c, i3cbus->scl_rate.i3c);
904 
905 	/*
906 	 * I3C/I2C frequency may have been overridden, check that user-provided
907 	 * values are not exceeding max possible frequency.
908 	 */
909 	if (i3cbus->scl_rate.i3c > I3C_BUS_I3C_SCL_MAX_RATE ||
910 	    i3cbus->scl_rate.i2c > I3C_BUS_I2C_FM_PLUS_SCL_MAX_RATE)
911 		return -EINVAL;
912 
913 	return 0;
914 }
915 
916 static struct i3c_master_controller *
917 i2c_adapter_to_i3c_master(struct i2c_adapter *adap)
918 {
919 	return container_of(adap, struct i3c_master_controller, i2c);
920 }
921 
922 static struct i2c_adapter *
923 i3c_master_to_i2c_adapter(struct i3c_master_controller *master)
924 {
925 	return &master->i2c;
926 }
927 
928 static void i3c_master_free_i2c_dev(struct i2c_dev_desc *dev)
929 {
930 	kfree(dev);
931 }
932 
933 static struct i2c_dev_desc *
934 i3c_master_alloc_i2c_dev(struct i3c_master_controller *master,
935 			 u16 addr, u8 lvr)
936 {
937 	struct i2c_dev_desc *dev;
938 
939 	dev = kzalloc_obj(*dev);
940 	if (!dev)
941 		return ERR_PTR(-ENOMEM);
942 
943 	dev->common.master = master;
944 	dev->addr = addr;
945 	dev->lvr = lvr;
946 
947 	return dev;
948 }
949 
950 static void *i3c_ccc_cmd_dest_init(struct i3c_ccc_cmd_dest *dest, u8 addr,
951 				   u16 payloadlen)
952 {
953 	dest->addr = addr;
954 	dest->payload.len = payloadlen;
955 	if (payloadlen)
956 		dest->payload.data = kzalloc(payloadlen, GFP_KERNEL);
957 	else
958 		dest->payload.data = NULL;
959 
960 	return dest->payload.data;
961 }
962 
963 static void i3c_ccc_cmd_dest_cleanup(struct i3c_ccc_cmd_dest *dest)
964 {
965 	kfree(dest->payload.data);
966 }
967 
968 static void i3c_ccc_cmd_init(struct i3c_ccc_cmd *cmd, bool rnw, u8 id,
969 			     struct i3c_ccc_cmd_dest *dests,
970 			     unsigned int ndests)
971 {
972 	cmd->rnw = rnw ? 1 : 0;
973 	cmd->id = id;
974 	cmd->dests = dests;
975 	cmd->ndests = ndests;
976 	cmd->err = I3C_ERROR_UNKNOWN;
977 }
978 
979 /**
980  * i3c_master_send_ccc_cmd_locked() - send a CCC (Common Command Codes)
981  * @master: master used to send frames on the bus
982  * @cmd: command to send
983  *
984  * Return: 0 in case of success, or a negative error code otherwise.
985  *         I3C Mx error codes are stored in cmd->err.
986  */
987 static int i3c_master_send_ccc_cmd_locked(struct i3c_master_controller *master,
988 					  struct i3c_ccc_cmd *cmd)
989 {
990 	if (!cmd || !master)
991 		return -EINVAL;
992 
993 	if (WARN_ON(master->init_done &&
994 		    !rwsem_is_locked(&master->bus.lock)))
995 		return -EINVAL;
996 
997 	if (!master->ops->send_ccc_cmd)
998 		return -EOPNOTSUPP;
999 
1000 	if ((cmd->id & I3C_CCC_DIRECT) && (!cmd->dests || !cmd->ndests))
1001 		return -EINVAL;
1002 
1003 	if (master->ops->supports_ccc_cmd &&
1004 	    !master->ops->supports_ccc_cmd(master, cmd))
1005 		return -EOPNOTSUPP;
1006 
1007 	return master->ops->send_ccc_cmd(master, cmd);
1008 }
1009 
1010 static struct i2c_dev_desc *
1011 i3c_master_find_i2c_dev_by_addr(const struct i3c_master_controller *master,
1012 				u16 addr)
1013 {
1014 	struct i2c_dev_desc *dev;
1015 
1016 	i3c_bus_for_each_i2cdev(&master->bus, dev) {
1017 		if (dev->addr == addr)
1018 			return dev;
1019 	}
1020 
1021 	return NULL;
1022 }
1023 
1024 /**
1025  * i3c_master_get_free_addr() - get a free address on the bus
1026  * @master: I3C master object
1027  * @start_addr: where to start searching
1028  *
1029  * This function must be called with the bus lock held in write mode.
1030  *
1031  * Return: the first free address starting at @start_addr (included) or -ENOMEM
1032  * if there's no more address available.
1033  */
1034 int i3c_master_get_free_addr(struct i3c_master_controller *master,
1035 			     u8 start_addr)
1036 {
1037 	return i3c_bus_get_free_addr(&master->bus, start_addr);
1038 }
1039 EXPORT_SYMBOL_GPL(i3c_master_get_free_addr);
1040 
1041 static void i3c_device_release(struct device *dev)
1042 {
1043 	struct i3c_device *i3cdev = dev_to_i3cdev(dev);
1044 
1045 	WARN_ON(i3cdev->desc);
1046 
1047 	of_node_put(i3cdev->dev.of_node);
1048 	kfree(i3cdev);
1049 }
1050 
1051 static void i3c_master_free_i3c_dev(struct i3c_dev_desc *dev)
1052 {
1053 	kfree(dev);
1054 }
1055 
1056 static struct i3c_dev_desc *
1057 i3c_master_alloc_i3c_dev(struct i3c_master_controller *master,
1058 			 const struct i3c_device_info *info)
1059 {
1060 	struct i3c_dev_desc *dev;
1061 
1062 	dev = kzalloc_obj(*dev);
1063 	if (!dev)
1064 		return ERR_PTR(-ENOMEM);
1065 
1066 	dev->common.master = master;
1067 	dev->info = *info;
1068 	mutex_init(&dev->ibi_lock);
1069 
1070 	return dev;
1071 }
1072 
1073 static int i3c_master_rstdaa_locked(struct i3c_master_controller *master,
1074 				    u8 addr)
1075 {
1076 	enum i3c_addr_slot_status addrstat;
1077 	struct i3c_ccc_cmd_dest dest;
1078 	struct i3c_ccc_cmd cmd;
1079 	int ret;
1080 
1081 	if (!master)
1082 		return -EINVAL;
1083 
1084 	addrstat = i3c_bus_get_addr_slot_status(&master->bus, addr);
1085 	if (addr != I3C_BROADCAST_ADDR && addrstat != I3C_ADDR_SLOT_I3C_DEV)
1086 		return -EINVAL;
1087 
1088 	i3c_ccc_cmd_dest_init(&dest, addr, 0);
1089 	i3c_ccc_cmd_init(&cmd, false,
1090 			 I3C_CCC_RSTDAA(addr == I3C_BROADCAST_ADDR),
1091 			 &dest, 1);
1092 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1093 	i3c_ccc_cmd_dest_cleanup(&dest);
1094 
1095 	/* No active devices on the bus. */
1096 	if (ret && cmd.err == I3C_ERROR_M2)
1097 		ret = 0;
1098 
1099 	return ret;
1100 }
1101 
1102 /**
1103  * i3c_master_entdaa_locked() - start a DAA (Dynamic Address Assignment)
1104  *				procedure
1105  * @master: master used to send frames on the bus
1106  *
1107  * Send a ENTDAA CCC command to start a DAA procedure.
1108  *
1109  * Note that this function only sends the ENTDAA CCC command, all the logic
1110  * behind dynamic address assignment has to be handled in the I3C master
1111  * driver.
1112  *
1113  * This function must be called with the bus lock held in write mode.
1114  *
1115  * Return: 0 in case of success, or a negative error code otherwise.
1116  */
1117 int i3c_master_entdaa_locked(struct i3c_master_controller *master)
1118 {
1119 	struct i3c_ccc_cmd_dest dest;
1120 	struct i3c_ccc_cmd cmd;
1121 	int ret;
1122 
1123 	i3c_ccc_cmd_dest_init(&dest, I3C_BROADCAST_ADDR, 0);
1124 	i3c_ccc_cmd_init(&cmd, false, I3C_CCC_ENTDAA, &dest, 1);
1125 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1126 	i3c_ccc_cmd_dest_cleanup(&dest);
1127 
1128 	/* No active devices need an address. */
1129 	if (ret && cmd.err == I3C_ERROR_M2)
1130 		ret = 0;
1131 
1132 	return ret;
1133 }
1134 EXPORT_SYMBOL_GPL(i3c_master_entdaa_locked);
1135 
1136 /**
1137  * i3c_master_enec_disec_locked() - send an ENEC or DISEC CCC command
1138  * @master: master used to send frames on the bus
1139  * @addr: a valid I3C slave address or %I3C_BROADCAST_ADDR
1140  * @enable: true to send ENEC, false to send DISEC
1141  * @evts: events to enable or disable
1142  * @suppress_m2: if true, treat an M2 (NACK) error from the CCC as success
1143  *
1144  * Send an ENEC or DISEC CCC command to enable or disable some or all events
1145  * coming from a specific slave, or all devices if @addr is
1146  * %I3C_BROADCAST_ADDR.
1147  *
1148  * When @suppress_m2 is true, a NACK of the broadcast (which can happen when
1149  * no devices are present on the bus) is not reported as an error. This is
1150  * useful for callers that want to configure event reporting unconditionally,
1151  * regardless of whether any devices are currently on the bus.
1152  *
1153  * This function must be called with the bus lock held in write mode.
1154  *
1155  * Return: 0 in case of success, or a negative error code otherwise.
1156  */
1157 int i3c_master_enec_disec_locked(struct i3c_master_controller *master, u8 addr,
1158 				 bool enable, u8 evts, bool suppress_m2)
1159 {
1160 	struct i3c_ccc_events *events;
1161 	struct i3c_ccc_cmd_dest dest;
1162 	struct i3c_ccc_cmd cmd;
1163 	int ret;
1164 
1165 	events = i3c_ccc_cmd_dest_init(&dest, addr, sizeof(*events));
1166 	if (!events)
1167 		return -ENOMEM;
1168 
1169 	events->events = evts;
1170 	i3c_ccc_cmd_init(&cmd, false,
1171 			 enable ?
1172 			 I3C_CCC_ENEC(addr == I3C_BROADCAST_ADDR) :
1173 			 I3C_CCC_DISEC(addr == I3C_BROADCAST_ADDR),
1174 			 &dest, 1);
1175 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1176 	i3c_ccc_cmd_dest_cleanup(&dest);
1177 
1178 	if (suppress_m2 && ret && cmd.err == I3C_ERROR_M2)
1179 		ret = 0;
1180 
1181 	return ret;
1182 }
1183 EXPORT_SYMBOL_GPL(i3c_master_enec_disec_locked);
1184 
1185 /**
1186  * i3c_master_disec_locked() - send a DISEC CCC command
1187  * @master: master used to send frames on the bus
1188  * @addr: a valid I3C slave address or %I3C_BROADCAST_ADDR
1189  * @evts: events to disable
1190  *
1191  * Send a DISEC CCC command to disable some or all events coming from a
1192  * specific slave, or all devices if @addr is %I3C_BROADCAST_ADDR.
1193  *
1194  * This function must be called with the bus lock held in write mode.
1195  *
1196  * Return: 0 in case of success, or a negative error code otherwise.
1197  */
1198 int i3c_master_disec_locked(struct i3c_master_controller *master, u8 addr,
1199 			    u8 evts)
1200 {
1201 	return i3c_master_enec_disec_locked(master, addr, false, evts, false);
1202 }
1203 EXPORT_SYMBOL_GPL(i3c_master_disec_locked);
1204 
1205 /**
1206  * i3c_master_enec_locked() - send an ENEC CCC command
1207  * @master: master used to send frames on the bus
1208  * @addr: a valid I3C slave address or %I3C_BROADCAST_ADDR
1209  * @evts: events to disable
1210  *
1211  * Sends an ENEC CCC command to enable some or all events coming from a
1212  * specific slave, or all devices if @addr is %I3C_BROADCAST_ADDR.
1213  *
1214  * This function must be called with the bus lock held in write mode.
1215  *
1216  * Return: 0 in case of success, or a negative error code otherwise.
1217  */
1218 int i3c_master_enec_locked(struct i3c_master_controller *master, u8 addr,
1219 			   u8 evts)
1220 {
1221 	return i3c_master_enec_disec_locked(master, addr, true, evts, false);
1222 }
1223 EXPORT_SYMBOL_GPL(i3c_master_enec_locked);
1224 
1225 /**
1226  * i3c_master_defslvs_locked() - send a DEFSLVS CCC command
1227  * @master: master used to send frames on the bus
1228  *
1229  * Send a DEFSLVS CCC command containing all the devices known to the @master.
1230  * This is useful when you have secondary masters on the bus to propagate
1231  * device information.
1232  *
1233  * This should be called after all I3C devices have been discovered (in other
1234  * words, after the DAA procedure has finished) and instantiated in
1235  * &i3c_master_controller_ops->bus_init().
1236  * It should also be called if a master ACKed an Hot-Join request and assigned
1237  * a dynamic address to the device joining the bus.
1238  *
1239  * This function must be called with the bus lock held in write mode.
1240  *
1241  * Return: 0 in case of success, or a negative error code otherwise.
1242  */
1243 int i3c_master_defslvs_locked(struct i3c_master_controller *master)
1244 {
1245 	struct i3c_ccc_defslvs *defslvs;
1246 	struct i3c_ccc_dev_desc *desc;
1247 	struct i3c_ccc_cmd_dest dest;
1248 	struct i3c_dev_desc *i3cdev;
1249 	struct i2c_dev_desc *i2cdev;
1250 	struct i3c_ccc_cmd cmd;
1251 	struct i3c_bus *bus;
1252 	bool send = false;
1253 	int ndevs = 0, ret;
1254 
1255 	if (!master)
1256 		return -EINVAL;
1257 
1258 	bus = i3c_master_get_bus(master);
1259 	i3c_bus_for_each_i3cdev(bus, i3cdev) {
1260 		ndevs++;
1261 
1262 		if (i3cdev == master->this)
1263 			continue;
1264 
1265 		if (I3C_BCR_DEVICE_ROLE(i3cdev->info.bcr) ==
1266 		    I3C_BCR_I3C_MASTER)
1267 			send = true;
1268 	}
1269 
1270 	/* No other master on the bus, skip DEFSLVS. */
1271 	if (!send)
1272 		return 0;
1273 
1274 	i3c_bus_for_each_i2cdev(bus, i2cdev)
1275 		ndevs++;
1276 
1277 	defslvs = i3c_ccc_cmd_dest_init(&dest, I3C_BROADCAST_ADDR,
1278 					struct_size(defslvs, slaves,
1279 						    ndevs - 1));
1280 	if (!defslvs)
1281 		return -ENOMEM;
1282 
1283 	defslvs->count = ndevs;
1284 	defslvs->master.bcr = master->this->info.bcr;
1285 	defslvs->master.dcr = master->this->info.dcr;
1286 	defslvs->master.dyn_addr = master->this->info.dyn_addr << 1;
1287 	defslvs->master.static_addr = I3C_BROADCAST_ADDR << 1;
1288 
1289 	desc = defslvs->slaves;
1290 	i3c_bus_for_each_i2cdev(bus, i2cdev) {
1291 		desc->lvr = i2cdev->lvr;
1292 		desc->static_addr = i2cdev->addr << 1;
1293 		desc++;
1294 	}
1295 
1296 	i3c_bus_for_each_i3cdev(bus, i3cdev) {
1297 		/* Skip the I3C dev representing this master. */
1298 		if (i3cdev == master->this)
1299 			continue;
1300 
1301 		desc->bcr = i3cdev->info.bcr;
1302 		desc->dcr = i3cdev->info.dcr;
1303 		desc->dyn_addr = i3cdev->info.dyn_addr << 1;
1304 		desc->static_addr = i3cdev->info.static_addr << 1;
1305 		desc++;
1306 	}
1307 
1308 	i3c_ccc_cmd_init(&cmd, false, I3C_CCC_DEFSLVS, &dest, 1);
1309 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1310 	i3c_ccc_cmd_dest_cleanup(&dest);
1311 
1312 	return ret;
1313 }
1314 EXPORT_SYMBOL_GPL(i3c_master_defslvs_locked);
1315 
1316 static int i3c_master_setda_locked(struct i3c_master_controller *master,
1317 				   u8 oldaddr, u8 newaddr, bool setdasa)
1318 {
1319 	struct i3c_ccc_cmd_dest dest;
1320 	struct i3c_ccc_setda *setda;
1321 	struct i3c_ccc_cmd cmd;
1322 	int ret;
1323 
1324 	if (!oldaddr || !newaddr)
1325 		return -EINVAL;
1326 
1327 	setda = i3c_ccc_cmd_dest_init(&dest, oldaddr, sizeof(*setda));
1328 	if (!setda)
1329 		return -ENOMEM;
1330 
1331 	setda->addr = newaddr << 1;
1332 	i3c_ccc_cmd_init(&cmd, false,
1333 			 setdasa ? I3C_CCC_SETDASA : I3C_CCC_SETNEWDA,
1334 			 &dest, 1);
1335 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1336 	i3c_ccc_cmd_dest_cleanup(&dest);
1337 
1338 	return ret;
1339 }
1340 
1341 static int i3c_master_setdasa_locked(struct i3c_master_controller *master,
1342 				     u8 static_addr, u8 dyn_addr)
1343 {
1344 	return i3c_master_setda_locked(master, static_addr, dyn_addr, true);
1345 }
1346 
1347 static int i3c_master_setnewda_locked(struct i3c_master_controller *master,
1348 				      u8 oldaddr, u8 newaddr)
1349 {
1350 	return i3c_master_setda_locked(master, oldaddr, newaddr, false);
1351 }
1352 
1353 static int i3c_master_getmrl_locked(struct i3c_master_controller *master,
1354 				    struct i3c_device_info *info)
1355 {
1356 	struct i3c_ccc_cmd_dest dest;
1357 	struct i3c_ccc_mrl *mrl;
1358 	struct i3c_ccc_cmd cmd;
1359 	int ret;
1360 
1361 	mrl = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr, sizeof(*mrl));
1362 	if (!mrl)
1363 		return -ENOMEM;
1364 
1365 	/*
1366 	 * When the device does not have IBI payload GETMRL only returns 2
1367 	 * bytes of data.
1368 	 */
1369 	if (!(info->bcr & I3C_BCR_IBI_PAYLOAD))
1370 		dest.payload.len -= 1;
1371 
1372 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETMRL, &dest, 1);
1373 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1374 	if (ret)
1375 		goto out;
1376 
1377 	switch (dest.payload.len) {
1378 	case 3:
1379 		info->max_ibi_len = mrl->ibi_len;
1380 		fallthrough;
1381 	case 2:
1382 		info->max_read_len = be16_to_cpu(mrl->read_len);
1383 		break;
1384 	default:
1385 		ret = -EIO;
1386 		goto out;
1387 	}
1388 
1389 out:
1390 	i3c_ccc_cmd_dest_cleanup(&dest);
1391 
1392 	return ret;
1393 }
1394 
1395 static int i3c_master_getmwl_locked(struct i3c_master_controller *master,
1396 				    struct i3c_device_info *info)
1397 {
1398 	struct i3c_ccc_cmd_dest dest;
1399 	struct i3c_ccc_mwl *mwl;
1400 	struct i3c_ccc_cmd cmd;
1401 	int ret;
1402 
1403 	mwl = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr, sizeof(*mwl));
1404 	if (!mwl)
1405 		return -ENOMEM;
1406 
1407 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETMWL, &dest, 1);
1408 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1409 	if (ret)
1410 		goto out;
1411 
1412 	if (dest.payload.len != sizeof(*mwl)) {
1413 		ret = -EIO;
1414 		goto out;
1415 	}
1416 
1417 	info->max_write_len = be16_to_cpu(mwl->len);
1418 
1419 out:
1420 	i3c_ccc_cmd_dest_cleanup(&dest);
1421 
1422 	return ret;
1423 }
1424 
1425 static int i3c_master_getmxds_locked(struct i3c_master_controller *master,
1426 				     struct i3c_device_info *info)
1427 {
1428 	struct i3c_ccc_getmxds *getmaxds;
1429 	struct i3c_ccc_cmd_dest dest;
1430 	struct i3c_ccc_cmd cmd;
1431 	int ret;
1432 
1433 	getmaxds = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr,
1434 					 sizeof(*getmaxds));
1435 	if (!getmaxds)
1436 		return -ENOMEM;
1437 
1438 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETMXDS, &dest, 1);
1439 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1440 	if (ret) {
1441 		/*
1442 		 * Retry when the device does not support max read turnaround
1443 		 * while expecting shorter length from this CCC command.
1444 		 */
1445 		dest.payload.len -= 3;
1446 		ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1447 		if (ret)
1448 			goto out;
1449 	}
1450 
1451 	if (dest.payload.len != 2 && dest.payload.len != 5) {
1452 		ret = -EIO;
1453 		goto out;
1454 	}
1455 
1456 	info->max_read_ds = getmaxds->maxrd;
1457 	info->max_write_ds = getmaxds->maxwr;
1458 	if (dest.payload.len == 5)
1459 		info->max_read_turnaround = getmaxds->maxrdturn[0] |
1460 					    ((u32)getmaxds->maxrdturn[1] << 8) |
1461 					    ((u32)getmaxds->maxrdturn[2] << 16);
1462 
1463 out:
1464 	i3c_ccc_cmd_dest_cleanup(&dest);
1465 
1466 	return ret;
1467 }
1468 
1469 static int i3c_master_gethdrcap_locked(struct i3c_master_controller *master,
1470 				       struct i3c_device_info *info)
1471 {
1472 	struct i3c_ccc_gethdrcap *gethdrcap;
1473 	struct i3c_ccc_cmd_dest dest;
1474 	struct i3c_ccc_cmd cmd;
1475 	int ret;
1476 
1477 	gethdrcap = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr,
1478 					  sizeof(*gethdrcap));
1479 	if (!gethdrcap)
1480 		return -ENOMEM;
1481 
1482 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETHDRCAP, &dest, 1);
1483 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1484 	if (ret)
1485 		goto out;
1486 
1487 	if (dest.payload.len != 1) {
1488 		ret = -EIO;
1489 		goto out;
1490 	}
1491 
1492 	info->hdr_cap = gethdrcap->modes;
1493 
1494 out:
1495 	i3c_ccc_cmd_dest_cleanup(&dest);
1496 
1497 	return ret;
1498 }
1499 
1500 static int i3c_master_getpid_locked(struct i3c_master_controller *master,
1501 				    struct i3c_device_info *info)
1502 {
1503 	struct i3c_ccc_getpid *getpid;
1504 	struct i3c_ccc_cmd_dest dest;
1505 	struct i3c_ccc_cmd cmd;
1506 	int ret, i;
1507 
1508 	getpid = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr, sizeof(*getpid));
1509 	if (!getpid)
1510 		return -ENOMEM;
1511 
1512 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETPID, &dest, 1);
1513 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1514 	if (ret)
1515 		goto out;
1516 
1517 	info->pid = 0;
1518 	for (i = 0; i < sizeof(getpid->pid); i++) {
1519 		int sft = (sizeof(getpid->pid) - i - 1) * 8;
1520 
1521 		info->pid |= (u64)getpid->pid[i] << sft;
1522 	}
1523 
1524 out:
1525 	i3c_ccc_cmd_dest_cleanup(&dest);
1526 
1527 	return ret;
1528 }
1529 
1530 static int i3c_master_getbcr_locked(struct i3c_master_controller *master,
1531 				    struct i3c_device_info *info)
1532 {
1533 	struct i3c_ccc_getbcr *getbcr;
1534 	struct i3c_ccc_cmd_dest dest;
1535 	struct i3c_ccc_cmd cmd;
1536 	int ret;
1537 
1538 	getbcr = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr, sizeof(*getbcr));
1539 	if (!getbcr)
1540 		return -ENOMEM;
1541 
1542 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETBCR, &dest, 1);
1543 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1544 	if (ret)
1545 		goto out;
1546 
1547 	info->bcr = getbcr->bcr;
1548 
1549 out:
1550 	i3c_ccc_cmd_dest_cleanup(&dest);
1551 
1552 	return ret;
1553 }
1554 
1555 static int i3c_master_getdcr_locked(struct i3c_master_controller *master,
1556 				    struct i3c_device_info *info)
1557 {
1558 	struct i3c_ccc_getdcr *getdcr;
1559 	struct i3c_ccc_cmd_dest dest;
1560 	struct i3c_ccc_cmd cmd;
1561 	int ret;
1562 
1563 	getdcr = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr, sizeof(*getdcr));
1564 	if (!getdcr)
1565 		return -ENOMEM;
1566 
1567 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETDCR, &dest, 1);
1568 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1569 	if (ret)
1570 		goto out;
1571 
1572 	info->dcr = getdcr->dcr;
1573 
1574 out:
1575 	i3c_ccc_cmd_dest_cleanup(&dest);
1576 
1577 	return ret;
1578 }
1579 
1580 static int i3c_master_retrieve_dev_info(struct i3c_dev_desc *dev)
1581 {
1582 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
1583 	enum i3c_addr_slot_status slot_status;
1584 	int ret;
1585 
1586 	if (!dev->info.dyn_addr)
1587 		return -EINVAL;
1588 
1589 	slot_status = i3c_bus_get_addr_slot_status(&master->bus,
1590 						   dev->info.dyn_addr);
1591 	if (slot_status == I3C_ADDR_SLOT_RSVD ||
1592 	    slot_status == I3C_ADDR_SLOT_I2C_DEV)
1593 		return -EINVAL;
1594 
1595 	ret = i3c_master_getpid_locked(master, &dev->info);
1596 	if (ret)
1597 		return ret;
1598 
1599 	ret = i3c_master_getbcr_locked(master, &dev->info);
1600 	if (ret)
1601 		return ret;
1602 
1603 	ret = i3c_master_getdcr_locked(master, &dev->info);
1604 	if (ret)
1605 		return ret;
1606 
1607 	if (dev->info.bcr & I3C_BCR_MAX_DATA_SPEED_LIM) {
1608 		ret = i3c_master_getmxds_locked(master, &dev->info);
1609 		if (ret)
1610 			return ret;
1611 	}
1612 
1613 	if (dev->info.bcr & I3C_BCR_IBI_PAYLOAD)
1614 		dev->info.max_ibi_len = 1;
1615 
1616 	i3c_master_getmrl_locked(master, &dev->info);
1617 	i3c_master_getmwl_locked(master, &dev->info);
1618 
1619 	if (dev->info.bcr & I3C_BCR_HDR_CAP) {
1620 		ret = i3c_master_gethdrcap_locked(master, &dev->info);
1621 		if (ret && ret != -EOPNOTSUPP)
1622 			return ret;
1623 	}
1624 
1625 	return 0;
1626 }
1627 
1628 static int i3c_master_getstatus_locked(struct i3c_master_controller *master,
1629 				       u8 addr, u16 *status)
1630 {
1631 	struct i3c_ccc_getstatus *getstatus;
1632 	struct i3c_ccc_cmd_dest dest;
1633 	struct i3c_ccc_cmd cmd;
1634 	int ret;
1635 
1636 	getstatus = i3c_ccc_cmd_dest_init(&dest, addr, sizeof(*getstatus));
1637 	if (!getstatus)
1638 		return -ENOMEM;
1639 
1640 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETSTATUS, &dest, 1);
1641 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1642 	if (ret)
1643 		goto out;
1644 
1645 	if (dest.payload.len != sizeof(*getstatus)) {
1646 		ret = -EIO;
1647 		goto out;
1648 	}
1649 
1650 	if (status)
1651 		*status = be16_to_cpu(getstatus->status);
1652 out:
1653 	i3c_ccc_cmd_dest_cleanup(&dest);
1654 
1655 	return ret;
1656 }
1657 
1658 /* Values are chosen to give the device plenty of opportunities to respond */
1659 #define I3C_DEV_PROBE_INITIAL_DELAY_US	20
1660 #define I3C_DEV_PROBE_DELAY_FACTOR	2
1661 #define I3C_DEV_PROBE_CNT		5
1662 
1663 static bool i3c_master_i3c_dev_present(struct i3c_master_controller *master, unsigned int addr)
1664 {
1665 	int delay = I3C_DEV_PROBE_INITIAL_DELAY_US;
1666 
1667 	for (int i = 0; i < I3C_DEV_PROBE_CNT; i++) {
1668 		if (i) {
1669 			fsleep(delay);
1670 			delay *= I3C_DEV_PROBE_DELAY_FACTOR;
1671 		}
1672 		if (!i3c_master_getstatus_locked(master, addr, NULL))
1673 			return true;
1674 	}
1675 
1676 	return false;
1677 }
1678 
1679 static void i3c_master_put_i3c_addrs(struct i3c_dev_desc *dev)
1680 {
1681 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
1682 
1683 	if (dev->info.static_addr)
1684 		i3c_bus_set_addr_slot_status(&master->bus,
1685 					     dev->info.static_addr,
1686 					     I3C_ADDR_SLOT_FREE);
1687 
1688 	if (dev->info.dyn_addr)
1689 		i3c_bus_set_addr_slot_status(&master->bus, dev->info.dyn_addr,
1690 					     I3C_ADDR_SLOT_FREE);
1691 
1692 	if (dev->boardinfo && dev->boardinfo->init_dyn_addr)
1693 		i3c_bus_set_addr_slot_status(&master->bus, dev->boardinfo->init_dyn_addr,
1694 					     I3C_ADDR_SLOT_FREE);
1695 }
1696 
1697 static int i3c_master_get_i3c_addrs(struct i3c_dev_desc *dev)
1698 {
1699 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
1700 	enum i3c_addr_slot_status status;
1701 
1702 	if (!dev->info.static_addr && !dev->info.dyn_addr)
1703 		return 0;
1704 
1705 	if (dev->info.static_addr) {
1706 		status = i3c_bus_get_addr_slot_status(&master->bus,
1707 						      dev->info.static_addr);
1708 		/* Since static address and assigned dynamic address can be
1709 		 * equal, allow this case to pass.
1710 		 */
1711 		if (status != I3C_ADDR_SLOT_FREE &&
1712 		    dev->info.static_addr != dev->boardinfo->init_dyn_addr)
1713 			return -EBUSY;
1714 
1715 		i3c_bus_set_addr_slot_status(&master->bus,
1716 					     dev->info.static_addr,
1717 					     I3C_ADDR_SLOT_I3C_DEV);
1718 	}
1719 
1720 	/*
1721 	 * ->init_dyn_addr should have been reserved before that, so, if we're
1722 	 * trying to apply a pre-reserved dynamic address, we should not try
1723 	 * to reserve the address slot a second time.
1724 	 */
1725 	if (dev->info.dyn_addr &&
1726 	    (!dev->boardinfo ||
1727 	     dev->boardinfo->init_dyn_addr != dev->info.dyn_addr)) {
1728 		status = i3c_bus_get_addr_slot_status(&master->bus,
1729 						      dev->info.dyn_addr);
1730 		if (status != I3C_ADDR_SLOT_FREE)
1731 			goto err_release_static_addr;
1732 
1733 		i3c_bus_set_addr_slot_status(&master->bus, dev->info.dyn_addr,
1734 					     I3C_ADDR_SLOT_I3C_DEV);
1735 	}
1736 
1737 	return 0;
1738 
1739 err_release_static_addr:
1740 	if (dev->info.static_addr)
1741 		i3c_bus_set_addr_slot_status(&master->bus,
1742 					     dev->info.static_addr,
1743 					     I3C_ADDR_SLOT_FREE);
1744 
1745 	return -EBUSY;
1746 }
1747 
1748 static int i3c_master_attach_i3c_dev(struct i3c_master_controller *master,
1749 				     struct i3c_dev_desc *dev)
1750 {
1751 	int ret;
1752 
1753 	/*
1754 	 * We don't attach devices to the controller until they are
1755 	 * addressable on the bus.
1756 	 */
1757 	if (!dev->info.static_addr && !dev->info.dyn_addr)
1758 		return 0;
1759 
1760 	ret = i3c_master_get_i3c_addrs(dev);
1761 	if (ret)
1762 		return ret;
1763 
1764 	/* Do not attach the master device itself. */
1765 	if (master->this != dev && master->ops->attach_i3c_dev) {
1766 		ret = master->ops->attach_i3c_dev(dev);
1767 		if (ret) {
1768 			i3c_master_put_i3c_addrs(dev);
1769 			return ret;
1770 		}
1771 	}
1772 
1773 	list_add_tail(&dev->common.node, &master->bus.devs.i3c);
1774 
1775 	return 0;
1776 }
1777 
1778 /**
1779  * i3c_master_reattach_i3c_dev_locked() - reattach an I3C device with a new address
1780  * @dev: I3C device descriptor to reattach
1781  * @old_dyn_addr: previous dynamic address of the device
1782  *
1783  * This function reattaches an existing I3C device to the bus when its dynamic
1784  * address has changed. It updates the bus address slot status accordingly:
1785  * - Marks the new dynamic address as occupied by an I3C device.
1786  * - Frees the old dynamic address slot if applicable.
1787  *
1788  * This function must be called with the bus lock held in write mode.
1789  *
1790  * Return: 0 on success, or a negative error code if reattachment fails
1791  *         (e.g. -EBUSY if the new address slot is not free).
1792  */
1793 int i3c_master_reattach_i3c_dev_locked(struct i3c_dev_desc *dev,
1794 				       u8 old_dyn_addr)
1795 {
1796 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
1797 	int ret;
1798 
1799 	if (dev->info.dyn_addr != old_dyn_addr) {
1800 		i3c_bus_set_addr_slot_status(&master->bus,
1801 					     dev->info.dyn_addr,
1802 					     I3C_ADDR_SLOT_I3C_DEV);
1803 		if (old_dyn_addr)
1804 			i3c_bus_set_addr_slot_status(&master->bus, old_dyn_addr,
1805 						     I3C_ADDR_SLOT_FREE);
1806 	}
1807 
1808 	if (master->ops->reattach_i3c_dev) {
1809 		ret = master->ops->reattach_i3c_dev(dev, old_dyn_addr);
1810 		if (ret) {
1811 			i3c_master_put_i3c_addrs(dev);
1812 			return ret;
1813 		}
1814 	}
1815 
1816 	return 0;
1817 }
1818 EXPORT_SYMBOL_GPL(i3c_master_reattach_i3c_dev_locked);
1819 
1820 static void i3c_master_detach_i3c_dev(struct i3c_dev_desc *dev)
1821 {
1822 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
1823 
1824 	/* Do not detach the master device itself. */
1825 	if (master->this != dev && master->ops->detach_i3c_dev)
1826 		master->ops->detach_i3c_dev(dev);
1827 
1828 	i3c_master_put_i3c_addrs(dev);
1829 	list_del(&dev->common.node);
1830 }
1831 
1832 static int i3c_master_attach_i2c_dev(struct i3c_master_controller *master,
1833 				     struct i2c_dev_desc *dev)
1834 {
1835 	int ret;
1836 
1837 	if (master->ops->attach_i2c_dev) {
1838 		ret = master->ops->attach_i2c_dev(dev);
1839 		if (ret)
1840 			return ret;
1841 	}
1842 
1843 	list_add_tail(&dev->common.node, &master->bus.devs.i2c);
1844 
1845 	return 0;
1846 }
1847 
1848 static void i3c_master_detach_i2c_dev(struct i2c_dev_desc *dev)
1849 {
1850 	struct i3c_master_controller *master = i2c_dev_get_master(dev);
1851 
1852 	list_del(&dev->common.node);
1853 
1854 	if (master->ops->detach_i2c_dev)
1855 		master->ops->detach_i2c_dev(dev);
1856 }
1857 
1858 static int i3c_master_early_i3c_dev_add(struct i3c_master_controller *master,
1859 					  struct i3c_dev_boardinfo *boardinfo)
1860 {
1861 	struct i3c_device_info info = {
1862 		.static_addr = boardinfo->static_addr,
1863 		.pid = boardinfo->pid,
1864 	};
1865 	struct i3c_dev_desc *i3cdev;
1866 	int ret;
1867 
1868 	i3cdev = i3c_master_alloc_i3c_dev(master, &info);
1869 	if (IS_ERR(i3cdev))
1870 		return -ENOMEM;
1871 
1872 	i3cdev->boardinfo = boardinfo;
1873 
1874 	ret = i3c_master_attach_i3c_dev(master, i3cdev);
1875 	if (ret)
1876 		goto err_free_dev;
1877 
1878 	ret = i3c_master_setdasa_locked(master, i3cdev->info.static_addr,
1879 					i3cdev->boardinfo->init_dyn_addr);
1880 	if (ret)
1881 		goto err_detach_dev;
1882 
1883 	i3cdev->info.dyn_addr = i3cdev->boardinfo->init_dyn_addr;
1884 	ret = i3c_master_reattach_i3c_dev_locked(i3cdev, 0);
1885 	if (ret)
1886 		goto err_rstdaa;
1887 
1888 	ret = i3c_master_retrieve_dev_info(i3cdev);
1889 	if (ret)
1890 		goto err_rstdaa;
1891 
1892 	return 0;
1893 
1894 err_rstdaa:
1895 	i3c_master_rstdaa_locked(master, i3cdev->boardinfo->init_dyn_addr);
1896 err_detach_dev:
1897 	i3c_master_detach_i3c_dev(i3cdev);
1898 err_free_dev:
1899 	i3c_master_free_i3c_dev(i3cdev);
1900 
1901 	return ret;
1902 }
1903 
1904 static void
1905 i3c_master_register_new_i3c_devs(struct i3c_master_controller *master)
1906 {
1907 	struct i3c_dev_desc *desc;
1908 	int ret;
1909 
1910 	if (!master->init_done)
1911 		return;
1912 
1913 	i3c_bus_for_each_i3cdev(&master->bus, desc) {
1914 		if (desc->dev || !desc->info.dyn_addr || desc == master->this)
1915 			continue;
1916 
1917 		desc->dev = kzalloc_obj(*desc->dev);
1918 		if (!desc->dev)
1919 			continue;
1920 
1921 		desc->dev->bus = &master->bus;
1922 		desc->dev->desc = desc;
1923 		desc->dev->dev.parent = &master->dev;
1924 		desc->dev->dev.type = &i3c_device_type;
1925 		desc->dev->dev.bus = &i3c_bus_type;
1926 		desc->dev->dev.release = i3c_device_release;
1927 		dev_set_name(&desc->dev->dev, "%d-%llx", master->bus.id,
1928 			     desc->info.pid);
1929 
1930 		if (desc->boardinfo)
1931 			desc->dev->dev.of_node = desc->boardinfo->of_node;
1932 
1933 		ret = device_register(&desc->dev->dev);
1934 		if (ret) {
1935 			dev_err(&master->dev,
1936 				"Failed to add I3C device (err = %d)\n", ret);
1937 			put_device(&desc->dev->dev);
1938 		}
1939 	}
1940 }
1941 
1942 static void i3c_master_reg_work_fn(struct work_struct *work)
1943 {
1944 	struct i3c_master_controller *master = container_of(work, typeof(*master), reg_work);
1945 
1946 	i3c_bus_normaluse_lock(&master->bus);
1947 	if (!master->shutting_down)
1948 		i3c_master_register_new_i3c_devs(master);
1949 	i3c_bus_normaluse_unlock(&master->bus);
1950 }
1951 
1952 /**
1953  * i3c_master_dma_map_single() - Map buffer for single DMA transfer
1954  * @dev: device object of a device doing DMA
1955  * @buf: destination/source buffer for DMA
1956  * @len: length of transfer
1957  * @force_bounce: true, force to use a bounce buffer,
1958  *                false, function will auto check is a bounce buffer required
1959  * @dir: DMA direction
1960  *
1961  * Map buffer for a DMA transfer and allocate a bounce buffer if required.
1962  *
1963  * Return: I3C DMA transfer descriptor or NULL in case of error.
1964  */
1965 struct i3c_dma *i3c_master_dma_map_single(struct device *dev, void *buf,
1966 	size_t len, bool force_bounce, enum dma_data_direction dir)
1967 {
1968 	void *bounce __free(kfree) = NULL;
1969 	void *dma_buf = buf;
1970 
1971 	struct i3c_dma *dma_xfer __free(kfree) = kzalloc_obj(*dma_xfer);
1972 	if (!dma_xfer)
1973 		return NULL;
1974 
1975 	dma_xfer->dev = dev;
1976 	dma_xfer->buf = buf;
1977 	dma_xfer->dir = dir;
1978 	dma_xfer->len = len;
1979 	dma_xfer->map_len = len;
1980 
1981 	if (is_vmalloc_addr(buf))
1982 		force_bounce = true;
1983 
1984 	if (force_bounce) {
1985 		dma_xfer->map_len = ALIGN(len, cache_line_size());
1986 		if (dir == DMA_FROM_DEVICE)
1987 			bounce = kzalloc(dma_xfer->map_len, GFP_KERNEL);
1988 		else
1989 			bounce = kmemdup(buf, dma_xfer->map_len, GFP_KERNEL);
1990 		if (!bounce)
1991 			return NULL;
1992 		dma_buf = bounce;
1993 	}
1994 
1995 	dma_xfer->addr = dma_map_single(dev, dma_buf, dma_xfer->map_len, dir);
1996 	if (dma_mapping_error(dev, dma_xfer->addr))
1997 		return NULL;
1998 
1999 	dma_xfer->bounce_buf = no_free_ptr(bounce);
2000 	return no_free_ptr(dma_xfer);
2001 }
2002 EXPORT_SYMBOL_GPL(i3c_master_dma_map_single);
2003 
2004 /**
2005  * i3c_master_dma_unmap_single() - Unmap buffer after DMA
2006  * @dma_xfer: DMA transfer and mapping descriptor
2007  *
2008  * Unmap buffer and cleanup DMA transfer descriptor.
2009  */
2010 void i3c_master_dma_unmap_single(struct i3c_dma *dma_xfer)
2011 {
2012 	dma_unmap_single(dma_xfer->dev, dma_xfer->addr,
2013 			 dma_xfer->map_len, dma_xfer->dir);
2014 	if (dma_xfer->bounce_buf) {
2015 		if (dma_xfer->dir == DMA_FROM_DEVICE)
2016 			memcpy(dma_xfer->buf, dma_xfer->bounce_buf,
2017 			       dma_xfer->len);
2018 		kfree(dma_xfer->bounce_buf);
2019 	}
2020 	kfree(dma_xfer);
2021 }
2022 EXPORT_SYMBOL_GPL(i3c_master_dma_unmap_single);
2023 
2024 /**
2025  * i3c_master_set_info() - set master device information
2026  * @master: master used to send frames on the bus
2027  * @info: I3C device information
2028  *
2029  * Set master device info. This should be called from
2030  * &i3c_master_controller_ops->bus_init().
2031  *
2032  * Not all &i3c_device_info fields are meaningful for a master device.
2033  * Here is a list of fields that should be properly filled:
2034  *
2035  * - &i3c_device_info->dyn_addr
2036  * - &i3c_device_info->bcr
2037  * - &i3c_device_info->dcr
2038  * - &i3c_device_info->pid
2039  * - &i3c_device_info->hdr_cap if %I3C_BCR_HDR_CAP bit is set in
2040  *   &i3c_device_info->bcr
2041  *
2042  * This function must be called with the bus lock held in maintenance mode.
2043  *
2044  * Return: 0 if @info contains valid information (not every piece of
2045  * information can be checked, but we can at least make sure @info->dyn_addr
2046  * and @info->bcr are correct), -EINVAL otherwise.
2047  */
2048 int i3c_master_set_info(struct i3c_master_controller *master,
2049 			const struct i3c_device_info *info)
2050 {
2051 	struct i3c_dev_desc *i3cdev;
2052 	int ret;
2053 
2054 	if (!i3c_bus_dev_addr_is_avail(&master->bus, info->dyn_addr))
2055 		return -EINVAL;
2056 
2057 	if (I3C_BCR_DEVICE_ROLE(info->bcr) == I3C_BCR_I3C_MASTER &&
2058 	    master->secondary)
2059 		return -EINVAL;
2060 
2061 	if (master->this)
2062 		return -EINVAL;
2063 
2064 	i3cdev = i3c_master_alloc_i3c_dev(master, info);
2065 	if (IS_ERR(i3cdev))
2066 		return PTR_ERR(i3cdev);
2067 
2068 	master->this = i3cdev;
2069 	master->bus.cur_master = master->this;
2070 
2071 	ret = i3c_master_attach_i3c_dev(master, i3cdev);
2072 	if (ret)
2073 		goto err_free_dev;
2074 
2075 	return 0;
2076 
2077 err_free_dev:
2078 	i3c_master_free_i3c_dev(i3cdev);
2079 
2080 	return ret;
2081 }
2082 EXPORT_SYMBOL_GPL(i3c_master_set_info);
2083 
2084 static void i3c_master_detach_free_devs(struct i3c_master_controller *master)
2085 {
2086 	struct i3c_dev_desc *i3cdev, *i3ctmp;
2087 	struct i2c_dev_desc *i2cdev, *i2ctmp;
2088 
2089 	list_for_each_entry_safe(i3cdev, i3ctmp, &master->bus.devs.i3c,
2090 				 common.node) {
2091 		i3c_master_detach_i3c_dev(i3cdev);
2092 
2093 		if (i3cdev->boardinfo && i3cdev->boardinfo->init_dyn_addr)
2094 			i3c_bus_set_addr_slot_status(&master->bus,
2095 					i3cdev->boardinfo->init_dyn_addr,
2096 					I3C_ADDR_SLOT_FREE);
2097 
2098 		i3c_master_free_i3c_dev(i3cdev);
2099 	}
2100 
2101 	list_for_each_entry_safe(i2cdev, i2ctmp, &master->bus.devs.i2c,
2102 				 common.node) {
2103 		i3c_master_detach_i2c_dev(i2cdev);
2104 		i3c_bus_set_addr_slot_status(&master->bus,
2105 					     i2cdev->addr,
2106 					     I3C_ADDR_SLOT_FREE);
2107 		i3c_master_free_i2c_dev(i2cdev);
2108 	}
2109 }
2110 
2111 /**
2112  * i3c_master_bus_init() - initialize an I3C bus
2113  * @master: main master initializing the bus
2114  *
2115  * This function is following all initialisation steps described in the I3C
2116  * specification:
2117  *
2118  * 1. Attach I2C devs to the master so that the master can fill its internal
2119  *    device table appropriately
2120  *
2121  * 2. Call &i3c_master_controller_ops->bus_init() method to initialize
2122  *    the master controller. That's usually where the bus mode is selected
2123  *    (pure bus or mixed fast/slow bus)
2124  *
2125  * 3. Instruct all devices on the bus to drop their dynamic address. This is
2126  *    particularly important when the bus was previously configured by someone
2127  *    else (for example the bootloader)
2128  *
2129  * 4. Disable all slave events.
2130  *
2131  * 5. Reserve address slots for I3C devices with init_dyn_addr. And if devices
2132  *    also have static_addr, try to pre-assign dynamic addresses requested by
2133  *    the FW with SETDASA and attach corresponding statically defined I3C
2134  *    devices to the master.
2135  *
2136  * 6. Do a DAA (Dynamic Address Assignment) to assign dynamic addresses to all
2137  *    remaining I3C devices
2138  *
2139  * Once this is done, all I3C and I2C devices should be usable.
2140  *
2141  * Return: a 0 in case of success, an negative error code otherwise.
2142  */
2143 static int i3c_master_bus_init(struct i3c_master_controller *master)
2144 {
2145 	enum i3c_addr_slot_status status;
2146 	struct i2c_dev_boardinfo *i2cboardinfo;
2147 	struct i3c_dev_boardinfo *i3cboardinfo;
2148 	struct i2c_dev_desc *i2cdev;
2149 	int ret;
2150 
2151 	/*
2152 	 * First attach all devices with static definitions provided by the
2153 	 * FW.
2154 	 */
2155 	list_for_each_entry(i2cboardinfo, &master->boardinfo.i2c, node) {
2156 		status = i3c_bus_get_addr_slot_status(&master->bus,
2157 						      i2cboardinfo->base.addr);
2158 		if (status != I3C_ADDR_SLOT_FREE) {
2159 			ret = -EBUSY;
2160 			goto err_detach_devs;
2161 		}
2162 
2163 		i3c_bus_set_addr_slot_status(&master->bus,
2164 					     i2cboardinfo->base.addr,
2165 					     I3C_ADDR_SLOT_I2C_DEV);
2166 
2167 		i2cdev = i3c_master_alloc_i2c_dev(master,
2168 						  i2cboardinfo->base.addr,
2169 						  i2cboardinfo->lvr);
2170 		if (IS_ERR(i2cdev)) {
2171 			ret = PTR_ERR(i2cdev);
2172 			goto err_detach_devs;
2173 		}
2174 
2175 		ret = i3c_master_attach_i2c_dev(master, i2cdev);
2176 		if (ret) {
2177 			i3c_master_free_i2c_dev(i2cdev);
2178 			goto err_detach_devs;
2179 		}
2180 	}
2181 
2182 	/*
2183 	 * Now execute the controller specific ->bus_init() routine, which
2184 	 * might configure its internal logic to match the bus limitations.
2185 	 */
2186 	ret = master->ops->bus_init(master);
2187 	if (ret)
2188 		goto err_detach_devs;
2189 
2190 	/*
2191 	 * The master device should have been instantiated in ->bus_init(),
2192 	 * complain if this was not the case.
2193 	 */
2194 	if (!master->this) {
2195 		dev_err(&master->dev,
2196 			"master_set_info() was not called in ->bus_init()\n");
2197 		ret = -EINVAL;
2198 		goto err_bus_cleanup;
2199 	}
2200 
2201 	if (master->ops->set_speed) {
2202 		ret = master->ops->set_speed(master, I3C_OPEN_DRAIN_SLOW_SPEED);
2203 		if (ret)
2204 			goto err_bus_cleanup;
2205 	}
2206 
2207 	/*
2208 	 * Reset all dynamic address that may have been assigned before
2209 	 * (assigned by the bootloader for example).
2210 	 */
2211 	ret = i3c_master_rstdaa_locked(master, I3C_BROADCAST_ADDR);
2212 	if (ret)
2213 		goto err_bus_cleanup;
2214 
2215 	if (master->ops->set_speed) {
2216 		ret = master->ops->set_speed(master, I3C_OPEN_DRAIN_NORMAL_SPEED);
2217 		if (ret)
2218 			goto err_bus_cleanup;
2219 	}
2220 
2221 	/*
2222 	 * Disable all slave events before starting DAA. When no active device
2223 	 * is on the bus, returns Mx error code M2, this error is ignored.
2224 	 */
2225 	ret = i3c_master_enec_disec_locked(master, I3C_BROADCAST_ADDR, false,
2226 					   I3C_CCC_EVENT_SIR | I3C_CCC_EVENT_MR |
2227 					   I3C_CCC_EVENT_HJ, true);
2228 	if (ret)
2229 		goto err_bus_cleanup;
2230 
2231 	/*
2232 	 * Reserve init_dyn_addr first, and then try to pre-assign dynamic
2233 	 * address and retrieve device information if needed.
2234 	 * In case pre-assign dynamic address fails, setting dynamic address to
2235 	 * the requested init_dyn_addr is retried after DAA is done in
2236 	 * i3c_master_add_i3c_dev_locked().
2237 	 */
2238 	list_for_each_entry(i3cboardinfo, &master->boardinfo.i3c, node) {
2239 
2240 		/*
2241 		 * We don't reserve a dynamic address for devices that
2242 		 * don't explicitly request one.
2243 		 */
2244 		if (!i3cboardinfo->init_dyn_addr)
2245 			continue;
2246 
2247 		ret = i3c_bus_get_addr_slot_status(&master->bus,
2248 						   i3cboardinfo->init_dyn_addr);
2249 		if (ret != I3C_ADDR_SLOT_FREE) {
2250 			ret = -EBUSY;
2251 			goto err_rstdaa;
2252 		}
2253 
2254 		/* Do not mark as occupied until real device exist in bus */
2255 		i3c_bus_set_addr_slot_status_mask(&master->bus,
2256 						  i3cboardinfo->init_dyn_addr,
2257 						  I3C_ADDR_SLOT_EXT_DESIRED,
2258 						  I3C_ADDR_SLOT_EXT_STATUS_MASK);
2259 
2260 		/*
2261 		 * Only try to create/attach devices that have a static
2262 		 * address. Other devices will be created/attached when
2263 		 * DAA happens, and the requested dynamic address will
2264 		 * be set using SETNEWDA once those devices become
2265 		 * addressable.
2266 		 */
2267 
2268 		if (i3cboardinfo->static_addr)
2269 			i3c_master_early_i3c_dev_add(master, i3cboardinfo);
2270 	}
2271 
2272 	ret = i3c_master_do_daa(master);
2273 	if (ret)
2274 		goto err_rstdaa;
2275 
2276 	return 0;
2277 
2278 err_rstdaa:
2279 	i3c_master_rstdaa_locked(master, I3C_BROADCAST_ADDR);
2280 
2281 err_bus_cleanup:
2282 	if (master->ops->bus_cleanup)
2283 		master->ops->bus_cleanup(master);
2284 
2285 err_detach_devs:
2286 	i3c_master_detach_free_devs(master);
2287 
2288 	return ret;
2289 }
2290 
2291 static void i3c_master_bus_cleanup(struct i3c_master_controller *master)
2292 {
2293 	if (master->ops->bus_cleanup) {
2294 		int ret = i3c_master_rpm_get(master);
2295 
2296 		if (ret) {
2297 			dev_err(&master->dev,
2298 				"runtime resume error: master bus_cleanup() not done\n");
2299 		} else {
2300 			master->ops->bus_cleanup(master);
2301 			i3c_master_rpm_put(master);
2302 		}
2303 	}
2304 
2305 	i3c_master_detach_free_devs(master);
2306 }
2307 
2308 static void i3c_master_attach_boardinfo(struct i3c_dev_desc *i3cdev)
2309 {
2310 	struct i3c_master_controller *master = i3cdev->common.master;
2311 	struct i3c_dev_boardinfo *i3cboardinfo;
2312 
2313 	list_for_each_entry(i3cboardinfo, &master->boardinfo.i3c, node) {
2314 		if (i3cdev->info.pid != i3cboardinfo->pid)
2315 			continue;
2316 
2317 		i3cdev->boardinfo = i3cboardinfo;
2318 		i3cdev->info.static_addr = i3cboardinfo->static_addr;
2319 		return;
2320 	}
2321 }
2322 
2323 static struct i3c_dev_desc *
2324 i3c_master_search_i3c_dev_duplicate(struct i3c_dev_desc *refdev)
2325 {
2326 	struct i3c_master_controller *master = i3c_dev_get_master(refdev);
2327 	struct i3c_dev_desc *i3cdev;
2328 
2329 	i3c_bus_for_each_i3cdev(&master->bus, i3cdev) {
2330 		if (i3cdev != refdev && i3cdev->info.pid == refdev->info.pid)
2331 			return i3cdev;
2332 	}
2333 
2334 	return NULL;
2335 }
2336 
2337 /**
2338  * __i3c_master_add_i3c_dev_locked() - add an I3C slave to the bus
2339  * @master: master used to send frames on the bus
2340  * @addr: I3C slave dynamic address assigned to the device
2341  * @probe: probe to see if the device is really present at @addr
2342  *
2343  * This function instantiates an I3C device object and adds it to the I3C device
2344  * list. All device information is retrieved using standard CCC commands.
2345  *
2346  * This function must be called with the bus lock held in write mode.
2347  */
2348 static void __i3c_master_add_i3c_dev_locked(struct i3c_master_controller *master,
2349 					    u8 addr, bool probe)
2350 {
2351 	struct i3c_device_info info = { .dyn_addr = addr };
2352 	struct i3c_dev_desc *newdev, *olddev;
2353 	u8 old_dyn_addr = addr, expected_dyn_addr;
2354 	struct i3c_ibi_setup ibireq = { };
2355 	bool enable_ibi = false;
2356 	bool no_dev = false;
2357 	int ret;
2358 
2359 	newdev = i3c_master_alloc_i3c_dev(master, &info);
2360 	if (IS_ERR(newdev)) {
2361 		ret = PTR_ERR(newdev);
2362 		goto err_prevent_addr_reuse;
2363 	}
2364 
2365 	ret = i3c_master_attach_i3c_dev(master, newdev);
2366 	if (ret)
2367 		goto err_free_dev;
2368 
2369 	/*
2370 	 * When a dynamic address is first assigned, there is no need to check
2371 	 * whether it is still assigned, however, if adding the device fails,
2372 	 * it will be attempted again later, at which point the address may
2373 	 * have been lost (e.g. due to power management), so for that case,
2374 	 * probe to see if the device is still present at the assigned address.
2375 	 */
2376 	if (probe && !i3c_master_i3c_dev_present(master, addr)) {
2377 		no_dev = true;
2378 		goto err_detach_dev;
2379 	}
2380 
2381 	ret = i3c_master_retrieve_dev_info(newdev);
2382 	if (ret)
2383 		goto err_detach_dev;
2384 
2385 	i3c_master_attach_boardinfo(newdev);
2386 
2387 	olddev = i3c_master_search_i3c_dev_duplicate(newdev);
2388 	if (olddev) {
2389 		newdev->dev = olddev->dev;
2390 		if (newdev->dev)
2391 			newdev->dev->desc = newdev;
2392 
2393 		/*
2394 		 * We need to restore the IBI state too, so let's save the
2395 		 * IBI information and try to restore them after olddev has
2396 		 * been detached+released and its IBI has been stopped and
2397 		 * the associated resources have been freed.
2398 		 */
2399 		mutex_lock(&olddev->ibi_lock);
2400 		if (olddev->ibi) {
2401 			ibireq.handler = olddev->ibi->handler;
2402 			ibireq.max_payload_len = olddev->ibi->max_payload_len;
2403 			ibireq.num_slots = olddev->ibi->num_slots;
2404 
2405 			if (olddev->ibi->enabled)
2406 				enable_ibi = true;
2407 			/*
2408 			 * The olddev should not receive any commands on the
2409 			 * i3c bus as it does not exist and has been assigned
2410 			 * a new address. This will result in NACK or timeout.
2411 			 * So, update the olddev->ibi->enabled flag to false
2412 			 * to avoid DISEC with OldAddr.
2413 			 */
2414 			olddev->ibi->enabled = false;
2415 			i3c_dev_free_ibi_locked(olddev);
2416 		}
2417 		mutex_unlock(&olddev->ibi_lock);
2418 
2419 		old_dyn_addr = olddev->info.dyn_addr;
2420 
2421 		i3c_master_detach_i3c_dev(olddev);
2422 		i3c_master_free_i3c_dev(olddev);
2423 	}
2424 
2425 	/*
2426 	 * Depending on our previous state, the expected dynamic address might
2427 	 * differ:
2428 	 * - if the device already had a dynamic address assigned, let's try to
2429 	 *   re-apply this one
2430 	 * - if the device did not have a dynamic address and the firmware
2431 	 *   requested a specific address, pick this one
2432 	 * - in any other case, keep the address automatically assigned by the
2433 	 *   master
2434 	 */
2435 	if (old_dyn_addr && old_dyn_addr != newdev->info.dyn_addr)
2436 		expected_dyn_addr = old_dyn_addr;
2437 	else if (newdev->boardinfo && newdev->boardinfo->init_dyn_addr)
2438 		expected_dyn_addr = newdev->boardinfo->init_dyn_addr;
2439 	else
2440 		expected_dyn_addr = newdev->info.dyn_addr;
2441 
2442 	if (newdev->info.dyn_addr != expected_dyn_addr &&
2443 	    i3c_bus_get_addr_slot_status(&master->bus, expected_dyn_addr) == I3C_ADDR_SLOT_FREE) {
2444 		/*
2445 		 * Try to apply the expected dynamic address. If it fails, keep
2446 		 * the address assigned by the master.
2447 		 */
2448 		ret = i3c_master_setnewda_locked(master,
2449 						 newdev->info.dyn_addr,
2450 						 expected_dyn_addr);
2451 		if (!ret) {
2452 			old_dyn_addr = newdev->info.dyn_addr;
2453 			newdev->info.dyn_addr = expected_dyn_addr;
2454 			i3c_master_reattach_i3c_dev_locked(newdev, old_dyn_addr);
2455 		} else {
2456 			dev_err(&master->dev,
2457 				"Failed to assign reserved/old address to device %d%llx",
2458 				master->bus.id, newdev->info.pid);
2459 		}
2460 	}
2461 
2462 	/*
2463 	 * Now is time to try to restore the IBI setup. If we're lucky,
2464 	 * everything works as before, otherwise, all we can do is complain.
2465 	 * FIXME: maybe we should add callback to inform the driver that it
2466 	 * should request the IBI again instead of trying to hide that from
2467 	 * him.
2468 	 */
2469 	if (ibireq.handler) {
2470 		mutex_lock(&newdev->ibi_lock);
2471 		ret = i3c_dev_request_ibi_locked(newdev, &ibireq);
2472 		if (ret) {
2473 			dev_err(&master->dev,
2474 				"Failed to request IBI on device %d-%llx",
2475 				master->bus.id, newdev->info.pid);
2476 		} else if (enable_ibi) {
2477 			ret = i3c_dev_enable_ibi_locked(newdev);
2478 			if (ret)
2479 				dev_err(&master->dev,
2480 					"Failed to re-enable IBI on device %d-%llx",
2481 					master->bus.id, newdev->info.pid);
2482 		}
2483 		mutex_unlock(&newdev->ibi_lock);
2484 	}
2485 
2486 	return;
2487 
2488 err_detach_dev:
2489 	if (newdev->dev && newdev->dev->desc)
2490 		newdev->dev->desc = NULL;
2491 
2492 	i3c_master_detach_i3c_dev(newdev);
2493 
2494 err_free_dev:
2495 	i3c_master_free_i3c_dev(newdev);
2496 
2497 err_prevent_addr_reuse:
2498 	if (no_dev)
2499 		return;
2500 	/*
2501 	 * Although the device has not been added, the address has been
2502 	 * assigned. Prevent the address from being used again.
2503 	 */
2504 	if (i3c_bus_get_addr_slot_status(&master->bus, addr) == I3C_ADDR_SLOT_FREE)
2505 		i3c_bus_set_addr_slot_status(&master->bus, addr, I3C_ADDR_SLOT_I3C_DEV);
2506 
2507 	dev_err(&master->dev, "Failed to add I3C device at address %u, error %d\n", addr, ret);
2508 }
2509 
2510 /**
2511  * i3c_master_add_i3c_dev_locked() - add an I3C slave to the bus
2512  * @master: master used to send frames on the bus
2513  * @addr: I3C slave dynamic address assigned to the device
2514  *
2515  * This function instantiates an I3C device object and adds it to the
2516  * I3C device list. All device information is automatically retrieved using
2517  * standard CCC commands.
2518  *
2519  * This function must be called with the bus lock held in write mode.
2520  */
2521 void i3c_master_add_i3c_dev_locked(struct i3c_master_controller *master, u8 addr)
2522 {
2523 	__i3c_master_add_i3c_dev_locked(master, addr, false);
2524 }
2525 EXPORT_SYMBOL_GPL(i3c_master_add_i3c_dev_locked);
2526 
2527 static void i3c_master_reconcile_dyn_addrs(struct i3c_master_controller *master)
2528 {
2529 	DECLARE_BITMAP(dev_dyn_addrs, I2C_MAX_ADDR + 1);
2530 	enum i3c_addr_slot_status status;
2531 	struct i3c_dev_desc *desc;
2532 
2533 	/* Mark all devices' dynamic and static addresses in the bitmap */
2534 	bitmap_zero(dev_dyn_addrs, I2C_MAX_ADDR + 1);
2535 	i3c_bus_for_each_i3cdev(&master->bus, desc) {
2536 		if (desc->info.static_addr)
2537 			__set_bit(desc->info.static_addr, dev_dyn_addrs);
2538 		__set_bit(desc->info.dyn_addr, dev_dyn_addrs);
2539 	}
2540 	/* Reconcile the bitmap with the bus address slot status */
2541 	for (unsigned int addr = 0; addr <= I2C_MAX_ADDR; addr++) {
2542 		status = i3c_bus_get_addr_slot_status(&master->bus, addr);
2543 		if (status != I3C_ADDR_SLOT_I3C_DEV || test_bit(addr, dev_dyn_addrs))
2544 			continue;
2545 		i3c_bus_set_addr_slot_status(&master->bus, addr, I3C_ADDR_SLOT_FREE);
2546 		/* Try to add the device, but probe to see if it is really present */
2547 		__i3c_master_add_i3c_dev_locked(master, addr, true);
2548 	}
2549 }
2550 
2551 /**
2552  * i3c_master_do_daa_ext() - Dynamic Address Assignment (extended version)
2553  * @master: controller
2554  * @rstdaa: whether to first perform Reset of Dynamic Addresses (RSTDAA)
2555  *
2556  * Perform Dynamic Address Assignment with optional support for System
2557  * Hibernation (@rstdaa is true).
2558  *
2559  * After System Hibernation, Dynamic Addresses can have been reassigned at boot
2560  * time to different values. A simple strategy is followed to handle that.
2561  * Perform a Reset of Dynamic Addresses (RSTDAA) followed by the normal DAA
2562  * procedure which has provision for reassigning addresses that differ from the
2563  * previously recorded addresses.
2564  *
2565  * Return: a 0 in case of success, an negative error code otherwise.
2566  */
2567 int i3c_master_do_daa_ext(struct i3c_master_controller *master, bool rstdaa)
2568 {
2569 	int rstret = 0;
2570 	int ret;
2571 
2572 	ret = i3c_master_rpm_get(master);
2573 	if (ret)
2574 		return ret;
2575 
2576 	i3c_bus_maintenance_lock(&master->bus);
2577 
2578 	if (master->shutting_down) {
2579 		ret = -ENODEV;
2580 	} else {
2581 		if (rstdaa)
2582 			rstret = i3c_master_rstdaa_locked(master, I3C_BROADCAST_ADDR);
2583 		ret = master->ops->do_daa(master);
2584 		/*
2585 		 * Handle cases where a dynamic address was assigned but the
2586 		 * device was not successfully added.
2587 		 */
2588 		i3c_master_reconcile_dyn_addrs(master);
2589 	}
2590 
2591 	i3c_bus_maintenance_unlock(&master->bus);
2592 
2593 	if (ret)
2594 		goto out;
2595 
2596 	queue_work(master->wq, &master->reg_work);
2597 out:
2598 	i3c_master_rpm_put(master);
2599 
2600 	return rstret ?: ret;
2601 }
2602 EXPORT_SYMBOL_GPL(i3c_master_do_daa_ext);
2603 
2604 /**
2605  * i3c_master_do_daa() - do a DAA (Dynamic Address Assignment)
2606  * @master: master doing the DAA
2607  *
2608  * This function instantiates I3C device objects and adds them to the
2609  * I3C device list. All device information is automatically retrieved using
2610  * standard CCC commands.
2611  *
2612  * Return: a 0 in case of success, an negative error code otherwise.
2613  */
2614 int i3c_master_do_daa(struct i3c_master_controller *master)
2615 {
2616 	return i3c_master_do_daa_ext(master, false);
2617 }
2618 EXPORT_SYMBOL_GPL(i3c_master_do_daa);
2619 
2620 #define OF_I3C_REG1_IS_I2C_DEV			BIT(31)
2621 
2622 static int
2623 of_i3c_master_add_i2c_boardinfo(struct i3c_master_controller *master,
2624 				struct device_node *node, u32 *reg)
2625 {
2626 	struct i2c_dev_boardinfo *boardinfo;
2627 	struct device *dev = &master->dev;
2628 	int ret;
2629 
2630 	boardinfo = devm_kzalloc(dev, sizeof(*boardinfo), GFP_KERNEL);
2631 	if (!boardinfo)
2632 		return -ENOMEM;
2633 
2634 	ret = of_i2c_get_board_info(dev, node, &boardinfo->base);
2635 	if (ret)
2636 		return ret;
2637 
2638 	/*
2639 	 * The I3C Specification does not clearly say I2C devices with 10-bit
2640 	 * address are supported. These devices can't be passed properly through
2641 	 * DEFSLVS command.
2642 	 */
2643 	if (boardinfo->base.flags & I2C_CLIENT_TEN) {
2644 		dev_err(dev, "I2C device with 10 bit address not supported.\n");
2645 		return -EOPNOTSUPP;
2646 	}
2647 
2648 	/* LVR is encoded in reg[2]. */
2649 	boardinfo->lvr = reg[2];
2650 
2651 	list_add_tail(&boardinfo->node, &master->boardinfo.i2c);
2652 	of_node_get(node);
2653 
2654 	return 0;
2655 }
2656 
2657 static int
2658 of_i3c_master_add_i3c_boardinfo(struct i3c_master_controller *master,
2659 				struct device_node *node, u32 *reg)
2660 {
2661 	struct i3c_dev_boardinfo *boardinfo;
2662 	struct device *dev = &master->dev;
2663 	enum i3c_addr_slot_status addrstatus;
2664 	u32 init_dyn_addr = 0;
2665 
2666 	boardinfo = devm_kzalloc(dev, sizeof(*boardinfo), GFP_KERNEL);
2667 	if (!boardinfo)
2668 		return -ENOMEM;
2669 
2670 	if (reg[0]) {
2671 		if (reg[0] > I3C_MAX_ADDR)
2672 			return -EINVAL;
2673 
2674 		addrstatus = i3c_bus_get_addr_slot_status(&master->bus,
2675 							  reg[0]);
2676 		if (addrstatus != I3C_ADDR_SLOT_FREE)
2677 			return -EINVAL;
2678 	}
2679 
2680 	boardinfo->static_addr = reg[0];
2681 
2682 	if (!of_property_read_u32(node, "assigned-address", &init_dyn_addr)) {
2683 		if (init_dyn_addr > I3C_MAX_ADDR)
2684 			return -EINVAL;
2685 
2686 		addrstatus = i3c_bus_get_addr_slot_status(&master->bus,
2687 							  init_dyn_addr);
2688 		if (addrstatus != I3C_ADDR_SLOT_FREE)
2689 			return -EINVAL;
2690 	}
2691 
2692 	boardinfo->pid = ((u64)reg[1] << 32) | reg[2];
2693 
2694 	if ((boardinfo->pid & GENMASK_ULL(63, 48)) ||
2695 	    I3C_PID_RND_LOWER_32BITS(boardinfo->pid))
2696 		return -EINVAL;
2697 
2698 	boardinfo->init_dyn_addr = init_dyn_addr;
2699 	boardinfo->of_node = of_node_get(node);
2700 	list_add_tail(&boardinfo->node, &master->boardinfo.i3c);
2701 
2702 	return 0;
2703 }
2704 
2705 static int of_i3c_master_add_dev(struct i3c_master_controller *master,
2706 				 struct device_node *node)
2707 {
2708 	u32 reg[3];
2709 	int ret;
2710 
2711 	if (!master)
2712 		return -EINVAL;
2713 
2714 	ret = of_property_read_u32_array(node, "reg", reg, ARRAY_SIZE(reg));
2715 	if (ret)
2716 		return ret;
2717 
2718 	/*
2719 	 * The manufacturer ID can't be 0. If reg[1] == 0 that means we're
2720 	 * dealing with an I2C device.
2721 	 */
2722 	if (!reg[1])
2723 		ret = of_i3c_master_add_i2c_boardinfo(master, node, reg);
2724 	else
2725 		ret = of_i3c_master_add_i3c_boardinfo(master, node, reg);
2726 
2727 	return ret;
2728 }
2729 
2730 static int of_populate_i3c_bus(struct i3c_master_controller *master)
2731 {
2732 	struct device *dev = &master->dev;
2733 	struct device_node *i3cbus_np = dev->of_node;
2734 	int ret;
2735 	u32 val;
2736 
2737 	if (!i3cbus_np)
2738 		return 0;
2739 
2740 	for_each_available_child_of_node_scoped(i3cbus_np, node) {
2741 		ret = of_i3c_master_add_dev(master, node);
2742 		if (ret)
2743 			return ret;
2744 	}
2745 
2746 	/*
2747 	 * The user might want to limit I2C and I3C speed in case some devices
2748 	 * on the bus are not supporting typical rates, or if the bus topology
2749 	 * prevents it from using max possible rate.
2750 	 */
2751 	if (!of_property_read_u32(i3cbus_np, "i2c-scl-hz", &val))
2752 		master->bus.scl_rate.i2c = val;
2753 
2754 	if (!of_property_read_u32(i3cbus_np, "i3c-scl-hz", &val))
2755 		master->bus.scl_rate.i3c = val;
2756 
2757 	return 0;
2758 }
2759 
2760 static int i3c_master_i2c_adapter_xfer(struct i2c_adapter *adap,
2761 				       struct i2c_msg *xfers, int nxfers)
2762 {
2763 	struct i3c_master_controller *master = i2c_adapter_to_i3c_master(adap);
2764 	struct i2c_dev_desc *dev;
2765 	int i, ret;
2766 	u16 addr;
2767 
2768 	if (!xfers || !master || nxfers <= 0)
2769 		return -EINVAL;
2770 
2771 	if (!master->ops->i2c_xfers)
2772 		return -EOPNOTSUPP;
2773 
2774 	/* Doing transfers to different devices is not supported. */
2775 	addr = xfers[0].addr;
2776 	for (i = 1; i < nxfers; i++) {
2777 		if (addr != xfers[i].addr)
2778 			return -EOPNOTSUPP;
2779 	}
2780 
2781 	ret = i3c_master_rpm_get(master);
2782 	if (ret)
2783 		return ret;
2784 
2785 	i3c_bus_normaluse_lock(&master->bus);
2786 	dev = i3c_master_find_i2c_dev_by_addr(master, addr);
2787 	if (!dev)
2788 		ret = -ENOENT;
2789 	else
2790 		ret = master->ops->i2c_xfers(dev, xfers, nxfers);
2791 	i3c_bus_normaluse_unlock(&master->bus);
2792 
2793 	i3c_master_rpm_put(master);
2794 
2795 	return ret ? ret : nxfers;
2796 }
2797 
2798 static u32 i3c_master_i2c_funcs(struct i2c_adapter *adapter)
2799 {
2800 	return I2C_FUNC_SMBUS_EMUL | I2C_FUNC_I2C;
2801 }
2802 
2803 static u8 i3c_master_i2c_get_lvr(struct i2c_client *client)
2804 {
2805 	/* Fall back to no spike filters and FM bus mode. */
2806 	u8 lvr = I3C_LVR_I2C_INDEX(2) | I3C_LVR_I2C_FM_MODE;
2807 	u32 reg[3];
2808 
2809 	if (!of_property_read_u32_array(client->dev.of_node, "reg", reg, ARRAY_SIZE(reg)))
2810 		lvr = reg[2];
2811 
2812 	return lvr;
2813 }
2814 
2815 static int i3c_master_i2c_attach(struct i2c_adapter *adap, struct i2c_client *client)
2816 {
2817 	struct i3c_master_controller *master = i2c_adapter_to_i3c_master(adap);
2818 	enum i3c_addr_slot_status status;
2819 	struct i2c_dev_desc *i2cdev;
2820 	int ret;
2821 
2822 	/* Already added by board info? */
2823 	if (i3c_master_find_i2c_dev_by_addr(master, client->addr))
2824 		return 0;
2825 
2826 	status = i3c_bus_get_addr_slot_status(&master->bus, client->addr);
2827 	if (status != I3C_ADDR_SLOT_FREE)
2828 		return -EBUSY;
2829 
2830 	i3c_bus_set_addr_slot_status(&master->bus, client->addr,
2831 				     I3C_ADDR_SLOT_I2C_DEV);
2832 
2833 	i2cdev = i3c_master_alloc_i2c_dev(master, client->addr,
2834 					  i3c_master_i2c_get_lvr(client));
2835 	if (IS_ERR(i2cdev)) {
2836 		ret = PTR_ERR(i2cdev);
2837 		goto out_clear_status;
2838 	}
2839 
2840 	ret = i3c_master_attach_i2c_dev(master, i2cdev);
2841 	if (ret)
2842 		goto out_free_dev;
2843 
2844 	return 0;
2845 
2846 out_free_dev:
2847 	i3c_master_free_i2c_dev(i2cdev);
2848 out_clear_status:
2849 	i3c_bus_set_addr_slot_status(&master->bus, client->addr,
2850 				     I3C_ADDR_SLOT_FREE);
2851 
2852 	return ret;
2853 }
2854 
2855 static int i3c_master_i2c_detach(struct i2c_adapter *adap, struct i2c_client *client)
2856 {
2857 	struct i3c_master_controller *master = i2c_adapter_to_i3c_master(adap);
2858 	struct i2c_dev_desc *dev;
2859 
2860 	dev = i3c_master_find_i2c_dev_by_addr(master, client->addr);
2861 	if (!dev)
2862 		return -ENODEV;
2863 
2864 	i3c_master_detach_i2c_dev(dev);
2865 	i3c_bus_set_addr_slot_status(&master->bus, dev->addr,
2866 				     I3C_ADDR_SLOT_FREE);
2867 	i3c_master_free_i2c_dev(dev);
2868 
2869 	return 0;
2870 }
2871 
2872 static const struct i2c_algorithm i3c_master_i2c_algo = {
2873 	.master_xfer = i3c_master_i2c_adapter_xfer,
2874 	.functionality = i3c_master_i2c_funcs,
2875 };
2876 
2877 static int i3c_i2c_notifier_call(struct notifier_block *nb, unsigned long action,
2878 				 void *data)
2879 {
2880 	struct i2c_adapter *adap;
2881 	struct i2c_client *client;
2882 	struct device *dev = data;
2883 	struct i3c_master_controller *master;
2884 	int ret;
2885 
2886 	if (dev->type != &i2c_client_type)
2887 		return 0;
2888 
2889 	client = to_i2c_client(dev);
2890 	adap = client->adapter;
2891 
2892 	if (adap->algo != &i3c_master_i2c_algo)
2893 		return 0;
2894 
2895 	master = i2c_adapter_to_i3c_master(adap);
2896 
2897 	ret = i3c_master_rpm_get(master);
2898 	if (ret)
2899 		return ret;
2900 
2901 	i3c_bus_maintenance_lock(&master->bus);
2902 	switch (action) {
2903 	case BUS_NOTIFY_ADD_DEVICE:
2904 		ret = i3c_master_i2c_attach(adap, client);
2905 		break;
2906 	case BUS_NOTIFY_DEL_DEVICE:
2907 		ret = i3c_master_i2c_detach(adap, client);
2908 		break;
2909 	default:
2910 		ret = -EINVAL;
2911 	}
2912 	i3c_bus_maintenance_unlock(&master->bus);
2913 
2914 	i3c_master_rpm_put(master);
2915 
2916 	return ret;
2917 }
2918 
2919 static struct notifier_block i2cdev_notifier = {
2920 	.notifier_call = i3c_i2c_notifier_call,
2921 };
2922 
2923 static int i3c_master_i2c_adapter_init(struct i3c_master_controller *master)
2924 {
2925 	struct i2c_adapter *adap = i3c_master_to_i2c_adapter(master);
2926 	struct i2c_dev_desc *i2cdev;
2927 	struct i2c_dev_boardinfo *i2cboardinfo;
2928 	int ret, id;
2929 
2930 	adap->dev.parent = master->dev.parent;
2931 	adap->owner = master->dev.parent->driver->owner;
2932 	adap->algo = &i3c_master_i2c_algo;
2933 	strscpy(adap->name, dev_name(master->dev.parent), sizeof(adap->name));
2934 	adap->timeout = HZ;
2935 	adap->retries = 3;
2936 
2937 	id = of_alias_get_id(master->dev.of_node, "i2c");
2938 	if (id >= 0) {
2939 		adap->nr = id;
2940 		ret = i2c_add_numbered_adapter(adap);
2941 	} else {
2942 		ret = i2c_add_adapter(adap);
2943 	}
2944 	if (ret)
2945 		return ret;
2946 
2947 	/*
2948 	 * We silently ignore failures here. The bus should keep working
2949 	 * correctly even if one or more i2c devices are not registered.
2950 	 */
2951 	list_for_each_entry(i2cboardinfo, &master->boardinfo.i2c, node) {
2952 		i2cdev = i3c_master_find_i2c_dev_by_addr(master,
2953 							 i2cboardinfo->base.addr);
2954 		if (WARN_ON(!i2cdev))
2955 			continue;
2956 		i2cdev->dev = i2c_new_client_device(adap, &i2cboardinfo->base);
2957 	}
2958 
2959 	return 0;
2960 }
2961 
2962 static void i3c_master_i2c_adapter_cleanup(struct i3c_master_controller *master)
2963 {
2964 	struct i2c_dev_desc *i2cdev;
2965 
2966 	i2c_del_adapter(&master->i2c);
2967 
2968 	i3c_bus_for_each_i2cdev(&master->bus, i2cdev)
2969 		i2cdev->dev = NULL;
2970 }
2971 
2972 static void i3c_master_unregister_i3c_devs(struct i3c_master_controller *master)
2973 {
2974 	struct i3c_dev_desc *i3cdev;
2975 
2976 	i3c_bus_for_each_i3cdev(&master->bus, i3cdev) {
2977 		if (!i3cdev->dev)
2978 			continue;
2979 
2980 		i3cdev->dev->desc = NULL;
2981 		if (device_is_registered(&i3cdev->dev->dev))
2982 			device_unregister(&i3cdev->dev->dev);
2983 		else
2984 			put_device(&i3cdev->dev->dev);
2985 		i3cdev->dev = NULL;
2986 	}
2987 }
2988 
2989 /**
2990  * i3c_master_queue_ibi() - Queue an IBI
2991  * @dev: the device this IBI is coming from
2992  * @slot: the IBI slot used to store the payload
2993  *
2994  * Queue an IBI to the controller workqueue. The IBI handler attached to
2995  * the dev will be called from a workqueue context.
2996  */
2997 void i3c_master_queue_ibi(struct i3c_dev_desc *dev, struct i3c_ibi_slot *slot)
2998 {
2999 	if (!dev->ibi || !slot)
3000 		return;
3001 
3002 	atomic_inc(&dev->ibi->pending_ibis);
3003 	queue_work(dev->ibi->wq, &slot->work);
3004 }
3005 EXPORT_SYMBOL_GPL(i3c_master_queue_ibi);
3006 
3007 static void i3c_master_handle_ibi(struct work_struct *work)
3008 {
3009 	struct i3c_ibi_slot *slot = container_of(work, struct i3c_ibi_slot,
3010 						 work);
3011 	struct i3c_dev_desc *dev = slot->dev;
3012 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
3013 	struct i3c_ibi_payload payload;
3014 
3015 	payload.data = slot->data;
3016 	payload.len = slot->len;
3017 
3018 	if (dev->dev)
3019 		dev->ibi->handler(dev->dev, &payload);
3020 
3021 	master->ops->recycle_ibi_slot(dev, slot);
3022 	if (atomic_dec_and_test(&dev->ibi->pending_ibis))
3023 		complete(&dev->ibi->all_ibis_handled);
3024 }
3025 
3026 static void i3c_master_init_ibi_slot(struct i3c_dev_desc *dev,
3027 				     struct i3c_ibi_slot *slot)
3028 {
3029 	slot->dev = dev;
3030 	INIT_WORK(&slot->work, i3c_master_handle_ibi);
3031 }
3032 
3033 struct i3c_generic_ibi_slot {
3034 	struct list_head node;
3035 	struct i3c_ibi_slot base;
3036 };
3037 
3038 struct i3c_generic_ibi_pool {
3039 	spinlock_t lock;
3040 	unsigned int num_slots;
3041 	void *payload_buf;
3042 	struct list_head free_slots;
3043 	struct list_head pending;
3044 	struct i3c_generic_ibi_slot slots[] __counted_by(num_slots);
3045 };
3046 
3047 /**
3048  * i3c_generic_ibi_free_pool() - Free a generic IBI pool
3049  * @pool: the IBI pool to free
3050  *
3051  * Free all IBI slots allated by a generic IBI pool.
3052  */
3053 void i3c_generic_ibi_free_pool(struct i3c_generic_ibi_pool *pool)
3054 {
3055 	struct i3c_generic_ibi_slot *slot;
3056 	unsigned int nslots = 0;
3057 
3058 	while (!list_empty(&pool->free_slots)) {
3059 		slot = list_first_entry(&pool->free_slots,
3060 					struct i3c_generic_ibi_slot, node);
3061 		list_del(&slot->node);
3062 		nslots++;
3063 	}
3064 
3065 	/*
3066 	 * If the number of freed slots is not equal to the number of allocated
3067 	 * slots we have a leak somewhere.
3068 	 */
3069 	WARN_ON(nslots != pool->num_slots);
3070 
3071 	kfree(pool->payload_buf);
3072 	kfree(pool);
3073 }
3074 EXPORT_SYMBOL_GPL(i3c_generic_ibi_free_pool);
3075 
3076 /**
3077  * i3c_generic_ibi_alloc_pool() - Create a generic IBI pool
3078  * @dev: the device this pool will be used for
3079  * @req: IBI setup request describing what the device driver expects
3080  *
3081  * Create a generic IBI pool based on the information provided in @req.
3082  *
3083  * Return: a valid IBI pool in case of success, an ERR_PTR() otherwise.
3084  */
3085 struct i3c_generic_ibi_pool *
3086 i3c_generic_ibi_alloc_pool(struct i3c_dev_desc *dev,
3087 			   const struct i3c_ibi_setup *req)
3088 {
3089 	struct i3c_generic_ibi_pool *pool;
3090 	struct i3c_generic_ibi_slot *slot;
3091 	unsigned int i;
3092 	int ret;
3093 
3094 	pool = kzalloc_flex(*pool, slots, req->num_slots);
3095 	if (!pool)
3096 		return ERR_PTR(-ENOMEM);
3097 
3098 	pool->num_slots = req->num_slots;
3099 
3100 	spin_lock_init(&pool->lock);
3101 	INIT_LIST_HEAD(&pool->free_slots);
3102 	INIT_LIST_HEAD(&pool->pending);
3103 
3104 	if (req->max_payload_len) {
3105 		pool->payload_buf = kcalloc(req->num_slots,
3106 					    req->max_payload_len, GFP_KERNEL);
3107 		if (!pool->payload_buf) {
3108 			ret = -ENOMEM;
3109 			goto err_free_pool;
3110 		}
3111 	}
3112 
3113 	for (i = 0; i < req->num_slots; i++) {
3114 		slot = &pool->slots[i];
3115 		i3c_master_init_ibi_slot(dev, &slot->base);
3116 
3117 		if (req->max_payload_len)
3118 			slot->base.data = pool->payload_buf +
3119 					  (i * req->max_payload_len);
3120 
3121 		list_add_tail(&slot->node, &pool->free_slots);
3122 	}
3123 
3124 	return pool;
3125 
3126 err_free_pool:
3127 	i3c_generic_ibi_free_pool(pool);
3128 	return ERR_PTR(ret);
3129 }
3130 EXPORT_SYMBOL_GPL(i3c_generic_ibi_alloc_pool);
3131 
3132 /**
3133  * i3c_generic_ibi_get_free_slot() - Get a free slot from a generic IBI pool
3134  * @pool: the pool to query an IBI slot on
3135  *
3136  * Search for a free slot in a generic IBI pool.
3137  * The slot should be returned to the pool using i3c_generic_ibi_recycle_slot()
3138  * when it's no longer needed.
3139  *
3140  * Return: a pointer to a free slot, or NULL if there's no free slot available.
3141  */
3142 struct i3c_ibi_slot *
3143 i3c_generic_ibi_get_free_slot(struct i3c_generic_ibi_pool *pool)
3144 {
3145 	struct i3c_generic_ibi_slot *slot;
3146 	unsigned long flags;
3147 
3148 	spin_lock_irqsave(&pool->lock, flags);
3149 	slot = list_first_entry_or_null(&pool->free_slots,
3150 					struct i3c_generic_ibi_slot, node);
3151 	if (slot)
3152 		list_del(&slot->node);
3153 	spin_unlock_irqrestore(&pool->lock, flags);
3154 
3155 	return slot ? &slot->base : NULL;
3156 }
3157 EXPORT_SYMBOL_GPL(i3c_generic_ibi_get_free_slot);
3158 
3159 /**
3160  * i3c_generic_ibi_recycle_slot() - Return a slot to a generic IBI pool
3161  * @pool: the pool to return the IBI slot to
3162  * @s: IBI slot to recycle
3163  *
3164  * Add an IBI slot back to its generic IBI pool. Should be called from the
3165  * master driver struct_master_controller_ops->recycle_ibi() method.
3166  */
3167 void i3c_generic_ibi_recycle_slot(struct i3c_generic_ibi_pool *pool,
3168 				  struct i3c_ibi_slot *s)
3169 {
3170 	struct i3c_generic_ibi_slot *slot;
3171 	unsigned long flags;
3172 
3173 	if (!s)
3174 		return;
3175 
3176 	slot = container_of(s, struct i3c_generic_ibi_slot, base);
3177 	spin_lock_irqsave(&pool->lock, flags);
3178 	list_add_tail(&slot->node, &pool->free_slots);
3179 	spin_unlock_irqrestore(&pool->lock, flags);
3180 }
3181 EXPORT_SYMBOL_GPL(i3c_generic_ibi_recycle_slot);
3182 
3183 static int i3c_master_check_ops(const struct i3c_master_controller_ops *ops)
3184 {
3185 	if (!ops || !ops->bus_init || !ops->i3c_xfers ||
3186 	    !ops->send_ccc_cmd || !ops->do_daa || !ops->i2c_xfers)
3187 		return -EINVAL;
3188 
3189 	if (ops->request_ibi &&
3190 	    (!ops->enable_ibi || !ops->disable_ibi || !ops->free_ibi ||
3191 	     !ops->recycle_ibi_slot))
3192 		return -EINVAL;
3193 
3194 	return 0;
3195 }
3196 
3197 /**
3198  * i3c_master_register() - register an I3C master
3199  * @master: master used to send frames on the bus
3200  * @parent: the parent device (the one that provides this I3C master
3201  *	    controller)
3202  * @ops: the master controller operations
3203  * @secondary: true if you are registering a secondary master. Will return
3204  *	       -EOPNOTSUPP if set to true since secondary masters are not yet
3205  *	       supported
3206  *
3207  * This function takes care of everything for you:
3208  *
3209  * - creates and initializes the I3C bus
3210  * - populates the bus with static I2C devs if @parent->of_node is not
3211  *   NULL
3212  * - registers all I3C devices added by the controller during bus
3213  *   initialization
3214  * - registers the I2C adapter and all I2C devices
3215  *
3216  * Return: 0 in case of success, a negative error code otherwise.
3217  */
3218 int i3c_master_register(struct i3c_master_controller *master,
3219 			struct device *parent,
3220 			const struct i3c_master_controller_ops *ops,
3221 			bool secondary)
3222 {
3223 	unsigned long i2c_scl_rate = I3C_BUS_I2C_FM_PLUS_SCL_MAX_RATE;
3224 	struct i3c_bus *i3cbus = i3c_master_get_bus(master);
3225 	enum i3c_bus_mode mode = I3C_BUS_MODE_PURE;
3226 	struct i2c_dev_boardinfo *i2cbi;
3227 	int ret;
3228 
3229 	/* We do not support secondary masters yet. */
3230 	if (secondary)
3231 		return -EOPNOTSUPP;
3232 
3233 	ret = i3c_master_check_ops(ops);
3234 	if (ret)
3235 		return ret;
3236 
3237 	master->dev.parent = parent;
3238 	master->dev.of_node = of_node_get(parent->of_node);
3239 	master->dev.bus = &i3c_bus_type;
3240 	master->dev.type = &i3c_masterdev_type;
3241 	master->dev.release = i3c_masterdev_release;
3242 	master->ops = ops;
3243 	master->secondary = secondary;
3244 	INIT_LIST_HEAD(&master->boardinfo.i2c);
3245 	INIT_LIST_HEAD(&master->boardinfo.i3c);
3246 
3247 	ret = i3c_master_rpm_get(master);
3248 	if (ret)
3249 		return ret;
3250 
3251 	device_initialize(&master->dev);
3252 
3253 	master->dev.dma_mask = parent->dma_mask;
3254 	master->dev.coherent_dma_mask = parent->coherent_dma_mask;
3255 	master->dev.dma_parms = parent->dma_parms;
3256 
3257 	ret = i3c_bus_init(i3cbus, master->dev.of_node);
3258 	if (ret)
3259 		goto err_put_dev;
3260 
3261 	dev_set_name(&master->dev, "i3c-%d", i3cbus->id);
3262 
3263 	ret = of_populate_i3c_bus(master);
3264 	if (ret)
3265 		goto err_put_dev;
3266 
3267 	list_for_each_entry(i2cbi, &master->boardinfo.i2c, node) {
3268 		switch (i2cbi->lvr & I3C_LVR_I2C_INDEX_MASK) {
3269 		case I3C_LVR_I2C_INDEX(0):
3270 			if (mode < I3C_BUS_MODE_MIXED_FAST)
3271 				mode = I3C_BUS_MODE_MIXED_FAST;
3272 			break;
3273 		case I3C_LVR_I2C_INDEX(1):
3274 			if (mode < I3C_BUS_MODE_MIXED_LIMITED)
3275 				mode = I3C_BUS_MODE_MIXED_LIMITED;
3276 			break;
3277 		case I3C_LVR_I2C_INDEX(2):
3278 			if (mode < I3C_BUS_MODE_MIXED_SLOW)
3279 				mode = I3C_BUS_MODE_MIXED_SLOW;
3280 			break;
3281 		default:
3282 			ret = -EINVAL;
3283 			goto err_put_dev;
3284 		}
3285 
3286 		if (i2cbi->lvr & I3C_LVR_I2C_FM_MODE)
3287 			i2c_scl_rate = I3C_BUS_I2C_FM_SCL_MAX_RATE;
3288 	}
3289 
3290 	ret = i3c_bus_set_mode(i3cbus, mode, i2c_scl_rate);
3291 	if (ret)
3292 		goto err_put_dev;
3293 
3294 	master->wq = alloc_workqueue("%s", WQ_PERCPU | WQ_FREEZABLE, 0, dev_name(parent));
3295 	if (!master->wq) {
3296 		ret = -ENOMEM;
3297 		goto err_put_dev;
3298 	}
3299 	INIT_WORK(&master->hj_work, i3c_master_hj_work_fn);
3300 	INIT_WORK(&master->reg_work, i3c_master_reg_work_fn);
3301 
3302 	ret = i3c_master_bus_init(master);
3303 	if (ret)
3304 		goto err_put_dev;
3305 
3306 	ret = device_add(&master->dev);
3307 	if (ret)
3308 		goto err_cleanup_bus;
3309 
3310 	/*
3311 	 * Expose our I3C bus as an I2C adapter so that I2C devices are exposed
3312 	 * through the I2C subsystem.
3313 	 */
3314 	ret = i3c_master_i2c_adapter_init(master);
3315 	if (ret)
3316 		goto err_del_dev;
3317 
3318 	i3c_bus_notify(i3cbus, I3C_NOTIFY_BUS_ADD);
3319 
3320 	pm_runtime_no_callbacks(&master->dev);
3321 	pm_suspend_ignore_children(&master->dev, true);
3322 	pm_runtime_enable(&master->dev);
3323 
3324 	/*
3325 	 * We're done initializing the bus and the controller, we can now
3326 	 * register I3C devices discovered during the initial DAA. Device
3327 	 * registration is done via reg_work because that keeps a single
3328 	 * registration code path and ensures the worker is the only writer
3329 	 * of desc->dev. Flush the work to preserve synchronous probe-time
3330 	 * behavior.
3331 	 */
3332 	master->init_done = true;
3333 	queue_work(master->wq, &master->reg_work);
3334 	flush_work(&master->reg_work);
3335 
3336 	if (master->ops->set_dev_nack_retry)
3337 		device_create_file(&master->dev, &dev_attr_dev_nack_retry_count);
3338 
3339 	i3c_master_rpm_put(master);
3340 
3341 	return 0;
3342 
3343 err_del_dev:
3344 	device_del(&master->dev);
3345 
3346 err_cleanup_bus:
3347 	i3c_master_bus_cleanup(master);
3348 
3349 err_put_dev:
3350 	i3c_master_rpm_put(master);
3351 	put_device(&master->dev);
3352 
3353 	return ret;
3354 }
3355 EXPORT_SYMBOL_GPL(i3c_master_register);
3356 
3357 /**
3358  * i3c_master_unregister() - unregister an I3C master
3359  * @master: master used to send frames on the bus
3360  *
3361  * Basically undo everything done in i3c_master_register().
3362  */
3363 void i3c_master_unregister(struct i3c_master_controller *master)
3364 {
3365 	i3c_bus_notify(&master->bus, I3C_NOTIFY_BUS_REMOVE);
3366 	i3c_master_shutdown(master);
3367 
3368 	if (master->ops->set_dev_nack_retry)
3369 		device_remove_file(&master->dev, &dev_attr_dev_nack_retry_count);
3370 
3371 	i3c_master_i2c_adapter_cleanup(master);
3372 	i3c_master_unregister_i3c_devs(master);
3373 	i3c_master_bus_cleanup(master);
3374 	pm_runtime_disable(&master->dev);
3375 	device_unregister(&master->dev);
3376 }
3377 EXPORT_SYMBOL_GPL(i3c_master_unregister);
3378 
3379 int i3c_dev_setdasa_locked(struct i3c_dev_desc *dev)
3380 {
3381 	struct i3c_master_controller *master;
3382 
3383 	if (!dev)
3384 		return -ENOENT;
3385 
3386 	master = i3c_dev_get_master(dev);
3387 	if (!master)
3388 		return -EINVAL;
3389 
3390 	if (!dev->boardinfo || !dev->boardinfo->init_dyn_addr ||
3391 		!dev->boardinfo->static_addr)
3392 		return -EINVAL;
3393 
3394 	return i3c_master_setdasa_locked(master, dev->info.static_addr,
3395 						dev->boardinfo->init_dyn_addr);
3396 }
3397 
3398 int i3c_dev_do_xfers_locked(struct i3c_dev_desc *dev, struct i3c_xfer *xfers,
3399 			    int nxfers, enum i3c_xfer_mode mode)
3400 {
3401 	struct i3c_master_controller *master;
3402 
3403 	if (!dev)
3404 		return -ENOENT;
3405 
3406 	master = i3c_dev_get_master(dev);
3407 	if (!master || !xfers)
3408 		return -EINVAL;
3409 
3410 	if (mode != I3C_SDR && !(master->this->info.hdr_cap & BIT(mode)))
3411 		return -EOPNOTSUPP;
3412 
3413 	return master->ops->i3c_xfers(dev, xfers, nxfers, mode);
3414 }
3415 
3416 /**
3417  * i3c_dev_disable_ibi_locked() - Disable IBIs coming from a specific device
3418  * @dev: device on which IBIs should be disabled
3419  *
3420  * This function disable IBIs coming from a specific device and wait for
3421  * all pending IBIs to be processed.
3422  *
3423  * Context: Must be called with mutex_lock(&dev->desc->ibi_lock) held.
3424  * Return: 0 in case of success, a negative error core otherwise.
3425  */
3426 int i3c_dev_disable_ibi_locked(struct i3c_dev_desc *dev)
3427 {
3428 	struct i3c_master_controller *master;
3429 	int ret;
3430 
3431 	if (!dev->ibi)
3432 		return -EINVAL;
3433 
3434 	master = i3c_dev_get_master(dev);
3435 	ret = master->ops->disable_ibi(dev);
3436 	if (ret)
3437 		return ret;
3438 
3439 	reinit_completion(&dev->ibi->all_ibis_handled);
3440 	if (atomic_read(&dev->ibi->pending_ibis))
3441 		wait_for_completion(&dev->ibi->all_ibis_handled);
3442 
3443 	dev->ibi->enabled = false;
3444 
3445 	return 0;
3446 }
3447 EXPORT_SYMBOL_GPL(i3c_dev_disable_ibi_locked);
3448 
3449 /**
3450  * i3c_dev_enable_ibi_locked() - Enable IBIs from a specific device (lock held)
3451  * @dev: device on which IBIs should be enabled
3452  *
3453  * This function enable IBIs coming from a specific device and wait for
3454  * all pending IBIs to be processed. This should be called on a device
3455  * where i3c_device_request_ibi() has succeeded.
3456  *
3457  * Note that IBIs from this device might be received before this function
3458  * returns to its caller.
3459  *
3460  * Context: Must be called with mutex_lock(&dev->desc->ibi_lock) held.
3461  * Return: 0 on success, or a negative error code on failure.
3462  */
3463 int i3c_dev_enable_ibi_locked(struct i3c_dev_desc *dev)
3464 {
3465 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
3466 	int ret;
3467 
3468 	if (!dev->ibi)
3469 		return -EINVAL;
3470 
3471 	ret = master->ops->enable_ibi(dev);
3472 	if (!ret)
3473 		dev->ibi->enabled = true;
3474 
3475 	return ret;
3476 }
3477 EXPORT_SYMBOL_GPL(i3c_dev_enable_ibi_locked);
3478 
3479 /**
3480  * i3c_dev_request_ibi_locked() - Request an IBI
3481  * @dev: device for which we should enable IBIs
3482  * @req: setup requested for this IBI
3483  *
3484  * This function is responsible for pre-allocating all resources needed to
3485  * process IBIs coming from @dev. When this function returns, the IBI is not
3486  * enabled until i3c_device_enable_ibi() is called.
3487  *
3488  * Context: Must be called with mutex_lock(&dev->desc->ibi_lock) held.
3489  * Return: 0 in case of success, a negative error core otherwise.
3490  */
3491 int i3c_dev_request_ibi_locked(struct i3c_dev_desc *dev,
3492 			       const struct i3c_ibi_setup *req)
3493 {
3494 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
3495 	struct i3c_device_ibi_info *ibi;
3496 	int ret;
3497 
3498 	if (!master->ops->request_ibi)
3499 		return -EOPNOTSUPP;
3500 
3501 	if (dev->ibi)
3502 		return -EBUSY;
3503 
3504 	ibi = kzalloc_obj(*ibi);
3505 	if (!ibi)
3506 		return -ENOMEM;
3507 
3508 	ibi->wq = alloc_ordered_workqueue(dev_name(i3cdev_to_dev(dev->dev)), WQ_MEM_RECLAIM);
3509 	if (!ibi->wq) {
3510 		kfree(ibi);
3511 		return -ENOMEM;
3512 	}
3513 
3514 	atomic_set(&ibi->pending_ibis, 0);
3515 	init_completion(&ibi->all_ibis_handled);
3516 	ibi->handler = req->handler;
3517 	ibi->max_payload_len = req->max_payload_len;
3518 	ibi->num_slots = req->num_slots;
3519 
3520 	dev->ibi = ibi;
3521 	ret = master->ops->request_ibi(dev, req);
3522 	if (ret) {
3523 		kfree(ibi);
3524 		dev->ibi = NULL;
3525 	}
3526 
3527 	return ret;
3528 }
3529 EXPORT_SYMBOL_GPL(i3c_dev_request_ibi_locked);
3530 
3531 /**
3532  * i3c_dev_free_ibi_locked() - Free all resources needed for IBI handling
3533  * @dev: device on which you want to release IBI resources
3534  *
3535  * This function is responsible for de-allocating resources previously
3536  * allocated by i3c_device_request_ibi(). It should be called after disabling
3537  * IBIs with i3c_device_disable_ibi().
3538  *
3539  * Context: Must be called with mutex_lock(&dev->desc->ibi_lock) held.
3540  */
3541 void i3c_dev_free_ibi_locked(struct i3c_dev_desc *dev)
3542 {
3543 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
3544 
3545 	if (!dev->ibi)
3546 		return;
3547 
3548 	if (dev->ibi->enabled) {
3549 		int ret;
3550 
3551 		dev_err(&master->dev, "Freeing IBI that is still enabled\n");
3552 		ret = i3c_master_rpm_get(master);
3553 		if (!ret) {
3554 			ret = i3c_dev_disable_ibi_locked(dev);
3555 			i3c_master_rpm_put(master);
3556 		}
3557 		if (ret)
3558 			dev_err(&master->dev, "Failed to disable IBI before freeing\n");
3559 	}
3560 
3561 	master->ops->free_ibi(dev);
3562 
3563 	if (dev->ibi->wq) {
3564 		destroy_workqueue(dev->ibi->wq);
3565 		dev->ibi->wq = NULL;
3566 	}
3567 
3568 	kfree(dev->ibi);
3569 	dev->ibi = NULL;
3570 }
3571 EXPORT_SYMBOL_GPL(i3c_dev_free_ibi_locked);
3572 
3573 static int __init i3c_init(void)
3574 {
3575 	int res;
3576 
3577 	res = of_alias_get_highest_id("i3c");
3578 	if (res >= 0) {
3579 		mutex_lock(&i3c_core_lock);
3580 		__i3c_first_dynamic_bus_num = res + 1;
3581 		mutex_unlock(&i3c_core_lock);
3582 	}
3583 
3584 	res = bus_register_notifier(&i2c_bus_type, &i2cdev_notifier);
3585 	if (res)
3586 		return res;
3587 
3588 	res = bus_register(&i3c_bus_type);
3589 	if (res)
3590 		goto out_unreg_notifier;
3591 
3592 	return 0;
3593 
3594 out_unreg_notifier:
3595 	bus_unregister_notifier(&i2c_bus_type, &i2cdev_notifier);
3596 
3597 	return res;
3598 }
3599 subsys_initcall(i3c_init);
3600 
3601 static void __exit i3c_exit(void)
3602 {
3603 	bus_unregister_notifier(&i2c_bus_type, &i2cdev_notifier);
3604 	idr_destroy(&i3c_bus_idr);
3605 	bus_unregister(&i3c_bus_type);
3606 }
3607 module_exit(i3c_exit);
3608 
3609 MODULE_AUTHOR("Boris Brezillon <boris.brezillon@bootlin.com>");
3610 MODULE_DESCRIPTION("I3C core");
3611 MODULE_LICENSE("GPL v2");
3612