xref: /linux/drivers/i3c/master.c (revision b3ba8383da4d0cff15810e32ea785eceb0a80813)
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_do_daa_ext() - Dynamic Address Assignment (extended version)
1875  * @master: controller
1876  * @rstdaa: whether to first perform Reset of Dynamic Addresses (RSTDAA)
1877  *
1878  * Perform Dynamic Address Assignment with optional support for System
1879  * Hibernation (@rstdaa is true).
1880  *
1881  * After System Hibernation, Dynamic Addresses can have been reassigned at boot
1882  * time to different values. A simple strategy is followed to handle that.
1883  * Perform a Reset of Dynamic Addresses (RSTDAA) followed by the normal DAA
1884  * procedure which has provision for reassigning addresses that differ from the
1885  * previously recorded addresses.
1886  *
1887  * Return: a 0 in case of success, an negative error code otherwise.
1888  */
1889 int i3c_master_do_daa_ext(struct i3c_master_controller *master, bool rstdaa)
1890 {
1891 	int rstret = 0;
1892 	int ret;
1893 
1894 	ret = i3c_master_rpm_get(master);
1895 	if (ret)
1896 		return ret;
1897 
1898 	i3c_bus_maintenance_lock(&master->bus);
1899 
1900 	if (master->shutting_down) {
1901 		ret = -ENODEV;
1902 	} else {
1903 		if (rstdaa)
1904 			rstret = i3c_master_rstdaa_locked(master, I3C_BROADCAST_ADDR);
1905 		ret = master->ops->do_daa(master);
1906 	}
1907 
1908 	i3c_bus_maintenance_unlock(&master->bus);
1909 
1910 	if (ret)
1911 		goto out;
1912 
1913 	queue_work(master->wq, &master->reg_work);
1914 out:
1915 	i3c_master_rpm_put(master);
1916 
1917 	return rstret ?: ret;
1918 }
1919 EXPORT_SYMBOL_GPL(i3c_master_do_daa_ext);
1920 
1921 /**
1922  * i3c_master_do_daa() - do a DAA (Dynamic Address Assignment)
1923  * @master: master doing the DAA
1924  *
1925  * This function instantiates I3C device objects and adds them to the
1926  * I3C device list. All device information is automatically retrieved using
1927  * standard CCC commands.
1928  *
1929  * Return: a 0 in case of success, an negative error code otherwise.
1930  */
1931 int i3c_master_do_daa(struct i3c_master_controller *master)
1932 {
1933 	return i3c_master_do_daa_ext(master, false);
1934 }
1935 EXPORT_SYMBOL_GPL(i3c_master_do_daa);
1936 
1937 /**
1938  * i3c_master_dma_map_single() - Map buffer for single DMA transfer
1939  * @dev: device object of a device doing DMA
1940  * @buf: destination/source buffer for DMA
1941  * @len: length of transfer
1942  * @force_bounce: true, force to use a bounce buffer,
1943  *                false, function will auto check is a bounce buffer required
1944  * @dir: DMA direction
1945  *
1946  * Map buffer for a DMA transfer and allocate a bounce buffer if required.
1947  *
1948  * Return: I3C DMA transfer descriptor or NULL in case of error.
1949  */
1950 struct i3c_dma *i3c_master_dma_map_single(struct device *dev, void *buf,
1951 	size_t len, bool force_bounce, enum dma_data_direction dir)
1952 {
1953 	void *bounce __free(kfree) = NULL;
1954 	void *dma_buf = buf;
1955 
1956 	struct i3c_dma *dma_xfer __free(kfree) = kzalloc_obj(*dma_xfer);
1957 	if (!dma_xfer)
1958 		return NULL;
1959 
1960 	dma_xfer->dev = dev;
1961 	dma_xfer->buf = buf;
1962 	dma_xfer->dir = dir;
1963 	dma_xfer->len = len;
1964 	dma_xfer->map_len = len;
1965 
1966 	if (is_vmalloc_addr(buf))
1967 		force_bounce = true;
1968 
1969 	if (force_bounce) {
1970 		dma_xfer->map_len = ALIGN(len, cache_line_size());
1971 		if (dir == DMA_FROM_DEVICE)
1972 			bounce = kzalloc(dma_xfer->map_len, GFP_KERNEL);
1973 		else
1974 			bounce = kmemdup(buf, dma_xfer->map_len, GFP_KERNEL);
1975 		if (!bounce)
1976 			return NULL;
1977 		dma_buf = bounce;
1978 	}
1979 
1980 	dma_xfer->addr = dma_map_single(dev, dma_buf, dma_xfer->map_len, dir);
1981 	if (dma_mapping_error(dev, dma_xfer->addr))
1982 		return NULL;
1983 
1984 	dma_xfer->bounce_buf = no_free_ptr(bounce);
1985 	return no_free_ptr(dma_xfer);
1986 }
1987 EXPORT_SYMBOL_GPL(i3c_master_dma_map_single);
1988 
1989 /**
1990  * i3c_master_dma_unmap_single() - Unmap buffer after DMA
1991  * @dma_xfer: DMA transfer and mapping descriptor
1992  *
1993  * Unmap buffer and cleanup DMA transfer descriptor.
1994  */
1995 void i3c_master_dma_unmap_single(struct i3c_dma *dma_xfer)
1996 {
1997 	dma_unmap_single(dma_xfer->dev, dma_xfer->addr,
1998 			 dma_xfer->map_len, dma_xfer->dir);
1999 	if (dma_xfer->bounce_buf) {
2000 		if (dma_xfer->dir == DMA_FROM_DEVICE)
2001 			memcpy(dma_xfer->buf, dma_xfer->bounce_buf,
2002 			       dma_xfer->len);
2003 		kfree(dma_xfer->bounce_buf);
2004 	}
2005 	kfree(dma_xfer);
2006 }
2007 EXPORT_SYMBOL_GPL(i3c_master_dma_unmap_single);
2008 
2009 /**
2010  * i3c_master_set_info() - set master device information
2011  * @master: master used to send frames on the bus
2012  * @info: I3C device information
2013  *
2014  * Set master device info. This should be called from
2015  * &i3c_master_controller_ops->bus_init().
2016  *
2017  * Not all &i3c_device_info fields are meaningful for a master device.
2018  * Here is a list of fields that should be properly filled:
2019  *
2020  * - &i3c_device_info->dyn_addr
2021  * - &i3c_device_info->bcr
2022  * - &i3c_device_info->dcr
2023  * - &i3c_device_info->pid
2024  * - &i3c_device_info->hdr_cap if %I3C_BCR_HDR_CAP bit is set in
2025  *   &i3c_device_info->bcr
2026  *
2027  * This function must be called with the bus lock held in maintenance mode.
2028  *
2029  * Return: 0 if @info contains valid information (not every piece of
2030  * information can be checked, but we can at least make sure @info->dyn_addr
2031  * and @info->bcr are correct), -EINVAL otherwise.
2032  */
2033 int i3c_master_set_info(struct i3c_master_controller *master,
2034 			const struct i3c_device_info *info)
2035 {
2036 	struct i3c_dev_desc *i3cdev;
2037 	int ret;
2038 
2039 	if (!i3c_bus_dev_addr_is_avail(&master->bus, info->dyn_addr))
2040 		return -EINVAL;
2041 
2042 	if (I3C_BCR_DEVICE_ROLE(info->bcr) == I3C_BCR_I3C_MASTER &&
2043 	    master->secondary)
2044 		return -EINVAL;
2045 
2046 	if (master->this)
2047 		return -EINVAL;
2048 
2049 	i3cdev = i3c_master_alloc_i3c_dev(master, info);
2050 	if (IS_ERR(i3cdev))
2051 		return PTR_ERR(i3cdev);
2052 
2053 	master->this = i3cdev;
2054 	master->bus.cur_master = master->this;
2055 
2056 	ret = i3c_master_attach_i3c_dev(master, i3cdev);
2057 	if (ret)
2058 		goto err_free_dev;
2059 
2060 	return 0;
2061 
2062 err_free_dev:
2063 	i3c_master_free_i3c_dev(i3cdev);
2064 
2065 	return ret;
2066 }
2067 EXPORT_SYMBOL_GPL(i3c_master_set_info);
2068 
2069 static void i3c_master_detach_free_devs(struct i3c_master_controller *master)
2070 {
2071 	struct i3c_dev_desc *i3cdev, *i3ctmp;
2072 	struct i2c_dev_desc *i2cdev, *i2ctmp;
2073 
2074 	list_for_each_entry_safe(i3cdev, i3ctmp, &master->bus.devs.i3c,
2075 				 common.node) {
2076 		i3c_master_detach_i3c_dev(i3cdev);
2077 
2078 		if (i3cdev->boardinfo && i3cdev->boardinfo->init_dyn_addr)
2079 			i3c_bus_set_addr_slot_status(&master->bus,
2080 					i3cdev->boardinfo->init_dyn_addr,
2081 					I3C_ADDR_SLOT_FREE);
2082 
2083 		i3c_master_free_i3c_dev(i3cdev);
2084 	}
2085 
2086 	list_for_each_entry_safe(i2cdev, i2ctmp, &master->bus.devs.i2c,
2087 				 common.node) {
2088 		i3c_master_detach_i2c_dev(i2cdev);
2089 		i3c_bus_set_addr_slot_status(&master->bus,
2090 					     i2cdev->addr,
2091 					     I3C_ADDR_SLOT_FREE);
2092 		i3c_master_free_i2c_dev(i2cdev);
2093 	}
2094 }
2095 
2096 /**
2097  * i3c_master_bus_init() - initialize an I3C bus
2098  * @master: main master initializing the bus
2099  *
2100  * This function is following all initialisation steps described in the I3C
2101  * specification:
2102  *
2103  * 1. Attach I2C devs to the master so that the master can fill its internal
2104  *    device table appropriately
2105  *
2106  * 2. Call &i3c_master_controller_ops->bus_init() method to initialize
2107  *    the master controller. That's usually where the bus mode is selected
2108  *    (pure bus or mixed fast/slow bus)
2109  *
2110  * 3. Instruct all devices on the bus to drop their dynamic address. This is
2111  *    particularly important when the bus was previously configured by someone
2112  *    else (for example the bootloader)
2113  *
2114  * 4. Disable all slave events.
2115  *
2116  * 5. Reserve address slots for I3C devices with init_dyn_addr. And if devices
2117  *    also have static_addr, try to pre-assign dynamic addresses requested by
2118  *    the FW with SETDASA and attach corresponding statically defined I3C
2119  *    devices to the master.
2120  *
2121  * 6. Do a DAA (Dynamic Address Assignment) to assign dynamic addresses to all
2122  *    remaining I3C devices
2123  *
2124  * Once this is done, all I3C and I2C devices should be usable.
2125  *
2126  * Return: a 0 in case of success, an negative error code otherwise.
2127  */
2128 static int i3c_master_bus_init(struct i3c_master_controller *master)
2129 {
2130 	enum i3c_addr_slot_status status;
2131 	struct i2c_dev_boardinfo *i2cboardinfo;
2132 	struct i3c_dev_boardinfo *i3cboardinfo;
2133 	struct i2c_dev_desc *i2cdev;
2134 	int ret;
2135 
2136 	/*
2137 	 * First attach all devices with static definitions provided by the
2138 	 * FW.
2139 	 */
2140 	list_for_each_entry(i2cboardinfo, &master->boardinfo.i2c, node) {
2141 		status = i3c_bus_get_addr_slot_status(&master->bus,
2142 						      i2cboardinfo->base.addr);
2143 		if (status != I3C_ADDR_SLOT_FREE) {
2144 			ret = -EBUSY;
2145 			goto err_detach_devs;
2146 		}
2147 
2148 		i3c_bus_set_addr_slot_status(&master->bus,
2149 					     i2cboardinfo->base.addr,
2150 					     I3C_ADDR_SLOT_I2C_DEV);
2151 
2152 		i2cdev = i3c_master_alloc_i2c_dev(master,
2153 						  i2cboardinfo->base.addr,
2154 						  i2cboardinfo->lvr);
2155 		if (IS_ERR(i2cdev)) {
2156 			ret = PTR_ERR(i2cdev);
2157 			goto err_detach_devs;
2158 		}
2159 
2160 		ret = i3c_master_attach_i2c_dev(master, i2cdev);
2161 		if (ret) {
2162 			i3c_master_free_i2c_dev(i2cdev);
2163 			goto err_detach_devs;
2164 		}
2165 	}
2166 
2167 	/*
2168 	 * Now execute the controller specific ->bus_init() routine, which
2169 	 * might configure its internal logic to match the bus limitations.
2170 	 */
2171 	ret = master->ops->bus_init(master);
2172 	if (ret)
2173 		goto err_detach_devs;
2174 
2175 	/*
2176 	 * The master device should have been instantiated in ->bus_init(),
2177 	 * complain if this was not the case.
2178 	 */
2179 	if (!master->this) {
2180 		dev_err(&master->dev,
2181 			"master_set_info() was not called in ->bus_init()\n");
2182 		ret = -EINVAL;
2183 		goto err_bus_cleanup;
2184 	}
2185 
2186 	if (master->ops->set_speed) {
2187 		ret = master->ops->set_speed(master, I3C_OPEN_DRAIN_SLOW_SPEED);
2188 		if (ret)
2189 			goto err_bus_cleanup;
2190 	}
2191 
2192 	/*
2193 	 * Reset all dynamic address that may have been assigned before
2194 	 * (assigned by the bootloader for example).
2195 	 */
2196 	ret = i3c_master_rstdaa_locked(master, I3C_BROADCAST_ADDR);
2197 	if (ret)
2198 		goto err_bus_cleanup;
2199 
2200 	if (master->ops->set_speed) {
2201 		ret = master->ops->set_speed(master, I3C_OPEN_DRAIN_NORMAL_SPEED);
2202 		if (ret)
2203 			goto err_bus_cleanup;
2204 	}
2205 
2206 	/*
2207 	 * Disable all slave events before starting DAA. When no active device
2208 	 * is on the bus, returns Mx error code M2, this error is ignored.
2209 	 */
2210 	ret = i3c_master_enec_disec_locked(master, I3C_BROADCAST_ADDR, false,
2211 					   I3C_CCC_EVENT_SIR | I3C_CCC_EVENT_MR |
2212 					   I3C_CCC_EVENT_HJ, true);
2213 	if (ret)
2214 		goto err_bus_cleanup;
2215 
2216 	/*
2217 	 * Reserve init_dyn_addr first, and then try to pre-assign dynamic
2218 	 * address and retrieve device information if needed.
2219 	 * In case pre-assign dynamic address fails, setting dynamic address to
2220 	 * the requested init_dyn_addr is retried after DAA is done in
2221 	 * i3c_master_add_i3c_dev_locked().
2222 	 */
2223 	list_for_each_entry(i3cboardinfo, &master->boardinfo.i3c, node) {
2224 
2225 		/*
2226 		 * We don't reserve a dynamic address for devices that
2227 		 * don't explicitly request one.
2228 		 */
2229 		if (!i3cboardinfo->init_dyn_addr)
2230 			continue;
2231 
2232 		ret = i3c_bus_get_addr_slot_status(&master->bus,
2233 						   i3cboardinfo->init_dyn_addr);
2234 		if (ret != I3C_ADDR_SLOT_FREE) {
2235 			ret = -EBUSY;
2236 			goto err_rstdaa;
2237 		}
2238 
2239 		/* Do not mark as occupied until real device exist in bus */
2240 		i3c_bus_set_addr_slot_status_mask(&master->bus,
2241 						  i3cboardinfo->init_dyn_addr,
2242 						  I3C_ADDR_SLOT_EXT_DESIRED,
2243 						  I3C_ADDR_SLOT_EXT_STATUS_MASK);
2244 
2245 		/*
2246 		 * Only try to create/attach devices that have a static
2247 		 * address. Other devices will be created/attached when
2248 		 * DAA happens, and the requested dynamic address will
2249 		 * be set using SETNEWDA once those devices become
2250 		 * addressable.
2251 		 */
2252 
2253 		if (i3cboardinfo->static_addr)
2254 			i3c_master_early_i3c_dev_add(master, i3cboardinfo);
2255 	}
2256 
2257 	ret = i3c_master_do_daa(master);
2258 	if (ret)
2259 		goto err_rstdaa;
2260 
2261 	return 0;
2262 
2263 err_rstdaa:
2264 	i3c_master_rstdaa_locked(master, I3C_BROADCAST_ADDR);
2265 
2266 err_bus_cleanup:
2267 	if (master->ops->bus_cleanup)
2268 		master->ops->bus_cleanup(master);
2269 
2270 err_detach_devs:
2271 	i3c_master_detach_free_devs(master);
2272 
2273 	return ret;
2274 }
2275 
2276 static void i3c_master_bus_cleanup(struct i3c_master_controller *master)
2277 {
2278 	if (master->ops->bus_cleanup) {
2279 		int ret = i3c_master_rpm_get(master);
2280 
2281 		if (ret) {
2282 			dev_err(&master->dev,
2283 				"runtime resume error: master bus_cleanup() not done\n");
2284 		} else {
2285 			master->ops->bus_cleanup(master);
2286 			i3c_master_rpm_put(master);
2287 		}
2288 	}
2289 
2290 	i3c_master_detach_free_devs(master);
2291 }
2292 
2293 static void i3c_master_attach_boardinfo(struct i3c_dev_desc *i3cdev)
2294 {
2295 	struct i3c_master_controller *master = i3cdev->common.master;
2296 	struct i3c_dev_boardinfo *i3cboardinfo;
2297 
2298 	list_for_each_entry(i3cboardinfo, &master->boardinfo.i3c, node) {
2299 		if (i3cdev->info.pid != i3cboardinfo->pid)
2300 			continue;
2301 
2302 		i3cdev->boardinfo = i3cboardinfo;
2303 		i3cdev->info.static_addr = i3cboardinfo->static_addr;
2304 		return;
2305 	}
2306 }
2307 
2308 static struct i3c_dev_desc *
2309 i3c_master_search_i3c_dev_duplicate(struct i3c_dev_desc *refdev)
2310 {
2311 	struct i3c_master_controller *master = i3c_dev_get_master(refdev);
2312 	struct i3c_dev_desc *i3cdev;
2313 
2314 	i3c_bus_for_each_i3cdev(&master->bus, i3cdev) {
2315 		if (i3cdev != refdev && i3cdev->info.pid == refdev->info.pid)
2316 			return i3cdev;
2317 	}
2318 
2319 	return NULL;
2320 }
2321 
2322 /**
2323  * i3c_master_add_i3c_dev_locked() - add an I3C slave to the bus
2324  * @master: master used to send frames on the bus
2325  * @addr: I3C slave dynamic address assigned to the device
2326  *
2327  * This function is instantiating an I3C device object and adding it to the
2328  * I3C device list. All device information are automatically retrieved using
2329  * standard CCC commands.
2330  *
2331  * The I3C device object is returned in case the master wants to attach
2332  * private data to it using i3c_dev_set_master_data().
2333  *
2334  * This function must be called with the bus lock held in write mode.
2335  *
2336  * Return: a 0 in case of success, an negative error code otherwise.
2337  */
2338 int i3c_master_add_i3c_dev_locked(struct i3c_master_controller *master,
2339 				  u8 addr)
2340 {
2341 	struct i3c_device_info info = { .dyn_addr = addr };
2342 	struct i3c_dev_desc *newdev, *olddev;
2343 	u8 old_dyn_addr = addr, expected_dyn_addr;
2344 	struct i3c_ibi_setup ibireq = { };
2345 	bool enable_ibi = false;
2346 	int ret;
2347 
2348 	newdev = i3c_master_alloc_i3c_dev(master, &info);
2349 	if (IS_ERR(newdev)) {
2350 		ret = PTR_ERR(newdev);
2351 		goto err_prevent_addr_reuse;
2352 	}
2353 
2354 	ret = i3c_master_attach_i3c_dev(master, newdev);
2355 	if (ret)
2356 		goto err_free_dev;
2357 
2358 	ret = i3c_master_retrieve_dev_info(newdev);
2359 	if (ret)
2360 		goto err_detach_dev;
2361 
2362 	i3c_master_attach_boardinfo(newdev);
2363 
2364 	olddev = i3c_master_search_i3c_dev_duplicate(newdev);
2365 	if (olddev) {
2366 		newdev->dev = olddev->dev;
2367 		if (newdev->dev)
2368 			newdev->dev->desc = newdev;
2369 
2370 		/*
2371 		 * We need to restore the IBI state too, so let's save the
2372 		 * IBI information and try to restore them after olddev has
2373 		 * been detached+released and its IBI has been stopped and
2374 		 * the associated resources have been freed.
2375 		 */
2376 		mutex_lock(&olddev->ibi_lock);
2377 		if (olddev->ibi) {
2378 			ibireq.handler = olddev->ibi->handler;
2379 			ibireq.max_payload_len = olddev->ibi->max_payload_len;
2380 			ibireq.num_slots = olddev->ibi->num_slots;
2381 
2382 			if (olddev->ibi->enabled)
2383 				enable_ibi = true;
2384 			/*
2385 			 * The olddev should not receive any commands on the
2386 			 * i3c bus as it does not exist and has been assigned
2387 			 * a new address. This will result in NACK or timeout.
2388 			 * So, update the olddev->ibi->enabled flag to false
2389 			 * to avoid DISEC with OldAddr.
2390 			 */
2391 			olddev->ibi->enabled = false;
2392 			i3c_dev_free_ibi_locked(olddev);
2393 		}
2394 		mutex_unlock(&olddev->ibi_lock);
2395 
2396 		old_dyn_addr = olddev->info.dyn_addr;
2397 
2398 		i3c_master_detach_i3c_dev(olddev);
2399 		i3c_master_free_i3c_dev(olddev);
2400 	}
2401 
2402 	/*
2403 	 * Depending on our previous state, the expected dynamic address might
2404 	 * differ:
2405 	 * - if the device already had a dynamic address assigned, let's try to
2406 	 *   re-apply this one
2407 	 * - if the device did not have a dynamic address and the firmware
2408 	 *   requested a specific address, pick this one
2409 	 * - in any other case, keep the address automatically assigned by the
2410 	 *   master
2411 	 */
2412 	if (old_dyn_addr && old_dyn_addr != newdev->info.dyn_addr)
2413 		expected_dyn_addr = old_dyn_addr;
2414 	else if (newdev->boardinfo && newdev->boardinfo->init_dyn_addr)
2415 		expected_dyn_addr = newdev->boardinfo->init_dyn_addr;
2416 	else
2417 		expected_dyn_addr = newdev->info.dyn_addr;
2418 
2419 	if (newdev->info.dyn_addr != expected_dyn_addr &&
2420 	    i3c_bus_get_addr_slot_status(&master->bus, expected_dyn_addr) == I3C_ADDR_SLOT_FREE) {
2421 		/*
2422 		 * Try to apply the expected dynamic address. If it fails, keep
2423 		 * the address assigned by the master.
2424 		 */
2425 		ret = i3c_master_setnewda_locked(master,
2426 						 newdev->info.dyn_addr,
2427 						 expected_dyn_addr);
2428 		if (!ret) {
2429 			old_dyn_addr = newdev->info.dyn_addr;
2430 			newdev->info.dyn_addr = expected_dyn_addr;
2431 			i3c_master_reattach_i3c_dev(newdev, old_dyn_addr);
2432 		} else {
2433 			dev_err(&master->dev,
2434 				"Failed to assign reserved/old address to device %d%llx",
2435 				master->bus.id, newdev->info.pid);
2436 		}
2437 	}
2438 
2439 	/*
2440 	 * Now is time to try to restore the IBI setup. If we're lucky,
2441 	 * everything works as before, otherwise, all we can do is complain.
2442 	 * FIXME: maybe we should add callback to inform the driver that it
2443 	 * should request the IBI again instead of trying to hide that from
2444 	 * him.
2445 	 */
2446 	if (ibireq.handler) {
2447 		mutex_lock(&newdev->ibi_lock);
2448 		ret = i3c_dev_request_ibi_locked(newdev, &ibireq);
2449 		if (ret) {
2450 			dev_err(&master->dev,
2451 				"Failed to request IBI on device %d-%llx",
2452 				master->bus.id, newdev->info.pid);
2453 		} else if (enable_ibi) {
2454 			ret = i3c_dev_enable_ibi_locked(newdev);
2455 			if (ret)
2456 				dev_err(&master->dev,
2457 					"Failed to re-enable IBI on device %d-%llx",
2458 					master->bus.id, newdev->info.pid);
2459 		}
2460 		mutex_unlock(&newdev->ibi_lock);
2461 	}
2462 
2463 	return 0;
2464 
2465 err_detach_dev:
2466 	if (newdev->dev && newdev->dev->desc)
2467 		newdev->dev->desc = NULL;
2468 
2469 	i3c_master_detach_i3c_dev(newdev);
2470 
2471 err_free_dev:
2472 	i3c_master_free_i3c_dev(newdev);
2473 
2474 err_prevent_addr_reuse:
2475 	/*
2476 	 * Although the device has not been added, the address has been
2477 	 * assigned. Prevent the address from being used again.
2478 	 */
2479 	if (i3c_bus_get_addr_slot_status(&master->bus, addr) == I3C_ADDR_SLOT_FREE)
2480 		i3c_bus_set_addr_slot_status(&master->bus, addr, I3C_ADDR_SLOT_I3C_DEV);
2481 
2482 	dev_err(&master->dev, "Failed to add I3C device at address %u, error %d\n", addr, ret);
2483 
2484 	return ret;
2485 }
2486 EXPORT_SYMBOL_GPL(i3c_master_add_i3c_dev_locked);
2487 
2488 #define OF_I3C_REG1_IS_I2C_DEV			BIT(31)
2489 
2490 static int
2491 of_i3c_master_add_i2c_boardinfo(struct i3c_master_controller *master,
2492 				struct device_node *node, u32 *reg)
2493 {
2494 	struct i2c_dev_boardinfo *boardinfo;
2495 	struct device *dev = &master->dev;
2496 	int ret;
2497 
2498 	boardinfo = devm_kzalloc(dev, sizeof(*boardinfo), GFP_KERNEL);
2499 	if (!boardinfo)
2500 		return -ENOMEM;
2501 
2502 	ret = of_i2c_get_board_info(dev, node, &boardinfo->base);
2503 	if (ret)
2504 		return ret;
2505 
2506 	/*
2507 	 * The I3C Specification does not clearly say I2C devices with 10-bit
2508 	 * address are supported. These devices can't be passed properly through
2509 	 * DEFSLVS command.
2510 	 */
2511 	if (boardinfo->base.flags & I2C_CLIENT_TEN) {
2512 		dev_err(dev, "I2C device with 10 bit address not supported.\n");
2513 		return -EOPNOTSUPP;
2514 	}
2515 
2516 	/* LVR is encoded in reg[2]. */
2517 	boardinfo->lvr = reg[2];
2518 
2519 	list_add_tail(&boardinfo->node, &master->boardinfo.i2c);
2520 	of_node_get(node);
2521 
2522 	return 0;
2523 }
2524 
2525 static int
2526 of_i3c_master_add_i3c_boardinfo(struct i3c_master_controller *master,
2527 				struct device_node *node, u32 *reg)
2528 {
2529 	struct i3c_dev_boardinfo *boardinfo;
2530 	struct device *dev = &master->dev;
2531 	enum i3c_addr_slot_status addrstatus;
2532 	u32 init_dyn_addr = 0;
2533 
2534 	boardinfo = devm_kzalloc(dev, sizeof(*boardinfo), GFP_KERNEL);
2535 	if (!boardinfo)
2536 		return -ENOMEM;
2537 
2538 	if (reg[0]) {
2539 		if (reg[0] > I3C_MAX_ADDR)
2540 			return -EINVAL;
2541 
2542 		addrstatus = i3c_bus_get_addr_slot_status(&master->bus,
2543 							  reg[0]);
2544 		if (addrstatus != I3C_ADDR_SLOT_FREE)
2545 			return -EINVAL;
2546 	}
2547 
2548 	boardinfo->static_addr = reg[0];
2549 
2550 	if (!of_property_read_u32(node, "assigned-address", &init_dyn_addr)) {
2551 		if (init_dyn_addr > I3C_MAX_ADDR)
2552 			return -EINVAL;
2553 
2554 		addrstatus = i3c_bus_get_addr_slot_status(&master->bus,
2555 							  init_dyn_addr);
2556 		if (addrstatus != I3C_ADDR_SLOT_FREE)
2557 			return -EINVAL;
2558 	}
2559 
2560 	boardinfo->pid = ((u64)reg[1] << 32) | reg[2];
2561 
2562 	if ((boardinfo->pid & GENMASK_ULL(63, 48)) ||
2563 	    I3C_PID_RND_LOWER_32BITS(boardinfo->pid))
2564 		return -EINVAL;
2565 
2566 	boardinfo->init_dyn_addr = init_dyn_addr;
2567 	boardinfo->of_node = of_node_get(node);
2568 	list_add_tail(&boardinfo->node, &master->boardinfo.i3c);
2569 
2570 	return 0;
2571 }
2572 
2573 static int of_i3c_master_add_dev(struct i3c_master_controller *master,
2574 				 struct device_node *node)
2575 {
2576 	u32 reg[3];
2577 	int ret;
2578 
2579 	if (!master)
2580 		return -EINVAL;
2581 
2582 	ret = of_property_read_u32_array(node, "reg", reg, ARRAY_SIZE(reg));
2583 	if (ret)
2584 		return ret;
2585 
2586 	/*
2587 	 * The manufacturer ID can't be 0. If reg[1] == 0 that means we're
2588 	 * dealing with an I2C device.
2589 	 */
2590 	if (!reg[1])
2591 		ret = of_i3c_master_add_i2c_boardinfo(master, node, reg);
2592 	else
2593 		ret = of_i3c_master_add_i3c_boardinfo(master, node, reg);
2594 
2595 	return ret;
2596 }
2597 
2598 static int of_populate_i3c_bus(struct i3c_master_controller *master)
2599 {
2600 	struct device *dev = &master->dev;
2601 	struct device_node *i3cbus_np = dev->of_node;
2602 	int ret;
2603 	u32 val;
2604 
2605 	if (!i3cbus_np)
2606 		return 0;
2607 
2608 	for_each_available_child_of_node_scoped(i3cbus_np, node) {
2609 		ret = of_i3c_master_add_dev(master, node);
2610 		if (ret)
2611 			return ret;
2612 	}
2613 
2614 	/*
2615 	 * The user might want to limit I2C and I3C speed in case some devices
2616 	 * on the bus are not supporting typical rates, or if the bus topology
2617 	 * prevents it from using max possible rate.
2618 	 */
2619 	if (!of_property_read_u32(i3cbus_np, "i2c-scl-hz", &val))
2620 		master->bus.scl_rate.i2c = val;
2621 
2622 	if (!of_property_read_u32(i3cbus_np, "i3c-scl-hz", &val))
2623 		master->bus.scl_rate.i3c = val;
2624 
2625 	return 0;
2626 }
2627 
2628 static int i3c_master_i2c_adapter_xfer(struct i2c_adapter *adap,
2629 				       struct i2c_msg *xfers, int nxfers)
2630 {
2631 	struct i3c_master_controller *master = i2c_adapter_to_i3c_master(adap);
2632 	struct i2c_dev_desc *dev;
2633 	int i, ret;
2634 	u16 addr;
2635 
2636 	if (!xfers || !master || nxfers <= 0)
2637 		return -EINVAL;
2638 
2639 	if (!master->ops->i2c_xfers)
2640 		return -EOPNOTSUPP;
2641 
2642 	/* Doing transfers to different devices is not supported. */
2643 	addr = xfers[0].addr;
2644 	for (i = 1; i < nxfers; i++) {
2645 		if (addr != xfers[i].addr)
2646 			return -EOPNOTSUPP;
2647 	}
2648 
2649 	ret = i3c_master_rpm_get(master);
2650 	if (ret)
2651 		return ret;
2652 
2653 	i3c_bus_normaluse_lock(&master->bus);
2654 	dev = i3c_master_find_i2c_dev_by_addr(master, addr);
2655 	if (!dev)
2656 		ret = -ENOENT;
2657 	else
2658 		ret = master->ops->i2c_xfers(dev, xfers, nxfers);
2659 	i3c_bus_normaluse_unlock(&master->bus);
2660 
2661 	i3c_master_rpm_put(master);
2662 
2663 	return ret ? ret : nxfers;
2664 }
2665 
2666 static u32 i3c_master_i2c_funcs(struct i2c_adapter *adapter)
2667 {
2668 	return I2C_FUNC_SMBUS_EMUL | I2C_FUNC_I2C;
2669 }
2670 
2671 static u8 i3c_master_i2c_get_lvr(struct i2c_client *client)
2672 {
2673 	/* Fall back to no spike filters and FM bus mode. */
2674 	u8 lvr = I3C_LVR_I2C_INDEX(2) | I3C_LVR_I2C_FM_MODE;
2675 	u32 reg[3];
2676 
2677 	if (!of_property_read_u32_array(client->dev.of_node, "reg", reg, ARRAY_SIZE(reg)))
2678 		lvr = reg[2];
2679 
2680 	return lvr;
2681 }
2682 
2683 static int i3c_master_i2c_attach(struct i2c_adapter *adap, struct i2c_client *client)
2684 {
2685 	struct i3c_master_controller *master = i2c_adapter_to_i3c_master(adap);
2686 	enum i3c_addr_slot_status status;
2687 	struct i2c_dev_desc *i2cdev;
2688 	int ret;
2689 
2690 	/* Already added by board info? */
2691 	if (i3c_master_find_i2c_dev_by_addr(master, client->addr))
2692 		return 0;
2693 
2694 	status = i3c_bus_get_addr_slot_status(&master->bus, client->addr);
2695 	if (status != I3C_ADDR_SLOT_FREE)
2696 		return -EBUSY;
2697 
2698 	i3c_bus_set_addr_slot_status(&master->bus, client->addr,
2699 				     I3C_ADDR_SLOT_I2C_DEV);
2700 
2701 	i2cdev = i3c_master_alloc_i2c_dev(master, client->addr,
2702 					  i3c_master_i2c_get_lvr(client));
2703 	if (IS_ERR(i2cdev)) {
2704 		ret = PTR_ERR(i2cdev);
2705 		goto out_clear_status;
2706 	}
2707 
2708 	ret = i3c_master_attach_i2c_dev(master, i2cdev);
2709 	if (ret)
2710 		goto out_free_dev;
2711 
2712 	return 0;
2713 
2714 out_free_dev:
2715 	i3c_master_free_i2c_dev(i2cdev);
2716 out_clear_status:
2717 	i3c_bus_set_addr_slot_status(&master->bus, client->addr,
2718 				     I3C_ADDR_SLOT_FREE);
2719 
2720 	return ret;
2721 }
2722 
2723 static int i3c_master_i2c_detach(struct i2c_adapter *adap, struct i2c_client *client)
2724 {
2725 	struct i3c_master_controller *master = i2c_adapter_to_i3c_master(adap);
2726 	struct i2c_dev_desc *dev;
2727 
2728 	dev = i3c_master_find_i2c_dev_by_addr(master, client->addr);
2729 	if (!dev)
2730 		return -ENODEV;
2731 
2732 	i3c_master_detach_i2c_dev(dev);
2733 	i3c_bus_set_addr_slot_status(&master->bus, dev->addr,
2734 				     I3C_ADDR_SLOT_FREE);
2735 	i3c_master_free_i2c_dev(dev);
2736 
2737 	return 0;
2738 }
2739 
2740 static const struct i2c_algorithm i3c_master_i2c_algo = {
2741 	.master_xfer = i3c_master_i2c_adapter_xfer,
2742 	.functionality = i3c_master_i2c_funcs,
2743 };
2744 
2745 static int i3c_i2c_notifier_call(struct notifier_block *nb, unsigned long action,
2746 				 void *data)
2747 {
2748 	struct i2c_adapter *adap;
2749 	struct i2c_client *client;
2750 	struct device *dev = data;
2751 	struct i3c_master_controller *master;
2752 	int ret;
2753 
2754 	if (dev->type != &i2c_client_type)
2755 		return 0;
2756 
2757 	client = to_i2c_client(dev);
2758 	adap = client->adapter;
2759 
2760 	if (adap->algo != &i3c_master_i2c_algo)
2761 		return 0;
2762 
2763 	master = i2c_adapter_to_i3c_master(adap);
2764 
2765 	ret = i3c_master_rpm_get(master);
2766 	if (ret)
2767 		return ret;
2768 
2769 	i3c_bus_maintenance_lock(&master->bus);
2770 	switch (action) {
2771 	case BUS_NOTIFY_ADD_DEVICE:
2772 		ret = i3c_master_i2c_attach(adap, client);
2773 		break;
2774 	case BUS_NOTIFY_DEL_DEVICE:
2775 		ret = i3c_master_i2c_detach(adap, client);
2776 		break;
2777 	default:
2778 		ret = -EINVAL;
2779 	}
2780 	i3c_bus_maintenance_unlock(&master->bus);
2781 
2782 	i3c_master_rpm_put(master);
2783 
2784 	return ret;
2785 }
2786 
2787 static struct notifier_block i2cdev_notifier = {
2788 	.notifier_call = i3c_i2c_notifier_call,
2789 };
2790 
2791 static int i3c_master_i2c_adapter_init(struct i3c_master_controller *master)
2792 {
2793 	struct i2c_adapter *adap = i3c_master_to_i2c_adapter(master);
2794 	struct i2c_dev_desc *i2cdev;
2795 	struct i2c_dev_boardinfo *i2cboardinfo;
2796 	int ret, id;
2797 
2798 	adap->dev.parent = master->dev.parent;
2799 	adap->owner = master->dev.parent->driver->owner;
2800 	adap->algo = &i3c_master_i2c_algo;
2801 	strscpy(adap->name, dev_name(master->dev.parent), sizeof(adap->name));
2802 	adap->timeout = HZ;
2803 	adap->retries = 3;
2804 
2805 	id = of_alias_get_id(master->dev.of_node, "i2c");
2806 	if (id >= 0) {
2807 		adap->nr = id;
2808 		ret = i2c_add_numbered_adapter(adap);
2809 	} else {
2810 		ret = i2c_add_adapter(adap);
2811 	}
2812 	if (ret)
2813 		return ret;
2814 
2815 	/*
2816 	 * We silently ignore failures here. The bus should keep working
2817 	 * correctly even if one or more i2c devices are not registered.
2818 	 */
2819 	list_for_each_entry(i2cboardinfo, &master->boardinfo.i2c, node) {
2820 		i2cdev = i3c_master_find_i2c_dev_by_addr(master,
2821 							 i2cboardinfo->base.addr);
2822 		if (WARN_ON(!i2cdev))
2823 			continue;
2824 		i2cdev->dev = i2c_new_client_device(adap, &i2cboardinfo->base);
2825 	}
2826 
2827 	return 0;
2828 }
2829 
2830 static void i3c_master_i2c_adapter_cleanup(struct i3c_master_controller *master)
2831 {
2832 	struct i2c_dev_desc *i2cdev;
2833 
2834 	i2c_del_adapter(&master->i2c);
2835 
2836 	i3c_bus_for_each_i2cdev(&master->bus, i2cdev)
2837 		i2cdev->dev = NULL;
2838 }
2839 
2840 static void i3c_master_unregister_i3c_devs(struct i3c_master_controller *master)
2841 {
2842 	struct i3c_dev_desc *i3cdev;
2843 
2844 	i3c_bus_for_each_i3cdev(&master->bus, i3cdev) {
2845 		if (!i3cdev->dev)
2846 			continue;
2847 
2848 		i3cdev->dev->desc = NULL;
2849 		if (device_is_registered(&i3cdev->dev->dev))
2850 			device_unregister(&i3cdev->dev->dev);
2851 		else
2852 			put_device(&i3cdev->dev->dev);
2853 		i3cdev->dev = NULL;
2854 	}
2855 }
2856 
2857 /**
2858  * i3c_master_queue_ibi() - Queue an IBI
2859  * @dev: the device this IBI is coming from
2860  * @slot: the IBI slot used to store the payload
2861  *
2862  * Queue an IBI to the controller workqueue. The IBI handler attached to
2863  * the dev will be called from a workqueue context.
2864  */
2865 void i3c_master_queue_ibi(struct i3c_dev_desc *dev, struct i3c_ibi_slot *slot)
2866 {
2867 	if (!dev->ibi || !slot)
2868 		return;
2869 
2870 	atomic_inc(&dev->ibi->pending_ibis);
2871 	queue_work(dev->ibi->wq, &slot->work);
2872 }
2873 EXPORT_SYMBOL_GPL(i3c_master_queue_ibi);
2874 
2875 static void i3c_master_handle_ibi(struct work_struct *work)
2876 {
2877 	struct i3c_ibi_slot *slot = container_of(work, struct i3c_ibi_slot,
2878 						 work);
2879 	struct i3c_dev_desc *dev = slot->dev;
2880 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
2881 	struct i3c_ibi_payload payload;
2882 
2883 	payload.data = slot->data;
2884 	payload.len = slot->len;
2885 
2886 	if (dev->dev)
2887 		dev->ibi->handler(dev->dev, &payload);
2888 
2889 	master->ops->recycle_ibi_slot(dev, slot);
2890 	if (atomic_dec_and_test(&dev->ibi->pending_ibis))
2891 		complete(&dev->ibi->all_ibis_handled);
2892 }
2893 
2894 static void i3c_master_init_ibi_slot(struct i3c_dev_desc *dev,
2895 				     struct i3c_ibi_slot *slot)
2896 {
2897 	slot->dev = dev;
2898 	INIT_WORK(&slot->work, i3c_master_handle_ibi);
2899 }
2900 
2901 struct i3c_generic_ibi_slot {
2902 	struct list_head node;
2903 	struct i3c_ibi_slot base;
2904 };
2905 
2906 struct i3c_generic_ibi_pool {
2907 	spinlock_t lock;
2908 	unsigned int num_slots;
2909 	void *payload_buf;
2910 	struct list_head free_slots;
2911 	struct list_head pending;
2912 	struct i3c_generic_ibi_slot slots[] __counted_by(num_slots);
2913 };
2914 
2915 /**
2916  * i3c_generic_ibi_free_pool() - Free a generic IBI pool
2917  * @pool: the IBI pool to free
2918  *
2919  * Free all IBI slots allated by a generic IBI pool.
2920  */
2921 void i3c_generic_ibi_free_pool(struct i3c_generic_ibi_pool *pool)
2922 {
2923 	struct i3c_generic_ibi_slot *slot;
2924 	unsigned int nslots = 0;
2925 
2926 	while (!list_empty(&pool->free_slots)) {
2927 		slot = list_first_entry(&pool->free_slots,
2928 					struct i3c_generic_ibi_slot, node);
2929 		list_del(&slot->node);
2930 		nslots++;
2931 	}
2932 
2933 	/*
2934 	 * If the number of freed slots is not equal to the number of allocated
2935 	 * slots we have a leak somewhere.
2936 	 */
2937 	WARN_ON(nslots != pool->num_slots);
2938 
2939 	kfree(pool->payload_buf);
2940 	kfree(pool);
2941 }
2942 EXPORT_SYMBOL_GPL(i3c_generic_ibi_free_pool);
2943 
2944 /**
2945  * i3c_generic_ibi_alloc_pool() - Create a generic IBI pool
2946  * @dev: the device this pool will be used for
2947  * @req: IBI setup request describing what the device driver expects
2948  *
2949  * Create a generic IBI pool based on the information provided in @req.
2950  *
2951  * Return: a valid IBI pool in case of success, an ERR_PTR() otherwise.
2952  */
2953 struct i3c_generic_ibi_pool *
2954 i3c_generic_ibi_alloc_pool(struct i3c_dev_desc *dev,
2955 			   const struct i3c_ibi_setup *req)
2956 {
2957 	struct i3c_generic_ibi_pool *pool;
2958 	struct i3c_generic_ibi_slot *slot;
2959 	unsigned int i;
2960 	int ret;
2961 
2962 	pool = kzalloc_flex(*pool, slots, req->num_slots);
2963 	if (!pool)
2964 		return ERR_PTR(-ENOMEM);
2965 
2966 	pool->num_slots = req->num_slots;
2967 
2968 	spin_lock_init(&pool->lock);
2969 	INIT_LIST_HEAD(&pool->free_slots);
2970 	INIT_LIST_HEAD(&pool->pending);
2971 
2972 	if (req->max_payload_len) {
2973 		pool->payload_buf = kcalloc(req->num_slots,
2974 					    req->max_payload_len, GFP_KERNEL);
2975 		if (!pool->payload_buf) {
2976 			ret = -ENOMEM;
2977 			goto err_free_pool;
2978 		}
2979 	}
2980 
2981 	for (i = 0; i < req->num_slots; i++) {
2982 		slot = &pool->slots[i];
2983 		i3c_master_init_ibi_slot(dev, &slot->base);
2984 
2985 		if (req->max_payload_len)
2986 			slot->base.data = pool->payload_buf +
2987 					  (i * req->max_payload_len);
2988 
2989 		list_add_tail(&slot->node, &pool->free_slots);
2990 	}
2991 
2992 	return pool;
2993 
2994 err_free_pool:
2995 	i3c_generic_ibi_free_pool(pool);
2996 	return ERR_PTR(ret);
2997 }
2998 EXPORT_SYMBOL_GPL(i3c_generic_ibi_alloc_pool);
2999 
3000 /**
3001  * i3c_generic_ibi_get_free_slot() - Get a free slot from a generic IBI pool
3002  * @pool: the pool to query an IBI slot on
3003  *
3004  * Search for a free slot in a generic IBI pool.
3005  * The slot should be returned to the pool using i3c_generic_ibi_recycle_slot()
3006  * when it's no longer needed.
3007  *
3008  * Return: a pointer to a free slot, or NULL if there's no free slot available.
3009  */
3010 struct i3c_ibi_slot *
3011 i3c_generic_ibi_get_free_slot(struct i3c_generic_ibi_pool *pool)
3012 {
3013 	struct i3c_generic_ibi_slot *slot;
3014 	unsigned long flags;
3015 
3016 	spin_lock_irqsave(&pool->lock, flags);
3017 	slot = list_first_entry_or_null(&pool->free_slots,
3018 					struct i3c_generic_ibi_slot, node);
3019 	if (slot)
3020 		list_del(&slot->node);
3021 	spin_unlock_irqrestore(&pool->lock, flags);
3022 
3023 	return slot ? &slot->base : NULL;
3024 }
3025 EXPORT_SYMBOL_GPL(i3c_generic_ibi_get_free_slot);
3026 
3027 /**
3028  * i3c_generic_ibi_recycle_slot() - Return a slot to a generic IBI pool
3029  * @pool: the pool to return the IBI slot to
3030  * @s: IBI slot to recycle
3031  *
3032  * Add an IBI slot back to its generic IBI pool. Should be called from the
3033  * master driver struct_master_controller_ops->recycle_ibi() method.
3034  */
3035 void i3c_generic_ibi_recycle_slot(struct i3c_generic_ibi_pool *pool,
3036 				  struct i3c_ibi_slot *s)
3037 {
3038 	struct i3c_generic_ibi_slot *slot;
3039 	unsigned long flags;
3040 
3041 	if (!s)
3042 		return;
3043 
3044 	slot = container_of(s, struct i3c_generic_ibi_slot, base);
3045 	spin_lock_irqsave(&pool->lock, flags);
3046 	list_add_tail(&slot->node, &pool->free_slots);
3047 	spin_unlock_irqrestore(&pool->lock, flags);
3048 }
3049 EXPORT_SYMBOL_GPL(i3c_generic_ibi_recycle_slot);
3050 
3051 static int i3c_master_check_ops(const struct i3c_master_controller_ops *ops)
3052 {
3053 	if (!ops || !ops->bus_init || !ops->i3c_xfers ||
3054 	    !ops->send_ccc_cmd || !ops->do_daa || !ops->i2c_xfers)
3055 		return -EINVAL;
3056 
3057 	if (ops->request_ibi &&
3058 	    (!ops->enable_ibi || !ops->disable_ibi || !ops->free_ibi ||
3059 	     !ops->recycle_ibi_slot))
3060 		return -EINVAL;
3061 
3062 	return 0;
3063 }
3064 
3065 /**
3066  * i3c_master_register() - register an I3C master
3067  * @master: master used to send frames on the bus
3068  * @parent: the parent device (the one that provides this I3C master
3069  *	    controller)
3070  * @ops: the master controller operations
3071  * @secondary: true if you are registering a secondary master. Will return
3072  *	       -EOPNOTSUPP if set to true since secondary masters are not yet
3073  *	       supported
3074  *
3075  * This function takes care of everything for you:
3076  *
3077  * - creates and initializes the I3C bus
3078  * - populates the bus with static I2C devs if @parent->of_node is not
3079  *   NULL
3080  * - registers all I3C devices added by the controller during bus
3081  *   initialization
3082  * - registers the I2C adapter and all I2C devices
3083  *
3084  * Return: 0 in case of success, a negative error code otherwise.
3085  */
3086 int i3c_master_register(struct i3c_master_controller *master,
3087 			struct device *parent,
3088 			const struct i3c_master_controller_ops *ops,
3089 			bool secondary)
3090 {
3091 	unsigned long i2c_scl_rate = I3C_BUS_I2C_FM_PLUS_SCL_MAX_RATE;
3092 	struct i3c_bus *i3cbus = i3c_master_get_bus(master);
3093 	enum i3c_bus_mode mode = I3C_BUS_MODE_PURE;
3094 	struct i2c_dev_boardinfo *i2cbi;
3095 	int ret;
3096 
3097 	/* We do not support secondary masters yet. */
3098 	if (secondary)
3099 		return -EOPNOTSUPP;
3100 
3101 	ret = i3c_master_check_ops(ops);
3102 	if (ret)
3103 		return ret;
3104 
3105 	master->dev.parent = parent;
3106 	master->dev.of_node = of_node_get(parent->of_node);
3107 	master->dev.bus = &i3c_bus_type;
3108 	master->dev.type = &i3c_masterdev_type;
3109 	master->dev.release = i3c_masterdev_release;
3110 	master->ops = ops;
3111 	master->secondary = secondary;
3112 	INIT_LIST_HEAD(&master->boardinfo.i2c);
3113 	INIT_LIST_HEAD(&master->boardinfo.i3c);
3114 
3115 	ret = i3c_master_rpm_get(master);
3116 	if (ret)
3117 		return ret;
3118 
3119 	device_initialize(&master->dev);
3120 
3121 	master->dev.dma_mask = parent->dma_mask;
3122 	master->dev.coherent_dma_mask = parent->coherent_dma_mask;
3123 	master->dev.dma_parms = parent->dma_parms;
3124 
3125 	ret = i3c_bus_init(i3cbus, master->dev.of_node);
3126 	if (ret)
3127 		goto err_put_dev;
3128 
3129 	dev_set_name(&master->dev, "i3c-%d", i3cbus->id);
3130 
3131 	ret = of_populate_i3c_bus(master);
3132 	if (ret)
3133 		goto err_put_dev;
3134 
3135 	list_for_each_entry(i2cbi, &master->boardinfo.i2c, node) {
3136 		switch (i2cbi->lvr & I3C_LVR_I2C_INDEX_MASK) {
3137 		case I3C_LVR_I2C_INDEX(0):
3138 			if (mode < I3C_BUS_MODE_MIXED_FAST)
3139 				mode = I3C_BUS_MODE_MIXED_FAST;
3140 			break;
3141 		case I3C_LVR_I2C_INDEX(1):
3142 			if (mode < I3C_BUS_MODE_MIXED_LIMITED)
3143 				mode = I3C_BUS_MODE_MIXED_LIMITED;
3144 			break;
3145 		case I3C_LVR_I2C_INDEX(2):
3146 			if (mode < I3C_BUS_MODE_MIXED_SLOW)
3147 				mode = I3C_BUS_MODE_MIXED_SLOW;
3148 			break;
3149 		default:
3150 			ret = -EINVAL;
3151 			goto err_put_dev;
3152 		}
3153 
3154 		if (i2cbi->lvr & I3C_LVR_I2C_FM_MODE)
3155 			i2c_scl_rate = I3C_BUS_I2C_FM_SCL_MAX_RATE;
3156 	}
3157 
3158 	ret = i3c_bus_set_mode(i3cbus, mode, i2c_scl_rate);
3159 	if (ret)
3160 		goto err_put_dev;
3161 
3162 	master->wq = alloc_workqueue("%s", WQ_PERCPU | WQ_FREEZABLE, 0, dev_name(parent));
3163 	if (!master->wq) {
3164 		ret = -ENOMEM;
3165 		goto err_put_dev;
3166 	}
3167 	INIT_WORK(&master->hj_work, i3c_master_hj_work_fn);
3168 	INIT_WORK(&master->reg_work, i3c_master_reg_work_fn);
3169 
3170 	ret = i3c_master_bus_init(master);
3171 	if (ret)
3172 		goto err_put_dev;
3173 
3174 	ret = device_add(&master->dev);
3175 	if (ret)
3176 		goto err_cleanup_bus;
3177 
3178 	/*
3179 	 * Expose our I3C bus as an I2C adapter so that I2C devices are exposed
3180 	 * through the I2C subsystem.
3181 	 */
3182 	ret = i3c_master_i2c_adapter_init(master);
3183 	if (ret)
3184 		goto err_del_dev;
3185 
3186 	i3c_bus_notify(i3cbus, I3C_NOTIFY_BUS_ADD);
3187 
3188 	pm_runtime_no_callbacks(&master->dev);
3189 	pm_suspend_ignore_children(&master->dev, true);
3190 	pm_runtime_enable(&master->dev);
3191 
3192 	/*
3193 	 * We're done initializing the bus and the controller, we can now
3194 	 * register I3C devices discovered during the initial DAA. Device
3195 	 * registration is done via reg_work because that keeps a single
3196 	 * registration code path and ensures the worker is the only writer
3197 	 * of desc->dev. Flush the work to preserve synchronous probe-time
3198 	 * behavior.
3199 	 */
3200 	master->init_done = true;
3201 	queue_work(master->wq, &master->reg_work);
3202 	flush_work(&master->reg_work);
3203 
3204 	if (master->ops->set_dev_nack_retry)
3205 		device_create_file(&master->dev, &dev_attr_dev_nack_retry_count);
3206 
3207 	i3c_master_rpm_put(master);
3208 
3209 	return 0;
3210 
3211 err_del_dev:
3212 	device_del(&master->dev);
3213 
3214 err_cleanup_bus:
3215 	i3c_master_bus_cleanup(master);
3216 
3217 err_put_dev:
3218 	i3c_master_rpm_put(master);
3219 	put_device(&master->dev);
3220 
3221 	return ret;
3222 }
3223 EXPORT_SYMBOL_GPL(i3c_master_register);
3224 
3225 /**
3226  * i3c_master_unregister() - unregister an I3C master
3227  * @master: master used to send frames on the bus
3228  *
3229  * Basically undo everything done in i3c_master_register().
3230  */
3231 void i3c_master_unregister(struct i3c_master_controller *master)
3232 {
3233 	i3c_bus_notify(&master->bus, I3C_NOTIFY_BUS_REMOVE);
3234 	i3c_master_shutdown(master);
3235 
3236 	if (master->ops->set_dev_nack_retry)
3237 		device_remove_file(&master->dev, &dev_attr_dev_nack_retry_count);
3238 
3239 	i3c_master_i2c_adapter_cleanup(master);
3240 	i3c_master_unregister_i3c_devs(master);
3241 	i3c_master_bus_cleanup(master);
3242 	pm_runtime_disable(&master->dev);
3243 	device_unregister(&master->dev);
3244 }
3245 EXPORT_SYMBOL_GPL(i3c_master_unregister);
3246 
3247 int i3c_dev_setdasa_locked(struct i3c_dev_desc *dev)
3248 {
3249 	struct i3c_master_controller *master;
3250 
3251 	if (!dev)
3252 		return -ENOENT;
3253 
3254 	master = i3c_dev_get_master(dev);
3255 	if (!master)
3256 		return -EINVAL;
3257 
3258 	if (!dev->boardinfo || !dev->boardinfo->init_dyn_addr ||
3259 		!dev->boardinfo->static_addr)
3260 		return -EINVAL;
3261 
3262 	return i3c_master_setdasa_locked(master, dev->info.static_addr,
3263 						dev->boardinfo->init_dyn_addr);
3264 }
3265 
3266 int i3c_dev_do_xfers_locked(struct i3c_dev_desc *dev, struct i3c_xfer *xfers,
3267 			    int nxfers, enum i3c_xfer_mode mode)
3268 {
3269 	struct i3c_master_controller *master;
3270 
3271 	if (!dev)
3272 		return -ENOENT;
3273 
3274 	master = i3c_dev_get_master(dev);
3275 	if (!master || !xfers)
3276 		return -EINVAL;
3277 
3278 	if (mode != I3C_SDR && !(master->this->info.hdr_cap & BIT(mode)))
3279 		return -EOPNOTSUPP;
3280 
3281 	return master->ops->i3c_xfers(dev, xfers, nxfers, mode);
3282 }
3283 
3284 int i3c_dev_disable_ibi_locked(struct i3c_dev_desc *dev)
3285 {
3286 	struct i3c_master_controller *master;
3287 	int ret;
3288 
3289 	if (!dev->ibi)
3290 		return -EINVAL;
3291 
3292 	master = i3c_dev_get_master(dev);
3293 	ret = master->ops->disable_ibi(dev);
3294 	if (ret)
3295 		return ret;
3296 
3297 	reinit_completion(&dev->ibi->all_ibis_handled);
3298 	if (atomic_read(&dev->ibi->pending_ibis))
3299 		wait_for_completion(&dev->ibi->all_ibis_handled);
3300 
3301 	dev->ibi->enabled = false;
3302 
3303 	return 0;
3304 }
3305 
3306 int i3c_dev_enable_ibi_locked(struct i3c_dev_desc *dev)
3307 {
3308 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
3309 	int ret;
3310 
3311 	if (!dev->ibi)
3312 		return -EINVAL;
3313 
3314 	ret = master->ops->enable_ibi(dev);
3315 	if (!ret)
3316 		dev->ibi->enabled = true;
3317 
3318 	return ret;
3319 }
3320 
3321 int i3c_dev_request_ibi_locked(struct i3c_dev_desc *dev,
3322 			       const struct i3c_ibi_setup *req)
3323 {
3324 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
3325 	struct i3c_device_ibi_info *ibi;
3326 	int ret;
3327 
3328 	if (!master->ops->request_ibi)
3329 		return -EOPNOTSUPP;
3330 
3331 	if (dev->ibi)
3332 		return -EBUSY;
3333 
3334 	ibi = kzalloc_obj(*ibi);
3335 	if (!ibi)
3336 		return -ENOMEM;
3337 
3338 	ibi->wq = alloc_ordered_workqueue(dev_name(i3cdev_to_dev(dev->dev)), WQ_MEM_RECLAIM);
3339 	if (!ibi->wq) {
3340 		kfree(ibi);
3341 		return -ENOMEM;
3342 	}
3343 
3344 	atomic_set(&ibi->pending_ibis, 0);
3345 	init_completion(&ibi->all_ibis_handled);
3346 	ibi->handler = req->handler;
3347 	ibi->max_payload_len = req->max_payload_len;
3348 	ibi->num_slots = req->num_slots;
3349 
3350 	dev->ibi = ibi;
3351 	ret = master->ops->request_ibi(dev, req);
3352 	if (ret) {
3353 		kfree(ibi);
3354 		dev->ibi = NULL;
3355 	}
3356 
3357 	return ret;
3358 }
3359 
3360 void i3c_dev_free_ibi_locked(struct i3c_dev_desc *dev)
3361 {
3362 	struct i3c_master_controller *master = i3c_dev_get_master(dev);
3363 
3364 	if (!dev->ibi)
3365 		return;
3366 
3367 	if (dev->ibi->enabled) {
3368 		int ret;
3369 
3370 		dev_err(&master->dev, "Freeing IBI that is still enabled\n");
3371 		ret = i3c_master_rpm_get(master);
3372 		if (!ret) {
3373 			ret = i3c_dev_disable_ibi_locked(dev);
3374 			i3c_master_rpm_put(master);
3375 		}
3376 		if (ret)
3377 			dev_err(&master->dev, "Failed to disable IBI before freeing\n");
3378 	}
3379 
3380 	master->ops->free_ibi(dev);
3381 
3382 	if (dev->ibi->wq) {
3383 		destroy_workqueue(dev->ibi->wq);
3384 		dev->ibi->wq = NULL;
3385 	}
3386 
3387 	kfree(dev->ibi);
3388 	dev->ibi = NULL;
3389 }
3390 
3391 static int __init i3c_init(void)
3392 {
3393 	int res;
3394 
3395 	res = of_alias_get_highest_id("i3c");
3396 	if (res >= 0) {
3397 		mutex_lock(&i3c_core_lock);
3398 		__i3c_first_dynamic_bus_num = res + 1;
3399 		mutex_unlock(&i3c_core_lock);
3400 	}
3401 
3402 	res = bus_register_notifier(&i2c_bus_type, &i2cdev_notifier);
3403 	if (res)
3404 		return res;
3405 
3406 	res = bus_register(&i3c_bus_type);
3407 	if (res)
3408 		goto out_unreg_notifier;
3409 
3410 	return 0;
3411 
3412 out_unreg_notifier:
3413 	bus_unregister_notifier(&i2c_bus_type, &i2cdev_notifier);
3414 
3415 	return res;
3416 }
3417 subsys_initcall(i3c_init);
3418 
3419 static void __exit i3c_exit(void)
3420 {
3421 	bus_unregister_notifier(&i2c_bus_type, &i2cdev_notifier);
3422 	idr_destroy(&i3c_bus_idr);
3423 	bus_unregister(&i3c_bus_type);
3424 }
3425 module_exit(i3c_exit);
3426 
3427 MODULE_AUTHOR("Boris Brezillon <boris.brezillon@bootlin.com>");
3428 MODULE_DESCRIPTION("I3C core");
3429 MODULE_LICENSE("GPL v2");
3430