xref: /openbmc/linux/sound/usb/power.c (revision b8d312aa)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *   UAC3 Power Domain state management functions
4  */
5 
6 #include <linux/slab.h>
7 #include <linux/usb.h>
8 #include <linux/usb/audio.h>
9 #include <linux/usb/audio-v2.h>
10 #include <linux/usb/audio-v3.h>
11 
12 #include "usbaudio.h"
13 #include "helper.h"
14 #include "power.h"
15 
16 struct snd_usb_power_domain *
17 snd_usb_find_power_domain(struct usb_host_interface *ctrl_iface,
18 			  unsigned char id)
19 {
20 	struct snd_usb_power_domain *pd;
21 	void *p;
22 
23 	pd = kzalloc(sizeof(*pd), GFP_KERNEL);
24 	if (!pd)
25 		return NULL;
26 
27 	p = NULL;
28 	while ((p = snd_usb_find_csint_desc(ctrl_iface->extra,
29 					    ctrl_iface->extralen,
30 					    p, UAC3_POWER_DOMAIN)) != NULL) {
31 		struct uac3_power_domain_descriptor *pd_desc = p;
32 		int i;
33 
34 		for (i = 0; i < pd_desc->bNrEntities; i++) {
35 			if (pd_desc->baEntityID[i] == id) {
36 				pd->pd_id = pd_desc->bPowerDomainID;
37 				pd->pd_d1d0_rec =
38 					le16_to_cpu(pd_desc->waRecoveryTime1);
39 				pd->pd_d2d0_rec =
40 					le16_to_cpu(pd_desc->waRecoveryTime2);
41 				return pd;
42 			}
43 		}
44 	}
45 
46 	kfree(pd);
47 	return NULL;
48 }
49 
50 int snd_usb_power_domain_set(struct snd_usb_audio *chip,
51 			     struct snd_usb_power_domain *pd,
52 			     unsigned char state)
53 {
54 	struct usb_device *dev = chip->dev;
55 	unsigned char current_state;
56 	int err, idx;
57 
58 	idx = snd_usb_ctrl_intf(chip) | (pd->pd_id << 8);
59 
60 	err = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0),
61 			      UAC2_CS_CUR,
62 			      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
63 			      UAC3_AC_POWER_DOMAIN_CONTROL << 8, idx,
64 			      &current_state, sizeof(current_state));
65 	if (err < 0) {
66 		dev_err(&dev->dev, "Can't get UAC3 power state for id %d\n",
67 			pd->pd_id);
68 		return err;
69 	}
70 
71 	if (current_state == state) {
72 		dev_dbg(&dev->dev, "UAC3 power domain id %d already in state %d\n",
73 			pd->pd_id, state);
74 		return 0;
75 	}
76 
77 	err = snd_usb_ctl_msg(chip->dev, usb_sndctrlpipe(chip->dev, 0), UAC2_CS_CUR,
78 			      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
79 			      UAC3_AC_POWER_DOMAIN_CONTROL << 8, idx,
80 			      &state, sizeof(state));
81 	if (err < 0) {
82 		dev_err(&dev->dev, "Can't set UAC3 power state to %d for id %d\n",
83 			state, pd->pd_id);
84 		return err;
85 	}
86 
87 	if (state == UAC3_PD_STATE_D0) {
88 		switch (current_state) {
89 		case UAC3_PD_STATE_D2:
90 			udelay(pd->pd_d2d0_rec * 50);
91 			break;
92 		case UAC3_PD_STATE_D1:
93 			udelay(pd->pd_d1d0_rec * 50);
94 			break;
95 		default:
96 			return -EINVAL;
97 		}
98 	}
99 
100 	dev_dbg(&dev->dev, "UAC3 power domain id %d change to state %d\n",
101 		pd->pd_id, state);
102 
103 	return 0;
104 }
105