xref: /linux/drivers/i3c/master.c (revision 94daedb41d288d9ce798332fc2feb523875676e1)
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 /**
1125  * i3c_master_enec_disec_locked() - send an ENEC or DISEC CCC command
1126  * @master: master used to send frames on the bus
1127  * @addr: a valid I3C slave address or %I3C_BROADCAST_ADDR
1128  * @enable: true to send ENEC, false to send DISEC
1129  * @evts: events to enable or disable
1130  * @suppress_m2: if true, treat an M2 (NACK) error from the CCC as success
1131  *
1132  * Send an ENEC or DISEC CCC command to enable or disable some or all events
1133  * coming from a specific slave, or all devices if @addr is
1134  * %I3C_BROADCAST_ADDR.
1135  *
1136  * When @suppress_m2 is true, a NACK of the broadcast (which can happen when
1137  * no devices are present on the bus) is not reported as an error. This is
1138  * useful for callers that want to configure event reporting unconditionally,
1139  * regardless of whether any devices are currently on the bus.
1140  *
1141  * This function must be called with the bus lock held in write mode.
1142  *
1143  * Return: 0 in case of success, or a negative error code otherwise.
1144  */
1145 int i3c_master_enec_disec_locked(struct i3c_master_controller *master, u8 addr,
1146 				 bool enable, u8 evts, bool suppress_m2)
1147 {
1148 	struct i3c_ccc_events *events;
1149 	struct i3c_ccc_cmd_dest dest;
1150 	struct i3c_ccc_cmd cmd;
1151 	int ret;
1152 
1153 	events = i3c_ccc_cmd_dest_init(&dest, addr, sizeof(*events));
1154 	if (!events)
1155 		return -ENOMEM;
1156 
1157 	events->events = evts;
1158 	i3c_ccc_cmd_init(&cmd, false,
1159 			 enable ?
1160 			 I3C_CCC_ENEC(addr == I3C_BROADCAST_ADDR) :
1161 			 I3C_CCC_DISEC(addr == I3C_BROADCAST_ADDR),
1162 			 &dest, 1);
1163 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1164 	i3c_ccc_cmd_dest_cleanup(&dest);
1165 
1166 	if (suppress_m2 && ret && cmd.err == I3C_ERROR_M2)
1167 		ret = 0;
1168 
1169 	return ret;
1170 }
1171 EXPORT_SYMBOL_GPL(i3c_master_enec_disec_locked);
1172 
1173 /**
1174  * i3c_master_disec_locked() - send a DISEC CCC command
1175  * @master: master used to send frames on the bus
1176  * @addr: a valid I3C slave address or %I3C_BROADCAST_ADDR
1177  * @evts: events to disable
1178  *
1179  * Send a DISEC CCC command to disable some or all events coming from a
1180  * specific slave, or all devices if @addr is %I3C_BROADCAST_ADDR.
1181  *
1182  * This function must be called with the bus lock held in write mode.
1183  *
1184  * Return: 0 in case of success, or a negative error code otherwise.
1185  */
1186 int i3c_master_disec_locked(struct i3c_master_controller *master, u8 addr,
1187 			    u8 evts)
1188 {
1189 	return i3c_master_enec_disec_locked(master, addr, false, evts, false);
1190 }
1191 EXPORT_SYMBOL_GPL(i3c_master_disec_locked);
1192 
1193 /**
1194  * i3c_master_enec_locked() - send an ENEC CCC command
1195  * @master: master used to send frames on the bus
1196  * @addr: a valid I3C slave address or %I3C_BROADCAST_ADDR
1197  * @evts: events to disable
1198  *
1199  * Sends an ENEC CCC command to enable some or all events coming from a
1200  * specific slave, or all devices if @addr is %I3C_BROADCAST_ADDR.
1201  *
1202  * This function must be called with the bus lock held in write mode.
1203  *
1204  * Return: 0 in case of success, or a negative error code otherwise.
1205  */
1206 int i3c_master_enec_locked(struct i3c_master_controller *master, u8 addr,
1207 			   u8 evts)
1208 {
1209 	return i3c_master_enec_disec_locked(master, addr, true, evts, false);
1210 }
1211 EXPORT_SYMBOL_GPL(i3c_master_enec_locked);
1212 
1213 /**
1214  * i3c_master_defslvs_locked() - send a DEFSLVS CCC command
1215  * @master: master used to send frames on the bus
1216  *
1217  * Send a DEFSLVS CCC command containing all the devices known to the @master.
1218  * This is useful when you have secondary masters on the bus to propagate
1219  * device information.
1220  *
1221  * This should be called after all I3C devices have been discovered (in other
1222  * words, after the DAA procedure has finished) and instantiated in
1223  * &i3c_master_controller_ops->bus_init().
1224  * It should also be called if a master ACKed an Hot-Join request and assigned
1225  * a dynamic address to the device joining the bus.
1226  *
1227  * This function must be called with the bus lock held in write mode.
1228  *
1229  * Return: 0 in case of success, or a negative error code otherwise.
1230  */
1231 int i3c_master_defslvs_locked(struct i3c_master_controller *master)
1232 {
1233 	struct i3c_ccc_defslvs *defslvs;
1234 	struct i3c_ccc_dev_desc *desc;
1235 	struct i3c_ccc_cmd_dest dest;
1236 	struct i3c_dev_desc *i3cdev;
1237 	struct i2c_dev_desc *i2cdev;
1238 	struct i3c_ccc_cmd cmd;
1239 	struct i3c_bus *bus;
1240 	bool send = false;
1241 	int ndevs = 0, ret;
1242 
1243 	if (!master)
1244 		return -EINVAL;
1245 
1246 	bus = i3c_master_get_bus(master);
1247 	i3c_bus_for_each_i3cdev(bus, i3cdev) {
1248 		ndevs++;
1249 
1250 		if (i3cdev == master->this)
1251 			continue;
1252 
1253 		if (I3C_BCR_DEVICE_ROLE(i3cdev->info.bcr) ==
1254 		    I3C_BCR_I3C_MASTER)
1255 			send = true;
1256 	}
1257 
1258 	/* No other master on the bus, skip DEFSLVS. */
1259 	if (!send)
1260 		return 0;
1261 
1262 	i3c_bus_for_each_i2cdev(bus, i2cdev)
1263 		ndevs++;
1264 
1265 	defslvs = i3c_ccc_cmd_dest_init(&dest, I3C_BROADCAST_ADDR,
1266 					struct_size(defslvs, slaves,
1267 						    ndevs - 1));
1268 	if (!defslvs)
1269 		return -ENOMEM;
1270 
1271 	defslvs->count = ndevs;
1272 	defslvs->master.bcr = master->this->info.bcr;
1273 	defslvs->master.dcr = master->this->info.dcr;
1274 	defslvs->master.dyn_addr = master->this->info.dyn_addr << 1;
1275 	defslvs->master.static_addr = I3C_BROADCAST_ADDR << 1;
1276 
1277 	desc = defslvs->slaves;
1278 	i3c_bus_for_each_i2cdev(bus, i2cdev) {
1279 		desc->lvr = i2cdev->lvr;
1280 		desc->static_addr = i2cdev->addr << 1;
1281 		desc++;
1282 	}
1283 
1284 	i3c_bus_for_each_i3cdev(bus, i3cdev) {
1285 		/* Skip the I3C dev representing this master. */
1286 		if (i3cdev == master->this)
1287 			continue;
1288 
1289 		desc->bcr = i3cdev->info.bcr;
1290 		desc->dcr = i3cdev->info.dcr;
1291 		desc->dyn_addr = i3cdev->info.dyn_addr << 1;
1292 		desc->static_addr = i3cdev->info.static_addr << 1;
1293 		desc++;
1294 	}
1295 
1296 	i3c_ccc_cmd_init(&cmd, false, I3C_CCC_DEFSLVS, &dest, 1);
1297 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1298 	i3c_ccc_cmd_dest_cleanup(&dest);
1299 
1300 	return ret;
1301 }
1302 EXPORT_SYMBOL_GPL(i3c_master_defslvs_locked);
1303 
1304 static int i3c_master_setda_locked(struct i3c_master_controller *master,
1305 				   u8 oldaddr, u8 newaddr, bool setdasa)
1306 {
1307 	struct i3c_ccc_cmd_dest dest;
1308 	struct i3c_ccc_setda *setda;
1309 	struct i3c_ccc_cmd cmd;
1310 	int ret;
1311 
1312 	if (!oldaddr || !newaddr)
1313 		return -EINVAL;
1314 
1315 	setda = i3c_ccc_cmd_dest_init(&dest, oldaddr, sizeof(*setda));
1316 	if (!setda)
1317 		return -ENOMEM;
1318 
1319 	setda->addr = newaddr << 1;
1320 	i3c_ccc_cmd_init(&cmd, false,
1321 			 setdasa ? I3C_CCC_SETDASA : I3C_CCC_SETNEWDA,
1322 			 &dest, 1);
1323 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1324 	i3c_ccc_cmd_dest_cleanup(&dest);
1325 
1326 	return ret;
1327 }
1328 
1329 static int i3c_master_setdasa_locked(struct i3c_master_controller *master,
1330 				     u8 static_addr, u8 dyn_addr)
1331 {
1332 	return i3c_master_setda_locked(master, static_addr, dyn_addr, true);
1333 }
1334 
1335 static int i3c_master_setnewda_locked(struct i3c_master_controller *master,
1336 				      u8 oldaddr, u8 newaddr)
1337 {
1338 	return i3c_master_setda_locked(master, oldaddr, newaddr, false);
1339 }
1340 
1341 static int i3c_master_getmrl_locked(struct i3c_master_controller *master,
1342 				    struct i3c_device_info *info)
1343 {
1344 	struct i3c_ccc_cmd_dest dest;
1345 	struct i3c_ccc_mrl *mrl;
1346 	struct i3c_ccc_cmd cmd;
1347 	int ret;
1348 
1349 	mrl = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr, sizeof(*mrl));
1350 	if (!mrl)
1351 		return -ENOMEM;
1352 
1353 	/*
1354 	 * When the device does not have IBI payload GETMRL only returns 2
1355 	 * bytes of data.
1356 	 */
1357 	if (!(info->bcr & I3C_BCR_IBI_PAYLOAD))
1358 		dest.payload.len -= 1;
1359 
1360 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETMRL, &dest, 1);
1361 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1362 	if (ret)
1363 		goto out;
1364 
1365 	switch (dest.payload.len) {
1366 	case 3:
1367 		info->max_ibi_len = mrl->ibi_len;
1368 		fallthrough;
1369 	case 2:
1370 		info->max_read_len = be16_to_cpu(mrl->read_len);
1371 		break;
1372 	default:
1373 		ret = -EIO;
1374 		goto out;
1375 	}
1376 
1377 out:
1378 	i3c_ccc_cmd_dest_cleanup(&dest);
1379 
1380 	return ret;
1381 }
1382 
1383 static int i3c_master_getmwl_locked(struct i3c_master_controller *master,
1384 				    struct i3c_device_info *info)
1385 {
1386 	struct i3c_ccc_cmd_dest dest;
1387 	struct i3c_ccc_mwl *mwl;
1388 	struct i3c_ccc_cmd cmd;
1389 	int ret;
1390 
1391 	mwl = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr, sizeof(*mwl));
1392 	if (!mwl)
1393 		return -ENOMEM;
1394 
1395 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETMWL, &dest, 1);
1396 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1397 	if (ret)
1398 		goto out;
1399 
1400 	if (dest.payload.len != sizeof(*mwl)) {
1401 		ret = -EIO;
1402 		goto out;
1403 	}
1404 
1405 	info->max_write_len = be16_to_cpu(mwl->len);
1406 
1407 out:
1408 	i3c_ccc_cmd_dest_cleanup(&dest);
1409 
1410 	return ret;
1411 }
1412 
1413 static int i3c_master_getmxds_locked(struct i3c_master_controller *master,
1414 				     struct i3c_device_info *info)
1415 {
1416 	struct i3c_ccc_getmxds *getmaxds;
1417 	struct i3c_ccc_cmd_dest dest;
1418 	struct i3c_ccc_cmd cmd;
1419 	int ret;
1420 
1421 	getmaxds = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr,
1422 					 sizeof(*getmaxds));
1423 	if (!getmaxds)
1424 		return -ENOMEM;
1425 
1426 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETMXDS, &dest, 1);
1427 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1428 	if (ret) {
1429 		/*
1430 		 * Retry when the device does not support max read turnaround
1431 		 * while expecting shorter length from this CCC command.
1432 		 */
1433 		dest.payload.len -= 3;
1434 		ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1435 		if (ret)
1436 			goto out;
1437 	}
1438 
1439 	if (dest.payload.len != 2 && dest.payload.len != 5) {
1440 		ret = -EIO;
1441 		goto out;
1442 	}
1443 
1444 	info->max_read_ds = getmaxds->maxrd;
1445 	info->max_write_ds = getmaxds->maxwr;
1446 	if (dest.payload.len == 5)
1447 		info->max_read_turnaround = getmaxds->maxrdturn[0] |
1448 					    ((u32)getmaxds->maxrdturn[1] << 8) |
1449 					    ((u32)getmaxds->maxrdturn[2] << 16);
1450 
1451 out:
1452 	i3c_ccc_cmd_dest_cleanup(&dest);
1453 
1454 	return ret;
1455 }
1456 
1457 static int i3c_master_gethdrcap_locked(struct i3c_master_controller *master,
1458 				       struct i3c_device_info *info)
1459 {
1460 	struct i3c_ccc_gethdrcap *gethdrcap;
1461 	struct i3c_ccc_cmd_dest dest;
1462 	struct i3c_ccc_cmd cmd;
1463 	int ret;
1464 
1465 	gethdrcap = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr,
1466 					  sizeof(*gethdrcap));
1467 	if (!gethdrcap)
1468 		return -ENOMEM;
1469 
1470 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETHDRCAP, &dest, 1);
1471 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1472 	if (ret)
1473 		goto out;
1474 
1475 	if (dest.payload.len != 1) {
1476 		ret = -EIO;
1477 		goto out;
1478 	}
1479 
1480 	info->hdr_cap = gethdrcap->modes;
1481 
1482 out:
1483 	i3c_ccc_cmd_dest_cleanup(&dest);
1484 
1485 	return ret;
1486 }
1487 
1488 static int i3c_master_getpid_locked(struct i3c_master_controller *master,
1489 				    struct i3c_device_info *info)
1490 {
1491 	struct i3c_ccc_getpid *getpid;
1492 	struct i3c_ccc_cmd_dest dest;
1493 	struct i3c_ccc_cmd cmd;
1494 	int ret, i;
1495 
1496 	getpid = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr, sizeof(*getpid));
1497 	if (!getpid)
1498 		return -ENOMEM;
1499 
1500 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETPID, &dest, 1);
1501 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1502 	if (ret)
1503 		goto out;
1504 
1505 	info->pid = 0;
1506 	for (i = 0; i < sizeof(getpid->pid); i++) {
1507 		int sft = (sizeof(getpid->pid) - i - 1) * 8;
1508 
1509 		info->pid |= (u64)getpid->pid[i] << sft;
1510 	}
1511 
1512 out:
1513 	i3c_ccc_cmd_dest_cleanup(&dest);
1514 
1515 	return ret;
1516 }
1517 
1518 static int i3c_master_getbcr_locked(struct i3c_master_controller *master,
1519 				    struct i3c_device_info *info)
1520 {
1521 	struct i3c_ccc_getbcr *getbcr;
1522 	struct i3c_ccc_cmd_dest dest;
1523 	struct i3c_ccc_cmd cmd;
1524 	int ret;
1525 
1526 	getbcr = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr, sizeof(*getbcr));
1527 	if (!getbcr)
1528 		return -ENOMEM;
1529 
1530 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETBCR, &dest, 1);
1531 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1532 	if (ret)
1533 		goto out;
1534 
1535 	info->bcr = getbcr->bcr;
1536 
1537 out:
1538 	i3c_ccc_cmd_dest_cleanup(&dest);
1539 
1540 	return ret;
1541 }
1542 
1543 static int i3c_master_getdcr_locked(struct i3c_master_controller *master,
1544 				    struct i3c_device_info *info)
1545 {
1546 	struct i3c_ccc_getdcr *getdcr;
1547 	struct i3c_ccc_cmd_dest dest;
1548 	struct i3c_ccc_cmd cmd;
1549 	int ret;
1550 
1551 	getdcr = i3c_ccc_cmd_dest_init(&dest, info->dyn_addr, sizeof(*getdcr));
1552 	if (!getdcr)
1553 		return -ENOMEM;
1554 
1555 	i3c_ccc_cmd_init(&cmd, true, I3C_CCC_GETDCR, &dest, 1);
1556 	ret = i3c_master_send_ccc_cmd_locked(master, &cmd);
1557 	if (ret)
1558 		goto out;
1559 
1560 	info->dcr = getdcr->dcr;
1561 
1562 out:
1563 	i3c_ccc_cmd_dest_cleanup(&dest);
1564 
1565 	return ret;
1566 }
1567 
1568 static int i3c_master_retrieve_dev_info(struct i3c_dev_desc *dev)
1569 {
1570 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
1571 	enum i3c_addr_slot_status slot_status;
1572 	int ret;
1573 
1574 	if (!dev->info.dyn_addr)
1575 		return -EINVAL;
1576 
1577 	slot_status = i3c_bus_get_addr_slot_status(&master->bus,
1578 						   dev->info.dyn_addr);
1579 	if (slot_status == I3C_ADDR_SLOT_RSVD ||
1580 	    slot_status == I3C_ADDR_SLOT_I2C_DEV)
1581 		return -EINVAL;
1582 
1583 	ret = i3c_master_getpid_locked(master, &dev->info);
1584 	if (ret)
1585 		return ret;
1586 
1587 	ret = i3c_master_getbcr_locked(master, &dev->info);
1588 	if (ret)
1589 		return ret;
1590 
1591 	ret = i3c_master_getdcr_locked(master, &dev->info);
1592 	if (ret)
1593 		return ret;
1594 
1595 	if (dev->info.bcr & I3C_BCR_MAX_DATA_SPEED_LIM) {
1596 		ret = i3c_master_getmxds_locked(master, &dev->info);
1597 		if (ret)
1598 			return ret;
1599 	}
1600 
1601 	if (dev->info.bcr & I3C_BCR_IBI_PAYLOAD)
1602 		dev->info.max_ibi_len = 1;
1603 
1604 	i3c_master_getmrl_locked(master, &dev->info);
1605 	i3c_master_getmwl_locked(master, &dev->info);
1606 
1607 	if (dev->info.bcr & I3C_BCR_HDR_CAP) {
1608 		ret = i3c_master_gethdrcap_locked(master, &dev->info);
1609 		if (ret && ret != -EOPNOTSUPP)
1610 			return ret;
1611 	}
1612 
1613 	return 0;
1614 }
1615 
1616 static void i3c_master_put_i3c_addrs(struct i3c_dev_desc *dev)
1617 {
1618 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
1619 
1620 	if (dev->info.static_addr)
1621 		i3c_bus_set_addr_slot_status(&master->bus,
1622 					     dev->info.static_addr,
1623 					     I3C_ADDR_SLOT_FREE);
1624 
1625 	if (dev->info.dyn_addr)
1626 		i3c_bus_set_addr_slot_status(&master->bus, dev->info.dyn_addr,
1627 					     I3C_ADDR_SLOT_FREE);
1628 
1629 	if (dev->boardinfo && dev->boardinfo->init_dyn_addr)
1630 		i3c_bus_set_addr_slot_status(&master->bus, dev->boardinfo->init_dyn_addr,
1631 					     I3C_ADDR_SLOT_FREE);
1632 }
1633 
1634 static int i3c_master_get_i3c_addrs(struct i3c_dev_desc *dev)
1635 {
1636 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
1637 	enum i3c_addr_slot_status status;
1638 
1639 	if (!dev->info.static_addr && !dev->info.dyn_addr)
1640 		return 0;
1641 
1642 	if (dev->info.static_addr) {
1643 		status = i3c_bus_get_addr_slot_status(&master->bus,
1644 						      dev->info.static_addr);
1645 		/* Since static address and assigned dynamic address can be
1646 		 * equal, allow this case to pass.
1647 		 */
1648 		if (status != I3C_ADDR_SLOT_FREE &&
1649 		    dev->info.static_addr != dev->boardinfo->init_dyn_addr)
1650 			return -EBUSY;
1651 
1652 		i3c_bus_set_addr_slot_status(&master->bus,
1653 					     dev->info.static_addr,
1654 					     I3C_ADDR_SLOT_I3C_DEV);
1655 	}
1656 
1657 	/*
1658 	 * ->init_dyn_addr should have been reserved before that, so, if we're
1659 	 * trying to apply a pre-reserved dynamic address, we should not try
1660 	 * to reserve the address slot a second time.
1661 	 */
1662 	if (dev->info.dyn_addr &&
1663 	    (!dev->boardinfo ||
1664 	     dev->boardinfo->init_dyn_addr != dev->info.dyn_addr)) {
1665 		status = i3c_bus_get_addr_slot_status(&master->bus,
1666 						      dev->info.dyn_addr);
1667 		if (status != I3C_ADDR_SLOT_FREE)
1668 			goto err_release_static_addr;
1669 
1670 		i3c_bus_set_addr_slot_status(&master->bus, dev->info.dyn_addr,
1671 					     I3C_ADDR_SLOT_I3C_DEV);
1672 	}
1673 
1674 	return 0;
1675 
1676 err_release_static_addr:
1677 	if (dev->info.static_addr)
1678 		i3c_bus_set_addr_slot_status(&master->bus,
1679 					     dev->info.static_addr,
1680 					     I3C_ADDR_SLOT_FREE);
1681 
1682 	return -EBUSY;
1683 }
1684 
1685 static int i3c_master_attach_i3c_dev(struct i3c_master_controller *master,
1686 				     struct i3c_dev_desc *dev)
1687 {
1688 	int ret;
1689 
1690 	/*
1691 	 * We don't attach devices to the controller until they are
1692 	 * addressable on the bus.
1693 	 */
1694 	if (!dev->info.static_addr && !dev->info.dyn_addr)
1695 		return 0;
1696 
1697 	ret = i3c_master_get_i3c_addrs(dev);
1698 	if (ret)
1699 		return ret;
1700 
1701 	/* Do not attach the master device itself. */
1702 	if (master->this != dev && master->ops->attach_i3c_dev) {
1703 		ret = master->ops->attach_i3c_dev(dev);
1704 		if (ret) {
1705 			i3c_master_put_i3c_addrs(dev);
1706 			return ret;
1707 		}
1708 	}
1709 
1710 	list_add_tail(&dev->common.node, &master->bus.devs.i3c);
1711 
1712 	return 0;
1713 }
1714 
1715 static int i3c_master_reattach_i3c_dev(struct i3c_dev_desc *dev,
1716 				       u8 old_dyn_addr)
1717 {
1718 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
1719 	int ret;
1720 
1721 	if (dev->info.dyn_addr != old_dyn_addr) {
1722 		i3c_bus_set_addr_slot_status(&master->bus,
1723 					     dev->info.dyn_addr,
1724 					     I3C_ADDR_SLOT_I3C_DEV);
1725 		if (old_dyn_addr)
1726 			i3c_bus_set_addr_slot_status(&master->bus, old_dyn_addr,
1727 						     I3C_ADDR_SLOT_FREE);
1728 	}
1729 
1730 	if (master->ops->reattach_i3c_dev) {
1731 		ret = master->ops->reattach_i3c_dev(dev, old_dyn_addr);
1732 		if (ret) {
1733 			i3c_master_put_i3c_addrs(dev);
1734 			return ret;
1735 		}
1736 	}
1737 
1738 	return 0;
1739 }
1740 
1741 static void i3c_master_detach_i3c_dev(struct i3c_dev_desc *dev)
1742 {
1743 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
1744 
1745 	/* Do not detach the master device itself. */
1746 	if (master->this != dev && master->ops->detach_i3c_dev)
1747 		master->ops->detach_i3c_dev(dev);
1748 
1749 	i3c_master_put_i3c_addrs(dev);
1750 	list_del(&dev->common.node);
1751 }
1752 
1753 static int i3c_master_attach_i2c_dev(struct i3c_master_controller *master,
1754 				     struct i2c_dev_desc *dev)
1755 {
1756 	int ret;
1757 
1758 	if (master->ops->attach_i2c_dev) {
1759 		ret = master->ops->attach_i2c_dev(dev);
1760 		if (ret)
1761 			return ret;
1762 	}
1763 
1764 	list_add_tail(&dev->common.node, &master->bus.devs.i2c);
1765 
1766 	return 0;
1767 }
1768 
1769 static void i3c_master_detach_i2c_dev(struct i2c_dev_desc *dev)
1770 {
1771 	struct i3c_master_controller *master = i2c_dev_get_master(dev);
1772 
1773 	list_del(&dev->common.node);
1774 
1775 	if (master->ops->detach_i2c_dev)
1776 		master->ops->detach_i2c_dev(dev);
1777 }
1778 
1779 static int i3c_master_early_i3c_dev_add(struct i3c_master_controller *master,
1780 					  struct i3c_dev_boardinfo *boardinfo)
1781 {
1782 	struct i3c_device_info info = {
1783 		.static_addr = boardinfo->static_addr,
1784 		.pid = boardinfo->pid,
1785 	};
1786 	struct i3c_dev_desc *i3cdev;
1787 	int ret;
1788 
1789 	i3cdev = i3c_master_alloc_i3c_dev(master, &info);
1790 	if (IS_ERR(i3cdev))
1791 		return -ENOMEM;
1792 
1793 	i3cdev->boardinfo = boardinfo;
1794 
1795 	ret = i3c_master_attach_i3c_dev(master, i3cdev);
1796 	if (ret)
1797 		goto err_free_dev;
1798 
1799 	ret = i3c_master_setdasa_locked(master, i3cdev->info.static_addr,
1800 					i3cdev->boardinfo->init_dyn_addr);
1801 	if (ret)
1802 		goto err_detach_dev;
1803 
1804 	i3cdev->info.dyn_addr = i3cdev->boardinfo->init_dyn_addr;
1805 	ret = i3c_master_reattach_i3c_dev(i3cdev, 0);
1806 	if (ret)
1807 		goto err_rstdaa;
1808 
1809 	ret = i3c_master_retrieve_dev_info(i3cdev);
1810 	if (ret)
1811 		goto err_rstdaa;
1812 
1813 	return 0;
1814 
1815 err_rstdaa:
1816 	i3c_master_rstdaa_locked(master, i3cdev->boardinfo->init_dyn_addr);
1817 err_detach_dev:
1818 	i3c_master_detach_i3c_dev(i3cdev);
1819 err_free_dev:
1820 	i3c_master_free_i3c_dev(i3cdev);
1821 
1822 	return ret;
1823 }
1824 
1825 static void
1826 i3c_master_register_new_i3c_devs(struct i3c_master_controller *master)
1827 {
1828 	struct i3c_dev_desc *desc;
1829 	int ret;
1830 
1831 	if (!master->init_done)
1832 		return;
1833 
1834 	i3c_bus_for_each_i3cdev(&master->bus, desc) {
1835 		if (desc->dev || !desc->info.dyn_addr || desc == master->this)
1836 			continue;
1837 
1838 		desc->dev = kzalloc_obj(*desc->dev);
1839 		if (!desc->dev)
1840 			continue;
1841 
1842 		desc->dev->bus = &master->bus;
1843 		desc->dev->desc = desc;
1844 		desc->dev->dev.parent = &master->dev;
1845 		desc->dev->dev.type = &i3c_device_type;
1846 		desc->dev->dev.bus = &i3c_bus_type;
1847 		desc->dev->dev.release = i3c_device_release;
1848 		dev_set_name(&desc->dev->dev, "%d-%llx", master->bus.id,
1849 			     desc->info.pid);
1850 
1851 		if (desc->boardinfo)
1852 			desc->dev->dev.of_node = desc->boardinfo->of_node;
1853 
1854 		ret = device_register(&desc->dev->dev);
1855 		if (ret) {
1856 			dev_err(&master->dev,
1857 				"Failed to add I3C device (err = %d)\n", ret);
1858 			put_device(&desc->dev->dev);
1859 		}
1860 	}
1861 }
1862 
1863 static void i3c_master_reg_work_fn(struct work_struct *work)
1864 {
1865 	struct i3c_master_controller *master = container_of(work, typeof(*master), reg_work);
1866 
1867 	i3c_bus_normaluse_lock(&master->bus);
1868 	if (!master->shutting_down)
1869 		i3c_master_register_new_i3c_devs(master);
1870 	i3c_bus_normaluse_unlock(&master->bus);
1871 }
1872 
1873 /**
1874  * i3c_master_dma_map_single() - Map buffer for single DMA transfer
1875  * @dev: device object of a device doing DMA
1876  * @buf: destination/source buffer for DMA
1877  * @len: length of transfer
1878  * @force_bounce: true, force to use a bounce buffer,
1879  *                false, function will auto check is a bounce buffer required
1880  * @dir: DMA direction
1881  *
1882  * Map buffer for a DMA transfer and allocate a bounce buffer if required.
1883  *
1884  * Return: I3C DMA transfer descriptor or NULL in case of error.
1885  */
1886 struct i3c_dma *i3c_master_dma_map_single(struct device *dev, void *buf,
1887 	size_t len, bool force_bounce, enum dma_data_direction dir)
1888 {
1889 	void *bounce __free(kfree) = NULL;
1890 	void *dma_buf = buf;
1891 
1892 	struct i3c_dma *dma_xfer __free(kfree) = kzalloc_obj(*dma_xfer);
1893 	if (!dma_xfer)
1894 		return NULL;
1895 
1896 	dma_xfer->dev = dev;
1897 	dma_xfer->buf = buf;
1898 	dma_xfer->dir = dir;
1899 	dma_xfer->len = len;
1900 	dma_xfer->map_len = len;
1901 
1902 	if (is_vmalloc_addr(buf))
1903 		force_bounce = true;
1904 
1905 	if (force_bounce) {
1906 		dma_xfer->map_len = ALIGN(len, cache_line_size());
1907 		if (dir == DMA_FROM_DEVICE)
1908 			bounce = kzalloc(dma_xfer->map_len, GFP_KERNEL);
1909 		else
1910 			bounce = kmemdup(buf, dma_xfer->map_len, GFP_KERNEL);
1911 		if (!bounce)
1912 			return NULL;
1913 		dma_buf = bounce;
1914 	}
1915 
1916 	dma_xfer->addr = dma_map_single(dev, dma_buf, dma_xfer->map_len, dir);
1917 	if (dma_mapping_error(dev, dma_xfer->addr))
1918 		return NULL;
1919 
1920 	dma_xfer->bounce_buf = no_free_ptr(bounce);
1921 	return no_free_ptr(dma_xfer);
1922 }
1923 EXPORT_SYMBOL_GPL(i3c_master_dma_map_single);
1924 
1925 /**
1926  * i3c_master_dma_unmap_single() - Unmap buffer after DMA
1927  * @dma_xfer: DMA transfer and mapping descriptor
1928  *
1929  * Unmap buffer and cleanup DMA transfer descriptor.
1930  */
1931 void i3c_master_dma_unmap_single(struct i3c_dma *dma_xfer)
1932 {
1933 	dma_unmap_single(dma_xfer->dev, dma_xfer->addr,
1934 			 dma_xfer->map_len, dma_xfer->dir);
1935 	if (dma_xfer->bounce_buf) {
1936 		if (dma_xfer->dir == DMA_FROM_DEVICE)
1937 			memcpy(dma_xfer->buf, dma_xfer->bounce_buf,
1938 			       dma_xfer->len);
1939 		kfree(dma_xfer->bounce_buf);
1940 	}
1941 	kfree(dma_xfer);
1942 }
1943 EXPORT_SYMBOL_GPL(i3c_master_dma_unmap_single);
1944 
1945 /**
1946  * i3c_master_set_info() - set master device information
1947  * @master: master used to send frames on the bus
1948  * @info: I3C device information
1949  *
1950  * Set master device info. This should be called from
1951  * &i3c_master_controller_ops->bus_init().
1952  *
1953  * Not all &i3c_device_info fields are meaningful for a master device.
1954  * Here is a list of fields that should be properly filled:
1955  *
1956  * - &i3c_device_info->dyn_addr
1957  * - &i3c_device_info->bcr
1958  * - &i3c_device_info->dcr
1959  * - &i3c_device_info->pid
1960  * - &i3c_device_info->hdr_cap if %I3C_BCR_HDR_CAP bit is set in
1961  *   &i3c_device_info->bcr
1962  *
1963  * This function must be called with the bus lock held in maintenance mode.
1964  *
1965  * Return: 0 if @info contains valid information (not every piece of
1966  * information can be checked, but we can at least make sure @info->dyn_addr
1967  * and @info->bcr are correct), -EINVAL otherwise.
1968  */
1969 int i3c_master_set_info(struct i3c_master_controller *master,
1970 			const struct i3c_device_info *info)
1971 {
1972 	struct i3c_dev_desc *i3cdev;
1973 	int ret;
1974 
1975 	if (!i3c_bus_dev_addr_is_avail(&master->bus, info->dyn_addr))
1976 		return -EINVAL;
1977 
1978 	if (I3C_BCR_DEVICE_ROLE(info->bcr) == I3C_BCR_I3C_MASTER &&
1979 	    master->secondary)
1980 		return -EINVAL;
1981 
1982 	if (master->this)
1983 		return -EINVAL;
1984 
1985 	i3cdev = i3c_master_alloc_i3c_dev(master, info);
1986 	if (IS_ERR(i3cdev))
1987 		return PTR_ERR(i3cdev);
1988 
1989 	master->this = i3cdev;
1990 	master->bus.cur_master = master->this;
1991 
1992 	ret = i3c_master_attach_i3c_dev(master, i3cdev);
1993 	if (ret)
1994 		goto err_free_dev;
1995 
1996 	return 0;
1997 
1998 err_free_dev:
1999 	i3c_master_free_i3c_dev(i3cdev);
2000 
2001 	return ret;
2002 }
2003 EXPORT_SYMBOL_GPL(i3c_master_set_info);
2004 
2005 static void i3c_master_detach_free_devs(struct i3c_master_controller *master)
2006 {
2007 	struct i3c_dev_desc *i3cdev, *i3ctmp;
2008 	struct i2c_dev_desc *i2cdev, *i2ctmp;
2009 
2010 	list_for_each_entry_safe(i3cdev, i3ctmp, &master->bus.devs.i3c,
2011 				 common.node) {
2012 		i3c_master_detach_i3c_dev(i3cdev);
2013 
2014 		if (i3cdev->boardinfo && i3cdev->boardinfo->init_dyn_addr)
2015 			i3c_bus_set_addr_slot_status(&master->bus,
2016 					i3cdev->boardinfo->init_dyn_addr,
2017 					I3C_ADDR_SLOT_FREE);
2018 
2019 		i3c_master_free_i3c_dev(i3cdev);
2020 	}
2021 
2022 	list_for_each_entry_safe(i2cdev, i2ctmp, &master->bus.devs.i2c,
2023 				 common.node) {
2024 		i3c_master_detach_i2c_dev(i2cdev);
2025 		i3c_bus_set_addr_slot_status(&master->bus,
2026 					     i2cdev->addr,
2027 					     I3C_ADDR_SLOT_FREE);
2028 		i3c_master_free_i2c_dev(i2cdev);
2029 	}
2030 }
2031 
2032 /**
2033  * i3c_master_bus_init() - initialize an I3C bus
2034  * @master: main master initializing the bus
2035  *
2036  * This function is following all initialisation steps described in the I3C
2037  * specification:
2038  *
2039  * 1. Attach I2C devs to the master so that the master can fill its internal
2040  *    device table appropriately
2041  *
2042  * 2. Call &i3c_master_controller_ops->bus_init() method to initialize
2043  *    the master controller. That's usually where the bus mode is selected
2044  *    (pure bus or mixed fast/slow bus)
2045  *
2046  * 3. Instruct all devices on the bus to drop their dynamic address. This is
2047  *    particularly important when the bus was previously configured by someone
2048  *    else (for example the bootloader)
2049  *
2050  * 4. Disable all slave events.
2051  *
2052  * 5. Reserve address slots for I3C devices with init_dyn_addr. And if devices
2053  *    also have static_addr, try to pre-assign dynamic addresses requested by
2054  *    the FW with SETDASA and attach corresponding statically defined I3C
2055  *    devices to the master.
2056  *
2057  * 6. Do a DAA (Dynamic Address Assignment) to assign dynamic addresses to all
2058  *    remaining I3C devices
2059  *
2060  * Once this is done, all I3C and I2C devices should be usable.
2061  *
2062  * Return: a 0 in case of success, an negative error code otherwise.
2063  */
2064 static int i3c_master_bus_init(struct i3c_master_controller *master)
2065 {
2066 	enum i3c_addr_slot_status status;
2067 	struct i2c_dev_boardinfo *i2cboardinfo;
2068 	struct i3c_dev_boardinfo *i3cboardinfo;
2069 	struct i2c_dev_desc *i2cdev;
2070 	int ret;
2071 
2072 	/*
2073 	 * First attach all devices with static definitions provided by the
2074 	 * FW.
2075 	 */
2076 	list_for_each_entry(i2cboardinfo, &master->boardinfo.i2c, node) {
2077 		status = i3c_bus_get_addr_slot_status(&master->bus,
2078 						      i2cboardinfo->base.addr);
2079 		if (status != I3C_ADDR_SLOT_FREE) {
2080 			ret = -EBUSY;
2081 			goto err_detach_devs;
2082 		}
2083 
2084 		i3c_bus_set_addr_slot_status(&master->bus,
2085 					     i2cboardinfo->base.addr,
2086 					     I3C_ADDR_SLOT_I2C_DEV);
2087 
2088 		i2cdev = i3c_master_alloc_i2c_dev(master,
2089 						  i2cboardinfo->base.addr,
2090 						  i2cboardinfo->lvr);
2091 		if (IS_ERR(i2cdev)) {
2092 			ret = PTR_ERR(i2cdev);
2093 			goto err_detach_devs;
2094 		}
2095 
2096 		ret = i3c_master_attach_i2c_dev(master, i2cdev);
2097 		if (ret) {
2098 			i3c_master_free_i2c_dev(i2cdev);
2099 			goto err_detach_devs;
2100 		}
2101 	}
2102 
2103 	/*
2104 	 * Now execute the controller specific ->bus_init() routine, which
2105 	 * might configure its internal logic to match the bus limitations.
2106 	 */
2107 	ret = master->ops->bus_init(master);
2108 	if (ret)
2109 		goto err_detach_devs;
2110 
2111 	/*
2112 	 * The master device should have been instantiated in ->bus_init(),
2113 	 * complain if this was not the case.
2114 	 */
2115 	if (!master->this) {
2116 		dev_err(&master->dev,
2117 			"master_set_info() was not called in ->bus_init()\n");
2118 		ret = -EINVAL;
2119 		goto err_bus_cleanup;
2120 	}
2121 
2122 	if (master->ops->set_speed) {
2123 		ret = master->ops->set_speed(master, I3C_OPEN_DRAIN_SLOW_SPEED);
2124 		if (ret)
2125 			goto err_bus_cleanup;
2126 	}
2127 
2128 	/*
2129 	 * Reset all dynamic address that may have been assigned before
2130 	 * (assigned by the bootloader for example).
2131 	 */
2132 	ret = i3c_master_rstdaa_locked(master, I3C_BROADCAST_ADDR);
2133 	if (ret)
2134 		goto err_bus_cleanup;
2135 
2136 	if (master->ops->set_speed) {
2137 		ret = master->ops->set_speed(master, I3C_OPEN_DRAIN_NORMAL_SPEED);
2138 		if (ret)
2139 			goto err_bus_cleanup;
2140 	}
2141 
2142 	/*
2143 	 * Disable all slave events before starting DAA. When no active device
2144 	 * is on the bus, returns Mx error code M2, this error is ignored.
2145 	 */
2146 	ret = i3c_master_enec_disec_locked(master, I3C_BROADCAST_ADDR, false,
2147 					   I3C_CCC_EVENT_SIR | I3C_CCC_EVENT_MR |
2148 					   I3C_CCC_EVENT_HJ, true);
2149 	if (ret)
2150 		goto err_bus_cleanup;
2151 
2152 	/*
2153 	 * Reserve init_dyn_addr first, and then try to pre-assign dynamic
2154 	 * address and retrieve device information if needed.
2155 	 * In case pre-assign dynamic address fails, setting dynamic address to
2156 	 * the requested init_dyn_addr is retried after DAA is done in
2157 	 * i3c_master_add_i3c_dev_locked().
2158 	 */
2159 	list_for_each_entry(i3cboardinfo, &master->boardinfo.i3c, node) {
2160 
2161 		/*
2162 		 * We don't reserve a dynamic address for devices that
2163 		 * don't explicitly request one.
2164 		 */
2165 		if (!i3cboardinfo->init_dyn_addr)
2166 			continue;
2167 
2168 		ret = i3c_bus_get_addr_slot_status(&master->bus,
2169 						   i3cboardinfo->init_dyn_addr);
2170 		if (ret != I3C_ADDR_SLOT_FREE) {
2171 			ret = -EBUSY;
2172 			goto err_rstdaa;
2173 		}
2174 
2175 		/* Do not mark as occupied until real device exist in bus */
2176 		i3c_bus_set_addr_slot_status_mask(&master->bus,
2177 						  i3cboardinfo->init_dyn_addr,
2178 						  I3C_ADDR_SLOT_EXT_DESIRED,
2179 						  I3C_ADDR_SLOT_EXT_STATUS_MASK);
2180 
2181 		/*
2182 		 * Only try to create/attach devices that have a static
2183 		 * address. Other devices will be created/attached when
2184 		 * DAA happens, and the requested dynamic address will
2185 		 * be set using SETNEWDA once those devices become
2186 		 * addressable.
2187 		 */
2188 
2189 		if (i3cboardinfo->static_addr)
2190 			i3c_master_early_i3c_dev_add(master, i3cboardinfo);
2191 	}
2192 
2193 	ret = i3c_master_do_daa(master);
2194 	if (ret)
2195 		goto err_rstdaa;
2196 
2197 	return 0;
2198 
2199 err_rstdaa:
2200 	i3c_master_rstdaa_locked(master, I3C_BROADCAST_ADDR);
2201 
2202 err_bus_cleanup:
2203 	if (master->ops->bus_cleanup)
2204 		master->ops->bus_cleanup(master);
2205 
2206 err_detach_devs:
2207 	i3c_master_detach_free_devs(master);
2208 
2209 	return ret;
2210 }
2211 
2212 static void i3c_master_bus_cleanup(struct i3c_master_controller *master)
2213 {
2214 	if (master->ops->bus_cleanup) {
2215 		int ret = i3c_master_rpm_get(master);
2216 
2217 		if (ret) {
2218 			dev_err(&master->dev,
2219 				"runtime resume error: master bus_cleanup() not done\n");
2220 		} else {
2221 			master->ops->bus_cleanup(master);
2222 			i3c_master_rpm_put(master);
2223 		}
2224 	}
2225 
2226 	i3c_master_detach_free_devs(master);
2227 }
2228 
2229 static void i3c_master_attach_boardinfo(struct i3c_dev_desc *i3cdev)
2230 {
2231 	struct i3c_master_controller *master = i3cdev->common.master;
2232 	struct i3c_dev_boardinfo *i3cboardinfo;
2233 
2234 	list_for_each_entry(i3cboardinfo, &master->boardinfo.i3c, node) {
2235 		if (i3cdev->info.pid != i3cboardinfo->pid)
2236 			continue;
2237 
2238 		i3cdev->boardinfo = i3cboardinfo;
2239 		i3cdev->info.static_addr = i3cboardinfo->static_addr;
2240 		return;
2241 	}
2242 }
2243 
2244 static struct i3c_dev_desc *
2245 i3c_master_search_i3c_dev_duplicate(struct i3c_dev_desc *refdev)
2246 {
2247 	struct i3c_master_controller *master = i3c_dev_get_master(refdev);
2248 	struct i3c_dev_desc *i3cdev;
2249 
2250 	i3c_bus_for_each_i3cdev(&master->bus, i3cdev) {
2251 		if (i3cdev != refdev && i3cdev->info.pid == refdev->info.pid)
2252 			return i3cdev;
2253 	}
2254 
2255 	return NULL;
2256 }
2257 
2258 /**
2259  * i3c_master_add_i3c_dev_locked() - add an I3C slave to the bus
2260  * @master: master used to send frames on the bus
2261  * @addr: I3C slave dynamic address assigned to the device
2262  *
2263  * This function instantiates an I3C device object and adds it to the I3C device
2264  * list. All device information is retrieved using standard CCC commands.
2265  *
2266  * This function must be called with the bus lock held in write mode.
2267  */
2268 void i3c_master_add_i3c_dev_locked(struct i3c_master_controller *master, u8 addr)
2269 {
2270 	struct i3c_device_info info = { .dyn_addr = addr };
2271 	struct i3c_dev_desc *newdev, *olddev;
2272 	u8 old_dyn_addr = addr, expected_dyn_addr;
2273 	struct i3c_ibi_setup ibireq = { };
2274 	bool enable_ibi = false;
2275 	int ret;
2276 
2277 	newdev = i3c_master_alloc_i3c_dev(master, &info);
2278 	if (IS_ERR(newdev)) {
2279 		ret = PTR_ERR(newdev);
2280 		goto err_prevent_addr_reuse;
2281 	}
2282 
2283 	ret = i3c_master_attach_i3c_dev(master, newdev);
2284 	if (ret)
2285 		goto err_free_dev;
2286 
2287 	ret = i3c_master_retrieve_dev_info(newdev);
2288 	if (ret)
2289 		goto err_detach_dev;
2290 
2291 	i3c_master_attach_boardinfo(newdev);
2292 
2293 	olddev = i3c_master_search_i3c_dev_duplicate(newdev);
2294 	if (olddev) {
2295 		newdev->dev = olddev->dev;
2296 		if (newdev->dev)
2297 			newdev->dev->desc = newdev;
2298 
2299 		/*
2300 		 * We need to restore the IBI state too, so let's save the
2301 		 * IBI information and try to restore them after olddev has
2302 		 * been detached+released and its IBI has been stopped and
2303 		 * the associated resources have been freed.
2304 		 */
2305 		mutex_lock(&olddev->ibi_lock);
2306 		if (olddev->ibi) {
2307 			ibireq.handler = olddev->ibi->handler;
2308 			ibireq.max_payload_len = olddev->ibi->max_payload_len;
2309 			ibireq.num_slots = olddev->ibi->num_slots;
2310 
2311 			if (olddev->ibi->enabled)
2312 				enable_ibi = true;
2313 			/*
2314 			 * The olddev should not receive any commands on the
2315 			 * i3c bus as it does not exist and has been assigned
2316 			 * a new address. This will result in NACK or timeout.
2317 			 * So, update the olddev->ibi->enabled flag to false
2318 			 * to avoid DISEC with OldAddr.
2319 			 */
2320 			olddev->ibi->enabled = false;
2321 			i3c_dev_free_ibi_locked(olddev);
2322 		}
2323 		mutex_unlock(&olddev->ibi_lock);
2324 
2325 		old_dyn_addr = olddev->info.dyn_addr;
2326 
2327 		i3c_master_detach_i3c_dev(olddev);
2328 		i3c_master_free_i3c_dev(olddev);
2329 	}
2330 
2331 	/*
2332 	 * Depending on our previous state, the expected dynamic address might
2333 	 * differ:
2334 	 * - if the device already had a dynamic address assigned, let's try to
2335 	 *   re-apply this one
2336 	 * - if the device did not have a dynamic address and the firmware
2337 	 *   requested a specific address, pick this one
2338 	 * - in any other case, keep the address automatically assigned by the
2339 	 *   master
2340 	 */
2341 	if (old_dyn_addr && old_dyn_addr != newdev->info.dyn_addr)
2342 		expected_dyn_addr = old_dyn_addr;
2343 	else if (newdev->boardinfo && newdev->boardinfo->init_dyn_addr)
2344 		expected_dyn_addr = newdev->boardinfo->init_dyn_addr;
2345 	else
2346 		expected_dyn_addr = newdev->info.dyn_addr;
2347 
2348 	if (newdev->info.dyn_addr != expected_dyn_addr &&
2349 	    i3c_bus_get_addr_slot_status(&master->bus, expected_dyn_addr) == I3C_ADDR_SLOT_FREE) {
2350 		/*
2351 		 * Try to apply the expected dynamic address. If it fails, keep
2352 		 * the address assigned by the master.
2353 		 */
2354 		ret = i3c_master_setnewda_locked(master,
2355 						 newdev->info.dyn_addr,
2356 						 expected_dyn_addr);
2357 		if (!ret) {
2358 			old_dyn_addr = newdev->info.dyn_addr;
2359 			newdev->info.dyn_addr = expected_dyn_addr;
2360 			i3c_master_reattach_i3c_dev(newdev, old_dyn_addr);
2361 		} else {
2362 			dev_err(&master->dev,
2363 				"Failed to assign reserved/old address to device %d%llx",
2364 				master->bus.id, newdev->info.pid);
2365 		}
2366 	}
2367 
2368 	/*
2369 	 * Now is time to try to restore the IBI setup. If we're lucky,
2370 	 * everything works as before, otherwise, all we can do is complain.
2371 	 * FIXME: maybe we should add callback to inform the driver that it
2372 	 * should request the IBI again instead of trying to hide that from
2373 	 * him.
2374 	 */
2375 	if (ibireq.handler) {
2376 		mutex_lock(&newdev->ibi_lock);
2377 		ret = i3c_dev_request_ibi_locked(newdev, &ibireq);
2378 		if (ret) {
2379 			dev_err(&master->dev,
2380 				"Failed to request IBI on device %d-%llx",
2381 				master->bus.id, newdev->info.pid);
2382 		} else if (enable_ibi) {
2383 			ret = i3c_dev_enable_ibi_locked(newdev);
2384 			if (ret)
2385 				dev_err(&master->dev,
2386 					"Failed to re-enable IBI on device %d-%llx",
2387 					master->bus.id, newdev->info.pid);
2388 		}
2389 		mutex_unlock(&newdev->ibi_lock);
2390 	}
2391 
2392 	return;
2393 
2394 err_detach_dev:
2395 	if (newdev->dev && newdev->dev->desc)
2396 		newdev->dev->desc = NULL;
2397 
2398 	i3c_master_detach_i3c_dev(newdev);
2399 
2400 err_free_dev:
2401 	i3c_master_free_i3c_dev(newdev);
2402 
2403 err_prevent_addr_reuse:
2404 	/*
2405 	 * Although the device has not been added, the address has been
2406 	 * assigned. Prevent the address from being used again.
2407 	 */
2408 	if (i3c_bus_get_addr_slot_status(&master->bus, addr) == I3C_ADDR_SLOT_FREE)
2409 		i3c_bus_set_addr_slot_status(&master->bus, addr, I3C_ADDR_SLOT_I3C_DEV);
2410 
2411 	dev_err(&master->dev, "Failed to add I3C device at address %u, error %d\n", addr, ret);
2412 }
2413 EXPORT_SYMBOL_GPL(i3c_master_add_i3c_dev_locked);
2414 
2415 /**
2416  * i3c_master_do_daa_ext() - Dynamic Address Assignment (extended version)
2417  * @master: controller
2418  * @rstdaa: whether to first perform Reset of Dynamic Addresses (RSTDAA)
2419  *
2420  * Perform Dynamic Address Assignment with optional support for System
2421  * Hibernation (@rstdaa is true).
2422  *
2423  * After System Hibernation, Dynamic Addresses can have been reassigned at boot
2424  * time to different values. A simple strategy is followed to handle that.
2425  * Perform a Reset of Dynamic Addresses (RSTDAA) followed by the normal DAA
2426  * procedure which has provision for reassigning addresses that differ from the
2427  * previously recorded addresses.
2428  *
2429  * Return: a 0 in case of success, an negative error code otherwise.
2430  */
2431 int i3c_master_do_daa_ext(struct i3c_master_controller *master, bool rstdaa)
2432 {
2433 	int rstret = 0;
2434 	int ret;
2435 
2436 	ret = i3c_master_rpm_get(master);
2437 	if (ret)
2438 		return ret;
2439 
2440 	i3c_bus_maintenance_lock(&master->bus);
2441 
2442 	if (master->shutting_down) {
2443 		ret = -ENODEV;
2444 	} else {
2445 		if (rstdaa)
2446 			rstret = i3c_master_rstdaa_locked(master, I3C_BROADCAST_ADDR);
2447 		ret = master->ops->do_daa(master);
2448 	}
2449 
2450 	i3c_bus_maintenance_unlock(&master->bus);
2451 
2452 	if (ret)
2453 		goto out;
2454 
2455 	queue_work(master->wq, &master->reg_work);
2456 out:
2457 	i3c_master_rpm_put(master);
2458 
2459 	return rstret ?: ret;
2460 }
2461 EXPORT_SYMBOL_GPL(i3c_master_do_daa_ext);
2462 
2463 /**
2464  * i3c_master_do_daa() - do a DAA (Dynamic Address Assignment)
2465  * @master: master doing the DAA
2466  *
2467  * This function instantiates I3C device objects and adds them to the
2468  * I3C device list. All device information is automatically retrieved using
2469  * standard CCC commands.
2470  *
2471  * Return: a 0 in case of success, an negative error code otherwise.
2472  */
2473 int i3c_master_do_daa(struct i3c_master_controller *master)
2474 {
2475 	return i3c_master_do_daa_ext(master, false);
2476 }
2477 EXPORT_SYMBOL_GPL(i3c_master_do_daa);
2478 
2479 #define OF_I3C_REG1_IS_I2C_DEV			BIT(31)
2480 
2481 static int
2482 of_i3c_master_add_i2c_boardinfo(struct i3c_master_controller *master,
2483 				struct device_node *node, u32 *reg)
2484 {
2485 	struct i2c_dev_boardinfo *boardinfo;
2486 	struct device *dev = &master->dev;
2487 	int ret;
2488 
2489 	boardinfo = devm_kzalloc(dev, sizeof(*boardinfo), GFP_KERNEL);
2490 	if (!boardinfo)
2491 		return -ENOMEM;
2492 
2493 	ret = of_i2c_get_board_info(dev, node, &boardinfo->base);
2494 	if (ret)
2495 		return ret;
2496 
2497 	/*
2498 	 * The I3C Specification does not clearly say I2C devices with 10-bit
2499 	 * address are supported. These devices can't be passed properly through
2500 	 * DEFSLVS command.
2501 	 */
2502 	if (boardinfo->base.flags & I2C_CLIENT_TEN) {
2503 		dev_err(dev, "I2C device with 10 bit address not supported.\n");
2504 		return -EOPNOTSUPP;
2505 	}
2506 
2507 	/* LVR is encoded in reg[2]. */
2508 	boardinfo->lvr = reg[2];
2509 
2510 	list_add_tail(&boardinfo->node, &master->boardinfo.i2c);
2511 	of_node_get(node);
2512 
2513 	return 0;
2514 }
2515 
2516 static int
2517 of_i3c_master_add_i3c_boardinfo(struct i3c_master_controller *master,
2518 				struct device_node *node, u32 *reg)
2519 {
2520 	struct i3c_dev_boardinfo *boardinfo;
2521 	struct device *dev = &master->dev;
2522 	enum i3c_addr_slot_status addrstatus;
2523 	u32 init_dyn_addr = 0;
2524 
2525 	boardinfo = devm_kzalloc(dev, sizeof(*boardinfo), GFP_KERNEL);
2526 	if (!boardinfo)
2527 		return -ENOMEM;
2528 
2529 	if (reg[0]) {
2530 		if (reg[0] > I3C_MAX_ADDR)
2531 			return -EINVAL;
2532 
2533 		addrstatus = i3c_bus_get_addr_slot_status(&master->bus,
2534 							  reg[0]);
2535 		if (addrstatus != I3C_ADDR_SLOT_FREE)
2536 			return -EINVAL;
2537 	}
2538 
2539 	boardinfo->static_addr = reg[0];
2540 
2541 	if (!of_property_read_u32(node, "assigned-address", &init_dyn_addr)) {
2542 		if (init_dyn_addr > I3C_MAX_ADDR)
2543 			return -EINVAL;
2544 
2545 		addrstatus = i3c_bus_get_addr_slot_status(&master->bus,
2546 							  init_dyn_addr);
2547 		if (addrstatus != I3C_ADDR_SLOT_FREE)
2548 			return -EINVAL;
2549 	}
2550 
2551 	boardinfo->pid = ((u64)reg[1] << 32) | reg[2];
2552 
2553 	if ((boardinfo->pid & GENMASK_ULL(63, 48)) ||
2554 	    I3C_PID_RND_LOWER_32BITS(boardinfo->pid))
2555 		return -EINVAL;
2556 
2557 	boardinfo->init_dyn_addr = init_dyn_addr;
2558 	boardinfo->of_node = of_node_get(node);
2559 	list_add_tail(&boardinfo->node, &master->boardinfo.i3c);
2560 
2561 	return 0;
2562 }
2563 
2564 static int of_i3c_master_add_dev(struct i3c_master_controller *master,
2565 				 struct device_node *node)
2566 {
2567 	u32 reg[3];
2568 	int ret;
2569 
2570 	if (!master)
2571 		return -EINVAL;
2572 
2573 	ret = of_property_read_u32_array(node, "reg", reg, ARRAY_SIZE(reg));
2574 	if (ret)
2575 		return ret;
2576 
2577 	/*
2578 	 * The manufacturer ID can't be 0. If reg[1] == 0 that means we're
2579 	 * dealing with an I2C device.
2580 	 */
2581 	if (!reg[1])
2582 		ret = of_i3c_master_add_i2c_boardinfo(master, node, reg);
2583 	else
2584 		ret = of_i3c_master_add_i3c_boardinfo(master, node, reg);
2585 
2586 	return ret;
2587 }
2588 
2589 static int of_populate_i3c_bus(struct i3c_master_controller *master)
2590 {
2591 	struct device *dev = &master->dev;
2592 	struct device_node *i3cbus_np = dev->of_node;
2593 	int ret;
2594 	u32 val;
2595 
2596 	if (!i3cbus_np)
2597 		return 0;
2598 
2599 	for_each_available_child_of_node_scoped(i3cbus_np, node) {
2600 		ret = of_i3c_master_add_dev(master, node);
2601 		if (ret)
2602 			return ret;
2603 	}
2604 
2605 	/*
2606 	 * The user might want to limit I2C and I3C speed in case some devices
2607 	 * on the bus are not supporting typical rates, or if the bus topology
2608 	 * prevents it from using max possible rate.
2609 	 */
2610 	if (!of_property_read_u32(i3cbus_np, "i2c-scl-hz", &val))
2611 		master->bus.scl_rate.i2c = val;
2612 
2613 	if (!of_property_read_u32(i3cbus_np, "i3c-scl-hz", &val))
2614 		master->bus.scl_rate.i3c = val;
2615 
2616 	return 0;
2617 }
2618 
2619 static int i3c_master_i2c_adapter_xfer(struct i2c_adapter *adap,
2620 				       struct i2c_msg *xfers, int nxfers)
2621 {
2622 	struct i3c_master_controller *master = i2c_adapter_to_i3c_master(adap);
2623 	struct i2c_dev_desc *dev;
2624 	int i, ret;
2625 	u16 addr;
2626 
2627 	if (!xfers || !master || nxfers <= 0)
2628 		return -EINVAL;
2629 
2630 	if (!master->ops->i2c_xfers)
2631 		return -EOPNOTSUPP;
2632 
2633 	/* Doing transfers to different devices is not supported. */
2634 	addr = xfers[0].addr;
2635 	for (i = 1; i < nxfers; i++) {
2636 		if (addr != xfers[i].addr)
2637 			return -EOPNOTSUPP;
2638 	}
2639 
2640 	ret = i3c_master_rpm_get(master);
2641 	if (ret)
2642 		return ret;
2643 
2644 	i3c_bus_normaluse_lock(&master->bus);
2645 	dev = i3c_master_find_i2c_dev_by_addr(master, addr);
2646 	if (!dev)
2647 		ret = -ENOENT;
2648 	else
2649 		ret = master->ops->i2c_xfers(dev, xfers, nxfers);
2650 	i3c_bus_normaluse_unlock(&master->bus);
2651 
2652 	i3c_master_rpm_put(master);
2653 
2654 	return ret ? ret : nxfers;
2655 }
2656 
2657 static u32 i3c_master_i2c_funcs(struct i2c_adapter *adapter)
2658 {
2659 	return I2C_FUNC_SMBUS_EMUL | I2C_FUNC_I2C;
2660 }
2661 
2662 static u8 i3c_master_i2c_get_lvr(struct i2c_client *client)
2663 {
2664 	/* Fall back to no spike filters and FM bus mode. */
2665 	u8 lvr = I3C_LVR_I2C_INDEX(2) | I3C_LVR_I2C_FM_MODE;
2666 	u32 reg[3];
2667 
2668 	if (!of_property_read_u32_array(client->dev.of_node, "reg", reg, ARRAY_SIZE(reg)))
2669 		lvr = reg[2];
2670 
2671 	return lvr;
2672 }
2673 
2674 static int i3c_master_i2c_attach(struct i2c_adapter *adap, struct i2c_client *client)
2675 {
2676 	struct i3c_master_controller *master = i2c_adapter_to_i3c_master(adap);
2677 	enum i3c_addr_slot_status status;
2678 	struct i2c_dev_desc *i2cdev;
2679 	int ret;
2680 
2681 	/* Already added by board info? */
2682 	if (i3c_master_find_i2c_dev_by_addr(master, client->addr))
2683 		return 0;
2684 
2685 	status = i3c_bus_get_addr_slot_status(&master->bus, client->addr);
2686 	if (status != I3C_ADDR_SLOT_FREE)
2687 		return -EBUSY;
2688 
2689 	i3c_bus_set_addr_slot_status(&master->bus, client->addr,
2690 				     I3C_ADDR_SLOT_I2C_DEV);
2691 
2692 	i2cdev = i3c_master_alloc_i2c_dev(master, client->addr,
2693 					  i3c_master_i2c_get_lvr(client));
2694 	if (IS_ERR(i2cdev)) {
2695 		ret = PTR_ERR(i2cdev);
2696 		goto out_clear_status;
2697 	}
2698 
2699 	ret = i3c_master_attach_i2c_dev(master, i2cdev);
2700 	if (ret)
2701 		goto out_free_dev;
2702 
2703 	return 0;
2704 
2705 out_free_dev:
2706 	i3c_master_free_i2c_dev(i2cdev);
2707 out_clear_status:
2708 	i3c_bus_set_addr_slot_status(&master->bus, client->addr,
2709 				     I3C_ADDR_SLOT_FREE);
2710 
2711 	return ret;
2712 }
2713 
2714 static int i3c_master_i2c_detach(struct i2c_adapter *adap, struct i2c_client *client)
2715 {
2716 	struct i3c_master_controller *master = i2c_adapter_to_i3c_master(adap);
2717 	struct i2c_dev_desc *dev;
2718 
2719 	dev = i3c_master_find_i2c_dev_by_addr(master, client->addr);
2720 	if (!dev)
2721 		return -ENODEV;
2722 
2723 	i3c_master_detach_i2c_dev(dev);
2724 	i3c_bus_set_addr_slot_status(&master->bus, dev->addr,
2725 				     I3C_ADDR_SLOT_FREE);
2726 	i3c_master_free_i2c_dev(dev);
2727 
2728 	return 0;
2729 }
2730 
2731 static const struct i2c_algorithm i3c_master_i2c_algo = {
2732 	.master_xfer = i3c_master_i2c_adapter_xfer,
2733 	.functionality = i3c_master_i2c_funcs,
2734 };
2735 
2736 static int i3c_i2c_notifier_call(struct notifier_block *nb, unsigned long action,
2737 				 void *data)
2738 {
2739 	struct i2c_adapter *adap;
2740 	struct i2c_client *client;
2741 	struct device *dev = data;
2742 	struct i3c_master_controller *master;
2743 	int ret;
2744 
2745 	if (dev->type != &i2c_client_type)
2746 		return 0;
2747 
2748 	client = to_i2c_client(dev);
2749 	adap = client->adapter;
2750 
2751 	if (adap->algo != &i3c_master_i2c_algo)
2752 		return 0;
2753 
2754 	master = i2c_adapter_to_i3c_master(adap);
2755 
2756 	ret = i3c_master_rpm_get(master);
2757 	if (ret)
2758 		return ret;
2759 
2760 	i3c_bus_maintenance_lock(&master->bus);
2761 	switch (action) {
2762 	case BUS_NOTIFY_ADD_DEVICE:
2763 		ret = i3c_master_i2c_attach(adap, client);
2764 		break;
2765 	case BUS_NOTIFY_DEL_DEVICE:
2766 		ret = i3c_master_i2c_detach(adap, client);
2767 		break;
2768 	default:
2769 		ret = -EINVAL;
2770 	}
2771 	i3c_bus_maintenance_unlock(&master->bus);
2772 
2773 	i3c_master_rpm_put(master);
2774 
2775 	return ret;
2776 }
2777 
2778 static struct notifier_block i2cdev_notifier = {
2779 	.notifier_call = i3c_i2c_notifier_call,
2780 };
2781 
2782 static int i3c_master_i2c_adapter_init(struct i3c_master_controller *master)
2783 {
2784 	struct i2c_adapter *adap = i3c_master_to_i2c_adapter(master);
2785 	struct i2c_dev_desc *i2cdev;
2786 	struct i2c_dev_boardinfo *i2cboardinfo;
2787 	int ret, id;
2788 
2789 	adap->dev.parent = master->dev.parent;
2790 	adap->owner = master->dev.parent->driver->owner;
2791 	adap->algo = &i3c_master_i2c_algo;
2792 	strscpy(adap->name, dev_name(master->dev.parent), sizeof(adap->name));
2793 	adap->timeout = HZ;
2794 	adap->retries = 3;
2795 
2796 	id = of_alias_get_id(master->dev.of_node, "i2c");
2797 	if (id >= 0) {
2798 		adap->nr = id;
2799 		ret = i2c_add_numbered_adapter(adap);
2800 	} else {
2801 		ret = i2c_add_adapter(adap);
2802 	}
2803 	if (ret)
2804 		return ret;
2805 
2806 	/*
2807 	 * We silently ignore failures here. The bus should keep working
2808 	 * correctly even if one or more i2c devices are not registered.
2809 	 */
2810 	list_for_each_entry(i2cboardinfo, &master->boardinfo.i2c, node) {
2811 		i2cdev = i3c_master_find_i2c_dev_by_addr(master,
2812 							 i2cboardinfo->base.addr);
2813 		if (WARN_ON(!i2cdev))
2814 			continue;
2815 		i2cdev->dev = i2c_new_client_device(adap, &i2cboardinfo->base);
2816 	}
2817 
2818 	return 0;
2819 }
2820 
2821 static void i3c_master_i2c_adapter_cleanup(struct i3c_master_controller *master)
2822 {
2823 	struct i2c_dev_desc *i2cdev;
2824 
2825 	i2c_del_adapter(&master->i2c);
2826 
2827 	i3c_bus_for_each_i2cdev(&master->bus, i2cdev)
2828 		i2cdev->dev = NULL;
2829 }
2830 
2831 static void i3c_master_unregister_i3c_devs(struct i3c_master_controller *master)
2832 {
2833 	struct i3c_dev_desc *i3cdev;
2834 
2835 	i3c_bus_for_each_i3cdev(&master->bus, i3cdev) {
2836 		if (!i3cdev->dev)
2837 			continue;
2838 
2839 		i3cdev->dev->desc = NULL;
2840 		if (device_is_registered(&i3cdev->dev->dev))
2841 			device_unregister(&i3cdev->dev->dev);
2842 		else
2843 			put_device(&i3cdev->dev->dev);
2844 		i3cdev->dev = NULL;
2845 	}
2846 }
2847 
2848 /**
2849  * i3c_master_queue_ibi() - Queue an IBI
2850  * @dev: the device this IBI is coming from
2851  * @slot: the IBI slot used to store the payload
2852  *
2853  * Queue an IBI to the controller workqueue. The IBI handler attached to
2854  * the dev will be called from a workqueue context.
2855  */
2856 void i3c_master_queue_ibi(struct i3c_dev_desc *dev, struct i3c_ibi_slot *slot)
2857 {
2858 	if (!dev->ibi || !slot)
2859 		return;
2860 
2861 	atomic_inc(&dev->ibi->pending_ibis);
2862 	queue_work(dev->ibi->wq, &slot->work);
2863 }
2864 EXPORT_SYMBOL_GPL(i3c_master_queue_ibi);
2865 
2866 static void i3c_master_handle_ibi(struct work_struct *work)
2867 {
2868 	struct i3c_ibi_slot *slot = container_of(work, struct i3c_ibi_slot,
2869 						 work);
2870 	struct i3c_dev_desc *dev = slot->dev;
2871 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
2872 	struct i3c_ibi_payload payload;
2873 
2874 	payload.data = slot->data;
2875 	payload.len = slot->len;
2876 
2877 	if (dev->dev)
2878 		dev->ibi->handler(dev->dev, &payload);
2879 
2880 	master->ops->recycle_ibi_slot(dev, slot);
2881 	if (atomic_dec_and_test(&dev->ibi->pending_ibis))
2882 		complete(&dev->ibi->all_ibis_handled);
2883 }
2884 
2885 static void i3c_master_init_ibi_slot(struct i3c_dev_desc *dev,
2886 				     struct i3c_ibi_slot *slot)
2887 {
2888 	slot->dev = dev;
2889 	INIT_WORK(&slot->work, i3c_master_handle_ibi);
2890 }
2891 
2892 struct i3c_generic_ibi_slot {
2893 	struct list_head node;
2894 	struct i3c_ibi_slot base;
2895 };
2896 
2897 struct i3c_generic_ibi_pool {
2898 	spinlock_t lock;
2899 	unsigned int num_slots;
2900 	void *payload_buf;
2901 	struct list_head free_slots;
2902 	struct list_head pending;
2903 	struct i3c_generic_ibi_slot slots[] __counted_by(num_slots);
2904 };
2905 
2906 /**
2907  * i3c_generic_ibi_free_pool() - Free a generic IBI pool
2908  * @pool: the IBI pool to free
2909  *
2910  * Free all IBI slots allated by a generic IBI pool.
2911  */
2912 void i3c_generic_ibi_free_pool(struct i3c_generic_ibi_pool *pool)
2913 {
2914 	struct i3c_generic_ibi_slot *slot;
2915 	unsigned int nslots = 0;
2916 
2917 	while (!list_empty(&pool->free_slots)) {
2918 		slot = list_first_entry(&pool->free_slots,
2919 					struct i3c_generic_ibi_slot, node);
2920 		list_del(&slot->node);
2921 		nslots++;
2922 	}
2923 
2924 	/*
2925 	 * If the number of freed slots is not equal to the number of allocated
2926 	 * slots we have a leak somewhere.
2927 	 */
2928 	WARN_ON(nslots != pool->num_slots);
2929 
2930 	kfree(pool->payload_buf);
2931 	kfree(pool);
2932 }
2933 EXPORT_SYMBOL_GPL(i3c_generic_ibi_free_pool);
2934 
2935 /**
2936  * i3c_generic_ibi_alloc_pool() - Create a generic IBI pool
2937  * @dev: the device this pool will be used for
2938  * @req: IBI setup request describing what the device driver expects
2939  *
2940  * Create a generic IBI pool based on the information provided in @req.
2941  *
2942  * Return: a valid IBI pool in case of success, an ERR_PTR() otherwise.
2943  */
2944 struct i3c_generic_ibi_pool *
2945 i3c_generic_ibi_alloc_pool(struct i3c_dev_desc *dev,
2946 			   const struct i3c_ibi_setup *req)
2947 {
2948 	struct i3c_generic_ibi_pool *pool;
2949 	struct i3c_generic_ibi_slot *slot;
2950 	unsigned int i;
2951 	int ret;
2952 
2953 	pool = kzalloc_flex(*pool, slots, req->num_slots);
2954 	if (!pool)
2955 		return ERR_PTR(-ENOMEM);
2956 
2957 	pool->num_slots = req->num_slots;
2958 
2959 	spin_lock_init(&pool->lock);
2960 	INIT_LIST_HEAD(&pool->free_slots);
2961 	INIT_LIST_HEAD(&pool->pending);
2962 
2963 	if (req->max_payload_len) {
2964 		pool->payload_buf = kcalloc(req->num_slots,
2965 					    req->max_payload_len, GFP_KERNEL);
2966 		if (!pool->payload_buf) {
2967 			ret = -ENOMEM;
2968 			goto err_free_pool;
2969 		}
2970 	}
2971 
2972 	for (i = 0; i < req->num_slots; i++) {
2973 		slot = &pool->slots[i];
2974 		i3c_master_init_ibi_slot(dev, &slot->base);
2975 
2976 		if (req->max_payload_len)
2977 			slot->base.data = pool->payload_buf +
2978 					  (i * req->max_payload_len);
2979 
2980 		list_add_tail(&slot->node, &pool->free_slots);
2981 	}
2982 
2983 	return pool;
2984 
2985 err_free_pool:
2986 	i3c_generic_ibi_free_pool(pool);
2987 	return ERR_PTR(ret);
2988 }
2989 EXPORT_SYMBOL_GPL(i3c_generic_ibi_alloc_pool);
2990 
2991 /**
2992  * i3c_generic_ibi_get_free_slot() - Get a free slot from a generic IBI pool
2993  * @pool: the pool to query an IBI slot on
2994  *
2995  * Search for a free slot in a generic IBI pool.
2996  * The slot should be returned to the pool using i3c_generic_ibi_recycle_slot()
2997  * when it's no longer needed.
2998  *
2999  * Return: a pointer to a free slot, or NULL if there's no free slot available.
3000  */
3001 struct i3c_ibi_slot *
3002 i3c_generic_ibi_get_free_slot(struct i3c_generic_ibi_pool *pool)
3003 {
3004 	struct i3c_generic_ibi_slot *slot;
3005 	unsigned long flags;
3006 
3007 	spin_lock_irqsave(&pool->lock, flags);
3008 	slot = list_first_entry_or_null(&pool->free_slots,
3009 					struct i3c_generic_ibi_slot, node);
3010 	if (slot)
3011 		list_del(&slot->node);
3012 	spin_unlock_irqrestore(&pool->lock, flags);
3013 
3014 	return slot ? &slot->base : NULL;
3015 }
3016 EXPORT_SYMBOL_GPL(i3c_generic_ibi_get_free_slot);
3017 
3018 /**
3019  * i3c_generic_ibi_recycle_slot() - Return a slot to a generic IBI pool
3020  * @pool: the pool to return the IBI slot to
3021  * @s: IBI slot to recycle
3022  *
3023  * Add an IBI slot back to its generic IBI pool. Should be called from the
3024  * master driver struct_master_controller_ops->recycle_ibi() method.
3025  */
3026 void i3c_generic_ibi_recycle_slot(struct i3c_generic_ibi_pool *pool,
3027 				  struct i3c_ibi_slot *s)
3028 {
3029 	struct i3c_generic_ibi_slot *slot;
3030 	unsigned long flags;
3031 
3032 	if (!s)
3033 		return;
3034 
3035 	slot = container_of(s, struct i3c_generic_ibi_slot, base);
3036 	spin_lock_irqsave(&pool->lock, flags);
3037 	list_add_tail(&slot->node, &pool->free_slots);
3038 	spin_unlock_irqrestore(&pool->lock, flags);
3039 }
3040 EXPORT_SYMBOL_GPL(i3c_generic_ibi_recycle_slot);
3041 
3042 static int i3c_master_check_ops(const struct i3c_master_controller_ops *ops)
3043 {
3044 	if (!ops || !ops->bus_init || !ops->i3c_xfers ||
3045 	    !ops->send_ccc_cmd || !ops->do_daa || !ops->i2c_xfers)
3046 		return -EINVAL;
3047 
3048 	if (ops->request_ibi &&
3049 	    (!ops->enable_ibi || !ops->disable_ibi || !ops->free_ibi ||
3050 	     !ops->recycle_ibi_slot))
3051 		return -EINVAL;
3052 
3053 	return 0;
3054 }
3055 
3056 /**
3057  * i3c_master_register() - register an I3C master
3058  * @master: master used to send frames on the bus
3059  * @parent: the parent device (the one that provides this I3C master
3060  *	    controller)
3061  * @ops: the master controller operations
3062  * @secondary: true if you are registering a secondary master. Will return
3063  *	       -EOPNOTSUPP if set to true since secondary masters are not yet
3064  *	       supported
3065  *
3066  * This function takes care of everything for you:
3067  *
3068  * - creates and initializes the I3C bus
3069  * - populates the bus with static I2C devs if @parent->of_node is not
3070  *   NULL
3071  * - registers all I3C devices added by the controller during bus
3072  *   initialization
3073  * - registers the I2C adapter and all I2C devices
3074  *
3075  * Return: 0 in case of success, a negative error code otherwise.
3076  */
3077 int i3c_master_register(struct i3c_master_controller *master,
3078 			struct device *parent,
3079 			const struct i3c_master_controller_ops *ops,
3080 			bool secondary)
3081 {
3082 	unsigned long i2c_scl_rate = I3C_BUS_I2C_FM_PLUS_SCL_MAX_RATE;
3083 	struct i3c_bus *i3cbus = i3c_master_get_bus(master);
3084 	enum i3c_bus_mode mode = I3C_BUS_MODE_PURE;
3085 	struct i2c_dev_boardinfo *i2cbi;
3086 	int ret;
3087 
3088 	/* We do not support secondary masters yet. */
3089 	if (secondary)
3090 		return -EOPNOTSUPP;
3091 
3092 	ret = i3c_master_check_ops(ops);
3093 	if (ret)
3094 		return ret;
3095 
3096 	master->dev.parent = parent;
3097 	master->dev.of_node = of_node_get(parent->of_node);
3098 	master->dev.bus = &i3c_bus_type;
3099 	master->dev.type = &i3c_masterdev_type;
3100 	master->dev.release = i3c_masterdev_release;
3101 	master->ops = ops;
3102 	master->secondary = secondary;
3103 	INIT_LIST_HEAD(&master->boardinfo.i2c);
3104 	INIT_LIST_HEAD(&master->boardinfo.i3c);
3105 
3106 	ret = i3c_master_rpm_get(master);
3107 	if (ret)
3108 		return ret;
3109 
3110 	device_initialize(&master->dev);
3111 
3112 	master->dev.dma_mask = parent->dma_mask;
3113 	master->dev.coherent_dma_mask = parent->coherent_dma_mask;
3114 	master->dev.dma_parms = parent->dma_parms;
3115 
3116 	ret = i3c_bus_init(i3cbus, master->dev.of_node);
3117 	if (ret)
3118 		goto err_put_dev;
3119 
3120 	dev_set_name(&master->dev, "i3c-%d", i3cbus->id);
3121 
3122 	ret = of_populate_i3c_bus(master);
3123 	if (ret)
3124 		goto err_put_dev;
3125 
3126 	list_for_each_entry(i2cbi, &master->boardinfo.i2c, node) {
3127 		switch (i2cbi->lvr & I3C_LVR_I2C_INDEX_MASK) {
3128 		case I3C_LVR_I2C_INDEX(0):
3129 			if (mode < I3C_BUS_MODE_MIXED_FAST)
3130 				mode = I3C_BUS_MODE_MIXED_FAST;
3131 			break;
3132 		case I3C_LVR_I2C_INDEX(1):
3133 			if (mode < I3C_BUS_MODE_MIXED_LIMITED)
3134 				mode = I3C_BUS_MODE_MIXED_LIMITED;
3135 			break;
3136 		case I3C_LVR_I2C_INDEX(2):
3137 			if (mode < I3C_BUS_MODE_MIXED_SLOW)
3138 				mode = I3C_BUS_MODE_MIXED_SLOW;
3139 			break;
3140 		default:
3141 			ret = -EINVAL;
3142 			goto err_put_dev;
3143 		}
3144 
3145 		if (i2cbi->lvr & I3C_LVR_I2C_FM_MODE)
3146 			i2c_scl_rate = I3C_BUS_I2C_FM_SCL_MAX_RATE;
3147 	}
3148 
3149 	ret = i3c_bus_set_mode(i3cbus, mode, i2c_scl_rate);
3150 	if (ret)
3151 		goto err_put_dev;
3152 
3153 	master->wq = alloc_workqueue("%s", WQ_PERCPU | WQ_FREEZABLE, 0, dev_name(parent));
3154 	if (!master->wq) {
3155 		ret = -ENOMEM;
3156 		goto err_put_dev;
3157 	}
3158 	INIT_WORK(&master->hj_work, i3c_master_hj_work_fn);
3159 	INIT_WORK(&master->reg_work, i3c_master_reg_work_fn);
3160 
3161 	ret = i3c_master_bus_init(master);
3162 	if (ret)
3163 		goto err_put_dev;
3164 
3165 	ret = device_add(&master->dev);
3166 	if (ret)
3167 		goto err_cleanup_bus;
3168 
3169 	/*
3170 	 * Expose our I3C bus as an I2C adapter so that I2C devices are exposed
3171 	 * through the I2C subsystem.
3172 	 */
3173 	ret = i3c_master_i2c_adapter_init(master);
3174 	if (ret)
3175 		goto err_del_dev;
3176 
3177 	i3c_bus_notify(i3cbus, I3C_NOTIFY_BUS_ADD);
3178 
3179 	pm_runtime_no_callbacks(&master->dev);
3180 	pm_suspend_ignore_children(&master->dev, true);
3181 	pm_runtime_enable(&master->dev);
3182 
3183 	/*
3184 	 * We're done initializing the bus and the controller, we can now
3185 	 * register I3C devices discovered during the initial DAA. Device
3186 	 * registration is done via reg_work because that keeps a single
3187 	 * registration code path and ensures the worker is the only writer
3188 	 * of desc->dev. Flush the work to preserve synchronous probe-time
3189 	 * behavior.
3190 	 */
3191 	master->init_done = true;
3192 	queue_work(master->wq, &master->reg_work);
3193 	flush_work(&master->reg_work);
3194 
3195 	if (master->ops->set_dev_nack_retry)
3196 		device_create_file(&master->dev, &dev_attr_dev_nack_retry_count);
3197 
3198 	i3c_master_rpm_put(master);
3199 
3200 	return 0;
3201 
3202 err_del_dev:
3203 	device_del(&master->dev);
3204 
3205 err_cleanup_bus:
3206 	i3c_master_bus_cleanup(master);
3207 
3208 err_put_dev:
3209 	i3c_master_rpm_put(master);
3210 	put_device(&master->dev);
3211 
3212 	return ret;
3213 }
3214 EXPORT_SYMBOL_GPL(i3c_master_register);
3215 
3216 /**
3217  * i3c_master_unregister() - unregister an I3C master
3218  * @master: master used to send frames on the bus
3219  *
3220  * Basically undo everything done in i3c_master_register().
3221  */
3222 void i3c_master_unregister(struct i3c_master_controller *master)
3223 {
3224 	i3c_bus_notify(&master->bus, I3C_NOTIFY_BUS_REMOVE);
3225 	i3c_master_shutdown(master);
3226 
3227 	if (master->ops->set_dev_nack_retry)
3228 		device_remove_file(&master->dev, &dev_attr_dev_nack_retry_count);
3229 
3230 	i3c_master_i2c_adapter_cleanup(master);
3231 	i3c_master_unregister_i3c_devs(master);
3232 	i3c_master_bus_cleanup(master);
3233 	pm_runtime_disable(&master->dev);
3234 	device_unregister(&master->dev);
3235 }
3236 EXPORT_SYMBOL_GPL(i3c_master_unregister);
3237 
3238 int i3c_dev_setdasa_locked(struct i3c_dev_desc *dev)
3239 {
3240 	struct i3c_master_controller *master;
3241 
3242 	if (!dev)
3243 		return -ENOENT;
3244 
3245 	master = i3c_dev_get_master(dev);
3246 	if (!master)
3247 		return -EINVAL;
3248 
3249 	if (!dev->boardinfo || !dev->boardinfo->init_dyn_addr ||
3250 		!dev->boardinfo->static_addr)
3251 		return -EINVAL;
3252 
3253 	return i3c_master_setdasa_locked(master, dev->info.static_addr,
3254 						dev->boardinfo->init_dyn_addr);
3255 }
3256 
3257 int i3c_dev_do_xfers_locked(struct i3c_dev_desc *dev, struct i3c_xfer *xfers,
3258 			    int nxfers, enum i3c_xfer_mode mode)
3259 {
3260 	struct i3c_master_controller *master;
3261 
3262 	if (!dev)
3263 		return -ENOENT;
3264 
3265 	master = i3c_dev_get_master(dev);
3266 	if (!master || !xfers)
3267 		return -EINVAL;
3268 
3269 	if (mode != I3C_SDR && !(master->this->info.hdr_cap & BIT(mode)))
3270 		return -EOPNOTSUPP;
3271 
3272 	return master->ops->i3c_xfers(dev, xfers, nxfers, mode);
3273 }
3274 
3275 int i3c_dev_disable_ibi_locked(struct i3c_dev_desc *dev)
3276 {
3277 	struct i3c_master_controller *master;
3278 	int ret;
3279 
3280 	if (!dev->ibi)
3281 		return -EINVAL;
3282 
3283 	master = i3c_dev_get_master(dev);
3284 	ret = master->ops->disable_ibi(dev);
3285 	if (ret)
3286 		return ret;
3287 
3288 	reinit_completion(&dev->ibi->all_ibis_handled);
3289 	if (atomic_read(&dev->ibi->pending_ibis))
3290 		wait_for_completion(&dev->ibi->all_ibis_handled);
3291 
3292 	dev->ibi->enabled = false;
3293 
3294 	return 0;
3295 }
3296 
3297 int i3c_dev_enable_ibi_locked(struct i3c_dev_desc *dev)
3298 {
3299 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
3300 	int ret;
3301 
3302 	if (!dev->ibi)
3303 		return -EINVAL;
3304 
3305 	ret = master->ops->enable_ibi(dev);
3306 	if (!ret)
3307 		dev->ibi->enabled = true;
3308 
3309 	return ret;
3310 }
3311 
3312 int i3c_dev_request_ibi_locked(struct i3c_dev_desc *dev,
3313 			       const struct i3c_ibi_setup *req)
3314 {
3315 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
3316 	struct i3c_device_ibi_info *ibi;
3317 	int ret;
3318 
3319 	if (!master->ops->request_ibi)
3320 		return -EOPNOTSUPP;
3321 
3322 	if (dev->ibi)
3323 		return -EBUSY;
3324 
3325 	ibi = kzalloc_obj(*ibi);
3326 	if (!ibi)
3327 		return -ENOMEM;
3328 
3329 	ibi->wq = alloc_ordered_workqueue(dev_name(i3cdev_to_dev(dev->dev)), WQ_MEM_RECLAIM);
3330 	if (!ibi->wq) {
3331 		kfree(ibi);
3332 		return -ENOMEM;
3333 	}
3334 
3335 	atomic_set(&ibi->pending_ibis, 0);
3336 	init_completion(&ibi->all_ibis_handled);
3337 	ibi->handler = req->handler;
3338 	ibi->max_payload_len = req->max_payload_len;
3339 	ibi->num_slots = req->num_slots;
3340 
3341 	dev->ibi = ibi;
3342 	ret = master->ops->request_ibi(dev, req);
3343 	if (ret) {
3344 		kfree(ibi);
3345 		dev->ibi = NULL;
3346 	}
3347 
3348 	return ret;
3349 }
3350 
3351 void i3c_dev_free_ibi_locked(struct i3c_dev_desc *dev)
3352 {
3353 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
3354 
3355 	if (!dev->ibi)
3356 		return;
3357 
3358 	if (dev->ibi->enabled) {
3359 		int ret;
3360 
3361 		dev_err(&master->dev, "Freeing IBI that is still enabled\n");
3362 		ret = i3c_master_rpm_get(master);
3363 		if (!ret) {
3364 			ret = i3c_dev_disable_ibi_locked(dev);
3365 			i3c_master_rpm_put(master);
3366 		}
3367 		if (ret)
3368 			dev_err(&master->dev, "Failed to disable IBI before freeing\n");
3369 	}
3370 
3371 	master->ops->free_ibi(dev);
3372 
3373 	if (dev->ibi->wq) {
3374 		destroy_workqueue(dev->ibi->wq);
3375 		dev->ibi->wq = NULL;
3376 	}
3377 
3378 	kfree(dev->ibi);
3379 	dev->ibi = NULL;
3380 }
3381 
3382 static int __init i3c_init(void)
3383 {
3384 	int res;
3385 
3386 	res = of_alias_get_highest_id("i3c");
3387 	if (res >= 0) {
3388 		mutex_lock(&i3c_core_lock);
3389 		__i3c_first_dynamic_bus_num = res + 1;
3390 		mutex_unlock(&i3c_core_lock);
3391 	}
3392 
3393 	res = bus_register_notifier(&i2c_bus_type, &i2cdev_notifier);
3394 	if (res)
3395 		return res;
3396 
3397 	res = bus_register(&i3c_bus_type);
3398 	if (res)
3399 		goto out_unreg_notifier;
3400 
3401 	return 0;
3402 
3403 out_unreg_notifier:
3404 	bus_unregister_notifier(&i2c_bus_type, &i2cdev_notifier);
3405 
3406 	return res;
3407 }
3408 subsys_initcall(i3c_init);
3409 
3410 static void __exit i3c_exit(void)
3411 {
3412 	bus_unregister_notifier(&i2c_bus_type, &i2cdev_notifier);
3413 	idr_destroy(&i3c_bus_idr);
3414 	bus_unregister(&i3c_bus_type);
3415 }
3416 module_exit(i3c_exit);
3417 
3418 MODULE_AUTHOR("Boris Brezillon <boris.brezillon@bootlin.com>");
3419 MODULE_DESCRIPTION("I3C core");
3420 MODULE_LICENSE("GPL v2");
3421