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