xref: /linux/drivers/soundwire/bus.c (revision 404bec4c8f6c38ae5fa208344f1086d38026e93d)
1 // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
2 // Copyright(c) 2015-17 Intel Corporation.
3 
4 #include <linux/acpi.h>
5 #include <linux/delay.h>
6 #include <linux/mod_devicetable.h>
7 #include <linux/pm_runtime.h>
8 #include <linux/soundwire/sdw_registers.h>
9 #include <linux/soundwire/sdw.h>
10 #include <linux/soundwire/sdw_type.h>
11 #include "bus.h"
12 #include "sysfs_local.h"
13 
14 static DEFINE_IDA(sdw_ida);
15 
16 static int sdw_get_id(struct sdw_bus *bus)
17 {
18 	int rc = ida_alloc(&sdw_ida, GFP_KERNEL);
19 
20 	if (rc < 0)
21 		return rc;
22 
23 	bus->id = rc;
24 	return 0;
25 }
26 
27 /**
28  * sdw_bus_master_add() - add a bus Master instance
29  * @bus: bus instance
30  * @parent: parent device
31  * @fwnode: firmware node handle
32  *
33  * Initializes the bus instance, read properties and create child
34  * devices.
35  */
36 int sdw_bus_master_add(struct sdw_bus *bus, struct device *parent,
37 		       struct fwnode_handle *fwnode)
38 {
39 	struct sdw_master_prop *prop = NULL;
40 	int ret;
41 
42 	if (!parent) {
43 		pr_err("SoundWire parent device is not set\n");
44 		return -ENODEV;
45 	}
46 
47 	ret = sdw_get_id(bus);
48 	if (ret < 0) {
49 		dev_err(parent, "Failed to get bus id\n");
50 		return ret;
51 	}
52 
53 	ret = sdw_master_device_add(bus, parent, fwnode);
54 	if (ret < 0) {
55 		dev_err(parent, "Failed to add master device at link %d\n",
56 			bus->link_id);
57 		return ret;
58 	}
59 
60 	if (!bus->ops) {
61 		dev_err(bus->dev, "SoundWire Bus ops are not set\n");
62 		return -EINVAL;
63 	}
64 
65 	if (!bus->compute_params) {
66 		dev_err(bus->dev,
67 			"Bandwidth allocation not configured, compute_params no set\n");
68 		return -EINVAL;
69 	}
70 
71 	mutex_init(&bus->msg_lock);
72 	mutex_init(&bus->bus_lock);
73 	INIT_LIST_HEAD(&bus->slaves);
74 	INIT_LIST_HEAD(&bus->m_rt_list);
75 
76 	/*
77 	 * Initialize multi_link flag
78 	 * TODO: populate this flag by reading property from FW node
79 	 */
80 	bus->multi_link = false;
81 	if (bus->ops->read_prop) {
82 		ret = bus->ops->read_prop(bus);
83 		if (ret < 0) {
84 			dev_err(bus->dev,
85 				"Bus read properties failed:%d\n", ret);
86 			return ret;
87 		}
88 	}
89 
90 	sdw_bus_debugfs_init(bus);
91 
92 	/*
93 	 * Device numbers in SoundWire are 0 through 15. Enumeration device
94 	 * number (0), Broadcast device number (15), Group numbers (12 and
95 	 * 13) and Master device number (14) are not used for assignment so
96 	 * mask these and other higher bits.
97 	 */
98 
99 	/* Set higher order bits */
100 	*bus->assigned = ~GENMASK(SDW_BROADCAST_DEV_NUM, SDW_ENUM_DEV_NUM);
101 
102 	/* Set enumuration device number and broadcast device number */
103 	set_bit(SDW_ENUM_DEV_NUM, bus->assigned);
104 	set_bit(SDW_BROADCAST_DEV_NUM, bus->assigned);
105 
106 	/* Set group device numbers and master device number */
107 	set_bit(SDW_GROUP12_DEV_NUM, bus->assigned);
108 	set_bit(SDW_GROUP13_DEV_NUM, bus->assigned);
109 	set_bit(SDW_MASTER_DEV_NUM, bus->assigned);
110 
111 	/*
112 	 * SDW is an enumerable bus, but devices can be powered off. So,
113 	 * they won't be able to report as present.
114 	 *
115 	 * Create Slave devices based on Slaves described in
116 	 * the respective firmware (ACPI/DT)
117 	 */
118 	if (IS_ENABLED(CONFIG_ACPI) && ACPI_HANDLE(bus->dev))
119 		ret = sdw_acpi_find_slaves(bus);
120 	else if (IS_ENABLED(CONFIG_OF) && bus->dev->of_node)
121 		ret = sdw_of_find_slaves(bus);
122 	else
123 		ret = -ENOTSUPP; /* No ACPI/DT so error out */
124 
125 	if (ret < 0) {
126 		dev_err(bus->dev, "Finding slaves failed:%d\n", ret);
127 		return ret;
128 	}
129 
130 	/*
131 	 * Initialize clock values based on Master properties. The max
132 	 * frequency is read from max_clk_freq property. Current assumption
133 	 * is that the bus will start at highest clock frequency when
134 	 * powered on.
135 	 *
136 	 * Default active bank will be 0 as out of reset the Slaves have
137 	 * to start with bank 0 (Table 40 of Spec)
138 	 */
139 	prop = &bus->prop;
140 	bus->params.max_dr_freq = prop->max_clk_freq * SDW_DOUBLE_RATE_FACTOR;
141 	bus->params.curr_dr_freq = bus->params.max_dr_freq;
142 	bus->params.curr_bank = SDW_BANK0;
143 	bus->params.next_bank = SDW_BANK1;
144 
145 	return 0;
146 }
147 EXPORT_SYMBOL(sdw_bus_master_add);
148 
149 static int sdw_delete_slave(struct device *dev, void *data)
150 {
151 	struct sdw_slave *slave = dev_to_sdw_dev(dev);
152 	struct sdw_bus *bus = slave->bus;
153 
154 	pm_runtime_disable(dev);
155 
156 	sdw_slave_debugfs_exit(slave);
157 
158 	mutex_lock(&bus->bus_lock);
159 
160 	if (slave->dev_num) /* clear dev_num if assigned */
161 		clear_bit(slave->dev_num, bus->assigned);
162 
163 	list_del_init(&slave->node);
164 	mutex_unlock(&bus->bus_lock);
165 
166 	device_unregister(dev);
167 	return 0;
168 }
169 
170 /**
171  * sdw_bus_master_delete() - delete the bus master instance
172  * @bus: bus to be deleted
173  *
174  * Remove the instance, delete the child devices.
175  */
176 void sdw_bus_master_delete(struct sdw_bus *bus)
177 {
178 	device_for_each_child(bus->dev, NULL, sdw_delete_slave);
179 	sdw_master_device_del(bus);
180 
181 	sdw_bus_debugfs_exit(bus);
182 	ida_free(&sdw_ida, bus->id);
183 }
184 EXPORT_SYMBOL(sdw_bus_master_delete);
185 
186 /*
187  * SDW IO Calls
188  */
189 
190 static inline int find_response_code(enum sdw_command_response resp)
191 {
192 	switch (resp) {
193 	case SDW_CMD_OK:
194 		return 0;
195 
196 	case SDW_CMD_IGNORED:
197 		return -ENODATA;
198 
199 	case SDW_CMD_TIMEOUT:
200 		return -ETIMEDOUT;
201 
202 	default:
203 		return -EIO;
204 	}
205 }
206 
207 static inline int do_transfer(struct sdw_bus *bus, struct sdw_msg *msg)
208 {
209 	int retry = bus->prop.err_threshold;
210 	enum sdw_command_response resp;
211 	int ret = 0, i;
212 
213 	for (i = 0; i <= retry; i++) {
214 		resp = bus->ops->xfer_msg(bus, msg);
215 		ret = find_response_code(resp);
216 
217 		/* if cmd is ok or ignored return */
218 		if (ret == 0 || ret == -ENODATA)
219 			return ret;
220 	}
221 
222 	return ret;
223 }
224 
225 static inline int do_transfer_defer(struct sdw_bus *bus,
226 				    struct sdw_msg *msg,
227 				    struct sdw_defer *defer)
228 {
229 	int retry = bus->prop.err_threshold;
230 	enum sdw_command_response resp;
231 	int ret = 0, i;
232 
233 	defer->msg = msg;
234 	defer->length = msg->len;
235 	init_completion(&defer->complete);
236 
237 	for (i = 0; i <= retry; i++) {
238 		resp = bus->ops->xfer_msg_defer(bus, msg, defer);
239 		ret = find_response_code(resp);
240 		/* if cmd is ok or ignored return */
241 		if (ret == 0 || ret == -ENODATA)
242 			return ret;
243 	}
244 
245 	return ret;
246 }
247 
248 static int sdw_reset_page(struct sdw_bus *bus, u16 dev_num)
249 {
250 	int retry = bus->prop.err_threshold;
251 	enum sdw_command_response resp;
252 	int ret = 0, i;
253 
254 	for (i = 0; i <= retry; i++) {
255 		resp = bus->ops->reset_page_addr(bus, dev_num);
256 		ret = find_response_code(resp);
257 		/* if cmd is ok or ignored return */
258 		if (ret == 0 || ret == -ENODATA)
259 			return ret;
260 	}
261 
262 	return ret;
263 }
264 
265 static int sdw_transfer_unlocked(struct sdw_bus *bus, struct sdw_msg *msg)
266 {
267 	int ret;
268 
269 	ret = do_transfer(bus, msg);
270 	if (ret != 0 && ret != -ENODATA)
271 		dev_err(bus->dev, "trf on Slave %d failed:%d %s addr %x count %d\n",
272 			msg->dev_num, ret,
273 			(msg->flags & SDW_MSG_FLAG_WRITE) ? "write" : "read",
274 			msg->addr, msg->len);
275 
276 	if (msg->page)
277 		sdw_reset_page(bus, msg->dev_num);
278 
279 	return ret;
280 }
281 
282 /**
283  * sdw_transfer() - Synchronous transfer message to a SDW Slave device
284  * @bus: SDW bus
285  * @msg: SDW message to be xfered
286  */
287 int sdw_transfer(struct sdw_bus *bus, struct sdw_msg *msg)
288 {
289 	int ret;
290 
291 	mutex_lock(&bus->msg_lock);
292 
293 	ret = sdw_transfer_unlocked(bus, msg);
294 
295 	mutex_unlock(&bus->msg_lock);
296 
297 	return ret;
298 }
299 
300 /**
301  * sdw_show_ping_status() - Direct report of PING status, to be used by Peripheral drivers
302  * @bus: SDW bus
303  * @sync_delay: Delay before reading status
304  */
305 void sdw_show_ping_status(struct sdw_bus *bus, bool sync_delay)
306 {
307 	u32 status;
308 
309 	if (!bus->ops->read_ping_status)
310 		return;
311 
312 	/*
313 	 * wait for peripheral to sync if desired. 10-15ms should be more than
314 	 * enough in most cases.
315 	 */
316 	if (sync_delay)
317 		usleep_range(10000, 15000);
318 
319 	mutex_lock(&bus->msg_lock);
320 
321 	status = bus->ops->read_ping_status(bus);
322 
323 	mutex_unlock(&bus->msg_lock);
324 
325 	if (!status)
326 		dev_warn(bus->dev, "%s: no peripherals attached\n", __func__);
327 	else
328 		dev_dbg(bus->dev, "PING status: %#x\n", status);
329 }
330 EXPORT_SYMBOL(sdw_show_ping_status);
331 
332 /**
333  * sdw_transfer_defer() - Asynchronously transfer message to a SDW Slave device
334  * @bus: SDW bus
335  * @msg: SDW message to be xfered
336  * @defer: Defer block for signal completion
337  *
338  * Caller needs to hold the msg_lock lock while calling this
339  */
340 int sdw_transfer_defer(struct sdw_bus *bus, struct sdw_msg *msg,
341 		       struct sdw_defer *defer)
342 {
343 	int ret;
344 
345 	if (!bus->ops->xfer_msg_defer)
346 		return -ENOTSUPP;
347 
348 	ret = do_transfer_defer(bus, msg, defer);
349 	if (ret != 0 && ret != -ENODATA)
350 		dev_err(bus->dev, "Defer trf on Slave %d failed:%d\n",
351 			msg->dev_num, ret);
352 
353 	if (msg->page)
354 		sdw_reset_page(bus, msg->dev_num);
355 
356 	return ret;
357 }
358 
359 int sdw_fill_msg(struct sdw_msg *msg, struct sdw_slave *slave,
360 		 u32 addr, size_t count, u16 dev_num, u8 flags, u8 *buf)
361 {
362 	memset(msg, 0, sizeof(*msg));
363 	msg->addr = addr; /* addr is 16 bit and truncated here */
364 	msg->len = count;
365 	msg->dev_num = dev_num;
366 	msg->flags = flags;
367 	msg->buf = buf;
368 
369 	if (addr < SDW_REG_NO_PAGE) /* no paging area */
370 		return 0;
371 
372 	if (addr >= SDW_REG_MAX) { /* illegal addr */
373 		pr_err("SDW: Invalid address %x passed\n", addr);
374 		return -EINVAL;
375 	}
376 
377 	if (addr < SDW_REG_OPTIONAL_PAGE) { /* 32k but no page */
378 		if (slave && !slave->prop.paging_support)
379 			return 0;
380 		/* no need for else as that will fall-through to paging */
381 	}
382 
383 	/* paging mandatory */
384 	if (dev_num == SDW_ENUM_DEV_NUM || dev_num == SDW_BROADCAST_DEV_NUM) {
385 		pr_err("SDW: Invalid device for paging :%d\n", dev_num);
386 		return -EINVAL;
387 	}
388 
389 	if (!slave) {
390 		pr_err("SDW: No slave for paging addr\n");
391 		return -EINVAL;
392 	}
393 
394 	if (!slave->prop.paging_support) {
395 		dev_err(&slave->dev,
396 			"address %x needs paging but no support\n", addr);
397 		return -EINVAL;
398 	}
399 
400 	msg->addr_page1 = FIELD_GET(SDW_SCP_ADDRPAGE1_MASK, addr);
401 	msg->addr_page2 = FIELD_GET(SDW_SCP_ADDRPAGE2_MASK, addr);
402 	msg->addr |= BIT(15);
403 	msg->page = true;
404 
405 	return 0;
406 }
407 
408 /*
409  * Read/Write IO functions.
410  * no_pm versions can only be called by the bus, e.g. while enumerating or
411  * handling suspend-resume sequences.
412  * all clients need to use the pm versions
413  */
414 
415 static int
416 sdw_nread_no_pm(struct sdw_slave *slave, u32 addr, size_t count, u8 *val)
417 {
418 	struct sdw_msg msg;
419 	int ret;
420 
421 	ret = sdw_fill_msg(&msg, slave, addr, count,
422 			   slave->dev_num, SDW_MSG_FLAG_READ, val);
423 	if (ret < 0)
424 		return ret;
425 
426 	ret = sdw_transfer(slave->bus, &msg);
427 	if (slave->is_mockup_device)
428 		ret = 0;
429 	return ret;
430 }
431 
432 static int
433 sdw_nwrite_no_pm(struct sdw_slave *slave, u32 addr, size_t count, const u8 *val)
434 {
435 	struct sdw_msg msg;
436 	int ret;
437 
438 	ret = sdw_fill_msg(&msg, slave, addr, count,
439 			   slave->dev_num, SDW_MSG_FLAG_WRITE, (u8 *)val);
440 	if (ret < 0)
441 		return ret;
442 
443 	ret = sdw_transfer(slave->bus, &msg);
444 	if (slave->is_mockup_device)
445 		ret = 0;
446 	return ret;
447 }
448 
449 int sdw_write_no_pm(struct sdw_slave *slave, u32 addr, u8 value)
450 {
451 	return sdw_nwrite_no_pm(slave, addr, 1, &value);
452 }
453 EXPORT_SYMBOL(sdw_write_no_pm);
454 
455 static int
456 sdw_bread_no_pm(struct sdw_bus *bus, u16 dev_num, u32 addr)
457 {
458 	struct sdw_msg msg;
459 	u8 buf;
460 	int ret;
461 
462 	ret = sdw_fill_msg(&msg, NULL, addr, 1, dev_num,
463 			   SDW_MSG_FLAG_READ, &buf);
464 	if (ret < 0)
465 		return ret;
466 
467 	ret = sdw_transfer(bus, &msg);
468 	if (ret < 0)
469 		return ret;
470 
471 	return buf;
472 }
473 
474 static int
475 sdw_bwrite_no_pm(struct sdw_bus *bus, u16 dev_num, u32 addr, u8 value)
476 {
477 	struct sdw_msg msg;
478 	int ret;
479 
480 	ret = sdw_fill_msg(&msg, NULL, addr, 1, dev_num,
481 			   SDW_MSG_FLAG_WRITE, &value);
482 	if (ret < 0)
483 		return ret;
484 
485 	return sdw_transfer(bus, &msg);
486 }
487 
488 int sdw_bread_no_pm_unlocked(struct sdw_bus *bus, u16 dev_num, u32 addr)
489 {
490 	struct sdw_msg msg;
491 	u8 buf;
492 	int ret;
493 
494 	ret = sdw_fill_msg(&msg, NULL, addr, 1, dev_num,
495 			   SDW_MSG_FLAG_READ, &buf);
496 	if (ret < 0)
497 		return ret;
498 
499 	ret = sdw_transfer_unlocked(bus, &msg);
500 	if (ret < 0)
501 		return ret;
502 
503 	return buf;
504 }
505 EXPORT_SYMBOL(sdw_bread_no_pm_unlocked);
506 
507 int sdw_bwrite_no_pm_unlocked(struct sdw_bus *bus, u16 dev_num, u32 addr, u8 value)
508 {
509 	struct sdw_msg msg;
510 	int ret;
511 
512 	ret = sdw_fill_msg(&msg, NULL, addr, 1, dev_num,
513 			   SDW_MSG_FLAG_WRITE, &value);
514 	if (ret < 0)
515 		return ret;
516 
517 	return sdw_transfer_unlocked(bus, &msg);
518 }
519 EXPORT_SYMBOL(sdw_bwrite_no_pm_unlocked);
520 
521 int sdw_read_no_pm(struct sdw_slave *slave, u32 addr)
522 {
523 	u8 buf;
524 	int ret;
525 
526 	ret = sdw_nread_no_pm(slave, addr, 1, &buf);
527 	if (ret < 0)
528 		return ret;
529 	else
530 		return buf;
531 }
532 EXPORT_SYMBOL(sdw_read_no_pm);
533 
534 int sdw_update_no_pm(struct sdw_slave *slave, u32 addr, u8 mask, u8 val)
535 {
536 	int tmp;
537 
538 	tmp = sdw_read_no_pm(slave, addr);
539 	if (tmp < 0)
540 		return tmp;
541 
542 	tmp = (tmp & ~mask) | val;
543 	return sdw_write_no_pm(slave, addr, tmp);
544 }
545 EXPORT_SYMBOL(sdw_update_no_pm);
546 
547 /* Read-Modify-Write Slave register */
548 int sdw_update(struct sdw_slave *slave, u32 addr, u8 mask, u8 val)
549 {
550 	int tmp;
551 
552 	tmp = sdw_read(slave, addr);
553 	if (tmp < 0)
554 		return tmp;
555 
556 	tmp = (tmp & ~mask) | val;
557 	return sdw_write(slave, addr, tmp);
558 }
559 EXPORT_SYMBOL(sdw_update);
560 
561 /**
562  * sdw_nread() - Read "n" contiguous SDW Slave registers
563  * @slave: SDW Slave
564  * @addr: Register address
565  * @count: length
566  * @val: Buffer for values to be read
567  */
568 int sdw_nread(struct sdw_slave *slave, u32 addr, size_t count, u8 *val)
569 {
570 	int ret;
571 
572 	ret = pm_runtime_resume_and_get(&slave->dev);
573 	if (ret < 0 && ret != -EACCES)
574 		return ret;
575 
576 	ret = sdw_nread_no_pm(slave, addr, count, val);
577 
578 	pm_runtime_mark_last_busy(&slave->dev);
579 	pm_runtime_put(&slave->dev);
580 
581 	return ret;
582 }
583 EXPORT_SYMBOL(sdw_nread);
584 
585 /**
586  * sdw_nwrite() - Write "n" contiguous SDW Slave registers
587  * @slave: SDW Slave
588  * @addr: Register address
589  * @count: length
590  * @val: Buffer for values to be written
591  */
592 int sdw_nwrite(struct sdw_slave *slave, u32 addr, size_t count, const u8 *val)
593 {
594 	int ret;
595 
596 	ret = pm_runtime_resume_and_get(&slave->dev);
597 	if (ret < 0 && ret != -EACCES)
598 		return ret;
599 
600 	ret = sdw_nwrite_no_pm(slave, addr, count, val);
601 
602 	pm_runtime_mark_last_busy(&slave->dev);
603 	pm_runtime_put(&slave->dev);
604 
605 	return ret;
606 }
607 EXPORT_SYMBOL(sdw_nwrite);
608 
609 /**
610  * sdw_read() - Read a SDW Slave register
611  * @slave: SDW Slave
612  * @addr: Register address
613  */
614 int sdw_read(struct sdw_slave *slave, u32 addr)
615 {
616 	u8 buf;
617 	int ret;
618 
619 	ret = sdw_nread(slave, addr, 1, &buf);
620 	if (ret < 0)
621 		return ret;
622 
623 	return buf;
624 }
625 EXPORT_SYMBOL(sdw_read);
626 
627 /**
628  * sdw_write() - Write a SDW Slave register
629  * @slave: SDW Slave
630  * @addr: Register address
631  * @value: Register value
632  */
633 int sdw_write(struct sdw_slave *slave, u32 addr, u8 value)
634 {
635 	return sdw_nwrite(slave, addr, 1, &value);
636 }
637 EXPORT_SYMBOL(sdw_write);
638 
639 /*
640  * SDW alert handling
641  */
642 
643 /* called with bus_lock held */
644 static struct sdw_slave *sdw_get_slave(struct sdw_bus *bus, int i)
645 {
646 	struct sdw_slave *slave;
647 
648 	list_for_each_entry(slave, &bus->slaves, node) {
649 		if (slave->dev_num == i)
650 			return slave;
651 	}
652 
653 	return NULL;
654 }
655 
656 int sdw_compare_devid(struct sdw_slave *slave, struct sdw_slave_id id)
657 {
658 	if (slave->id.mfg_id != id.mfg_id ||
659 	    slave->id.part_id != id.part_id ||
660 	    slave->id.class_id != id.class_id ||
661 	    (slave->id.unique_id != SDW_IGNORED_UNIQUE_ID &&
662 	     slave->id.unique_id != id.unique_id))
663 		return -ENODEV;
664 
665 	return 0;
666 }
667 EXPORT_SYMBOL(sdw_compare_devid);
668 
669 /* called with bus_lock held */
670 static int sdw_get_device_num(struct sdw_slave *slave)
671 {
672 	int bit;
673 
674 	bit = find_first_zero_bit(slave->bus->assigned, SDW_MAX_DEVICES);
675 	if (bit == SDW_MAX_DEVICES) {
676 		bit = -ENODEV;
677 		goto err;
678 	}
679 
680 	/*
681 	 * Do not update dev_num in Slave data structure here,
682 	 * Update once program dev_num is successful
683 	 */
684 	set_bit(bit, slave->bus->assigned);
685 
686 err:
687 	return bit;
688 }
689 
690 static int sdw_assign_device_num(struct sdw_slave *slave)
691 {
692 	struct sdw_bus *bus = slave->bus;
693 	int ret, dev_num;
694 	bool new_device = false;
695 
696 	/* check first if device number is assigned, if so reuse that */
697 	if (!slave->dev_num) {
698 		if (!slave->dev_num_sticky) {
699 			mutex_lock(&slave->bus->bus_lock);
700 			dev_num = sdw_get_device_num(slave);
701 			mutex_unlock(&slave->bus->bus_lock);
702 			if (dev_num < 0) {
703 				dev_err(bus->dev, "Get dev_num failed: %d\n",
704 					dev_num);
705 				return dev_num;
706 			}
707 			slave->dev_num = dev_num;
708 			slave->dev_num_sticky = dev_num;
709 			new_device = true;
710 		} else {
711 			slave->dev_num = slave->dev_num_sticky;
712 		}
713 	}
714 
715 	if (!new_device)
716 		dev_dbg(bus->dev,
717 			"Slave already registered, reusing dev_num:%d\n",
718 			slave->dev_num);
719 
720 	/* Clear the slave->dev_num to transfer message on device 0 */
721 	dev_num = slave->dev_num;
722 	slave->dev_num = 0;
723 
724 	ret = sdw_write_no_pm(slave, SDW_SCP_DEVNUMBER, dev_num);
725 	if (ret < 0) {
726 		dev_err(bus->dev, "Program device_num %d failed: %d\n",
727 			dev_num, ret);
728 		return ret;
729 	}
730 
731 	/* After xfer of msg, restore dev_num */
732 	slave->dev_num = slave->dev_num_sticky;
733 
734 	return 0;
735 }
736 
737 void sdw_extract_slave_id(struct sdw_bus *bus,
738 			  u64 addr, struct sdw_slave_id *id)
739 {
740 	dev_dbg(bus->dev, "SDW Slave Addr: %llx\n", addr);
741 
742 	id->sdw_version = SDW_VERSION(addr);
743 	id->unique_id = SDW_UNIQUE_ID(addr);
744 	id->mfg_id = SDW_MFG_ID(addr);
745 	id->part_id = SDW_PART_ID(addr);
746 	id->class_id = SDW_CLASS_ID(addr);
747 
748 	dev_dbg(bus->dev,
749 		"SDW Slave class_id 0x%02x, mfg_id 0x%04x, part_id 0x%04x, unique_id 0x%x, version 0x%x\n",
750 		id->class_id, id->mfg_id, id->part_id, id->unique_id, id->sdw_version);
751 }
752 EXPORT_SYMBOL(sdw_extract_slave_id);
753 
754 static int sdw_program_device_num(struct sdw_bus *bus)
755 {
756 	u8 buf[SDW_NUM_DEV_ID_REGISTERS] = {0};
757 	struct sdw_slave *slave, *_s;
758 	struct sdw_slave_id id;
759 	struct sdw_msg msg;
760 	bool found;
761 	int count = 0, ret;
762 	u64 addr;
763 
764 	/* No Slave, so use raw xfer api */
765 	ret = sdw_fill_msg(&msg, NULL, SDW_SCP_DEVID_0,
766 			   SDW_NUM_DEV_ID_REGISTERS, 0, SDW_MSG_FLAG_READ, buf);
767 	if (ret < 0)
768 		return ret;
769 
770 	do {
771 		ret = sdw_transfer(bus, &msg);
772 		if (ret == -ENODATA) { /* end of device id reads */
773 			dev_dbg(bus->dev, "No more devices to enumerate\n");
774 			ret = 0;
775 			break;
776 		}
777 		if (ret < 0) {
778 			dev_err(bus->dev, "DEVID read fail:%d\n", ret);
779 			break;
780 		}
781 
782 		/*
783 		 * Construct the addr and extract. Cast the higher shift
784 		 * bits to avoid truncation due to size limit.
785 		 */
786 		addr = buf[5] | (buf[4] << 8) | (buf[3] << 16) |
787 			((u64)buf[2] << 24) | ((u64)buf[1] << 32) |
788 			((u64)buf[0] << 40);
789 
790 		sdw_extract_slave_id(bus, addr, &id);
791 
792 		found = false;
793 		/* Now compare with entries */
794 		list_for_each_entry_safe(slave, _s, &bus->slaves, node) {
795 			if (sdw_compare_devid(slave, id) == 0) {
796 				found = true;
797 
798 				/*
799 				 * Assign a new dev_num to this Slave and
800 				 * not mark it present. It will be marked
801 				 * present after it reports ATTACHED on new
802 				 * dev_num
803 				 */
804 				ret = sdw_assign_device_num(slave);
805 				if (ret < 0) {
806 					dev_err(bus->dev,
807 						"Assign dev_num failed:%d\n",
808 						ret);
809 					return ret;
810 				}
811 
812 				break;
813 			}
814 		}
815 
816 		if (!found) {
817 			/* TODO: Park this device in Group 13 */
818 
819 			/*
820 			 * add Slave device even if there is no platform
821 			 * firmware description. There will be no driver probe
822 			 * but the user/integration will be able to see the
823 			 * device, enumeration status and device number in sysfs
824 			 */
825 			sdw_slave_add(bus, &id, NULL);
826 
827 			dev_err(bus->dev, "Slave Entry not found\n");
828 		}
829 
830 		count++;
831 
832 		/*
833 		 * Check till error out or retry (count) exhausts.
834 		 * Device can drop off and rejoin during enumeration
835 		 * so count till twice the bound.
836 		 */
837 
838 	} while (ret == 0 && count < (SDW_MAX_DEVICES * 2));
839 
840 	return ret;
841 }
842 
843 static void sdw_modify_slave_status(struct sdw_slave *slave,
844 				    enum sdw_slave_status status)
845 {
846 	struct sdw_bus *bus = slave->bus;
847 
848 	mutex_lock(&bus->bus_lock);
849 
850 	dev_vdbg(bus->dev,
851 		 "%s: changing status slave %d status %d new status %d\n",
852 		 __func__, slave->dev_num, slave->status, status);
853 
854 	if (status == SDW_SLAVE_UNATTACHED) {
855 		dev_dbg(&slave->dev,
856 			"%s: initializing enumeration and init completion for Slave %d\n",
857 			__func__, slave->dev_num);
858 
859 		init_completion(&slave->enumeration_complete);
860 		init_completion(&slave->initialization_complete);
861 
862 	} else if ((status == SDW_SLAVE_ATTACHED) &&
863 		   (slave->status == SDW_SLAVE_UNATTACHED)) {
864 		dev_dbg(&slave->dev,
865 			"%s: signaling enumeration completion for Slave %d\n",
866 			__func__, slave->dev_num);
867 
868 		complete(&slave->enumeration_complete);
869 	}
870 	slave->status = status;
871 	mutex_unlock(&bus->bus_lock);
872 }
873 
874 static int sdw_slave_clk_stop_callback(struct sdw_slave *slave,
875 				       enum sdw_clk_stop_mode mode,
876 				       enum sdw_clk_stop_type type)
877 {
878 	int ret = 0;
879 
880 	mutex_lock(&slave->sdw_dev_lock);
881 
882 	if (slave->probed)  {
883 		struct device *dev = &slave->dev;
884 		struct sdw_driver *drv = drv_to_sdw_driver(dev->driver);
885 
886 		if (drv->ops && drv->ops->clk_stop)
887 			ret = drv->ops->clk_stop(slave, mode, type);
888 	}
889 
890 	mutex_unlock(&slave->sdw_dev_lock);
891 
892 	return ret;
893 }
894 
895 static int sdw_slave_clk_stop_prepare(struct sdw_slave *slave,
896 				      enum sdw_clk_stop_mode mode,
897 				      bool prepare)
898 {
899 	bool wake_en;
900 	u32 val = 0;
901 	int ret;
902 
903 	wake_en = slave->prop.wake_capable;
904 
905 	if (prepare) {
906 		val = SDW_SCP_SYSTEMCTRL_CLK_STP_PREP;
907 
908 		if (mode == SDW_CLK_STOP_MODE1)
909 			val |= SDW_SCP_SYSTEMCTRL_CLK_STP_MODE1;
910 
911 		if (wake_en)
912 			val |= SDW_SCP_SYSTEMCTRL_WAKE_UP_EN;
913 	} else {
914 		ret = sdw_read_no_pm(slave, SDW_SCP_SYSTEMCTRL);
915 		if (ret < 0) {
916 			if (ret != -ENODATA)
917 				dev_err(&slave->dev, "SDW_SCP_SYSTEMCTRL read failed:%d\n", ret);
918 			return ret;
919 		}
920 		val = ret;
921 		val &= ~(SDW_SCP_SYSTEMCTRL_CLK_STP_PREP);
922 	}
923 
924 	ret = sdw_write_no_pm(slave, SDW_SCP_SYSTEMCTRL, val);
925 
926 	if (ret < 0 && ret != -ENODATA)
927 		dev_err(&slave->dev, "SDW_SCP_SYSTEMCTRL write failed:%d\n", ret);
928 
929 	return ret;
930 }
931 
932 static int sdw_bus_wait_for_clk_prep_deprep(struct sdw_bus *bus, u16 dev_num)
933 {
934 	int retry = bus->clk_stop_timeout;
935 	int val;
936 
937 	do {
938 		val = sdw_bread_no_pm(bus, dev_num, SDW_SCP_STAT);
939 		if (val < 0) {
940 			if (val != -ENODATA)
941 				dev_err(bus->dev, "SDW_SCP_STAT bread failed:%d\n", val);
942 			return val;
943 		}
944 		val &= SDW_SCP_STAT_CLK_STP_NF;
945 		if (!val) {
946 			dev_dbg(bus->dev, "clock stop prep/de-prep done slave:%d\n",
947 				dev_num);
948 			return 0;
949 		}
950 
951 		usleep_range(1000, 1500);
952 		retry--;
953 	} while (retry);
954 
955 	dev_err(bus->dev, "clock stop prep/de-prep failed slave:%d\n",
956 		dev_num);
957 
958 	return -ETIMEDOUT;
959 }
960 
961 /**
962  * sdw_bus_prep_clk_stop: prepare Slave(s) for clock stop
963  *
964  * @bus: SDW bus instance
965  *
966  * Query Slave for clock stop mode and prepare for that mode.
967  */
968 int sdw_bus_prep_clk_stop(struct sdw_bus *bus)
969 {
970 	bool simple_clk_stop = true;
971 	struct sdw_slave *slave;
972 	bool is_slave = false;
973 	int ret = 0;
974 
975 	/*
976 	 * In order to save on transition time, prepare
977 	 * each Slave and then wait for all Slave(s) to be
978 	 * prepared for clock stop.
979 	 * If one of the Slave devices has lost sync and
980 	 * replies with Command Ignored/-ENODATA, we continue
981 	 * the loop
982 	 */
983 	list_for_each_entry(slave, &bus->slaves, node) {
984 		if (!slave->dev_num)
985 			continue;
986 
987 		if (slave->status != SDW_SLAVE_ATTACHED &&
988 		    slave->status != SDW_SLAVE_ALERT)
989 			continue;
990 
991 		/* Identify if Slave(s) are available on Bus */
992 		is_slave = true;
993 
994 		ret = sdw_slave_clk_stop_callback(slave,
995 						  SDW_CLK_STOP_MODE0,
996 						  SDW_CLK_PRE_PREPARE);
997 		if (ret < 0 && ret != -ENODATA) {
998 			dev_err(&slave->dev, "clock stop pre-prepare cb failed:%d\n", ret);
999 			return ret;
1000 		}
1001 
1002 		/* Only prepare a Slave device if needed */
1003 		if (!slave->prop.simple_clk_stop_capable) {
1004 			simple_clk_stop = false;
1005 
1006 			ret = sdw_slave_clk_stop_prepare(slave,
1007 							 SDW_CLK_STOP_MODE0,
1008 							 true);
1009 			if (ret < 0 && ret != -ENODATA) {
1010 				dev_err(&slave->dev, "clock stop prepare failed:%d\n", ret);
1011 				return ret;
1012 			}
1013 		}
1014 	}
1015 
1016 	/* Skip remaining clock stop preparation if no Slave is attached */
1017 	if (!is_slave)
1018 		return 0;
1019 
1020 	/*
1021 	 * Don't wait for all Slaves to be ready if they follow the simple
1022 	 * state machine
1023 	 */
1024 	if (!simple_clk_stop) {
1025 		ret = sdw_bus_wait_for_clk_prep_deprep(bus,
1026 						       SDW_BROADCAST_DEV_NUM);
1027 		/*
1028 		 * if there are no Slave devices present and the reply is
1029 		 * Command_Ignored/-ENODATA, we don't need to continue with the
1030 		 * flow and can just return here. The error code is not modified
1031 		 * and its handling left as an exercise for the caller.
1032 		 */
1033 		if (ret < 0)
1034 			return ret;
1035 	}
1036 
1037 	/* Inform slaves that prep is done */
1038 	list_for_each_entry(slave, &bus->slaves, node) {
1039 		if (!slave->dev_num)
1040 			continue;
1041 
1042 		if (slave->status != SDW_SLAVE_ATTACHED &&
1043 		    slave->status != SDW_SLAVE_ALERT)
1044 			continue;
1045 
1046 		ret = sdw_slave_clk_stop_callback(slave,
1047 						  SDW_CLK_STOP_MODE0,
1048 						  SDW_CLK_POST_PREPARE);
1049 
1050 		if (ret < 0 && ret != -ENODATA) {
1051 			dev_err(&slave->dev, "clock stop post-prepare cb failed:%d\n", ret);
1052 			return ret;
1053 		}
1054 	}
1055 
1056 	return 0;
1057 }
1058 EXPORT_SYMBOL(sdw_bus_prep_clk_stop);
1059 
1060 /**
1061  * sdw_bus_clk_stop: stop bus clock
1062  *
1063  * @bus: SDW bus instance
1064  *
1065  * After preparing the Slaves for clock stop, stop the clock by broadcasting
1066  * write to SCP_CTRL register.
1067  */
1068 int sdw_bus_clk_stop(struct sdw_bus *bus)
1069 {
1070 	int ret;
1071 
1072 	/*
1073 	 * broadcast clock stop now, attached Slaves will ACK this,
1074 	 * unattached will ignore
1075 	 */
1076 	ret = sdw_bwrite_no_pm(bus, SDW_BROADCAST_DEV_NUM,
1077 			       SDW_SCP_CTRL, SDW_SCP_CTRL_CLK_STP_NOW);
1078 	if (ret < 0) {
1079 		if (ret != -ENODATA)
1080 			dev_err(bus->dev, "ClockStopNow Broadcast msg failed %d\n", ret);
1081 		return ret;
1082 	}
1083 
1084 	return 0;
1085 }
1086 EXPORT_SYMBOL(sdw_bus_clk_stop);
1087 
1088 /**
1089  * sdw_bus_exit_clk_stop: Exit clock stop mode
1090  *
1091  * @bus: SDW bus instance
1092  *
1093  * This De-prepares the Slaves by exiting Clock Stop Mode 0. For the Slaves
1094  * exiting Clock Stop Mode 1, they will be de-prepared after they enumerate
1095  * back.
1096  */
1097 int sdw_bus_exit_clk_stop(struct sdw_bus *bus)
1098 {
1099 	bool simple_clk_stop = true;
1100 	struct sdw_slave *slave;
1101 	bool is_slave = false;
1102 	int ret;
1103 
1104 	/*
1105 	 * In order to save on transition time, de-prepare
1106 	 * each Slave and then wait for all Slave(s) to be
1107 	 * de-prepared after clock resume.
1108 	 */
1109 	list_for_each_entry(slave, &bus->slaves, node) {
1110 		if (!slave->dev_num)
1111 			continue;
1112 
1113 		if (slave->status != SDW_SLAVE_ATTACHED &&
1114 		    slave->status != SDW_SLAVE_ALERT)
1115 			continue;
1116 
1117 		/* Identify if Slave(s) are available on Bus */
1118 		is_slave = true;
1119 
1120 		ret = sdw_slave_clk_stop_callback(slave, SDW_CLK_STOP_MODE0,
1121 						  SDW_CLK_PRE_DEPREPARE);
1122 		if (ret < 0)
1123 			dev_warn(&slave->dev, "clock stop pre-deprepare cb failed:%d\n", ret);
1124 
1125 		/* Only de-prepare a Slave device if needed */
1126 		if (!slave->prop.simple_clk_stop_capable) {
1127 			simple_clk_stop = false;
1128 
1129 			ret = sdw_slave_clk_stop_prepare(slave, SDW_CLK_STOP_MODE0,
1130 							 false);
1131 
1132 			if (ret < 0)
1133 				dev_warn(&slave->dev, "clock stop deprepare failed:%d\n", ret);
1134 		}
1135 	}
1136 
1137 	/* Skip remaining clock stop de-preparation if no Slave is attached */
1138 	if (!is_slave)
1139 		return 0;
1140 
1141 	/*
1142 	 * Don't wait for all Slaves to be ready if they follow the simple
1143 	 * state machine
1144 	 */
1145 	if (!simple_clk_stop) {
1146 		ret = sdw_bus_wait_for_clk_prep_deprep(bus, SDW_BROADCAST_DEV_NUM);
1147 		if (ret < 0)
1148 			dev_warn(bus->dev, "clock stop deprepare wait failed:%d\n", ret);
1149 	}
1150 
1151 	list_for_each_entry(slave, &bus->slaves, node) {
1152 		if (!slave->dev_num)
1153 			continue;
1154 
1155 		if (slave->status != SDW_SLAVE_ATTACHED &&
1156 		    slave->status != SDW_SLAVE_ALERT)
1157 			continue;
1158 
1159 		ret = sdw_slave_clk_stop_callback(slave, SDW_CLK_STOP_MODE0,
1160 						  SDW_CLK_POST_DEPREPARE);
1161 		if (ret < 0)
1162 			dev_warn(&slave->dev, "clock stop post-deprepare cb failed:%d\n", ret);
1163 	}
1164 
1165 	return 0;
1166 }
1167 EXPORT_SYMBOL(sdw_bus_exit_clk_stop);
1168 
1169 int sdw_configure_dpn_intr(struct sdw_slave *slave,
1170 			   int port, bool enable, int mask)
1171 {
1172 	u32 addr;
1173 	int ret;
1174 	u8 val = 0;
1175 
1176 	if (slave->bus->params.s_data_mode != SDW_PORT_DATA_MODE_NORMAL) {
1177 		dev_dbg(&slave->dev, "TEST FAIL interrupt %s\n",
1178 			enable ? "on" : "off");
1179 		mask |= SDW_DPN_INT_TEST_FAIL;
1180 	}
1181 
1182 	addr = SDW_DPN_INTMASK(port);
1183 
1184 	/* Set/Clear port ready interrupt mask */
1185 	if (enable) {
1186 		val |= mask;
1187 		val |= SDW_DPN_INT_PORT_READY;
1188 	} else {
1189 		val &= ~(mask);
1190 		val &= ~SDW_DPN_INT_PORT_READY;
1191 	}
1192 
1193 	ret = sdw_update(slave, addr, (mask | SDW_DPN_INT_PORT_READY), val);
1194 	if (ret < 0)
1195 		dev_err(&slave->dev,
1196 			"SDW_DPN_INTMASK write failed:%d\n", val);
1197 
1198 	return ret;
1199 }
1200 
1201 static int sdw_slave_set_frequency(struct sdw_slave *slave)
1202 {
1203 	u32 mclk_freq = slave->bus->prop.mclk_freq;
1204 	u32 curr_freq = slave->bus->params.curr_dr_freq >> 1;
1205 	unsigned int scale;
1206 	u8 scale_index;
1207 	u8 base;
1208 	int ret;
1209 
1210 	/*
1211 	 * frequency base and scale registers are required for SDCA
1212 	 * devices. They may also be used for 1.2+/non-SDCA devices,
1213 	 * but we will need a DisCo property to cover this case
1214 	 */
1215 	if (!slave->id.class_id)
1216 		return 0;
1217 
1218 	if (!mclk_freq) {
1219 		dev_err(&slave->dev,
1220 			"no bus MCLK, cannot set SDW_SCP_BUS_CLOCK_BASE\n");
1221 		return -EINVAL;
1222 	}
1223 
1224 	/*
1225 	 * map base frequency using Table 89 of SoundWire 1.2 spec.
1226 	 * The order of the tests just follows the specification, this
1227 	 * is not a selection between possible values or a search for
1228 	 * the best value but just a mapping.  Only one case per platform
1229 	 * is relevant.
1230 	 * Some BIOS have inconsistent values for mclk_freq but a
1231 	 * correct root so we force the mclk_freq to avoid variations.
1232 	 */
1233 	if (!(19200000 % mclk_freq)) {
1234 		mclk_freq = 19200000;
1235 		base = SDW_SCP_BASE_CLOCK_19200000_HZ;
1236 	} else if (!(24000000 % mclk_freq)) {
1237 		mclk_freq = 24000000;
1238 		base = SDW_SCP_BASE_CLOCK_24000000_HZ;
1239 	} else if (!(24576000 % mclk_freq)) {
1240 		mclk_freq = 24576000;
1241 		base = SDW_SCP_BASE_CLOCK_24576000_HZ;
1242 	} else if (!(22579200 % mclk_freq)) {
1243 		mclk_freq = 22579200;
1244 		base = SDW_SCP_BASE_CLOCK_22579200_HZ;
1245 	} else if (!(32000000 % mclk_freq)) {
1246 		mclk_freq = 32000000;
1247 		base = SDW_SCP_BASE_CLOCK_32000000_HZ;
1248 	} else {
1249 		dev_err(&slave->dev,
1250 			"Unsupported clock base, mclk %d\n",
1251 			mclk_freq);
1252 		return -EINVAL;
1253 	}
1254 
1255 	if (mclk_freq % curr_freq) {
1256 		dev_err(&slave->dev,
1257 			"mclk %d is not multiple of bus curr_freq %d\n",
1258 			mclk_freq, curr_freq);
1259 		return -EINVAL;
1260 	}
1261 
1262 	scale = mclk_freq / curr_freq;
1263 
1264 	/*
1265 	 * map scale to Table 90 of SoundWire 1.2 spec - and check
1266 	 * that the scale is a power of two and maximum 64
1267 	 */
1268 	scale_index = ilog2(scale);
1269 
1270 	if (BIT(scale_index) != scale || scale_index > 6) {
1271 		dev_err(&slave->dev,
1272 			"No match found for scale %d, bus mclk %d curr_freq %d\n",
1273 			scale, mclk_freq, curr_freq);
1274 		return -EINVAL;
1275 	}
1276 	scale_index++;
1277 
1278 	ret = sdw_write_no_pm(slave, SDW_SCP_BUS_CLOCK_BASE, base);
1279 	if (ret < 0) {
1280 		dev_err(&slave->dev,
1281 			"SDW_SCP_BUS_CLOCK_BASE write failed:%d\n", ret);
1282 		return ret;
1283 	}
1284 
1285 	/* initialize scale for both banks */
1286 	ret = sdw_write_no_pm(slave, SDW_SCP_BUSCLOCK_SCALE_B0, scale_index);
1287 	if (ret < 0) {
1288 		dev_err(&slave->dev,
1289 			"SDW_SCP_BUSCLOCK_SCALE_B0 write failed:%d\n", ret);
1290 		return ret;
1291 	}
1292 	ret = sdw_write_no_pm(slave, SDW_SCP_BUSCLOCK_SCALE_B1, scale_index);
1293 	if (ret < 0)
1294 		dev_err(&slave->dev,
1295 			"SDW_SCP_BUSCLOCK_SCALE_B1 write failed:%d\n", ret);
1296 
1297 	dev_dbg(&slave->dev,
1298 		"Configured bus base %d, scale %d, mclk %d, curr_freq %d\n",
1299 		base, scale_index, mclk_freq, curr_freq);
1300 
1301 	return ret;
1302 }
1303 
1304 static int sdw_initialize_slave(struct sdw_slave *slave)
1305 {
1306 	struct sdw_slave_prop *prop = &slave->prop;
1307 	int status;
1308 	int ret;
1309 	u8 val;
1310 
1311 	ret = sdw_slave_set_frequency(slave);
1312 	if (ret < 0)
1313 		return ret;
1314 
1315 	if (slave->bus->prop.quirks & SDW_MASTER_QUIRKS_CLEAR_INITIAL_CLASH) {
1316 		/* Clear bus clash interrupt before enabling interrupt mask */
1317 		status = sdw_read_no_pm(slave, SDW_SCP_INT1);
1318 		if (status < 0) {
1319 			dev_err(&slave->dev,
1320 				"SDW_SCP_INT1 (BUS_CLASH) read failed:%d\n", status);
1321 			return status;
1322 		}
1323 		if (status & SDW_SCP_INT1_BUS_CLASH) {
1324 			dev_warn(&slave->dev, "Bus clash detected before INT mask is enabled\n");
1325 			ret = sdw_write_no_pm(slave, SDW_SCP_INT1, SDW_SCP_INT1_BUS_CLASH);
1326 			if (ret < 0) {
1327 				dev_err(&slave->dev,
1328 					"SDW_SCP_INT1 (BUS_CLASH) write failed:%d\n", ret);
1329 				return ret;
1330 			}
1331 		}
1332 	}
1333 	if ((slave->bus->prop.quirks & SDW_MASTER_QUIRKS_CLEAR_INITIAL_PARITY) &&
1334 	    !(slave->prop.quirks & SDW_SLAVE_QUIRKS_INVALID_INITIAL_PARITY)) {
1335 		/* Clear parity interrupt before enabling interrupt mask */
1336 		status = sdw_read_no_pm(slave, SDW_SCP_INT1);
1337 		if (status < 0) {
1338 			dev_err(&slave->dev,
1339 				"SDW_SCP_INT1 (PARITY) read failed:%d\n", status);
1340 			return status;
1341 		}
1342 		if (status & SDW_SCP_INT1_PARITY) {
1343 			dev_warn(&slave->dev, "PARITY error detected before INT mask is enabled\n");
1344 			ret = sdw_write_no_pm(slave, SDW_SCP_INT1, SDW_SCP_INT1_PARITY);
1345 			if (ret < 0) {
1346 				dev_err(&slave->dev,
1347 					"SDW_SCP_INT1 (PARITY) write failed:%d\n", ret);
1348 				return ret;
1349 			}
1350 		}
1351 	}
1352 
1353 	/*
1354 	 * Set SCP_INT1_MASK register, typically bus clash and
1355 	 * implementation-defined interrupt mask. The Parity detection
1356 	 * may not always be correct on startup so its use is
1357 	 * device-dependent, it might e.g. only be enabled in
1358 	 * steady-state after a couple of frames.
1359 	 */
1360 	val = slave->prop.scp_int1_mask;
1361 
1362 	/* Enable SCP interrupts */
1363 	ret = sdw_update_no_pm(slave, SDW_SCP_INTMASK1, val, val);
1364 	if (ret < 0) {
1365 		dev_err(&slave->dev,
1366 			"SDW_SCP_INTMASK1 write failed:%d\n", ret);
1367 		return ret;
1368 	}
1369 
1370 	/* No need to continue if DP0 is not present */
1371 	if (!slave->prop.dp0_prop)
1372 		return 0;
1373 
1374 	/* Enable DP0 interrupts */
1375 	val = prop->dp0_prop->imp_def_interrupts;
1376 	val |= SDW_DP0_INT_PORT_READY | SDW_DP0_INT_BRA_FAILURE;
1377 
1378 	ret = sdw_update_no_pm(slave, SDW_DP0_INTMASK, val, val);
1379 	if (ret < 0)
1380 		dev_err(&slave->dev,
1381 			"SDW_DP0_INTMASK read failed:%d\n", ret);
1382 	return ret;
1383 }
1384 
1385 static int sdw_handle_dp0_interrupt(struct sdw_slave *slave, u8 *slave_status)
1386 {
1387 	u8 clear, impl_int_mask;
1388 	int status, status2, ret, count = 0;
1389 
1390 	status = sdw_read_no_pm(slave, SDW_DP0_INT);
1391 	if (status < 0) {
1392 		dev_err(&slave->dev,
1393 			"SDW_DP0_INT read failed:%d\n", status);
1394 		return status;
1395 	}
1396 
1397 	do {
1398 		clear = status & ~SDW_DP0_INTERRUPTS;
1399 
1400 		if (status & SDW_DP0_INT_TEST_FAIL) {
1401 			dev_err(&slave->dev, "Test fail for port 0\n");
1402 			clear |= SDW_DP0_INT_TEST_FAIL;
1403 		}
1404 
1405 		/*
1406 		 * Assumption: PORT_READY interrupt will be received only for
1407 		 * ports implementing Channel Prepare state machine (CP_SM)
1408 		 */
1409 
1410 		if (status & SDW_DP0_INT_PORT_READY) {
1411 			complete(&slave->port_ready[0]);
1412 			clear |= SDW_DP0_INT_PORT_READY;
1413 		}
1414 
1415 		if (status & SDW_DP0_INT_BRA_FAILURE) {
1416 			dev_err(&slave->dev, "BRA failed\n");
1417 			clear |= SDW_DP0_INT_BRA_FAILURE;
1418 		}
1419 
1420 		impl_int_mask = SDW_DP0_INT_IMPDEF1 |
1421 			SDW_DP0_INT_IMPDEF2 | SDW_DP0_INT_IMPDEF3;
1422 
1423 		if (status & impl_int_mask) {
1424 			clear |= impl_int_mask;
1425 			*slave_status = clear;
1426 		}
1427 
1428 		/* clear the interrupts but don't touch reserved and SDCA_CASCADE fields */
1429 		ret = sdw_write_no_pm(slave, SDW_DP0_INT, clear);
1430 		if (ret < 0) {
1431 			dev_err(&slave->dev,
1432 				"SDW_DP0_INT write failed:%d\n", ret);
1433 			return ret;
1434 		}
1435 
1436 		/* Read DP0 interrupt again */
1437 		status2 = sdw_read_no_pm(slave, SDW_DP0_INT);
1438 		if (status2 < 0) {
1439 			dev_err(&slave->dev,
1440 				"SDW_DP0_INT read failed:%d\n", status2);
1441 			return status2;
1442 		}
1443 		/* filter to limit loop to interrupts identified in the first status read */
1444 		status &= status2;
1445 
1446 		count++;
1447 
1448 		/* we can get alerts while processing so keep retrying */
1449 	} while ((status & SDW_DP0_INTERRUPTS) && (count < SDW_READ_INTR_CLEAR_RETRY));
1450 
1451 	if (count == SDW_READ_INTR_CLEAR_RETRY)
1452 		dev_warn(&slave->dev, "Reached MAX_RETRY on DP0 read\n");
1453 
1454 	return ret;
1455 }
1456 
1457 static int sdw_handle_port_interrupt(struct sdw_slave *slave,
1458 				     int port, u8 *slave_status)
1459 {
1460 	u8 clear, impl_int_mask;
1461 	int status, status2, ret, count = 0;
1462 	u32 addr;
1463 
1464 	if (port == 0)
1465 		return sdw_handle_dp0_interrupt(slave, slave_status);
1466 
1467 	addr = SDW_DPN_INT(port);
1468 	status = sdw_read_no_pm(slave, addr);
1469 	if (status < 0) {
1470 		dev_err(&slave->dev,
1471 			"SDW_DPN_INT read failed:%d\n", status);
1472 
1473 		return status;
1474 	}
1475 
1476 	do {
1477 		clear = status & ~SDW_DPN_INTERRUPTS;
1478 
1479 		if (status & SDW_DPN_INT_TEST_FAIL) {
1480 			dev_err(&slave->dev, "Test fail for port:%d\n", port);
1481 			clear |= SDW_DPN_INT_TEST_FAIL;
1482 		}
1483 
1484 		/*
1485 		 * Assumption: PORT_READY interrupt will be received only
1486 		 * for ports implementing CP_SM.
1487 		 */
1488 		if (status & SDW_DPN_INT_PORT_READY) {
1489 			complete(&slave->port_ready[port]);
1490 			clear |= SDW_DPN_INT_PORT_READY;
1491 		}
1492 
1493 		impl_int_mask = SDW_DPN_INT_IMPDEF1 |
1494 			SDW_DPN_INT_IMPDEF2 | SDW_DPN_INT_IMPDEF3;
1495 
1496 		if (status & impl_int_mask) {
1497 			clear |= impl_int_mask;
1498 			*slave_status = clear;
1499 		}
1500 
1501 		/* clear the interrupt but don't touch reserved fields */
1502 		ret = sdw_write_no_pm(slave, addr, clear);
1503 		if (ret < 0) {
1504 			dev_err(&slave->dev,
1505 				"SDW_DPN_INT write failed:%d\n", ret);
1506 			return ret;
1507 		}
1508 
1509 		/* Read DPN interrupt again */
1510 		status2 = sdw_read_no_pm(slave, addr);
1511 		if (status2 < 0) {
1512 			dev_err(&slave->dev,
1513 				"SDW_DPN_INT read failed:%d\n", status2);
1514 			return status2;
1515 		}
1516 		/* filter to limit loop to interrupts identified in the first status read */
1517 		status &= status2;
1518 
1519 		count++;
1520 
1521 		/* we can get alerts while processing so keep retrying */
1522 	} while ((status & SDW_DPN_INTERRUPTS) && (count < SDW_READ_INTR_CLEAR_RETRY));
1523 
1524 	if (count == SDW_READ_INTR_CLEAR_RETRY)
1525 		dev_warn(&slave->dev, "Reached MAX_RETRY on port read");
1526 
1527 	return ret;
1528 }
1529 
1530 static int sdw_handle_slave_alerts(struct sdw_slave *slave)
1531 {
1532 	struct sdw_slave_intr_status slave_intr;
1533 	u8 clear = 0, bit, port_status[15] = {0};
1534 	int port_num, stat, ret, count = 0;
1535 	unsigned long port;
1536 	bool slave_notify;
1537 	u8 sdca_cascade = 0;
1538 	u8 buf, buf2[2], _buf, _buf2[2];
1539 	bool parity_check;
1540 	bool parity_quirk;
1541 
1542 	sdw_modify_slave_status(slave, SDW_SLAVE_ALERT);
1543 
1544 	ret = pm_runtime_resume_and_get(&slave->dev);
1545 	if (ret < 0 && ret != -EACCES) {
1546 		dev_err(&slave->dev, "Failed to resume device: %d\n", ret);
1547 		return ret;
1548 	}
1549 
1550 	/* Read Intstat 1, Intstat 2 and Intstat 3 registers */
1551 	ret = sdw_read_no_pm(slave, SDW_SCP_INT1);
1552 	if (ret < 0) {
1553 		dev_err(&slave->dev,
1554 			"SDW_SCP_INT1 read failed:%d\n", ret);
1555 		goto io_err;
1556 	}
1557 	buf = ret;
1558 
1559 	ret = sdw_nread_no_pm(slave, SDW_SCP_INTSTAT2, 2, buf2);
1560 	if (ret < 0) {
1561 		dev_err(&slave->dev,
1562 			"SDW_SCP_INT2/3 read failed:%d\n", ret);
1563 		goto io_err;
1564 	}
1565 
1566 	if (slave->prop.is_sdca) {
1567 		ret = sdw_read_no_pm(slave, SDW_DP0_INT);
1568 		if (ret < 0) {
1569 			dev_err(&slave->dev,
1570 				"SDW_DP0_INT read failed:%d\n", ret);
1571 			goto io_err;
1572 		}
1573 		sdca_cascade = ret & SDW_DP0_SDCA_CASCADE;
1574 	}
1575 
1576 	do {
1577 		slave_notify = false;
1578 
1579 		/*
1580 		 * Check parity, bus clash and Slave (impl defined)
1581 		 * interrupt
1582 		 */
1583 		if (buf & SDW_SCP_INT1_PARITY) {
1584 			parity_check = slave->prop.scp_int1_mask & SDW_SCP_INT1_PARITY;
1585 			parity_quirk = !slave->first_interrupt_done &&
1586 				(slave->prop.quirks & SDW_SLAVE_QUIRKS_INVALID_INITIAL_PARITY);
1587 
1588 			if (parity_check && !parity_quirk)
1589 				dev_err(&slave->dev, "Parity error detected\n");
1590 			clear |= SDW_SCP_INT1_PARITY;
1591 		}
1592 
1593 		if (buf & SDW_SCP_INT1_BUS_CLASH) {
1594 			if (slave->prop.scp_int1_mask & SDW_SCP_INT1_BUS_CLASH)
1595 				dev_err(&slave->dev, "Bus clash detected\n");
1596 			clear |= SDW_SCP_INT1_BUS_CLASH;
1597 		}
1598 
1599 		/*
1600 		 * When bus clash or parity errors are detected, such errors
1601 		 * are unlikely to be recoverable errors.
1602 		 * TODO: In such scenario, reset bus. Make this configurable
1603 		 * via sysfs property with bus reset being the default.
1604 		 */
1605 
1606 		if (buf & SDW_SCP_INT1_IMPL_DEF) {
1607 			if (slave->prop.scp_int1_mask & SDW_SCP_INT1_IMPL_DEF) {
1608 				dev_dbg(&slave->dev, "Slave impl defined interrupt\n");
1609 				slave_notify = true;
1610 			}
1611 			clear |= SDW_SCP_INT1_IMPL_DEF;
1612 		}
1613 
1614 		/* the SDCA interrupts are cleared in the codec driver .interrupt_callback() */
1615 		if (sdca_cascade)
1616 			slave_notify = true;
1617 
1618 		/* Check port 0 - 3 interrupts */
1619 		port = buf & SDW_SCP_INT1_PORT0_3;
1620 
1621 		/* To get port number corresponding to bits, shift it */
1622 		port = FIELD_GET(SDW_SCP_INT1_PORT0_3, port);
1623 		for_each_set_bit(bit, &port, 8) {
1624 			sdw_handle_port_interrupt(slave, bit,
1625 						  &port_status[bit]);
1626 		}
1627 
1628 		/* Check if cascade 2 interrupt is present */
1629 		if (buf & SDW_SCP_INT1_SCP2_CASCADE) {
1630 			port = buf2[0] & SDW_SCP_INTSTAT2_PORT4_10;
1631 			for_each_set_bit(bit, &port, 8) {
1632 				/* scp2 ports start from 4 */
1633 				port_num = bit + 3;
1634 				sdw_handle_port_interrupt(slave,
1635 						port_num,
1636 						&port_status[port_num]);
1637 			}
1638 		}
1639 
1640 		/* now check last cascade */
1641 		if (buf2[0] & SDW_SCP_INTSTAT2_SCP3_CASCADE) {
1642 			port = buf2[1] & SDW_SCP_INTSTAT3_PORT11_14;
1643 			for_each_set_bit(bit, &port, 8) {
1644 				/* scp3 ports start from 11 */
1645 				port_num = bit + 10;
1646 				sdw_handle_port_interrupt(slave,
1647 						port_num,
1648 						&port_status[port_num]);
1649 			}
1650 		}
1651 
1652 		/* Update the Slave driver */
1653 		if (slave_notify) {
1654 			mutex_lock(&slave->sdw_dev_lock);
1655 
1656 			if (slave->probed) {
1657 				struct device *dev = &slave->dev;
1658 				struct sdw_driver *drv = drv_to_sdw_driver(dev->driver);
1659 
1660 				if (drv->ops && drv->ops->interrupt_callback) {
1661 					slave_intr.sdca_cascade = sdca_cascade;
1662 					slave_intr.control_port = clear;
1663 					memcpy(slave_intr.port, &port_status,
1664 					       sizeof(slave_intr.port));
1665 
1666 					drv->ops->interrupt_callback(slave, &slave_intr);
1667 				}
1668 			}
1669 
1670 			mutex_unlock(&slave->sdw_dev_lock);
1671 		}
1672 
1673 		/* Ack interrupt */
1674 		ret = sdw_write_no_pm(slave, SDW_SCP_INT1, clear);
1675 		if (ret < 0) {
1676 			dev_err(&slave->dev,
1677 				"SDW_SCP_INT1 write failed:%d\n", ret);
1678 			goto io_err;
1679 		}
1680 
1681 		/* at this point all initial interrupt sources were handled */
1682 		slave->first_interrupt_done = true;
1683 
1684 		/*
1685 		 * Read status again to ensure no new interrupts arrived
1686 		 * while servicing interrupts.
1687 		 */
1688 		ret = sdw_read_no_pm(slave, SDW_SCP_INT1);
1689 		if (ret < 0) {
1690 			dev_err(&slave->dev,
1691 				"SDW_SCP_INT1 recheck read failed:%d\n", ret);
1692 			goto io_err;
1693 		}
1694 		_buf = ret;
1695 
1696 		ret = sdw_nread_no_pm(slave, SDW_SCP_INTSTAT2, 2, _buf2);
1697 		if (ret < 0) {
1698 			dev_err(&slave->dev,
1699 				"SDW_SCP_INT2/3 recheck read failed:%d\n", ret);
1700 			goto io_err;
1701 		}
1702 
1703 		if (slave->prop.is_sdca) {
1704 			ret = sdw_read_no_pm(slave, SDW_DP0_INT);
1705 			if (ret < 0) {
1706 				dev_err(&slave->dev,
1707 					"SDW_DP0_INT recheck read failed:%d\n", ret);
1708 				goto io_err;
1709 			}
1710 			sdca_cascade = ret & SDW_DP0_SDCA_CASCADE;
1711 		}
1712 
1713 		/*
1714 		 * Make sure no interrupts are pending, but filter to limit loop
1715 		 * to interrupts identified in the first status read
1716 		 */
1717 		buf &= _buf;
1718 		buf2[0] &= _buf2[0];
1719 		buf2[1] &= _buf2[1];
1720 		stat = buf || buf2[0] || buf2[1] || sdca_cascade;
1721 
1722 		/*
1723 		 * Exit loop if Slave is continuously in ALERT state even
1724 		 * after servicing the interrupt multiple times.
1725 		 */
1726 		count++;
1727 
1728 		/* we can get alerts while processing so keep retrying */
1729 	} while (stat != 0 && count < SDW_READ_INTR_CLEAR_RETRY);
1730 
1731 	if (count == SDW_READ_INTR_CLEAR_RETRY)
1732 		dev_warn(&slave->dev, "Reached MAX_RETRY on alert read\n");
1733 
1734 io_err:
1735 	pm_runtime_mark_last_busy(&slave->dev);
1736 	pm_runtime_put_autosuspend(&slave->dev);
1737 
1738 	return ret;
1739 }
1740 
1741 static int sdw_update_slave_status(struct sdw_slave *slave,
1742 				   enum sdw_slave_status status)
1743 {
1744 	int ret = 0;
1745 
1746 	mutex_lock(&slave->sdw_dev_lock);
1747 
1748 	if (slave->probed) {
1749 		struct device *dev = &slave->dev;
1750 		struct sdw_driver *drv = drv_to_sdw_driver(dev->driver);
1751 
1752 		if (drv->ops && drv->ops->update_status)
1753 			ret = drv->ops->update_status(slave, status);
1754 	}
1755 
1756 	mutex_unlock(&slave->sdw_dev_lock);
1757 
1758 	return ret;
1759 }
1760 
1761 /**
1762  * sdw_handle_slave_status() - Handle Slave status
1763  * @bus: SDW bus instance
1764  * @status: Status for all Slave(s)
1765  */
1766 int sdw_handle_slave_status(struct sdw_bus *bus,
1767 			    enum sdw_slave_status status[])
1768 {
1769 	enum sdw_slave_status prev_status;
1770 	struct sdw_slave *slave;
1771 	bool attached_initializing;
1772 	int i, ret = 0;
1773 
1774 	/* first check if any Slaves fell off the bus */
1775 	for (i = 1; i <= SDW_MAX_DEVICES; i++) {
1776 		mutex_lock(&bus->bus_lock);
1777 		if (test_bit(i, bus->assigned) == false) {
1778 			mutex_unlock(&bus->bus_lock);
1779 			continue;
1780 		}
1781 		mutex_unlock(&bus->bus_lock);
1782 
1783 		slave = sdw_get_slave(bus, i);
1784 		if (!slave)
1785 			continue;
1786 
1787 		if (status[i] == SDW_SLAVE_UNATTACHED &&
1788 		    slave->status != SDW_SLAVE_UNATTACHED) {
1789 			dev_warn(&slave->dev, "Slave %d state check1: UNATTACHED, status was %d\n",
1790 				 i, slave->status);
1791 			sdw_modify_slave_status(slave, SDW_SLAVE_UNATTACHED);
1792 		}
1793 	}
1794 
1795 	if (status[0] == SDW_SLAVE_ATTACHED) {
1796 		dev_dbg(bus->dev, "Slave attached, programming device number\n");
1797 		ret = sdw_program_device_num(bus);
1798 		if (ret < 0)
1799 			dev_err(bus->dev, "Slave attach failed: %d\n", ret);
1800 		/*
1801 		 * programming a device number will have side effects,
1802 		 * so we deal with other devices at a later time
1803 		 */
1804 		return ret;
1805 	}
1806 
1807 	/* Continue to check other slave statuses */
1808 	for (i = 1; i <= SDW_MAX_DEVICES; i++) {
1809 		mutex_lock(&bus->bus_lock);
1810 		if (test_bit(i, bus->assigned) == false) {
1811 			mutex_unlock(&bus->bus_lock);
1812 			continue;
1813 		}
1814 		mutex_unlock(&bus->bus_lock);
1815 
1816 		slave = sdw_get_slave(bus, i);
1817 		if (!slave)
1818 			continue;
1819 
1820 		attached_initializing = false;
1821 
1822 		switch (status[i]) {
1823 		case SDW_SLAVE_UNATTACHED:
1824 			if (slave->status == SDW_SLAVE_UNATTACHED)
1825 				break;
1826 
1827 			dev_warn(&slave->dev, "Slave %d state check2: UNATTACHED, status was %d\n",
1828 				 i, slave->status);
1829 
1830 			sdw_modify_slave_status(slave, SDW_SLAVE_UNATTACHED);
1831 			break;
1832 
1833 		case SDW_SLAVE_ALERT:
1834 			ret = sdw_handle_slave_alerts(slave);
1835 			if (ret < 0)
1836 				dev_err(&slave->dev,
1837 					"Slave %d alert handling failed: %d\n",
1838 					i, ret);
1839 			break;
1840 
1841 		case SDW_SLAVE_ATTACHED:
1842 			if (slave->status == SDW_SLAVE_ATTACHED)
1843 				break;
1844 
1845 			prev_status = slave->status;
1846 			sdw_modify_slave_status(slave, SDW_SLAVE_ATTACHED);
1847 
1848 			if (prev_status == SDW_SLAVE_ALERT)
1849 				break;
1850 
1851 			attached_initializing = true;
1852 
1853 			ret = sdw_initialize_slave(slave);
1854 			if (ret < 0)
1855 				dev_err(&slave->dev,
1856 					"Slave %d initialization failed: %d\n",
1857 					i, ret);
1858 
1859 			break;
1860 
1861 		default:
1862 			dev_err(&slave->dev, "Invalid slave %d status:%d\n",
1863 				i, status[i]);
1864 			break;
1865 		}
1866 
1867 		ret = sdw_update_slave_status(slave, status[i]);
1868 		if (ret < 0)
1869 			dev_err(&slave->dev,
1870 				"Update Slave status failed:%d\n", ret);
1871 		if (attached_initializing) {
1872 			dev_dbg(&slave->dev,
1873 				"%s: signaling initialization completion for Slave %d\n",
1874 				__func__, slave->dev_num);
1875 
1876 			complete(&slave->initialization_complete);
1877 
1878 			/*
1879 			 * If the manager became pm_runtime active, the peripherals will be
1880 			 * restarted and attach, but their pm_runtime status may remain
1881 			 * suspended. If the 'update_slave_status' callback initiates
1882 			 * any sort of deferred processing, this processing would not be
1883 			 * cancelled on pm_runtime suspend.
1884 			 * To avoid such zombie states, we queue a request to resume.
1885 			 * This would be a no-op in case the peripheral was being resumed
1886 			 * by e.g. the ALSA/ASoC framework.
1887 			 */
1888 			pm_request_resume(&slave->dev);
1889 		}
1890 	}
1891 
1892 	return ret;
1893 }
1894 EXPORT_SYMBOL(sdw_handle_slave_status);
1895 
1896 void sdw_clear_slave_status(struct sdw_bus *bus, u32 request)
1897 {
1898 	struct sdw_slave *slave;
1899 	int i;
1900 
1901 	/* Check all non-zero devices */
1902 	for (i = 1; i <= SDW_MAX_DEVICES; i++) {
1903 		mutex_lock(&bus->bus_lock);
1904 		if (test_bit(i, bus->assigned) == false) {
1905 			mutex_unlock(&bus->bus_lock);
1906 			continue;
1907 		}
1908 		mutex_unlock(&bus->bus_lock);
1909 
1910 		slave = sdw_get_slave(bus, i);
1911 		if (!slave)
1912 			continue;
1913 
1914 		if (slave->status != SDW_SLAVE_UNATTACHED) {
1915 			sdw_modify_slave_status(slave, SDW_SLAVE_UNATTACHED);
1916 			slave->first_interrupt_done = false;
1917 			sdw_update_slave_status(slave, SDW_SLAVE_UNATTACHED);
1918 		}
1919 
1920 		/* keep track of request, used in pm_runtime resume */
1921 		slave->unattach_request = request;
1922 	}
1923 }
1924 EXPORT_SYMBOL(sdw_clear_slave_status);
1925