xref: /linux/sound/hda/common/codec.c (revision c5e90e8844692deb7bbcd029e8b92b3a20441903)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Universal Interface for Intel High Definition Audio Codec
4  *
5  * Copyright (c) 2004 Takashi Iwai <tiwai@suse.de>
6  */
7 
8 #include <linux/init.h>
9 #include <linux/delay.h>
10 #include <linux/slab.h>
11 #include <linux/minmax.h>
12 #include <linux/mutex.h>
13 #include <linux/module.h>
14 #include <linux/pm.h>
15 #include <linux/pm_runtime.h>
16 #include <sound/core.h>
17 #include <sound/hda_codec.h>
18 #include <sound/asoundef.h>
19 #include <sound/tlv.h>
20 #include <sound/initval.h>
21 #include <sound/jack.h>
22 #include "hda_local.h"
23 #include "hda_beep.h"
24 #include "hda_jack.h"
25 #include <sound/hda_hwdep.h>
26 #include <sound/hda_component.h>
27 
28 #define codec_in_pm(codec)		snd_hdac_is_in_pm(&codec->core)
29 #define hda_codec_is_power_on(codec)	snd_hdac_is_power_on(&codec->core)
30 #define codec_has_epss(codec) \
31 	((codec)->core.power_caps & AC_PWRST_EPSS)
32 #define codec_has_clkstop(codec) \
33 	((codec)->core.power_caps & AC_PWRST_CLKSTOP)
34 
35 static int call_exec_verb(struct hda_bus *bus, struct hda_codec *codec,
36 			  unsigned int cmd, unsigned int flags,
37 			  unsigned int *res)
38 {
39 	int err;
40 
41 	CLASS(snd_hda_power_pm, pm)(codec);
42 	guard(mutex)(&bus->core.cmd_mutex);
43 	if (flags & HDA_RW_NO_RESPONSE_FALLBACK)
44 		bus->no_response_fallback = 1;
45 	err = snd_hdac_bus_exec_verb_unlocked(&bus->core, codec->core.addr,
46 					      cmd, res);
47 	bus->no_response_fallback = 0;
48 	return err;
49 }
50 
51 /*
52  * Send and receive a verb - passed to exec_verb override for hdac_device
53  */
54 static int codec_exec_verb(struct hdac_device *dev, unsigned int cmd,
55 			   unsigned int flags, unsigned int *res)
56 {
57 	struct hda_codec *codec = container_of(dev, struct hda_codec, core);
58 	struct hda_bus *bus = codec->bus;
59 	int err;
60 
61 	if (cmd == ~0)
62 		return -1;
63 
64  again:
65 	err = call_exec_verb(bus, codec, cmd, flags, res);
66 	if (!codec_in_pm(codec) && res && err == -EAGAIN) {
67 		if (bus->response_reset) {
68 			codec_dbg(codec,
69 				  "resetting BUS due to fatal communication error\n");
70 			snd_hda_bus_reset(bus);
71 		}
72 		goto again;
73 	}
74 	/* clear reset-flag when the communication gets recovered */
75 	if (!err || codec_in_pm(codec))
76 		bus->response_reset = 0;
77 	return err;
78 }
79 
80 /**
81  * snd_hda_sequence_write - sequence writes
82  * @codec: the HDA codec
83  * @seq: VERB array to send
84  *
85  * Send the commands sequentially from the given array.
86  * The array must be terminated with NID=0.
87  */
88 void snd_hda_sequence_write(struct hda_codec *codec, const struct hda_verb *seq)
89 {
90 	for (; seq->nid; seq++)
91 		snd_hda_codec_write(codec, seq->nid, 0, seq->verb, seq->param);
92 }
93 EXPORT_SYMBOL_GPL(snd_hda_sequence_write);
94 
95 /* connection list element */
96 struct hda_conn_list {
97 	struct list_head list;
98 	int len;
99 	hda_nid_t nid;
100 	hda_nid_t conns[] __counted_by(len);
101 };
102 
103 /* look up the cached results */
104 static struct hda_conn_list *
105 lookup_conn_list(struct hda_codec *codec, hda_nid_t nid)
106 {
107 	struct hda_conn_list *p;
108 	list_for_each_entry(p, &codec->conn_list, list) {
109 		if (p->nid == nid)
110 			return p;
111 	}
112 	return NULL;
113 }
114 
115 static int add_conn_list(struct hda_codec *codec, hda_nid_t nid, int len,
116 			 const hda_nid_t *list)
117 {
118 	struct hda_conn_list *p;
119 
120 	p = kmalloc_flex(*p, conns, len);
121 	if (!p)
122 		return -ENOMEM;
123 	p->len = len;
124 	p->nid = nid;
125 	memcpy(p->conns, list, len * sizeof(hda_nid_t));
126 	list_add(&p->list, &codec->conn_list);
127 	return 0;
128 }
129 
130 static void remove_conn_list(struct hda_codec *codec)
131 {
132 	while (!list_empty(&codec->conn_list)) {
133 		struct hda_conn_list *p;
134 		p = list_first_entry(&codec->conn_list, typeof(*p), list);
135 		list_del(&p->list);
136 		kfree(p);
137 	}
138 }
139 
140 /* read the connection and add to the cache */
141 static int read_and_add_raw_conns(struct hda_codec *codec, hda_nid_t nid)
142 {
143 	hda_nid_t list[32];
144 	hda_nid_t *result = list;
145 	int len;
146 
147 	len = snd_hda_get_raw_connections(codec, nid, list, ARRAY_SIZE(list));
148 	if (len == -ENOSPC) {
149 		len = snd_hda_get_num_raw_conns(codec, nid);
150 		result = kmalloc_objs(hda_nid_t, len);
151 		if (!result)
152 			return -ENOMEM;
153 		len = snd_hda_get_raw_connections(codec, nid, result, len);
154 	}
155 	if (len >= 0)
156 		len = snd_hda_override_conn_list(codec, nid, len, result);
157 	if (result != list)
158 		kfree(result);
159 	return len;
160 }
161 
162 /**
163  * snd_hda_get_conn_list - get connection list
164  * @codec: the HDA codec
165  * @nid: NID to parse
166  * @listp: the pointer to store NID list
167  *
168  * Parses the connection list of the given widget and stores the pointer
169  * to the list of NIDs.
170  *
171  * Returns the number of connections, or a negative error code.
172  *
173  * Note that the returned pointer isn't protected against the list
174  * modification.  If snd_hda_override_conn_list() might be called
175  * concurrently, protect with a mutex appropriately.
176  */
177 int snd_hda_get_conn_list(struct hda_codec *codec, hda_nid_t nid,
178 			  const hda_nid_t **listp)
179 {
180 	bool added = false;
181 
182 	for (;;) {
183 		int err;
184 		const struct hda_conn_list *p;
185 
186 		/* if the connection-list is already cached, read it */
187 		p = lookup_conn_list(codec, nid);
188 		if (p) {
189 			if (listp)
190 				*listp = p->conns;
191 			return p->len;
192 		}
193 		if (snd_BUG_ON(added))
194 			return -EINVAL;
195 
196 		err = read_and_add_raw_conns(codec, nid);
197 		if (err < 0)
198 			return err;
199 		added = true;
200 	}
201 }
202 EXPORT_SYMBOL_GPL(snd_hda_get_conn_list);
203 
204 /**
205  * snd_hda_get_connections - copy connection list
206  * @codec: the HDA codec
207  * @nid: NID to parse
208  * @conn_list: connection list array; when NULL, checks only the size
209  * @max_conns: max. number of connections to store
210  *
211  * Parses the connection list of the given widget and stores the list
212  * of NIDs.
213  *
214  * Returns the number of connections, or a negative error code.
215  */
216 int snd_hda_get_connections(struct hda_codec *codec, hda_nid_t nid,
217 			    hda_nid_t *conn_list, int max_conns)
218 {
219 	const hda_nid_t *list;
220 	int len = snd_hda_get_conn_list(codec, nid, &list);
221 
222 	if (len > 0 && conn_list) {
223 		if (len > max_conns) {
224 			codec_err(codec, "Too many connections %d for NID 0x%x\n",
225 				   len, nid);
226 			return -EINVAL;
227 		}
228 		memcpy(conn_list, list, len * sizeof(hda_nid_t));
229 	}
230 
231 	return len;
232 }
233 EXPORT_SYMBOL_GPL(snd_hda_get_connections);
234 
235 /**
236  * snd_hda_override_conn_list - add/modify the connection-list to cache
237  * @codec: the HDA codec
238  * @nid: NID to parse
239  * @len: number of connection list entries
240  * @list: the list of connection entries
241  *
242  * Add or modify the given connection-list to the cache.  If the corresponding
243  * cache already exists, invalidate it and append a new one.
244  *
245  * Returns zero or a negative error code.
246  */
247 int snd_hda_override_conn_list(struct hda_codec *codec, hda_nid_t nid, int len,
248 			       const hda_nid_t *list)
249 {
250 	struct hda_conn_list *p;
251 
252 	p = lookup_conn_list(codec, nid);
253 	if (p) {
254 		list_del(&p->list);
255 		kfree(p);
256 	}
257 
258 	return add_conn_list(codec, nid, len, list);
259 }
260 EXPORT_SYMBOL_GPL(snd_hda_override_conn_list);
261 
262 /**
263  * snd_hda_get_conn_index - get the connection index of the given NID
264  * @codec: the HDA codec
265  * @mux: NID containing the list
266  * @nid: NID to select
267  * @recursive: 1 when searching NID recursively, otherwise 0
268  *
269  * Parses the connection list of the widget @mux and checks whether the
270  * widget @nid is present.  If it is, return the connection index.
271  * Otherwise it returns -1.
272  */
273 int snd_hda_get_conn_index(struct hda_codec *codec, hda_nid_t mux,
274 			   hda_nid_t nid, int recursive)
275 {
276 	const hda_nid_t *conn;
277 	int i, nums;
278 
279 	nums = snd_hda_get_conn_list(codec, mux, &conn);
280 	for (i = 0; i < nums; i++)
281 		if (conn[i] == nid)
282 			return i;
283 	if (!recursive)
284 		return -1;
285 	if (recursive > 10) {
286 		codec_dbg(codec, "too deep connection for 0x%x\n", nid);
287 		return -1;
288 	}
289 	recursive++;
290 	for (i = 0; i < nums; i++) {
291 		unsigned int type = get_wcaps_type(get_wcaps(codec, conn[i]));
292 		if (type == AC_WID_PIN || type == AC_WID_AUD_OUT)
293 			continue;
294 		if (snd_hda_get_conn_index(codec, conn[i], nid, recursive) >= 0)
295 			return i;
296 	}
297 	return -1;
298 }
299 EXPORT_SYMBOL_GPL(snd_hda_get_conn_index);
300 
301 /**
302  * snd_hda_get_num_devices - get DEVLIST_LEN parameter of the given widget
303  *  @codec: the HDA codec
304  *  @nid: NID of the pin to parse
305  *
306  * Get the device entry number on the given widget. This is a feature of
307  * DP MST audio. Each pin can have several device entries in it.
308  */
309 unsigned int snd_hda_get_num_devices(struct hda_codec *codec, hda_nid_t nid)
310 {
311 	unsigned int wcaps = get_wcaps(codec, nid);
312 	int parm;
313 
314 	if (!codec->dp_mst || !(wcaps & AC_WCAP_DIGITAL) ||
315 	    get_wcaps_type(wcaps) != AC_WID_PIN)
316 		return 0;
317 
318 	parm = snd_hdac_read_parm_uncached(&codec->core, nid, AC_PAR_DEVLIST_LEN);
319 	if (parm == -1)
320 		parm = 0;
321 	return parm & AC_DEV_LIST_LEN_MASK;
322 }
323 EXPORT_SYMBOL_GPL(snd_hda_get_num_devices);
324 
325 /**
326  * snd_hda_get_devices - copy device list without cache
327  * @codec: the HDA codec
328  * @nid: NID of the pin to parse
329  * @dev_list: device list array
330  * @max_devices: max. number of devices to store
331  *
332  * Copy the device list. This info is dynamic and so not cached.
333  * Currently called only from hda_proc.c, so not exported.
334  */
335 unsigned int snd_hda_get_devices(struct hda_codec *codec, hda_nid_t nid,
336 				u8 *dev_list, unsigned int max_devices)
337 {
338 	unsigned int parm, i, dev_len, devices;
339 
340 	parm = snd_hda_get_num_devices(codec, nid);
341 	if (!parm)	/* not multi-stream capable */
342 		return 0;
343 
344 	dev_len = min(parm + 1, max_devices);
345 
346 	devices = 0;
347 	while (devices < dev_len) {
348 		if (snd_hdac_read(&codec->core, nid,
349 				  AC_VERB_GET_DEVICE_LIST, devices, &parm))
350 			break; /* error */
351 
352 		for (i = 0; i < 8; i++) {
353 			dev_list[devices] = (u8)parm;
354 			parm >>= 4;
355 			devices++;
356 			if (devices >= dev_len)
357 				break;
358 		}
359 	}
360 	return devices;
361 }
362 
363 /**
364  * snd_hda_get_dev_select - get device entry select on the pin
365  * @codec: the HDA codec
366  * @nid: NID of the pin to get device entry select
367  *
368  * Get the devcie entry select on the pin. Return the device entry
369  * id selected on the pin. Return 0 means the first device entry
370  * is selected or MST is not supported.
371  */
372 int snd_hda_get_dev_select(struct hda_codec *codec, hda_nid_t nid)
373 {
374 	/* not support dp_mst will always return 0, using first dev_entry */
375 	if (!codec->dp_mst)
376 		return 0;
377 
378 	return snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_DEVICE_SEL, 0);
379 }
380 EXPORT_SYMBOL_GPL(snd_hda_get_dev_select);
381 
382 /**
383  * snd_hda_set_dev_select - set device entry select on the pin
384  * @codec: the HDA codec
385  * @nid: NID of the pin to set device entry select
386  * @dev_id: device entry id to be set
387  *
388  * Set the device entry select on the pin nid.
389  */
390 int snd_hda_set_dev_select(struct hda_codec *codec, hda_nid_t nid, int dev_id)
391 {
392 	int ret, num_devices;
393 
394 	/* not support dp_mst will always return 0, using first dev_entry */
395 	if (!codec->dp_mst)
396 		return 0;
397 
398 	/* AC_PAR_DEVLIST_LEN is 0 based. */
399 	num_devices = snd_hda_get_num_devices(codec, nid) + 1;
400 	/* If Device List Length is 0 (num_device = 1),
401 	 * the pin is not multi stream capable.
402 	 * Do nothing in this case.
403 	 */
404 	if (num_devices == 1)
405 		return 0;
406 
407 	/* Behavior of setting index being equal to or greater than
408 	 * Device List Length is not predictable
409 	 */
410 	if (num_devices <= dev_id)
411 		return -EINVAL;
412 
413 	ret = snd_hda_codec_write(codec, nid, 0,
414 			AC_VERB_SET_DEVICE_SEL, dev_id);
415 
416 	return ret;
417 }
418 EXPORT_SYMBOL_GPL(snd_hda_set_dev_select);
419 
420 /*
421  * read widget caps for each widget and store in cache
422  */
423 static int read_widget_caps(struct hda_codec *codec, hda_nid_t fg_node)
424 {
425 	int i;
426 	hda_nid_t nid;
427 
428 	codec->wcaps = kmalloc_array(codec->core.num_nodes, 4, GFP_KERNEL);
429 	if (!codec->wcaps)
430 		return -ENOMEM;
431 	nid = codec->core.start_nid;
432 	for (i = 0; i < codec->core.num_nodes; i++, nid++)
433 		codec->wcaps[i] = snd_hdac_read_parm_uncached(&codec->core,
434 					nid, AC_PAR_AUDIO_WIDGET_CAP);
435 	return 0;
436 }
437 
438 /* read all pin default configurations and save codec->init_pins */
439 static int read_pin_defaults(struct hda_codec *codec)
440 {
441 	hda_nid_t nid;
442 
443 	for_each_hda_codec_node(nid, codec) {
444 		struct hda_pincfg *pin;
445 		unsigned int wcaps = get_wcaps(codec, nid);
446 		unsigned int wid_type = get_wcaps_type(wcaps);
447 		if (wid_type != AC_WID_PIN)
448 			continue;
449 		pin = snd_array_new(&codec->init_pins);
450 		if (!pin)
451 			return -ENOMEM;
452 		pin->nid = nid;
453 		pin->cfg = snd_hda_codec_read(codec, nid, 0,
454 					      AC_VERB_GET_CONFIG_DEFAULT, 0);
455 		/*
456 		 * all device entries are the same widget control so far
457 		 * fixme: if any codec is different, need fix here
458 		 */
459 		pin->ctrl = snd_hda_codec_read(codec, nid, 0,
460 					       AC_VERB_GET_PIN_WIDGET_CONTROL,
461 					       0);
462 	}
463 	return 0;
464 }
465 
466 /* look up the given pin config list and return the item matching with NID */
467 static struct hda_pincfg *look_up_pincfg(struct hda_codec *codec,
468 					 struct snd_array *array,
469 					 hda_nid_t nid)
470 {
471 	struct hda_pincfg *pin;
472 	int i;
473 
474 	snd_array_for_each(array, i, pin) {
475 		if (pin->nid == nid)
476 			return pin;
477 	}
478 	return NULL;
479 }
480 
481 /* set the current pin config value for the given NID.
482  * the value is cached, and read via snd_hda_codec_get_pincfg()
483  */
484 int snd_hda_add_pincfg(struct hda_codec *codec, struct snd_array *list,
485 		       hda_nid_t nid, unsigned int cfg)
486 {
487 	struct hda_pincfg *pin;
488 
489 	pin = look_up_pincfg(codec, list, nid);
490 	if (!pin) {
491 		pin = snd_array_new(list);
492 		if (!pin)
493 			return -ENOMEM;
494 		pin->nid = nid;
495 	}
496 	pin->cfg = cfg;
497 	return 0;
498 }
499 
500 /**
501  * snd_hda_codec_set_pincfg - Override a pin default configuration
502  * @codec: the HDA codec
503  * @nid: NID to set the pin config
504  * @cfg: the pin default config value
505  *
506  * Override a pin default configuration value in the cache.
507  * This value can be read by snd_hda_codec_get_pincfg() in a higher
508  * priority than the real hardware value.
509  */
510 int snd_hda_codec_set_pincfg(struct hda_codec *codec,
511 			     hda_nid_t nid, unsigned int cfg)
512 {
513 	return snd_hda_add_pincfg(codec, &codec->driver_pins, nid, cfg);
514 }
515 EXPORT_SYMBOL_GPL(snd_hda_codec_set_pincfg);
516 
517 /**
518  * snd_hda_codec_get_pincfg - Obtain a pin-default configuration
519  * @codec: the HDA codec
520  * @nid: NID to get the pin config
521  *
522  * Get the current pin config value of the given pin NID.
523  * If the pincfg value is cached or overridden via sysfs or driver,
524  * returns the cached value.
525  */
526 unsigned int snd_hda_codec_get_pincfg(struct hda_codec *codec, hda_nid_t nid)
527 {
528 	struct hda_pincfg *pin;
529 
530 #ifdef CONFIG_SND_HDA_RECONFIG
531 	{
532 		unsigned int cfg = 0;
533 		scoped_guard(mutex, &codec->user_mutex) {
534 			pin = look_up_pincfg(codec, &codec->user_pins, nid);
535 			if (pin)
536 				cfg = pin->cfg;
537 		}
538 		if (cfg)
539 			return cfg;
540 	}
541 #endif
542 	pin = look_up_pincfg(codec, &codec->driver_pins, nid);
543 	if (pin)
544 		return pin->cfg;
545 	pin = look_up_pincfg(codec, &codec->init_pins, nid);
546 	if (pin)
547 		return pin->cfg;
548 	return 0;
549 }
550 EXPORT_SYMBOL_GPL(snd_hda_codec_get_pincfg);
551 
552 /**
553  * snd_hda_codec_set_pin_target - remember the current pinctl target value
554  * @codec: the HDA codec
555  * @nid: pin NID
556  * @val: assigned pinctl value
557  *
558  * This function stores the given value to a pinctl target value in the
559  * pincfg table.  This isn't always as same as the actually written value
560  * but can be referred at any time via snd_hda_codec_get_pin_target().
561  */
562 int snd_hda_codec_set_pin_target(struct hda_codec *codec, hda_nid_t nid,
563 				 unsigned int val)
564 {
565 	struct hda_pincfg *pin;
566 
567 	pin = look_up_pincfg(codec, &codec->init_pins, nid);
568 	if (!pin)
569 		return -EINVAL;
570 	pin->target = val;
571 	return 0;
572 }
573 EXPORT_SYMBOL_GPL(snd_hda_codec_set_pin_target);
574 
575 /**
576  * snd_hda_codec_get_pin_target - return the current pinctl target value
577  * @codec: the HDA codec
578  * @nid: pin NID
579  */
580 int snd_hda_codec_get_pin_target(struct hda_codec *codec, hda_nid_t nid)
581 {
582 	struct hda_pincfg *pin;
583 
584 	pin = look_up_pincfg(codec, &codec->init_pins, nid);
585 	if (!pin)
586 		return 0;
587 	return pin->target;
588 }
589 EXPORT_SYMBOL_GPL(snd_hda_codec_get_pin_target);
590 
591 /**
592  * snd_hda_shutup_pins - Shut up all pins
593  * @codec: the HDA codec
594  *
595  * Clear all pin controls to shup up before suspend for avoiding click noise.
596  * The controls aren't cached so that they can be resumed properly.
597  */
598 void snd_hda_shutup_pins(struct hda_codec *codec)
599 {
600 	const struct hda_pincfg *pin;
601 	int i;
602 
603 	/* don't shut up pins when unloading the driver; otherwise it breaks
604 	 * the default pin setup at the next load of the driver
605 	 */
606 	if (codec->bus->shutdown)
607 		return;
608 	snd_array_for_each(&codec->init_pins, i, pin) {
609 		snd_hda_codec_write_sync(codec, pin->nid, 0,
610 					 AC_VERB_SET_PIN_WIDGET_CONTROL, 0);
611 	}
612 	codec->pins_shutup = 1;
613 }
614 EXPORT_SYMBOL_GPL(snd_hda_shutup_pins);
615 
616 /* Restore the pin controls cleared previously via snd_hda_shutup_pins() */
617 static void restore_shutup_pins(struct hda_codec *codec)
618 {
619 	const struct hda_pincfg *pin;
620 	int i;
621 
622 	if (!codec->pins_shutup)
623 		return;
624 	if (codec->bus->shutdown)
625 		return;
626 	snd_array_for_each(&codec->init_pins, i, pin) {
627 		snd_hda_codec_write(codec, pin->nid, 0,
628 				    AC_VERB_SET_PIN_WIDGET_CONTROL,
629 				    pin->ctrl);
630 	}
631 	codec->pins_shutup = 0;
632 }
633 
634 static void hda_jackpoll_work(struct work_struct *work)
635 {
636 	struct hda_codec *codec =
637 		container_of(work, struct hda_codec, jackpoll_work.work);
638 
639 	if (!codec->jackpoll_interval)
640 		return;
641 
642 	/* the power-up/down sequence triggers the runtime resume */
643 	CLASS(snd_hda_power, pm)(codec);
644 	/* update jacks manually if polling is required, too */
645 	snd_hda_jack_set_dirty_all(codec);
646 	snd_hda_jack_poll_all(codec);
647 	schedule_delayed_work(&codec->jackpoll_work, codec->jackpoll_interval);
648 }
649 
650 /* release all pincfg lists */
651 static void free_init_pincfgs(struct hda_codec *codec)
652 {
653 	snd_array_free(&codec->driver_pins);
654 #ifdef CONFIG_SND_HDA_RECONFIG
655 	snd_array_free(&codec->user_pins);
656 #endif
657 	snd_array_free(&codec->init_pins);
658 }
659 
660 /*
661  * audio-converter setup caches
662  */
663 struct hda_cvt_setup {
664 	hda_nid_t nid;
665 	u8 stream_tag;
666 	u8 channel_id;
667 	u16 format_id;
668 	unsigned char active;	/* cvt is currently used */
669 	unsigned char dirty;	/* setups should be cleared */
670 };
671 
672 /* get or create a cache entry for the given audio converter NID */
673 static struct hda_cvt_setup *
674 get_hda_cvt_setup(struct hda_codec *codec, hda_nid_t nid)
675 {
676 	struct hda_cvt_setup *p;
677 	int i;
678 
679 	snd_array_for_each(&codec->cvt_setups, i, p) {
680 		if (p->nid == nid)
681 			return p;
682 	}
683 	p = snd_array_new(&codec->cvt_setups);
684 	if (p)
685 		p->nid = nid;
686 	return p;
687 }
688 
689 /*
690  * PCM device
691  */
692 struct hda_pcm *snd_hda_codec_pcm_new(struct hda_codec *codec,
693 				      const char *fmt, ...)
694 {
695 	struct hda_pcm *pcm;
696 	va_list args;
697 
698 	pcm = kzalloc_obj(*pcm);
699 	if (!pcm)
700 		return NULL;
701 
702 	pcm->codec = codec;
703 	va_start(args, fmt);
704 	pcm->name = kvasprintf(GFP_KERNEL, fmt, args);
705 	va_end(args);
706 	if (!pcm->name) {
707 		kfree(pcm);
708 		return NULL;
709 	}
710 
711 	list_add_tail(&pcm->list, &codec->pcm_list_head);
712 	snd_hda_codec_pcm_get(pcm);
713 	return pcm;
714 }
715 EXPORT_SYMBOL_GPL(snd_hda_codec_pcm_new);
716 
717 /*
718  * codec destructor
719  */
720 void snd_hda_codec_disconnect_pcms(struct hda_codec *codec)
721 {
722 	struct hda_pcm *pcm;
723 
724 	list_for_each_entry(pcm, &codec->pcm_list_head, list) {
725 		if (pcm->disconnected)
726 			continue;
727 		if (pcm->pcm)
728 			snd_device_disconnect(codec->card, pcm->pcm);
729 		snd_hda_codec_pcm_put(pcm);
730 		pcm->disconnected = 1;
731 	}
732 }
733 
734 static void codec_release_pcms(struct hda_codec *codec)
735 {
736 	struct hda_pcm *pcm, *n;
737 
738 	list_for_each_entry_safe(pcm, n, &codec->pcm_list_head, list) {
739 		list_del(&pcm->list);
740 		if (pcm->pcm)
741 			snd_device_free(pcm->codec->card, pcm->pcm);
742 		clear_bit(pcm->device, pcm->codec->bus->pcm_dev_bits);
743 		kfree(pcm->name);
744 		kfree(pcm);
745 	}
746 }
747 
748 /**
749  * snd_hda_codec_cleanup_for_unbind - Prepare codec for removal
750  * @codec: codec device to cleanup
751  */
752 void snd_hda_codec_cleanup_for_unbind(struct hda_codec *codec)
753 {
754 	if (codec->core.registered) {
755 		/* pm_runtime_put() is called in snd_hdac_device_exit() */
756 		pm_runtime_get_noresume(hda_codec_dev(codec));
757 		pm_runtime_disable(hda_codec_dev(codec));
758 		codec->core.registered = 0;
759 	}
760 
761 	snd_hda_codec_disconnect_pcms(codec);
762 	cancel_delayed_work_sync(&codec->jackpoll_work);
763 	if (!codec->in_freeing)
764 		snd_hda_ctls_clear(codec);
765 	codec_release_pcms(codec);
766 	snd_hda_detach_beep_device(codec);
767 	snd_hda_jack_tbl_clear(codec);
768 	codec->proc_widget_hook = NULL;
769 	codec->spec = NULL;
770 
771 	/* free only driver_pins so that init_pins + user_pins are restored */
772 	snd_array_free(&codec->driver_pins);
773 	snd_array_free(&codec->cvt_setups);
774 	snd_array_free(&codec->spdif_out);
775 	snd_array_free(&codec->verbs);
776 	codec->follower_dig_outs = NULL;
777 	codec->spdif_status_reset = 0;
778 	snd_array_free(&codec->mixers);
779 	snd_array_free(&codec->nids);
780 	remove_conn_list(codec);
781 	snd_hdac_regmap_exit(&codec->core);
782 	codec->configured = 0;
783 	snd_refcount_init(&codec->pcm_ref); /* reset refcount */
784 }
785 EXPORT_SYMBOL_GPL(snd_hda_codec_cleanup_for_unbind);
786 
787 static unsigned int hda_set_power_state(struct hda_codec *codec,
788 				unsigned int power_state);
789 
790 /* enable/disable display power per codec */
791 void snd_hda_codec_display_power(struct hda_codec *codec, bool enable)
792 {
793 	if (codec->display_power_control)
794 		snd_hdac_display_power(&codec->bus->core, codec->addr, enable);
795 }
796 
797 /**
798  * snd_hda_codec_register - Finalize codec initialization
799  * @codec: codec device to register
800  *
801  * Also called from hda_bind.c
802  */
803 void snd_hda_codec_register(struct hda_codec *codec)
804 {
805 	if (codec->core.registered)
806 		return;
807 	if (device_is_registered(hda_codec_dev(codec))) {
808 		snd_hda_codec_display_power(codec, true);
809 		pm_runtime_enable(hda_codec_dev(codec));
810 		/* it was powered up in snd_hda_codec_new(), now all done */
811 		snd_hda_power_down(codec);
812 		codec->core.registered = 1;
813 	}
814 }
815 EXPORT_SYMBOL_GPL(snd_hda_codec_register);
816 
817 static int snd_hda_codec_dev_register(struct snd_device *device)
818 {
819 	snd_hda_codec_register(device->device_data);
820 	return 0;
821 }
822 
823 /**
824  * snd_hda_codec_unregister - Unregister specified codec device
825  * @codec: codec device to unregister
826  */
827 void snd_hda_codec_unregister(struct hda_codec *codec)
828 {
829 	codec->in_freeing = 1;
830 	/*
831 	 * snd_hda_codec_device_new() is used by legacy HDA and ASoC driver.
832 	 * We can't unregister ASoC device since it will be unregistered in
833 	 * snd_hdac_ext_bus_device_remove().
834 	 */
835 	if (codec->core.type == HDA_DEV_LEGACY)
836 		snd_hdac_device_unregister(&codec->core);
837 	snd_hda_codec_display_power(codec, false);
838 
839 	/*
840 	 * In the case of ASoC HD-audio bus, the device refcount is released in
841 	 * snd_hdac_ext_bus_device_remove() explicitly.
842 	 */
843 	if (codec->core.type == HDA_DEV_LEGACY)
844 		put_device(hda_codec_dev(codec));
845 }
846 EXPORT_SYMBOL_GPL(snd_hda_codec_unregister);
847 
848 static int snd_hda_codec_dev_free(struct snd_device *device)
849 {
850 	snd_hda_codec_unregister(device->device_data);
851 	return 0;
852 }
853 
854 static void snd_hda_codec_dev_release(struct device *dev)
855 {
856 	struct hda_codec *codec = dev_to_hda_codec(dev);
857 
858 	free_init_pincfgs(codec);
859 	snd_hdac_device_exit(&codec->core);
860 	snd_hda_sysfs_clear(codec);
861 	kfree(codec->modelname);
862 	kfree(codec->wcaps);
863 	kfree(codec);
864 }
865 
866 #define DEV_NAME_LEN 31
867 
868 /**
869  * snd_hda_codec_device_init - allocate HDA codec device
870  * @bus: codec's parent bus
871  * @codec_addr: the codec address on the parent bus
872  * @fmt: format string for the device's name
873  *
874  * Returns newly allocated codec device or ERR_PTR() on failure.
875  */
876 struct hda_codec *
877 snd_hda_codec_device_init(struct hda_bus *bus, unsigned int codec_addr,
878 			  const char *fmt, ...)
879 {
880 	va_list vargs;
881 	char name[DEV_NAME_LEN];
882 	struct hda_codec *codec;
883 	int err;
884 
885 	if (snd_BUG_ON(!bus))
886 		return ERR_PTR(-EINVAL);
887 	if (snd_BUG_ON(codec_addr > HDA_MAX_CODEC_ADDRESS))
888 		return ERR_PTR(-EINVAL);
889 
890 	codec = kzalloc_obj(*codec);
891 	if (!codec)
892 		return ERR_PTR(-ENOMEM);
893 
894 	va_start(vargs, fmt);
895 	vsprintf(name, fmt, vargs);
896 	va_end(vargs);
897 
898 	err = snd_hdac_device_init(&codec->core, &bus->core, name, codec_addr);
899 	if (err < 0) {
900 		kfree(codec);
901 		return ERR_PTR(err);
902 	}
903 
904 	codec->bus = bus;
905 	codec->depop_delay = -1;
906 	codec->fixup_id = HDA_FIXUP_ID_NOT_SET;
907 	codec->core.dev.release = snd_hda_codec_dev_release;
908 	codec->core.type = HDA_DEV_LEGACY;
909 
910 	mutex_init(&codec->spdif_mutex);
911 	mutex_init(&codec->control_mutex);
912 	snd_array_init(&codec->mixers, sizeof(struct hda_nid_item), 32);
913 	snd_array_init(&codec->nids, sizeof(struct hda_nid_item), 32);
914 	snd_array_init(&codec->init_pins, sizeof(struct hda_pincfg), 16);
915 	snd_array_init(&codec->driver_pins, sizeof(struct hda_pincfg), 16);
916 	snd_array_init(&codec->cvt_setups, sizeof(struct hda_cvt_setup), 8);
917 	snd_array_init(&codec->spdif_out, sizeof(struct hda_spdif_out), 16);
918 	snd_array_init(&codec->jacktbl, sizeof(struct hda_jack_tbl), 16);
919 	snd_array_init(&codec->verbs, sizeof(struct hda_verb *), 8);
920 	INIT_LIST_HEAD(&codec->conn_list);
921 	INIT_LIST_HEAD(&codec->pcm_list_head);
922 	INIT_DELAYED_WORK(&codec->jackpoll_work, hda_jackpoll_work);
923 	snd_refcount_init(&codec->pcm_ref);
924 
925 	return codec;
926 }
927 EXPORT_SYMBOL_GPL(snd_hda_codec_device_init);
928 
929 /**
930  * snd_hda_codec_new - create a HDA codec
931  * @bus: the bus to assign
932  * @card: card for this codec
933  * @codec_addr: the codec address
934  * @codecp: the pointer to store the generated codec
935  *
936  * Returns 0 if successful, or a negative error code.
937  */
938 int snd_hda_codec_new(struct hda_bus *bus, struct snd_card *card,
939 		      unsigned int codec_addr, struct hda_codec **codecp)
940 {
941 	struct hda_codec *codec;
942 	int ret;
943 
944 	codec = snd_hda_codec_device_init(bus, codec_addr, "hdaudioC%dD%d",
945 					  card->number, codec_addr);
946 	if (IS_ERR(codec))
947 		return PTR_ERR(codec);
948 	*codecp = codec;
949 
950 	ret = snd_hda_codec_device_new(bus, card, codec_addr, *codecp, true);
951 	if (ret)
952 		put_device(hda_codec_dev(*codecp));
953 
954 	return ret;
955 }
956 EXPORT_SYMBOL_GPL(snd_hda_codec_new);
957 
958 int snd_hda_codec_device_new(struct hda_bus *bus, struct snd_card *card,
959 			unsigned int codec_addr, struct hda_codec *codec,
960 			bool snddev_managed)
961 {
962 	char component[31];
963 	hda_nid_t fg;
964 	int err;
965 	static const struct snd_device_ops dev_ops = {
966 		.dev_register = snd_hda_codec_dev_register,
967 		.dev_free = snd_hda_codec_dev_free,
968 	};
969 
970 	dev_dbg(card->dev, "%s: entry\n", __func__);
971 
972 	if (snd_BUG_ON(!bus))
973 		return -EINVAL;
974 	if (snd_BUG_ON(codec_addr > HDA_MAX_CODEC_ADDRESS))
975 		return -EINVAL;
976 
977 	codec->core.exec_verb = codec_exec_verb;
978 	codec->card = card;
979 	codec->addr = codec_addr;
980 
981 	codec->power_jiffies = jiffies;
982 
983 	snd_hda_sysfs_init(codec);
984 
985 	if (codec->bus->modelname) {
986 		codec->modelname = kstrdup(codec->bus->modelname, GFP_KERNEL);
987 		if (!codec->modelname)
988 			return -ENOMEM;
989 	}
990 
991 	fg = codec->core.afg ? codec->core.afg : codec->core.mfg;
992 	err = read_widget_caps(codec, fg);
993 	if (err < 0)
994 		return err;
995 	err = read_pin_defaults(codec);
996 	if (err < 0)
997 		return err;
998 
999 	/* power-up all before initialization */
1000 	hda_set_power_state(codec, AC_PWRST_D0);
1001 	codec->core.dev.power.power_state = PMSG_ON;
1002 
1003 	snd_hda_codec_proc_new(codec);
1004 
1005 	snd_hda_create_hwdep(codec);
1006 
1007 	sprintf(component, "HDA:%08x,%08x,%08x", codec->core.vendor_id,
1008 		codec->core.subsystem_id, codec->core.revision_id);
1009 	snd_component_add(card, component);
1010 
1011 	if (snddev_managed) {
1012 		/* ASoC features component management instead */
1013 		err = snd_device_new(card, SNDRV_DEV_CODEC, codec, &dev_ops);
1014 		if (err < 0)
1015 			return err;
1016 	}
1017 
1018 #ifdef CONFIG_PM
1019 	/* PM runtime needs to be enabled later after binding codec */
1020 	if (codec->core.dev.power.runtime_auto)
1021 		pm_runtime_forbid(&codec->core.dev);
1022 	else
1023 		/* Keep the usage_count consistent across subsequent probing */
1024 		pm_runtime_get_noresume(&codec->core.dev);
1025 #endif
1026 
1027 	return 0;
1028 }
1029 EXPORT_SYMBOL_GPL(snd_hda_codec_device_new);
1030 
1031 /**
1032  * snd_hda_codec_update_widgets - Refresh widget caps and pin defaults
1033  * @codec: the HDA codec
1034  *
1035  * Forcibly refresh the all widget caps and the init pin configurations of
1036  * the given codec.
1037  */
1038 int snd_hda_codec_update_widgets(struct hda_codec *codec)
1039 {
1040 	hda_nid_t fg;
1041 	int err;
1042 
1043 	err = snd_hdac_refresh_widgets(&codec->core);
1044 	if (err < 0)
1045 		return err;
1046 
1047 	/* Assume the function group node does not change,
1048 	 * only the widget nodes may change.
1049 	 */
1050 	kfree(codec->wcaps);
1051 	fg = codec->core.afg ? codec->core.afg : codec->core.mfg;
1052 	err = read_widget_caps(codec, fg);
1053 	if (err < 0)
1054 		return err;
1055 
1056 	snd_array_free(&codec->init_pins);
1057 	err = read_pin_defaults(codec);
1058 
1059 	return err;
1060 }
1061 EXPORT_SYMBOL_GPL(snd_hda_codec_update_widgets);
1062 
1063 /* update the stream-id if changed */
1064 static void update_pcm_stream_id(struct hda_codec *codec,
1065 				 struct hda_cvt_setup *p, hda_nid_t nid,
1066 				 u32 stream_tag, int channel_id)
1067 {
1068 	unsigned int oldval, newval;
1069 
1070 	if (p->stream_tag != stream_tag || p->channel_id != channel_id) {
1071 		oldval = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_CONV, 0);
1072 		newval = (stream_tag << 4) | channel_id;
1073 		if (oldval != newval)
1074 			snd_hda_codec_write(codec, nid, 0,
1075 					    AC_VERB_SET_CHANNEL_STREAMID,
1076 					    newval);
1077 		p->stream_tag = stream_tag;
1078 		p->channel_id = channel_id;
1079 	}
1080 }
1081 
1082 /* update the format-id if changed */
1083 static void update_pcm_format(struct hda_codec *codec, struct hda_cvt_setup *p,
1084 			      hda_nid_t nid, int format)
1085 {
1086 	unsigned int oldval;
1087 
1088 	if (p->format_id != format) {
1089 		oldval = snd_hda_codec_read(codec, nid, 0,
1090 					    AC_VERB_GET_STREAM_FORMAT, 0);
1091 		if (oldval != format) {
1092 			msleep(1);
1093 			snd_hda_codec_write(codec, nid, 0,
1094 					    AC_VERB_SET_STREAM_FORMAT,
1095 					    format);
1096 		}
1097 		p->format_id = format;
1098 	}
1099 }
1100 
1101 /**
1102  * snd_hda_codec_setup_stream - set up the codec for streaming
1103  * @codec: the CODEC to set up
1104  * @nid: the NID to set up
1105  * @stream_tag: stream tag to pass, it's between 0x1 and 0xf.
1106  * @channel_id: channel id to pass, zero based.
1107  * @format: stream format.
1108  */
1109 void snd_hda_codec_setup_stream(struct hda_codec *codec, hda_nid_t nid,
1110 				u32 stream_tag,
1111 				int channel_id, int format)
1112 {
1113 	struct hda_codec_driver *driver = hda_codec_to_driver(codec);
1114 	struct hda_codec *c;
1115 	struct hda_cvt_setup *p;
1116 	int type;
1117 	int i;
1118 
1119 	if (!nid)
1120 		return;
1121 
1122 	codec_dbg(codec,
1123 		  "hda_codec_setup_stream: NID=0x%x, stream=0x%x, channel=%d, format=0x%x\n",
1124 		  nid, stream_tag, channel_id, format);
1125 	p = get_hda_cvt_setup(codec, nid);
1126 	if (!p)
1127 		return;
1128 
1129 	if (driver->ops->stream_pm)
1130 		driver->ops->stream_pm(codec, nid, true);
1131 	if (codec->pcm_format_first)
1132 		update_pcm_format(codec, p, nid, format);
1133 	update_pcm_stream_id(codec, p, nid, stream_tag, channel_id);
1134 	if (!codec->pcm_format_first)
1135 		update_pcm_format(codec, p, nid, format);
1136 
1137 	p->active = 1;
1138 	p->dirty = 0;
1139 
1140 	/* make other inactive cvts with the same stream-tag dirty */
1141 	type = get_wcaps_type(get_wcaps(codec, nid));
1142 	list_for_each_codec(c, codec->bus) {
1143 		snd_array_for_each(&c->cvt_setups, i, p) {
1144 			if (!p->active && p->stream_tag == stream_tag &&
1145 			    get_wcaps_type(get_wcaps(c, p->nid)) == type)
1146 				p->dirty = 1;
1147 		}
1148 	}
1149 }
1150 EXPORT_SYMBOL_GPL(snd_hda_codec_setup_stream);
1151 
1152 static void really_cleanup_stream(struct hda_codec *codec,
1153 				  struct hda_cvt_setup *q);
1154 
1155 /**
1156  * __snd_hda_codec_cleanup_stream - clean up the codec for closing
1157  * @codec: the CODEC to clean up
1158  * @nid: the NID to clean up
1159  * @do_now: really clean up the stream instead of clearing the active flag
1160  */
1161 void __snd_hda_codec_cleanup_stream(struct hda_codec *codec, hda_nid_t nid,
1162 				    int do_now)
1163 {
1164 	struct hda_cvt_setup *p;
1165 
1166 	if (!nid)
1167 		return;
1168 
1169 	if (codec->no_sticky_stream)
1170 		do_now = 1;
1171 
1172 	codec_dbg(codec, "hda_codec_cleanup_stream: NID=0x%x\n", nid);
1173 	p = get_hda_cvt_setup(codec, nid);
1174 	if (p) {
1175 		/* here we just clear the active flag when do_now isn't set;
1176 		 * actual clean-ups will be done later in
1177 		 * purify_inactive_streams() called from snd_hda_codec_prpapre()
1178 		 */
1179 		if (do_now)
1180 			really_cleanup_stream(codec, p);
1181 		else
1182 			p->active = 0;
1183 	}
1184 }
1185 EXPORT_SYMBOL_GPL(__snd_hda_codec_cleanup_stream);
1186 
1187 static void really_cleanup_stream(struct hda_codec *codec,
1188 				  struct hda_cvt_setup *q)
1189 {
1190 	struct hda_codec_driver *driver = hda_codec_to_driver(codec);
1191 	hda_nid_t nid = q->nid;
1192 
1193 	if (q->stream_tag || q->channel_id)
1194 		snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_CHANNEL_STREAMID, 0);
1195 	if (q->format_id)
1196 		snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_STREAM_FORMAT, 0
1197 );
1198 	memset(q, 0, sizeof(*q));
1199 	q->nid = nid;
1200 	if (driver->ops->stream_pm)
1201 		driver->ops->stream_pm(codec, nid, false);
1202 }
1203 
1204 /* clean up the all conflicting obsolete streams */
1205 static void purify_inactive_streams(struct hda_codec *codec)
1206 {
1207 	struct hda_codec *c;
1208 	struct hda_cvt_setup *p;
1209 	int i;
1210 
1211 	list_for_each_codec(c, codec->bus) {
1212 		snd_array_for_each(&c->cvt_setups, i, p) {
1213 			if (p->dirty)
1214 				really_cleanup_stream(c, p);
1215 		}
1216 	}
1217 }
1218 
1219 /* clean up all streams; called from suspend */
1220 static void hda_cleanup_all_streams(struct hda_codec *codec)
1221 {
1222 	struct hda_cvt_setup *p;
1223 	int i;
1224 
1225 	snd_array_for_each(&codec->cvt_setups, i, p) {
1226 		if (p->stream_tag)
1227 			really_cleanup_stream(codec, p);
1228 	}
1229 }
1230 
1231 /*
1232  * amp access functions
1233  */
1234 
1235 /**
1236  * query_amp_caps - query AMP capabilities
1237  * @codec: the HD-auio codec
1238  * @nid: the NID to query
1239  * @direction: either #HDA_INPUT or #HDA_OUTPUT
1240  *
1241  * Query AMP capabilities for the given widget and direction.
1242  * Returns the obtained capability bits.
1243  *
1244  * When cap bits have been already read, this doesn't read again but
1245  * returns the cached value.
1246  */
1247 u32 query_amp_caps(struct hda_codec *codec, hda_nid_t nid, int direction)
1248 {
1249 	if (!(get_wcaps(codec, nid) & AC_WCAP_AMP_OVRD))
1250 		nid = codec->core.afg;
1251 	return snd_hda_param_read(codec, nid,
1252 				  direction == HDA_OUTPUT ?
1253 				  AC_PAR_AMP_OUT_CAP : AC_PAR_AMP_IN_CAP);
1254 }
1255 EXPORT_SYMBOL_GPL(query_amp_caps);
1256 
1257 /**
1258  * snd_hda_check_amp_caps - query AMP capabilities
1259  * @codec: the HD-audio codec
1260  * @nid: the NID to query
1261  * @dir: either #HDA_INPUT or #HDA_OUTPUT
1262  * @bits: bit mask to check the result
1263  *
1264  * Check whether the widget has the given amp capability for the direction.
1265  */
1266 bool snd_hda_check_amp_caps(struct hda_codec *codec, hda_nid_t nid,
1267 			   int dir, unsigned int bits)
1268 {
1269 	if (!nid)
1270 		return false;
1271 	if (get_wcaps(codec, nid) & (1 << (dir + 1)))
1272 		if (query_amp_caps(codec, nid, dir) & bits)
1273 			return true;
1274 	return false;
1275 }
1276 EXPORT_SYMBOL_GPL(snd_hda_check_amp_caps);
1277 
1278 /**
1279  * snd_hda_override_amp_caps - Override the AMP capabilities
1280  * @codec: the CODEC to clean up
1281  * @nid: the NID to clean up
1282  * @dir: either #HDA_INPUT or #HDA_OUTPUT
1283  * @caps: the capability bits to set
1284  *
1285  * Override the cached AMP caps bits value by the given one.
1286  * This function is useful if the driver needs to adjust the AMP ranges,
1287  * e.g. limit to 0dB, etc.
1288  *
1289  * Returns zero if successful or a negative error code.
1290  */
1291 int snd_hda_override_amp_caps(struct hda_codec *codec, hda_nid_t nid, int dir,
1292 			      unsigned int caps)
1293 {
1294 	unsigned int parm;
1295 
1296 	snd_hda_override_wcaps(codec, nid,
1297 			       get_wcaps(codec, nid) | AC_WCAP_AMP_OVRD);
1298 	parm = dir == HDA_OUTPUT ? AC_PAR_AMP_OUT_CAP : AC_PAR_AMP_IN_CAP;
1299 	return snd_hdac_override_parm(&codec->core, nid, parm, caps);
1300 }
1301 EXPORT_SYMBOL_GPL(snd_hda_override_amp_caps);
1302 
1303 static unsigned int encode_amp(struct hda_codec *codec, hda_nid_t nid,
1304 			       int ch, int dir, int idx)
1305 {
1306 	unsigned int cmd = snd_hdac_regmap_encode_amp(nid, ch, dir, idx);
1307 
1308 	/* enable fake mute if no h/w mute but min=mute */
1309 	if ((query_amp_caps(codec, nid, dir) &
1310 	     (AC_AMPCAP_MUTE | AC_AMPCAP_MIN_MUTE)) == AC_AMPCAP_MIN_MUTE)
1311 		cmd |= AC_AMP_FAKE_MUTE;
1312 	return cmd;
1313 }
1314 
1315 /**
1316  * snd_hda_codec_amp_update - update the AMP mono value
1317  * @codec: HD-audio codec
1318  * @nid: NID to read the AMP value
1319  * @ch: channel to update (0 or 1)
1320  * @dir: #HDA_INPUT or #HDA_OUTPUT
1321  * @idx: the index value (only for input direction)
1322  * @mask: bit mask to set
1323  * @val: the bits value to set
1324  *
1325  * Update the AMP values for the given channel, direction and index.
1326  */
1327 int snd_hda_codec_amp_update(struct hda_codec *codec, hda_nid_t nid,
1328 			     int ch, int dir, int idx, int mask, int val)
1329 {
1330 	unsigned int cmd = encode_amp(codec, nid, ch, dir, idx);
1331 
1332 	return snd_hdac_regmap_update_raw(&codec->core, cmd, mask, val);
1333 }
1334 EXPORT_SYMBOL_GPL(snd_hda_codec_amp_update);
1335 
1336 /**
1337  * snd_hda_codec_amp_stereo - update the AMP stereo values
1338  * @codec: HD-audio codec
1339  * @nid: NID to read the AMP value
1340  * @direction: #HDA_INPUT or #HDA_OUTPUT
1341  * @idx: the index value (only for input direction)
1342  * @mask: bit mask to set
1343  * @val: the bits value to set
1344  *
1345  * Update the AMP values like snd_hda_codec_amp_update(), but for a
1346  * stereo widget with the same mask and value.
1347  */
1348 int snd_hda_codec_amp_stereo(struct hda_codec *codec, hda_nid_t nid,
1349 			     int direction, int idx, int mask, int val)
1350 {
1351 	int ch, ret = 0;
1352 
1353 	if (snd_BUG_ON(mask & ~0xff))
1354 		mask &= 0xff;
1355 	for (ch = 0; ch < 2; ch++)
1356 		ret |= snd_hda_codec_amp_update(codec, nid, ch, direction,
1357 						idx, mask, val);
1358 	return ret;
1359 }
1360 EXPORT_SYMBOL_GPL(snd_hda_codec_amp_stereo);
1361 
1362 /**
1363  * snd_hda_codec_amp_init - initialize the AMP value
1364  * @codec: the HDA codec
1365  * @nid: NID to read the AMP value
1366  * @ch: channel (left=0 or right=1)
1367  * @dir: #HDA_INPUT or #HDA_OUTPUT
1368  * @idx: the index value (only for input direction)
1369  * @mask: bit mask to set
1370  * @val: the bits value to set
1371  *
1372  * Works like snd_hda_codec_amp_update() but it writes the value only at
1373  * the first access.  If the amp was already initialized / updated beforehand,
1374  * this does nothing.
1375  */
1376 int snd_hda_codec_amp_init(struct hda_codec *codec, hda_nid_t nid, int ch,
1377 			   int dir, int idx, int mask, int val)
1378 {
1379 	unsigned int cmd = encode_amp(codec, nid, ch, dir, idx);
1380 
1381 	if (!codec->core.regmap)
1382 		return -EINVAL;
1383 	return snd_hdac_regmap_update_raw_once(&codec->core, cmd, mask, val);
1384 }
1385 EXPORT_SYMBOL_GPL(snd_hda_codec_amp_init);
1386 
1387 /**
1388  * snd_hda_codec_amp_init_stereo - initialize the stereo AMP value
1389  * @codec: the HDA codec
1390  * @nid: NID to read the AMP value
1391  * @dir: #HDA_INPUT or #HDA_OUTPUT
1392  * @idx: the index value (only for input direction)
1393  * @mask: bit mask to set
1394  * @val: the bits value to set
1395  *
1396  * Call snd_hda_codec_amp_init() for both stereo channels.
1397  */
1398 int snd_hda_codec_amp_init_stereo(struct hda_codec *codec, hda_nid_t nid,
1399 				  int dir, int idx, int mask, int val)
1400 {
1401 	int ch, ret = 0;
1402 
1403 	if (snd_BUG_ON(mask & ~0xff))
1404 		mask &= 0xff;
1405 	for (ch = 0; ch < 2; ch++)
1406 		ret |= snd_hda_codec_amp_init(codec, nid, ch, dir,
1407 					      idx, mask, val);
1408 	return ret;
1409 }
1410 EXPORT_SYMBOL_GPL(snd_hda_codec_amp_init_stereo);
1411 
1412 static u32 get_amp_max_value(struct hda_codec *codec, hda_nid_t nid, int dir,
1413 			     unsigned int ofs)
1414 {
1415 	u32 caps = query_amp_caps(codec, nid, dir);
1416 	/* get num steps */
1417 	caps = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
1418 	if (ofs < caps)
1419 		caps -= ofs;
1420 	return caps;
1421 }
1422 
1423 /**
1424  * snd_hda_mixer_amp_volume_info - Info callback for a standard AMP mixer
1425  * @kcontrol: referred ctl element
1426  * @uinfo: pointer to get/store the data
1427  *
1428  * The control element is supposed to have the private_value field
1429  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1430  */
1431 int snd_hda_mixer_amp_volume_info(struct snd_kcontrol *kcontrol,
1432 				  struct snd_ctl_elem_info *uinfo)
1433 {
1434 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1435 	u16 nid = get_amp_nid(kcontrol);
1436 	u8 chs = get_amp_channels(kcontrol);
1437 	int dir = get_amp_direction(kcontrol);
1438 	unsigned int ofs = get_amp_offset(kcontrol);
1439 
1440 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1441 	uinfo->count = chs == 3 ? 2 : 1;
1442 	uinfo->value.integer.min = 0;
1443 	uinfo->value.integer.max = get_amp_max_value(codec, nid, dir, ofs);
1444 	if (!uinfo->value.integer.max) {
1445 		codec_warn(codec,
1446 			   "num_steps = 0 for NID=0x%x (ctl = %s)\n",
1447 			   nid, kcontrol->id.name);
1448 		return -EINVAL;
1449 	}
1450 	return 0;
1451 }
1452 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_volume_info);
1453 
1454 
1455 static inline unsigned int
1456 read_amp_value(struct hda_codec *codec, hda_nid_t nid,
1457 	       int ch, int dir, int idx, unsigned int ofs)
1458 {
1459 	unsigned int val;
1460 	val = snd_hda_codec_amp_read(codec, nid, ch, dir, idx);
1461 	val &= HDA_AMP_VOLMASK;
1462 	if (val >= ofs)
1463 		val -= ofs;
1464 	else
1465 		val = 0;
1466 	return val;
1467 }
1468 
1469 static inline int
1470 update_amp_value(struct hda_codec *codec, hda_nid_t nid,
1471 		 int ch, int dir, int idx, unsigned int ofs,
1472 		 unsigned int val)
1473 {
1474 	unsigned int maxval;
1475 
1476 	if (val > 0)
1477 		val += ofs;
1478 	/* ofs = 0: raw max value */
1479 	maxval = get_amp_max_value(codec, nid, dir, 0);
1480 	if (val > maxval)
1481 		return -EINVAL;
1482 	return snd_hda_codec_amp_update(codec, nid, ch, dir, idx,
1483 					HDA_AMP_VOLMASK, val);
1484 }
1485 
1486 /**
1487  * snd_hda_mixer_amp_volume_get - Get callback for a standard AMP mixer volume
1488  * @kcontrol: ctl element
1489  * @ucontrol: pointer to get/store the data
1490  *
1491  * The control element is supposed to have the private_value field
1492  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1493  */
1494 int snd_hda_mixer_amp_volume_get(struct snd_kcontrol *kcontrol,
1495 				 struct snd_ctl_elem_value *ucontrol)
1496 {
1497 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1498 	hda_nid_t nid = get_amp_nid(kcontrol);
1499 	int chs = get_amp_channels(kcontrol);
1500 	int dir = get_amp_direction(kcontrol);
1501 	int idx = get_amp_index(kcontrol);
1502 	unsigned int ofs = get_amp_offset(kcontrol);
1503 	long *valp = ucontrol->value.integer.value;
1504 
1505 	if (chs & 1)
1506 		*valp++ = read_amp_value(codec, nid, 0, dir, idx, ofs);
1507 	if (chs & 2)
1508 		*valp = read_amp_value(codec, nid, 1, dir, idx, ofs);
1509 	return 0;
1510 }
1511 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_volume_get);
1512 
1513 /**
1514  * snd_hda_mixer_amp_volume_put - Put callback for a standard AMP mixer volume
1515  * @kcontrol: ctl element
1516  * @ucontrol: pointer to get/store the data
1517  *
1518  * The control element is supposed to have the private_value field
1519  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1520  */
1521 int snd_hda_mixer_amp_volume_put(struct snd_kcontrol *kcontrol,
1522 				 struct snd_ctl_elem_value *ucontrol)
1523 {
1524 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1525 	hda_nid_t nid = get_amp_nid(kcontrol);
1526 	int chs = get_amp_channels(kcontrol);
1527 	int dir = get_amp_direction(kcontrol);
1528 	int idx = get_amp_index(kcontrol);
1529 	unsigned int ofs = get_amp_offset(kcontrol);
1530 	long *valp = ucontrol->value.integer.value;
1531 	int change = 0;
1532 	int err;
1533 
1534 	if (chs & 1) {
1535 		err = update_amp_value(codec, nid, 0, dir, idx, ofs, *valp);
1536 		if (err < 0)
1537 			return err;
1538 		change |= err;
1539 		valp++;
1540 	}
1541 	if (chs & 2) {
1542 		err = update_amp_value(codec, nid, 1, dir, idx, ofs, *valp);
1543 		if (err < 0)
1544 			return err;
1545 		change |= err;
1546 	}
1547 	return change;
1548 }
1549 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_volume_put);
1550 
1551 /* inquiry the amp caps and convert to TLV */
1552 static void get_ctl_amp_tlv(struct snd_kcontrol *kcontrol, unsigned int *tlv)
1553 {
1554 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1555 	hda_nid_t nid = get_amp_nid(kcontrol);
1556 	int dir = get_amp_direction(kcontrol);
1557 	unsigned int ofs = get_amp_offset(kcontrol);
1558 	bool min_mute = get_amp_min_mute(kcontrol);
1559 	u32 caps, val1, val2;
1560 
1561 	caps = query_amp_caps(codec, nid, dir);
1562 	val2 = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT;
1563 	val2 = (val2 + 1) * 25;
1564 	val1 = -((caps & AC_AMPCAP_OFFSET) >> AC_AMPCAP_OFFSET_SHIFT);
1565 	val1 += ofs;
1566 	val1 = ((int)val1) * ((int)val2);
1567 	if (min_mute || (caps & AC_AMPCAP_MIN_MUTE))
1568 		val2 |= TLV_DB_SCALE_MUTE;
1569 	tlv[SNDRV_CTL_TLVO_TYPE] = SNDRV_CTL_TLVT_DB_SCALE;
1570 	tlv[SNDRV_CTL_TLVO_LEN] = 2 * sizeof(unsigned int);
1571 	tlv[SNDRV_CTL_TLVO_DB_SCALE_MIN] = val1;
1572 	tlv[SNDRV_CTL_TLVO_DB_SCALE_MUTE_AND_STEP] = val2;
1573 }
1574 
1575 /**
1576  * snd_hda_mixer_amp_tlv - TLV callback for a standard AMP mixer volume
1577  * @kcontrol: ctl element
1578  * @op_flag: operation flag
1579  * @size: byte size of input TLV
1580  * @_tlv: TLV data
1581  *
1582  * The control element is supposed to have the private_value field
1583  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1584  */
1585 int snd_hda_mixer_amp_tlv(struct snd_kcontrol *kcontrol, int op_flag,
1586 			  unsigned int size, unsigned int __user *_tlv)
1587 {
1588 	unsigned int tlv[4];
1589 
1590 	if (size < 4 * sizeof(unsigned int))
1591 		return -ENOMEM;
1592 	get_ctl_amp_tlv(kcontrol, tlv);
1593 	if (copy_to_user(_tlv, tlv, sizeof(tlv)))
1594 		return -EFAULT;
1595 	return 0;
1596 }
1597 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_tlv);
1598 
1599 /**
1600  * snd_hda_set_vmaster_tlv - Set TLV for a virtual master control
1601  * @codec: HD-audio codec
1602  * @nid: NID of a reference widget
1603  * @dir: #HDA_INPUT or #HDA_OUTPUT
1604  * @tlv: TLV data to be stored, at least 4 elements
1605  *
1606  * Set (static) TLV data for a virtual master volume using the AMP caps
1607  * obtained from the reference NID.
1608  * The volume range is recalculated as if the max volume is 0dB.
1609  */
1610 void snd_hda_set_vmaster_tlv(struct hda_codec *codec, hda_nid_t nid, int dir,
1611 			     unsigned int *tlv)
1612 {
1613 	u32 caps;
1614 	int nums, step;
1615 
1616 	caps = query_amp_caps(codec, nid, dir);
1617 	nums = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
1618 	step = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT;
1619 	step = (step + 1) * 25;
1620 	tlv[SNDRV_CTL_TLVO_TYPE] = SNDRV_CTL_TLVT_DB_SCALE;
1621 	tlv[SNDRV_CTL_TLVO_LEN] = 2 * sizeof(unsigned int);
1622 	tlv[SNDRV_CTL_TLVO_DB_SCALE_MIN] = -nums * step;
1623 	tlv[SNDRV_CTL_TLVO_DB_SCALE_MUTE_AND_STEP] = step;
1624 }
1625 EXPORT_SYMBOL_GPL(snd_hda_set_vmaster_tlv);
1626 
1627 /* find a mixer control element with the given name */
1628 static struct snd_kcontrol *
1629 find_mixer_ctl(struct hda_codec *codec, const char *name, int dev, int idx)
1630 {
1631 	struct snd_ctl_elem_id id;
1632 	memset(&id, 0, sizeof(id));
1633 	id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
1634 	id.device = dev;
1635 	id.index = idx;
1636 	if (snd_BUG_ON(strlen(name) >= sizeof(id.name)))
1637 		return NULL;
1638 	strscpy(id.name, name);
1639 	return snd_ctl_find_id(codec->card, &id);
1640 }
1641 
1642 /**
1643  * snd_hda_find_mixer_ctl - Find a mixer control element with the given name
1644  * @codec: HD-audio codec
1645  * @name: ctl id name string
1646  *
1647  * Get the control element with the given id string and IFACE_MIXER.
1648  */
1649 struct snd_kcontrol *snd_hda_find_mixer_ctl(struct hda_codec *codec,
1650 					    const char *name)
1651 {
1652 	return find_mixer_ctl(codec, name, 0, 0);
1653 }
1654 EXPORT_SYMBOL_GPL(snd_hda_find_mixer_ctl);
1655 
1656 static int find_empty_mixer_ctl_idx(struct hda_codec *codec, const char *name,
1657 				    int start_idx)
1658 {
1659 	int i, idx;
1660 	/* 16 ctlrs should be large enough */
1661 	for (i = 0, idx = start_idx; i < 16; i++, idx++) {
1662 		if (!find_mixer_ctl(codec, name, 0, idx))
1663 			return idx;
1664 	}
1665 	return -EBUSY;
1666 }
1667 
1668 /**
1669  * snd_hda_ctl_add - Add a control element and assign to the codec
1670  * @codec: HD-audio codec
1671  * @nid: corresponding NID (optional)
1672  * @kctl: the control element to assign
1673  *
1674  * Add the given control element to an array inside the codec instance.
1675  * All control elements belonging to a codec are supposed to be added
1676  * by this function so that a proper clean-up works at the free or
1677  * reconfiguration time.
1678  *
1679  * If non-zero @nid is passed, the NID is assigned to the control element.
1680  * The assignment is shown in the codec proc file.
1681  *
1682  * snd_hda_ctl_add() checks the control subdev id field whether
1683  * #HDA_SUBDEV_NID_FLAG bit is set.  If set (and @nid is zero), the lower
1684  * bits value is taken as the NID to assign. The #HDA_NID_ITEM_AMP bit
1685  * specifies if kctl->private_value is a HDA amplifier value.
1686  */
1687 int snd_hda_ctl_add(struct hda_codec *codec, hda_nid_t nid,
1688 		    struct snd_kcontrol *kctl)
1689 {
1690 	int err;
1691 	unsigned short flags = 0;
1692 	struct hda_nid_item *item;
1693 
1694 	if (!kctl)
1695 		return -EINVAL;
1696 
1697 	if (kctl->id.subdevice & HDA_SUBDEV_AMP_FLAG) {
1698 		flags |= HDA_NID_ITEM_AMP;
1699 		if (nid == 0)
1700 			nid = get_amp_nid_(kctl->private_value);
1701 	}
1702 	if ((kctl->id.subdevice & HDA_SUBDEV_NID_FLAG) != 0 && nid == 0)
1703 		nid = kctl->id.subdevice & 0xffff;
1704 	if (kctl->id.subdevice & (HDA_SUBDEV_NID_FLAG|HDA_SUBDEV_AMP_FLAG))
1705 		kctl->id.subdevice = 0;
1706 	err = snd_ctl_add(codec->card, kctl);
1707 	if (err < 0)
1708 		return err;
1709 	item = snd_array_new(&codec->mixers);
1710 	if (!item)
1711 		return -ENOMEM;
1712 	item->kctl = kctl;
1713 	item->nid = nid;
1714 	item->flags = flags;
1715 	return 0;
1716 }
1717 EXPORT_SYMBOL_GPL(snd_hda_ctl_add);
1718 
1719 /**
1720  * snd_hda_ctls_clear - Clear all controls assigned to the given codec
1721  * @codec: HD-audio codec
1722  */
1723 void snd_hda_ctls_clear(struct hda_codec *codec)
1724 {
1725 	int i;
1726 	struct hda_nid_item *items = codec->mixers.list;
1727 
1728 	for (i = 0; i < codec->mixers.used; i++)
1729 		snd_ctl_remove(codec->card, items[i].kctl);
1730 	snd_array_free(&codec->mixers);
1731 	snd_array_free(&codec->nids);
1732 }
1733 
1734 /**
1735  * snd_hda_lock_devices - pseudo device locking
1736  * @bus: the BUS
1737  *
1738  * toggle card->shutdown to allow/disallow the device access (as a hack)
1739  */
1740 int snd_hda_lock_devices(struct hda_bus *bus)
1741 {
1742 	struct snd_card *card = bus->card;
1743 	struct hda_codec *codec;
1744 
1745 	guard(spinlock)(&card->files_lock);
1746 	if (card->shutdown)
1747 		return -EINVAL;
1748 	card->shutdown = 1;
1749 	if (!list_empty(&card->ctl_files))
1750 		goto err_clear;
1751 
1752 	list_for_each_codec(codec, bus) {
1753 		struct hda_pcm *cpcm;
1754 		list_for_each_entry(cpcm, &codec->pcm_list_head, list) {
1755 			if (!cpcm->pcm)
1756 				continue;
1757 			if (cpcm->pcm->streams[0].substream_opened ||
1758 			    cpcm->pcm->streams[1].substream_opened)
1759 				goto err_clear;
1760 		}
1761 	}
1762 	return 0;
1763 
1764  err_clear:
1765 	card->shutdown = 0;
1766 	return -EINVAL;
1767 }
1768 EXPORT_SYMBOL_GPL(snd_hda_lock_devices);
1769 
1770 /**
1771  * snd_hda_unlock_devices - pseudo device unlocking
1772  * @bus: the BUS
1773  */
1774 void snd_hda_unlock_devices(struct hda_bus *bus)
1775 {
1776 	struct snd_card *card = bus->card;
1777 
1778 	guard(spinlock)(&card->files_lock);
1779 	card->shutdown = 0;
1780 }
1781 EXPORT_SYMBOL_GPL(snd_hda_unlock_devices);
1782 
1783 /**
1784  * snd_hda_codec_reset - Clear all objects assigned to the codec
1785  * @codec: HD-audio codec
1786  *
1787  * This frees the all PCM and control elements assigned to the codec, and
1788  * clears the caches and restores the pin default configurations.
1789  *
1790  * When a device is being used, it returns -EBSY.  If successfully freed,
1791  * returns zero.
1792  */
1793 int snd_hda_codec_reset(struct hda_codec *codec)
1794 {
1795 	struct hda_bus *bus = codec->bus;
1796 
1797 	if (snd_hda_lock_devices(bus) < 0)
1798 		return -EBUSY;
1799 
1800 	/* OK, let it free */
1801 	device_release_driver(hda_codec_dev(codec));
1802 
1803 	/* allow device access again */
1804 	snd_hda_unlock_devices(bus);
1805 	return 0;
1806 }
1807 
1808 typedef int (*map_follower_func_t)(struct hda_codec *, void *, struct snd_kcontrol *);
1809 
1810 /* apply the function to all matching follower ctls in the mixer list */
1811 static int map_followers(struct hda_codec *codec, const char * const *followers,
1812 			 const char *suffix, map_follower_func_t func, void *data)
1813 {
1814 	struct hda_nid_item *items;
1815 	const char * const *s;
1816 	int i, err;
1817 
1818 	items = codec->mixers.list;
1819 	for (i = 0; i < codec->mixers.used; i++) {
1820 		struct snd_kcontrol *sctl = items[i].kctl;
1821 		if (!sctl || sctl->id.iface != SNDRV_CTL_ELEM_IFACE_MIXER)
1822 			continue;
1823 		for (s = followers; *s; s++) {
1824 			char tmpname[sizeof(sctl->id.name)];
1825 			const char *name = *s;
1826 			if (suffix) {
1827 				snprintf(tmpname, sizeof(tmpname), "%s %s",
1828 					 name, suffix);
1829 				name = tmpname;
1830 			}
1831 			if (!strcmp(sctl->id.name, name)) {
1832 				err = func(codec, data, sctl);
1833 				if (err)
1834 					return err;
1835 				break;
1836 			}
1837 		}
1838 	}
1839 	return 0;
1840 }
1841 
1842 static int check_follower_present(struct hda_codec *codec,
1843 				  void *data, struct snd_kcontrol *sctl)
1844 {
1845 	return 1;
1846 }
1847 
1848 /* call kctl->put with the given value(s) */
1849 static int put_kctl_with_value(struct snd_kcontrol *kctl, int val)
1850 {
1851 	struct snd_ctl_elem_value *ucontrol __free(kfree) =
1852 		kzalloc_obj(*ucontrol);
1853 
1854 	if (!ucontrol)
1855 		return -ENOMEM;
1856 	ucontrol->value.integer.value[0] = val;
1857 	ucontrol->value.integer.value[1] = val;
1858 	kctl->put(kctl, ucontrol);
1859 	return 0;
1860 }
1861 
1862 struct follower_init_arg {
1863 	struct hda_codec *codec;
1864 	int step;
1865 };
1866 
1867 /* initialize the follower volume with 0dB via snd_ctl_apply_vmaster_followers() */
1868 static int init_follower_0dB(struct snd_kcontrol *follower,
1869 			     struct snd_kcontrol *kctl,
1870 			     void *_arg)
1871 {
1872 	struct follower_init_arg *arg = _arg;
1873 	int _tlv[4];
1874 	const int *tlv = NULL;
1875 	int step;
1876 	int val;
1877 
1878 	if (kctl->vd[0].access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) {
1879 		if (kctl->tlv.c != snd_hda_mixer_amp_tlv) {
1880 			codec_err(arg->codec,
1881 				  "Unexpected TLV callback for follower %s:%d\n",
1882 				  kctl->id.name, kctl->id.index);
1883 			return 0; /* ignore */
1884 		}
1885 		get_ctl_amp_tlv(kctl, _tlv);
1886 		tlv = _tlv;
1887 	} else if (kctl->vd[0].access & SNDRV_CTL_ELEM_ACCESS_TLV_READ)
1888 		tlv = kctl->tlv.p;
1889 
1890 	if (!tlv || tlv[SNDRV_CTL_TLVO_TYPE] != SNDRV_CTL_TLVT_DB_SCALE)
1891 		return 0;
1892 
1893 	step = tlv[SNDRV_CTL_TLVO_DB_SCALE_MUTE_AND_STEP];
1894 	step &= ~TLV_DB_SCALE_MUTE;
1895 	if (!step)
1896 		return 0;
1897 	if (arg->step && arg->step != step) {
1898 		codec_err(arg->codec,
1899 			  "Mismatching dB step for vmaster follower (%d!=%d)\n",
1900 			  arg->step, step);
1901 		return 0;
1902 	}
1903 
1904 	arg->step = step;
1905 	val = -tlv[SNDRV_CTL_TLVO_DB_SCALE_MIN] / step;
1906 	if (val > 0) {
1907 		put_kctl_with_value(follower, val);
1908 		return val;
1909 	}
1910 
1911 	return 0;
1912 }
1913 
1914 /* unmute the follower via snd_ctl_apply_vmaster_followers() */
1915 static int init_follower_unmute(struct snd_kcontrol *follower,
1916 				struct snd_kcontrol *kctl,
1917 				void *_arg)
1918 {
1919 	return put_kctl_with_value(follower, 1);
1920 }
1921 
1922 static int add_follower(struct hda_codec *codec,
1923 			void *data, struct snd_kcontrol *follower)
1924 {
1925 	return snd_ctl_add_follower(data, follower);
1926 }
1927 
1928 /**
1929  * __snd_hda_add_vmaster - create a virtual master control and add followers
1930  * @codec: HD-audio codec
1931  * @name: vmaster control name
1932  * @tlv: TLV data (optional)
1933  * @followers: follower control names (optional)
1934  * @suffix: suffix string to each follower name (optional)
1935  * @init_follower_vol: initialize followers to unmute/0dB
1936  * @access: kcontrol access rights
1937  * @ctl_ret: store the vmaster kcontrol in return
1938  *
1939  * Create a virtual master control with the given name.  The TLV data
1940  * must be either NULL or a valid data.
1941  *
1942  * @followers is a NULL-terminated array of strings, each of which is a
1943  * follower control name.  All controls with these names are assigned to
1944  * the new virtual master control.
1945  *
1946  * This function returns zero if successful or a negative error code.
1947  */
1948 int __snd_hda_add_vmaster(struct hda_codec *codec, char *name,
1949 			  unsigned int *tlv, const char * const *followers,
1950 			  const char *suffix, bool init_follower_vol,
1951 			  unsigned int access, struct snd_kcontrol **ctl_ret)
1952 {
1953 	struct snd_kcontrol *kctl;
1954 	int err;
1955 
1956 	if (ctl_ret)
1957 		*ctl_ret = NULL;
1958 
1959 	err = map_followers(codec, followers, suffix, check_follower_present, NULL);
1960 	if (err != 1) {
1961 		codec_dbg(codec, "No follower found for %s\n", name);
1962 		return 0;
1963 	}
1964 	kctl = snd_ctl_make_virtual_master(name, tlv);
1965 	if (!kctl)
1966 		return -ENOMEM;
1967 	kctl->vd[0].access |= access;
1968 	err = snd_hda_ctl_add(codec, 0, kctl);
1969 	if (err < 0)
1970 		return err;
1971 
1972 	err = map_followers(codec, followers, suffix, add_follower, kctl);
1973 	if (err < 0)
1974 		return err;
1975 
1976 	/* init with master mute & zero volume */
1977 	put_kctl_with_value(kctl, 0);
1978 	if (init_follower_vol) {
1979 		struct follower_init_arg arg = {
1980 			.codec = codec,
1981 			.step = 0,
1982 		};
1983 		snd_ctl_apply_vmaster_followers(kctl,
1984 						tlv ? init_follower_0dB : init_follower_unmute,
1985 						&arg);
1986 	}
1987 
1988 	if (ctl_ret)
1989 		*ctl_ret = kctl;
1990 	return 0;
1991 }
1992 EXPORT_SYMBOL_GPL(__snd_hda_add_vmaster);
1993 
1994 /* meta hook to call each driver's vmaster hook */
1995 static void vmaster_hook(void *private_data, int enabled)
1996 {
1997 	struct hda_vmaster_mute_hook *hook = private_data;
1998 
1999 	hook->hook(hook->codec, enabled);
2000 }
2001 
2002 /**
2003  * snd_hda_add_vmaster_hook - Add a vmaster hw specific hook
2004  * @codec: the HDA codec
2005  * @hook: the vmaster hook object
2006  *
2007  * Add a hw specific hook (like EAPD) with the given vmaster switch kctl.
2008  */
2009 int snd_hda_add_vmaster_hook(struct hda_codec *codec,
2010 			     struct hda_vmaster_mute_hook *hook)
2011 {
2012 	if (!hook->hook || !hook->sw_kctl)
2013 		return 0;
2014 	hook->codec = codec;
2015 	snd_ctl_add_vmaster_hook(hook->sw_kctl, vmaster_hook, hook);
2016 	return 0;
2017 }
2018 EXPORT_SYMBOL_GPL(snd_hda_add_vmaster_hook);
2019 
2020 /**
2021  * snd_hda_sync_vmaster_hook - Sync vmaster hook
2022  * @hook: the vmaster hook
2023  *
2024  * Call the hook with the current value for synchronization.
2025  * Should be called in init callback.
2026  */
2027 void snd_hda_sync_vmaster_hook(struct hda_vmaster_mute_hook *hook)
2028 {
2029 	if (!hook->hook || !hook->codec)
2030 		return;
2031 	/* don't call vmaster hook in the destructor since it might have
2032 	 * been already destroyed
2033 	 */
2034 	if (hook->codec->bus->shutdown)
2035 		return;
2036 	snd_ctl_sync_vmaster_hook(hook->sw_kctl);
2037 }
2038 EXPORT_SYMBOL_GPL(snd_hda_sync_vmaster_hook);
2039 
2040 
2041 /**
2042  * snd_hda_mixer_amp_switch_info - Info callback for a standard AMP mixer switch
2043  * @kcontrol: referred ctl element
2044  * @uinfo: pointer to get/store the data
2045  *
2046  * The control element is supposed to have the private_value field
2047  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2048  */
2049 int snd_hda_mixer_amp_switch_info(struct snd_kcontrol *kcontrol,
2050 				  struct snd_ctl_elem_info *uinfo)
2051 {
2052 	int chs = get_amp_channels(kcontrol);
2053 
2054 	uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2055 	uinfo->count = chs == 3 ? 2 : 1;
2056 	uinfo->value.integer.min = 0;
2057 	uinfo->value.integer.max = 1;
2058 	return 0;
2059 }
2060 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_switch_info);
2061 
2062 /**
2063  * snd_hda_mixer_amp_switch_get - Get callback for a standard AMP mixer switch
2064  * @kcontrol: ctl element
2065  * @ucontrol: pointer to get/store the data
2066  *
2067  * The control element is supposed to have the private_value field
2068  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2069  */
2070 int snd_hda_mixer_amp_switch_get(struct snd_kcontrol *kcontrol,
2071 				 struct snd_ctl_elem_value *ucontrol)
2072 {
2073 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2074 	hda_nid_t nid = get_amp_nid(kcontrol);
2075 	int chs = get_amp_channels(kcontrol);
2076 	int dir = get_amp_direction(kcontrol);
2077 	int idx = get_amp_index(kcontrol);
2078 	long *valp = ucontrol->value.integer.value;
2079 
2080 	if (chs & 1)
2081 		*valp++ = (snd_hda_codec_amp_read(codec, nid, 0, dir, idx) &
2082 			   HDA_AMP_MUTE) ? 0 : 1;
2083 	if (chs & 2)
2084 		*valp = (snd_hda_codec_amp_read(codec, nid, 1, dir, idx) &
2085 			 HDA_AMP_MUTE) ? 0 : 1;
2086 	return 0;
2087 }
2088 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_switch_get);
2089 
2090 /**
2091  * snd_hda_mixer_amp_switch_put - Put callback for a standard AMP mixer switch
2092  * @kcontrol: ctl element
2093  * @ucontrol: pointer to get/store the data
2094  *
2095  * The control element is supposed to have the private_value field
2096  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2097  */
2098 int snd_hda_mixer_amp_switch_put(struct snd_kcontrol *kcontrol,
2099 				 struct snd_ctl_elem_value *ucontrol)
2100 {
2101 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2102 	hda_nid_t nid = get_amp_nid(kcontrol);
2103 	int chs = get_amp_channels(kcontrol);
2104 	int dir = get_amp_direction(kcontrol);
2105 	int idx = get_amp_index(kcontrol);
2106 	long *valp = ucontrol->value.integer.value;
2107 	int change = 0;
2108 
2109 	if (chs & 1) {
2110 		if (*valp < 0 || *valp > 1)
2111 			return -EINVAL;
2112 		change = snd_hda_codec_amp_update(codec, nid, 0, dir, idx,
2113 						  HDA_AMP_MUTE,
2114 						  *valp ? 0 : HDA_AMP_MUTE);
2115 		valp++;
2116 	}
2117 	if (chs & 2) {
2118 		if (*valp < 0 || *valp > 1)
2119 			return -EINVAL;
2120 		change |= snd_hda_codec_amp_update(codec, nid, 1, dir, idx,
2121 						   HDA_AMP_MUTE,
2122 						   *valp ? 0 : HDA_AMP_MUTE);
2123 	}
2124 	hda_call_check_power_status(codec, nid);
2125 	return change;
2126 }
2127 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_switch_put);
2128 
2129 /*
2130  * SPDIF out controls
2131  */
2132 
2133 static int snd_hda_spdif_mask_info(struct snd_kcontrol *kcontrol,
2134 				   struct snd_ctl_elem_info *uinfo)
2135 {
2136 	uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
2137 	uinfo->count = 1;
2138 	return 0;
2139 }
2140 
2141 static int snd_hda_spdif_cmask_get(struct snd_kcontrol *kcontrol,
2142 				   struct snd_ctl_elem_value *ucontrol)
2143 {
2144 	ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
2145 					   IEC958_AES0_NONAUDIO |
2146 					   IEC958_AES0_CON_EMPHASIS_5015 |
2147 					   IEC958_AES0_CON_NOT_COPYRIGHT;
2148 	ucontrol->value.iec958.status[1] = IEC958_AES1_CON_CATEGORY |
2149 					   IEC958_AES1_CON_ORIGINAL;
2150 	return 0;
2151 }
2152 
2153 static int snd_hda_spdif_pmask_get(struct snd_kcontrol *kcontrol,
2154 				   struct snd_ctl_elem_value *ucontrol)
2155 {
2156 	ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
2157 					   IEC958_AES0_NONAUDIO |
2158 					   IEC958_AES0_PRO_EMPHASIS_5015;
2159 	return 0;
2160 }
2161 
2162 static int snd_hda_spdif_default_get(struct snd_kcontrol *kcontrol,
2163 				     struct snd_ctl_elem_value *ucontrol)
2164 {
2165 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2166 	int idx = kcontrol->private_value;
2167 	struct hda_spdif_out *spdif;
2168 
2169 	if (WARN_ON(codec->spdif_out.used <= idx))
2170 		return -EINVAL;
2171 	guard(mutex)(&codec->spdif_mutex);
2172 	spdif = snd_array_elem(&codec->spdif_out, idx);
2173 	ucontrol->value.iec958.status[0] = spdif->status & 0xff;
2174 	ucontrol->value.iec958.status[1] = (spdif->status >> 8) & 0xff;
2175 	ucontrol->value.iec958.status[2] = (spdif->status >> 16) & 0xff;
2176 	ucontrol->value.iec958.status[3] = (spdif->status >> 24) & 0xff;
2177 
2178 	return 0;
2179 }
2180 
2181 /* convert from SPDIF status bits to HDA SPDIF bits
2182  * bit 0 (DigEn) is always set zero (to be filled later)
2183  */
2184 static unsigned short convert_from_spdif_status(unsigned int sbits)
2185 {
2186 	unsigned short val = 0;
2187 
2188 	if (sbits & IEC958_AES0_PROFESSIONAL)
2189 		val |= AC_DIG1_PROFESSIONAL;
2190 	if (sbits & IEC958_AES0_NONAUDIO)
2191 		val |= AC_DIG1_NONAUDIO;
2192 	if (sbits & IEC958_AES0_PROFESSIONAL) {
2193 		if ((sbits & IEC958_AES0_PRO_EMPHASIS) ==
2194 		    IEC958_AES0_PRO_EMPHASIS_5015)
2195 			val |= AC_DIG1_EMPHASIS;
2196 	} else {
2197 		if ((sbits & IEC958_AES0_CON_EMPHASIS) ==
2198 		    IEC958_AES0_CON_EMPHASIS_5015)
2199 			val |= AC_DIG1_EMPHASIS;
2200 		if (!(sbits & IEC958_AES0_CON_NOT_COPYRIGHT))
2201 			val |= AC_DIG1_COPYRIGHT;
2202 		if (sbits & (IEC958_AES1_CON_ORIGINAL << 8))
2203 			val |= AC_DIG1_LEVEL;
2204 		val |= sbits & (IEC958_AES1_CON_CATEGORY << 8);
2205 	}
2206 	return val;
2207 }
2208 
2209 /* convert to SPDIF status bits from HDA SPDIF bits
2210  */
2211 static unsigned int convert_to_spdif_status(unsigned short val)
2212 {
2213 	unsigned int sbits = 0;
2214 
2215 	if (val & AC_DIG1_NONAUDIO)
2216 		sbits |= IEC958_AES0_NONAUDIO;
2217 	if (val & AC_DIG1_PROFESSIONAL)
2218 		sbits |= IEC958_AES0_PROFESSIONAL;
2219 	if (sbits & IEC958_AES0_PROFESSIONAL) {
2220 		if (val & AC_DIG1_EMPHASIS)
2221 			sbits |= IEC958_AES0_PRO_EMPHASIS_5015;
2222 	} else {
2223 		if (val & AC_DIG1_EMPHASIS)
2224 			sbits |= IEC958_AES0_CON_EMPHASIS_5015;
2225 		if (!(val & AC_DIG1_COPYRIGHT))
2226 			sbits |= IEC958_AES0_CON_NOT_COPYRIGHT;
2227 		if (val & AC_DIG1_LEVEL)
2228 			sbits |= (IEC958_AES1_CON_ORIGINAL << 8);
2229 		sbits |= val & (0x7f << 8);
2230 	}
2231 	return sbits;
2232 }
2233 
2234 /* set digital convert verbs both for the given NID and its followers */
2235 static void set_dig_out(struct hda_codec *codec, hda_nid_t nid,
2236 			int mask, int val)
2237 {
2238 	const hda_nid_t *d;
2239 
2240 	snd_hdac_regmap_update(&codec->core, nid, AC_VERB_SET_DIGI_CONVERT_1,
2241 			       mask, val);
2242 	d = codec->follower_dig_outs;
2243 	if (!d)
2244 		return;
2245 	for (; *d; d++)
2246 		snd_hdac_regmap_update(&codec->core, *d,
2247 				       AC_VERB_SET_DIGI_CONVERT_1, mask, val);
2248 }
2249 
2250 static inline void set_dig_out_convert(struct hda_codec *codec, hda_nid_t nid,
2251 				       int dig1, int dig2)
2252 {
2253 	unsigned int mask = 0;
2254 	unsigned int val = 0;
2255 
2256 	if (dig1 != -1) {
2257 		mask |= 0xff;
2258 		val = dig1;
2259 	}
2260 	if (dig2 != -1) {
2261 		mask |= 0xff00;
2262 		val |= dig2 << 8;
2263 	}
2264 	set_dig_out(codec, nid, mask, val);
2265 }
2266 
2267 static int snd_hda_spdif_default_put(struct snd_kcontrol *kcontrol,
2268 				     struct snd_ctl_elem_value *ucontrol)
2269 {
2270 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2271 	int idx = kcontrol->private_value;
2272 	struct hda_spdif_out *spdif;
2273 	hda_nid_t nid;
2274 	unsigned short val;
2275 	int change;
2276 
2277 	if (WARN_ON(codec->spdif_out.used <= idx))
2278 		return -EINVAL;
2279 	guard(mutex)(&codec->spdif_mutex);
2280 	spdif = snd_array_elem(&codec->spdif_out, idx);
2281 	nid = spdif->nid;
2282 	spdif->status = ucontrol->value.iec958.status[0] |
2283 		((unsigned int)ucontrol->value.iec958.status[1] << 8) |
2284 		((unsigned int)ucontrol->value.iec958.status[2] << 16) |
2285 		((unsigned int)ucontrol->value.iec958.status[3] << 24);
2286 	val = convert_from_spdif_status(spdif->status);
2287 	val |= spdif->ctls & 1;
2288 	change = spdif->ctls != val;
2289 	spdif->ctls = val;
2290 	if (change && nid != (u16)-1)
2291 		set_dig_out_convert(codec, nid, val & 0xff, (val >> 8) & 0xff);
2292 	return change;
2293 }
2294 
2295 #define snd_hda_spdif_out_switch_info	snd_ctl_boolean_mono_info
2296 
2297 static int snd_hda_spdif_out_switch_get(struct snd_kcontrol *kcontrol,
2298 					struct snd_ctl_elem_value *ucontrol)
2299 {
2300 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2301 	int idx = kcontrol->private_value;
2302 	struct hda_spdif_out *spdif;
2303 
2304 	if (WARN_ON(codec->spdif_out.used <= idx))
2305 		return -EINVAL;
2306 	guard(mutex)(&codec->spdif_mutex);
2307 	spdif = snd_array_elem(&codec->spdif_out, idx);
2308 	ucontrol->value.integer.value[0] = spdif->ctls & AC_DIG1_ENABLE;
2309 	return 0;
2310 }
2311 
2312 static inline void set_spdif_ctls(struct hda_codec *codec, hda_nid_t nid,
2313 				  int dig1, int dig2)
2314 {
2315 	set_dig_out_convert(codec, nid, dig1, dig2);
2316 	/* unmute amp switch (if any) */
2317 	if ((get_wcaps(codec, nid) & AC_WCAP_OUT_AMP) &&
2318 	    (dig1 & AC_DIG1_ENABLE))
2319 		snd_hda_codec_amp_stereo(codec, nid, HDA_OUTPUT, 0,
2320 					    HDA_AMP_MUTE, 0);
2321 }
2322 
2323 static int snd_hda_spdif_out_switch_put(struct snd_kcontrol *kcontrol,
2324 					struct snd_ctl_elem_value *ucontrol)
2325 {
2326 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2327 	int idx = kcontrol->private_value;
2328 	struct hda_spdif_out *spdif;
2329 	hda_nid_t nid;
2330 	unsigned short val;
2331 	int change;
2332 
2333 	if (WARN_ON(codec->spdif_out.used <= idx))
2334 		return -EINVAL;
2335 	guard(mutex)(&codec->spdif_mutex);
2336 	spdif = snd_array_elem(&codec->spdif_out, idx);
2337 	nid = spdif->nid;
2338 	val = spdif->ctls & ~AC_DIG1_ENABLE;
2339 	if (ucontrol->value.integer.value[0])
2340 		val |= AC_DIG1_ENABLE;
2341 	change = spdif->ctls != val;
2342 	spdif->ctls = val;
2343 	if (change && nid != (u16)-1)
2344 		set_spdif_ctls(codec, nid, val & 0xff, -1);
2345 	return change;
2346 }
2347 
2348 static const struct snd_kcontrol_new dig_mixes[] = {
2349 	{
2350 		.access = SNDRV_CTL_ELEM_ACCESS_READ,
2351 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2352 		.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, CON_MASK),
2353 		.info = snd_hda_spdif_mask_info,
2354 		.get = snd_hda_spdif_cmask_get,
2355 	},
2356 	{
2357 		.access = SNDRV_CTL_ELEM_ACCESS_READ,
2358 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2359 		.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, PRO_MASK),
2360 		.info = snd_hda_spdif_mask_info,
2361 		.get = snd_hda_spdif_pmask_get,
2362 	},
2363 	{
2364 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2365 		.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, DEFAULT),
2366 		.info = snd_hda_spdif_mask_info,
2367 		.get = snd_hda_spdif_default_get,
2368 		.put = snd_hda_spdif_default_put,
2369 	},
2370 	{
2371 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2372 		.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, SWITCH),
2373 		.info = snd_hda_spdif_out_switch_info,
2374 		.get = snd_hda_spdif_out_switch_get,
2375 		.put = snd_hda_spdif_out_switch_put,
2376 	},
2377 	{ } /* end */
2378 };
2379 
2380 /**
2381  * snd_hda_create_dig_out_ctls - create Output SPDIF-related controls
2382  * @codec: the HDA codec
2383  * @associated_nid: NID that new ctls associated with
2384  * @cvt_nid: converter NID
2385  * @type: HDA_PCM_TYPE_*
2386  * Creates controls related with the digital output.
2387  * Called from each codec driver supporting the digital out.
2388  *
2389  * Returns 0 if successful, or a negative error code.
2390  */
2391 int snd_hda_create_dig_out_ctls(struct hda_codec *codec,
2392 				hda_nid_t associated_nid,
2393 				hda_nid_t cvt_nid,
2394 				int type)
2395 {
2396 	int err;
2397 	struct snd_kcontrol *kctl;
2398 	const struct snd_kcontrol_new *dig_mix;
2399 	int idx = 0;
2400 	int val = 0;
2401 	const int spdif_index = 16;
2402 	struct hda_spdif_out *spdif;
2403 	struct hda_bus *bus = codec->bus;
2404 
2405 	if (bus->primary_dig_out_type == HDA_PCM_TYPE_HDMI &&
2406 	    type == HDA_PCM_TYPE_SPDIF) {
2407 		idx = spdif_index;
2408 	} else if (bus->primary_dig_out_type == HDA_PCM_TYPE_SPDIF &&
2409 		   type == HDA_PCM_TYPE_HDMI) {
2410 		/* suppose a single SPDIF device */
2411 		for (dig_mix = dig_mixes; dig_mix->name; dig_mix++) {
2412 			struct snd_ctl_elem_id id;
2413 
2414 			kctl = find_mixer_ctl(codec, dig_mix->name, 0, 0);
2415 			if (!kctl)
2416 				break;
2417 			id = kctl->id;
2418 			id.index = spdif_index;
2419 			err = snd_ctl_rename_id(codec->card, &kctl->id, &id);
2420 			if (err < 0)
2421 				return err;
2422 		}
2423 		bus->primary_dig_out_type = HDA_PCM_TYPE_HDMI;
2424 	}
2425 	if (!bus->primary_dig_out_type)
2426 		bus->primary_dig_out_type = type;
2427 
2428 	idx = find_empty_mixer_ctl_idx(codec, "IEC958 Playback Switch", idx);
2429 	if (idx < 0) {
2430 		codec_err(codec, "too many IEC958 outputs\n");
2431 		return -EBUSY;
2432 	}
2433 	spdif = snd_array_new(&codec->spdif_out);
2434 	if (!spdif)
2435 		return -ENOMEM;
2436 	for (dig_mix = dig_mixes; dig_mix->name; dig_mix++) {
2437 		kctl = snd_ctl_new1(dig_mix, codec);
2438 		if (!kctl)
2439 			return -ENOMEM;
2440 		kctl->id.index = idx;
2441 		kctl->private_value = codec->spdif_out.used - 1;
2442 		err = snd_hda_ctl_add(codec, associated_nid, kctl);
2443 		if (err < 0)
2444 			return err;
2445 	}
2446 	spdif->nid = cvt_nid;
2447 	snd_hdac_regmap_read(&codec->core, cvt_nid,
2448 			     AC_VERB_GET_DIGI_CONVERT_1, &val);
2449 	spdif->ctls = val;
2450 	spdif->status = convert_to_spdif_status(spdif->ctls);
2451 	return 0;
2452 }
2453 EXPORT_SYMBOL_GPL(snd_hda_create_dig_out_ctls);
2454 
2455 /**
2456  * snd_hda_spdif_out_of_nid - get the hda_spdif_out entry from the given NID
2457  * @codec: the HDA codec
2458  * @nid: widget NID
2459  *
2460  * call within spdif_mutex lock
2461  */
2462 struct hda_spdif_out *snd_hda_spdif_out_of_nid(struct hda_codec *codec,
2463 					       hda_nid_t nid)
2464 {
2465 	struct hda_spdif_out *spdif;
2466 	int i;
2467 
2468 	snd_array_for_each(&codec->spdif_out, i, spdif) {
2469 		if (spdif->nid == nid)
2470 			return spdif;
2471 	}
2472 	return NULL;
2473 }
2474 EXPORT_SYMBOL_GPL(snd_hda_spdif_out_of_nid);
2475 
2476 /**
2477  * snd_hda_spdif_ctls_unassign - Unassign the given SPDIF ctl
2478  * @codec: the HDA codec
2479  * @idx: the SPDIF ctl index
2480  *
2481  * Unassign the widget from the given SPDIF control.
2482  */
2483 void snd_hda_spdif_ctls_unassign(struct hda_codec *codec, int idx)
2484 {
2485 	struct hda_spdif_out *spdif;
2486 
2487 	if (WARN_ON(codec->spdif_out.used <= idx))
2488 		return;
2489 	guard(mutex)(&codec->spdif_mutex);
2490 	spdif = snd_array_elem(&codec->spdif_out, idx);
2491 	spdif->nid = (u16)-1;
2492 }
2493 EXPORT_SYMBOL_GPL(snd_hda_spdif_ctls_unassign);
2494 
2495 /**
2496  * snd_hda_spdif_ctls_assign - Assign the SPDIF controls to the given NID
2497  * @codec: the HDA codec
2498  * @idx: the SPDIF ctl idx
2499  * @nid: widget NID
2500  *
2501  * Assign the widget to the SPDIF control with the given index.
2502  */
2503 void snd_hda_spdif_ctls_assign(struct hda_codec *codec, int idx, hda_nid_t nid)
2504 {
2505 	struct hda_spdif_out *spdif;
2506 	unsigned short val;
2507 
2508 	if (WARN_ON(codec->spdif_out.used <= idx))
2509 		return;
2510 	guard(mutex)(&codec->spdif_mutex);
2511 	spdif = snd_array_elem(&codec->spdif_out, idx);
2512 	if (spdif->nid != nid) {
2513 		spdif->nid = nid;
2514 		val = spdif->ctls;
2515 		set_spdif_ctls(codec, nid, val & 0xff, (val >> 8) & 0xff);
2516 	}
2517 }
2518 EXPORT_SYMBOL_GPL(snd_hda_spdif_ctls_assign);
2519 
2520 /*
2521  * SPDIF sharing with analog output
2522  */
2523 static int spdif_share_sw_get(struct snd_kcontrol *kcontrol,
2524 			      struct snd_ctl_elem_value *ucontrol)
2525 {
2526 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2527 	struct hda_multi_out *mout = (void *)kcontrol->private_value;
2528 
2529 	guard(mutex)(&codec->spdif_mutex);
2530 	ucontrol->value.integer.value[0] = mout->share_spdif;
2531 	return 0;
2532 }
2533 
2534 static int spdif_share_sw_put(struct snd_kcontrol *kcontrol,
2535 			      struct snd_ctl_elem_value *ucontrol)
2536 {
2537 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2538 	struct hda_multi_out *mout = (void *)kcontrol->private_value;
2539 	bool val = !!ucontrol->value.integer.value[0];
2540 	int change;
2541 
2542 	guard(mutex)(&codec->spdif_mutex);
2543 	change = mout->share_spdif != val;
2544 	mout->share_spdif = val;
2545 	return change;
2546 }
2547 
2548 static const struct snd_kcontrol_new spdif_share_sw = {
2549 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2550 	.name = "IEC958 Default PCM Playback Switch",
2551 	.info = snd_ctl_boolean_mono_info,
2552 	.get = spdif_share_sw_get,
2553 	.put = spdif_share_sw_put,
2554 };
2555 
2556 static void notify_spdif_share_sw(struct hda_codec *codec,
2557 				  struct hda_multi_out *mout)
2558 {
2559 	if (mout->share_spdif_kctl)
2560 		snd_ctl_notify_one(codec->card, SNDRV_CTL_EVENT_MASK_VALUE,
2561 				   mout->share_spdif_kctl, 0);
2562 }
2563 
2564 /**
2565  * snd_hda_create_spdif_share_sw - create Default PCM switch
2566  * @codec: the HDA codec
2567  * @mout: multi-out instance
2568  */
2569 int snd_hda_create_spdif_share_sw(struct hda_codec *codec,
2570 				  struct hda_multi_out *mout)
2571 {
2572 	struct snd_kcontrol *kctl;
2573 	int err;
2574 
2575 	if (!mout->dig_out_nid)
2576 		return 0;
2577 
2578 	kctl = snd_ctl_new1(&spdif_share_sw, codec);
2579 	if (!kctl)
2580 		return -ENOMEM;
2581 	/* snd_ctl_new1() stores @codec in private_data; stash @mout in
2582 	 * private_value for the share-switch callbacks and cache the
2583 	 * assigned control for forced-disable notifications.
2584 	 */
2585 	kctl->private_value = (unsigned long)mout;
2586 	err = snd_hda_ctl_add(codec, mout->dig_out_nid, kctl);
2587 	if (err < 0)
2588 		return err;
2589 	mout->share_spdif_kctl = kctl;
2590 	return 0;
2591 }
2592 EXPORT_SYMBOL_GPL(snd_hda_create_spdif_share_sw);
2593 
2594 /*
2595  * SPDIF input
2596  */
2597 
2598 #define snd_hda_spdif_in_switch_info	snd_hda_spdif_out_switch_info
2599 
2600 static int snd_hda_spdif_in_switch_get(struct snd_kcontrol *kcontrol,
2601 				       struct snd_ctl_elem_value *ucontrol)
2602 {
2603 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2604 
2605 	ucontrol->value.integer.value[0] = codec->spdif_in_enable;
2606 	return 0;
2607 }
2608 
2609 static int snd_hda_spdif_in_switch_put(struct snd_kcontrol *kcontrol,
2610 				       struct snd_ctl_elem_value *ucontrol)
2611 {
2612 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2613 	hda_nid_t nid = kcontrol->private_value;
2614 	unsigned int val = !!ucontrol->value.integer.value[0];
2615 	int change;
2616 
2617 	guard(mutex)(&codec->spdif_mutex);
2618 	change = codec->spdif_in_enable != val;
2619 	if (change) {
2620 		codec->spdif_in_enable = val;
2621 		snd_hdac_regmap_write(&codec->core, nid,
2622 				      AC_VERB_SET_DIGI_CONVERT_1, val);
2623 	}
2624 	return change;
2625 }
2626 
2627 static int snd_hda_spdif_in_status_get(struct snd_kcontrol *kcontrol,
2628 				       struct snd_ctl_elem_value *ucontrol)
2629 {
2630 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2631 	hda_nid_t nid = kcontrol->private_value;
2632 	unsigned int val;
2633 	unsigned int sbits;
2634 
2635 	snd_hdac_regmap_read(&codec->core, nid,
2636 			     AC_VERB_GET_DIGI_CONVERT_1, &val);
2637 	sbits = convert_to_spdif_status(val);
2638 	ucontrol->value.iec958.status[0] = sbits;
2639 	ucontrol->value.iec958.status[1] = sbits >> 8;
2640 	ucontrol->value.iec958.status[2] = sbits >> 16;
2641 	ucontrol->value.iec958.status[3] = sbits >> 24;
2642 	return 0;
2643 }
2644 
2645 static const struct snd_kcontrol_new dig_in_ctls[] = {
2646 	{
2647 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2648 		.name = SNDRV_CTL_NAME_IEC958("", CAPTURE, SWITCH),
2649 		.info = snd_hda_spdif_in_switch_info,
2650 		.get = snd_hda_spdif_in_switch_get,
2651 		.put = snd_hda_spdif_in_switch_put,
2652 	},
2653 	{
2654 		.access = SNDRV_CTL_ELEM_ACCESS_READ,
2655 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2656 		.name = SNDRV_CTL_NAME_IEC958("", CAPTURE, DEFAULT),
2657 		.info = snd_hda_spdif_mask_info,
2658 		.get = snd_hda_spdif_in_status_get,
2659 	},
2660 	{ } /* end */
2661 };
2662 
2663 /**
2664  * snd_hda_create_spdif_in_ctls - create Input SPDIF-related controls
2665  * @codec: the HDA codec
2666  * @nid: audio in widget NID
2667  *
2668  * Creates controls related with the SPDIF input.
2669  * Called from each codec driver supporting the SPDIF in.
2670  *
2671  * Returns 0 if successful, or a negative error code.
2672  */
2673 int snd_hda_create_spdif_in_ctls(struct hda_codec *codec, hda_nid_t nid)
2674 {
2675 	int err;
2676 	struct snd_kcontrol *kctl;
2677 	const struct snd_kcontrol_new *dig_mix;
2678 	int idx;
2679 
2680 	idx = find_empty_mixer_ctl_idx(codec, "IEC958 Capture Switch", 0);
2681 	if (idx < 0) {
2682 		codec_err(codec, "too many IEC958 inputs\n");
2683 		return -EBUSY;
2684 	}
2685 	for (dig_mix = dig_in_ctls; dig_mix->name; dig_mix++) {
2686 		kctl = snd_ctl_new1(dig_mix, codec);
2687 		if (!kctl)
2688 			return -ENOMEM;
2689 		kctl->private_value = nid;
2690 		err = snd_hda_ctl_add(codec, nid, kctl);
2691 		if (err < 0)
2692 			return err;
2693 	}
2694 	codec->spdif_in_enable =
2695 		snd_hda_codec_read(codec, nid, 0,
2696 				   AC_VERB_GET_DIGI_CONVERT_1, 0) &
2697 		AC_DIG1_ENABLE;
2698 	return 0;
2699 }
2700 EXPORT_SYMBOL_GPL(snd_hda_create_spdif_in_ctls);
2701 
2702 /**
2703  * snd_hda_codec_set_power_to_all - Set the power state to all widgets
2704  * @codec: the HDA codec
2705  * @fg: function group (not used now)
2706  * @power_state: the power state to set (AC_PWRST_*)
2707  *
2708  * Set the given power state to all widgets that have the power control.
2709  * If the codec has power_filter set, it evaluates the power state and
2710  * filter out if it's unchanged as D3.
2711  */
2712 void snd_hda_codec_set_power_to_all(struct hda_codec *codec, hda_nid_t fg,
2713 				    unsigned int power_state)
2714 {
2715 	hda_nid_t nid;
2716 
2717 	for_each_hda_codec_node(nid, codec) {
2718 		unsigned int wcaps = get_wcaps(codec, nid);
2719 		unsigned int state = power_state;
2720 		if (!(wcaps & AC_WCAP_POWER))
2721 			continue;
2722 		if (codec->power_filter) {
2723 			state = codec->power_filter(codec, nid, power_state);
2724 			if (state != power_state && power_state == AC_PWRST_D3)
2725 				continue;
2726 		}
2727 		snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_POWER_STATE,
2728 				    state);
2729 	}
2730 }
2731 EXPORT_SYMBOL_GPL(snd_hda_codec_set_power_to_all);
2732 
2733 /**
2734  * snd_hda_codec_eapd_power_filter - A power filter callback for EAPD
2735  * @codec: the HDA codec
2736  * @nid: widget NID
2737  * @power_state: power state to evalue
2738  *
2739  * Don't power down the widget if it controls eapd and EAPD_BTLENABLE is set.
2740  * This can be used a codec power_filter callback.
2741  */
2742 unsigned int snd_hda_codec_eapd_power_filter(struct hda_codec *codec,
2743 					     hda_nid_t nid,
2744 					     unsigned int power_state)
2745 {
2746 	if (nid == codec->core.afg || nid == codec->core.mfg)
2747 		return power_state;
2748 	if (power_state == AC_PWRST_D3 &&
2749 	    get_wcaps_type(get_wcaps(codec, nid)) == AC_WID_PIN &&
2750 	    (snd_hda_query_pin_caps(codec, nid) & AC_PINCAP_EAPD)) {
2751 		int eapd = snd_hda_codec_read(codec, nid, 0,
2752 					      AC_VERB_GET_EAPD_BTLENABLE, 0);
2753 		if (eapd & 0x02)
2754 			return AC_PWRST_D0;
2755 	}
2756 	return power_state;
2757 }
2758 EXPORT_SYMBOL_GPL(snd_hda_codec_eapd_power_filter);
2759 
2760 /*
2761  * set power state of the codec, and return the power state
2762  */
2763 static unsigned int hda_set_power_state(struct hda_codec *codec,
2764 					unsigned int power_state)
2765 {
2766 	struct hda_codec_driver *driver = hda_codec_to_driver(codec);
2767 	hda_nid_t fg = codec->core.afg ? codec->core.afg : codec->core.mfg;
2768 	int count;
2769 	unsigned int state;
2770 	int flags = 0;
2771 
2772 	/* this delay seems necessary to avoid click noise at power-down */
2773 	if (power_state == AC_PWRST_D3) {
2774 		if (codec->depop_delay < 0)
2775 			msleep(codec_has_epss(codec) ? 10 : 100);
2776 		else if (codec->depop_delay > 0)
2777 			msleep(codec->depop_delay);
2778 		flags = HDA_RW_NO_RESPONSE_FALLBACK;
2779 	}
2780 
2781 	/* repeat power states setting at most 10 times*/
2782 	for (count = 0; count < 10; count++) {
2783 		/* might be called before binding to driver, too */
2784 		if (driver && driver->ops && driver->ops->set_power_state)
2785 			driver->ops->set_power_state(codec, fg, power_state);
2786 		else {
2787 			state = power_state;
2788 			if (codec->power_filter)
2789 				state = codec->power_filter(codec, fg, state);
2790 			if (state == power_state || power_state != AC_PWRST_D3)
2791 				snd_hda_codec_write_sync(codec, fg, flags,
2792 							 AC_VERB_SET_POWER_STATE,
2793 							 state);
2794 			snd_hda_codec_set_power_to_all(codec, fg, power_state);
2795 		}
2796 		state = snd_hda_sync_power_state(codec, fg, power_state);
2797 		if (!(state & AC_PWRST_ERROR))
2798 			break;
2799 	}
2800 
2801 	return state;
2802 }
2803 
2804 /* sync power states of all widgets;
2805  * this is called at the end of codec parsing
2806  */
2807 static void sync_power_up_states(struct hda_codec *codec)
2808 {
2809 	hda_nid_t nid;
2810 
2811 	/* don't care if no filter is used */
2812 	if (!codec->power_filter)
2813 		return;
2814 
2815 	for_each_hda_codec_node(nid, codec) {
2816 		unsigned int wcaps = get_wcaps(codec, nid);
2817 		unsigned int target;
2818 		if (!(wcaps & AC_WCAP_POWER))
2819 			continue;
2820 		target = codec->power_filter(codec, nid, AC_PWRST_D0);
2821 		if (target == AC_PWRST_D0)
2822 			continue;
2823 		if (!snd_hda_check_power_state(codec, nid, target))
2824 			snd_hda_codec_write(codec, nid, 0,
2825 					    AC_VERB_SET_POWER_STATE, target);
2826 	}
2827 }
2828 
2829 #ifdef CONFIG_SND_HDA_RECONFIG
2830 /* execute additional init verbs */
2831 static void hda_exec_init_verbs(struct hda_codec *codec)
2832 {
2833 	if (codec->init_verbs.list)
2834 		snd_hda_sequence_write(codec, codec->init_verbs.list);
2835 }
2836 #else
2837 static inline void hda_exec_init_verbs(struct hda_codec *codec) {}
2838 #endif
2839 
2840 /* update the power on/off account with the current jiffies */
2841 static void update_power_acct(struct hda_codec *codec, bool on)
2842 {
2843 	unsigned long delta = jiffies - codec->power_jiffies;
2844 
2845 	if (on)
2846 		codec->power_on_acct += delta;
2847 	else
2848 		codec->power_off_acct += delta;
2849 	codec->power_jiffies += delta;
2850 }
2851 
2852 void snd_hda_update_power_acct(struct hda_codec *codec)
2853 {
2854 	update_power_acct(codec, hda_codec_is_power_on(codec));
2855 }
2856 
2857 /*
2858  * call suspend and power-down; used both from PM and power-save
2859  * this function returns the power state in the end
2860  */
2861 static unsigned int hda_call_codec_suspend(struct hda_codec *codec)
2862 {
2863 	struct hda_codec_driver *driver = hda_codec_to_driver(codec);
2864 	unsigned int state;
2865 
2866 	snd_hdac_enter_pm(&codec->core);
2867 	if (driver->ops->suspend)
2868 		driver->ops->suspend(codec);
2869 	if (!codec->no_stream_clean_at_suspend)
2870 		hda_cleanup_all_streams(codec);
2871 	state = hda_set_power_state(codec, AC_PWRST_D3);
2872 	update_power_acct(codec, true);
2873 	snd_hdac_leave_pm(&codec->core);
2874 	return state;
2875 }
2876 
2877 /*
2878  * kick up codec; used both from PM and power-save
2879  */
2880 static void hda_call_codec_resume(struct hda_codec *codec)
2881 {
2882 	struct hda_codec_driver *driver = hda_codec_to_driver(codec);
2883 
2884 	snd_hdac_enter_pm(&codec->core);
2885 	if (codec->core.regmap)
2886 		regcache_mark_dirty(codec->core.regmap);
2887 
2888 	codec->power_jiffies = jiffies;
2889 
2890 	hda_set_power_state(codec, AC_PWRST_D0);
2891 	restore_shutup_pins(codec);
2892 	hda_exec_init_verbs(codec);
2893 	snd_hda_jack_set_dirty_all(codec);
2894 	if (driver->ops->resume)
2895 		driver->ops->resume(codec);
2896 	else {
2897 		snd_hda_codec_init(codec);
2898 		snd_hda_regmap_sync(codec);
2899 	}
2900 
2901 	snd_hda_jack_report_sync(codec);
2902 	codec->core.dev.power.power_state = PMSG_ON;
2903 	snd_hdac_leave_pm(&codec->core);
2904 	if (codec->jackpoll_interval)
2905 		schedule_delayed_work(&codec->jackpoll_work,
2906 				      codec->jackpoll_interval);
2907 }
2908 
2909 static int hda_codec_runtime_suspend(struct device *dev)
2910 {
2911 	struct hda_codec *codec = dev_to_hda_codec(dev);
2912 	unsigned int state;
2913 
2914 	/* Nothing to do if card registration fails and the component driver never probes */
2915 	if (!codec->card)
2916 		return 0;
2917 
2918 	state = hda_call_codec_suspend(codec);
2919 	if (codec->link_down_at_suspend ||
2920 	    (codec_has_clkstop(codec) && codec_has_epss(codec) &&
2921 	     (state & AC_PWRST_CLK_STOP_OK)))
2922 		snd_hdac_codec_link_down(&codec->core);
2923 	snd_hda_codec_display_power(codec, false);
2924 
2925 	return 0;
2926 }
2927 
2928 static int hda_codec_runtime_resume(struct device *dev)
2929 {
2930 	struct hda_codec *codec = dev_to_hda_codec(dev);
2931 
2932 	/* Nothing to do if card registration fails and the component driver never probes */
2933 	if (!codec->card)
2934 		return 0;
2935 
2936 	snd_hda_codec_display_power(codec, true);
2937 	snd_hdac_codec_link_up(&codec->core);
2938 	hda_call_codec_resume(codec);
2939 	pm_runtime_mark_last_busy(dev);
2940 	return 0;
2941 }
2942 
2943 static int hda_codec_runtime_idle(struct device *dev)
2944 {
2945 	struct hda_codec *codec = dev_to_hda_codec(dev);
2946 
2947 	if (codec->jackpoll_interval && !codec->bus->jackpoll_in_suspend)
2948 		return -EBUSY;
2949 	return 0;
2950 }
2951 
2952 static int hda_codec_pm_prepare(struct device *dev)
2953 {
2954 	struct hda_codec *codec = dev_to_hda_codec(dev);
2955 
2956 	cancel_delayed_work_sync(&codec->jackpoll_work);
2957 	dev->power.power_state = PMSG_SUSPEND;
2958 	return pm_runtime_suspended(dev);
2959 }
2960 
2961 static void hda_codec_pm_complete(struct device *dev)
2962 {
2963 	struct hda_codec *codec = dev_to_hda_codec(dev);
2964 
2965 	/* If no other pm-functions are called between prepare() and complete() */
2966 	if (dev->power.power_state.event == PM_EVENT_SUSPEND)
2967 		dev->power.power_state = PMSG_RESUME;
2968 
2969 	if (pm_runtime_suspended(dev) && (codec->jackpoll_interval ||
2970 	    hda_codec_need_resume(codec) || codec->forced_resume))
2971 		pm_request_resume(dev);
2972 }
2973 
2974 static int hda_codec_pm_suspend(struct device *dev)
2975 {
2976 	dev->power.power_state = PMSG_SUSPEND;
2977 	return pm_runtime_force_suspend(dev);
2978 }
2979 
2980 static int hda_codec_pm_resume(struct device *dev)
2981 {
2982 	dev->power.power_state = PMSG_RESUME;
2983 	return pm_runtime_force_resume(dev);
2984 }
2985 
2986 static int hda_codec_pm_freeze(struct device *dev)
2987 {
2988 	struct hda_codec *codec = dev_to_hda_codec(dev);
2989 
2990 	cancel_delayed_work_sync(&codec->jackpoll_work);
2991 	dev->power.power_state = PMSG_FREEZE;
2992 	return pm_runtime_force_suspend(dev);
2993 }
2994 
2995 static int hda_codec_pm_thaw(struct device *dev)
2996 {
2997 	dev->power.power_state = PMSG_THAW;
2998 	return pm_runtime_force_resume(dev);
2999 }
3000 
3001 static int hda_codec_pm_restore(struct device *dev)
3002 {
3003 	dev->power.power_state = PMSG_RESTORE;
3004 	return pm_runtime_force_resume(dev);
3005 }
3006 
3007 /* referred in hda_bind.c */
3008 const struct dev_pm_ops hda_codec_driver_pm = {
3009 	.prepare = pm_sleep_ptr(hda_codec_pm_prepare),
3010 	.complete = pm_sleep_ptr(hda_codec_pm_complete),
3011 	.suspend = pm_sleep_ptr(hda_codec_pm_suspend),
3012 	.resume = pm_sleep_ptr(hda_codec_pm_resume),
3013 	.freeze = pm_sleep_ptr(hda_codec_pm_freeze),
3014 	.thaw = pm_sleep_ptr(hda_codec_pm_thaw),
3015 	.poweroff = pm_sleep_ptr(hda_codec_pm_suspend),
3016 	.restore = pm_sleep_ptr(hda_codec_pm_restore),
3017 	RUNTIME_PM_OPS(hda_codec_runtime_suspend, hda_codec_runtime_resume,
3018 		       hda_codec_runtime_idle)
3019 };
3020 
3021 /* suspend the codec at shutdown; called from driver's shutdown callback */
3022 void snd_hda_codec_shutdown(struct hda_codec *codec)
3023 {
3024 	struct hda_pcm *cpcm;
3025 
3026 	/* Skip the shutdown if codec is not registered */
3027 	if (!codec->core.registered)
3028 		return;
3029 
3030 	codec->jackpoll_interval = 0; /* don't poll any longer */
3031 	cancel_delayed_work_sync(&codec->jackpoll_work);
3032 	list_for_each_entry(cpcm, &codec->pcm_list_head, list)
3033 		snd_pcm_suspend_all(cpcm->pcm);
3034 
3035 	pm_runtime_force_suspend(hda_codec_dev(codec));
3036 	pm_runtime_disable(hda_codec_dev(codec));
3037 }
3038 
3039 /*
3040  * add standard channel maps if not specified
3041  */
3042 static int add_std_chmaps(struct hda_codec *codec)
3043 {
3044 	struct hda_pcm *pcm;
3045 	int str, err;
3046 
3047 	list_for_each_entry(pcm, &codec->pcm_list_head, list) {
3048 		for (str = 0; str < 2; str++) {
3049 			struct hda_pcm_stream *hinfo = &pcm->stream[str];
3050 			struct snd_pcm_chmap *chmap;
3051 			const struct snd_pcm_chmap_elem *elem;
3052 
3053 			if (!pcm->pcm || pcm->own_chmap || !hinfo->substreams)
3054 				continue;
3055 			elem = hinfo->chmap ? hinfo->chmap : snd_pcm_std_chmaps;
3056 			err = snd_pcm_add_chmap_ctls(pcm->pcm, str, elem,
3057 						     hinfo->channels_max,
3058 						     0, &chmap);
3059 			if (err < 0)
3060 				return err;
3061 			chmap->channel_mask = SND_PCM_CHMAP_MASK_2468;
3062 		}
3063 	}
3064 	return 0;
3065 }
3066 
3067 /* default channel maps for 2.1 speakers;
3068  * since HD-audio supports only stereo, odd number channels are omitted
3069  */
3070 const struct snd_pcm_chmap_elem snd_pcm_2_1_chmaps[] = {
3071 	{ .channels = 2,
3072 	  .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR } },
3073 	{ .channels = 4,
3074 	  .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR,
3075 		   SNDRV_CHMAP_LFE, SNDRV_CHMAP_LFE } },
3076 	{ }
3077 };
3078 EXPORT_SYMBOL_GPL(snd_pcm_2_1_chmaps);
3079 
3080 int snd_hda_codec_build_controls(struct hda_codec *codec)
3081 {
3082 	struct hda_codec_driver *driver = hda_codec_to_driver(codec);
3083 	int err;
3084 
3085 	hda_exec_init_verbs(codec);
3086 	/* continue to initialize... */
3087 	err = snd_hda_codec_init(codec);
3088 	if (err < 0)
3089 		return err;
3090 
3091 	if (driver->ops->build_controls) {
3092 		err = driver->ops->build_controls(codec);
3093 		if (err < 0)
3094 			return err;
3095 	}
3096 
3097 	/* we create chmaps here instead of build_pcms */
3098 	err = add_std_chmaps(codec);
3099 	if (err < 0)
3100 		return err;
3101 
3102 	snd_hda_jack_report_sync(codec); /* call at the last init point */
3103 	if (codec->jackpoll_interval)
3104 		schedule_delayed_work(&codec->jackpoll_work,
3105 				      codec->jackpoll_interval);
3106 
3107 	sync_power_up_states(codec);
3108 	return 0;
3109 }
3110 EXPORT_SYMBOL_GPL(snd_hda_codec_build_controls);
3111 
3112 /*
3113  * PCM stuff
3114  */
3115 static int hda_pcm_default_open_close(struct hda_pcm_stream *hinfo,
3116 				      struct hda_codec *codec,
3117 				      struct snd_pcm_substream *substream)
3118 {
3119 	return 0;
3120 }
3121 
3122 static int hda_pcm_default_prepare(struct hda_pcm_stream *hinfo,
3123 				   struct hda_codec *codec,
3124 				   unsigned int stream_tag,
3125 				   unsigned int format,
3126 				   struct snd_pcm_substream *substream)
3127 {
3128 	snd_hda_codec_setup_stream(codec, hinfo->nid, stream_tag, 0, format);
3129 	return 0;
3130 }
3131 
3132 static int hda_pcm_default_cleanup(struct hda_pcm_stream *hinfo,
3133 				   struct hda_codec *codec,
3134 				   struct snd_pcm_substream *substream)
3135 {
3136 	snd_hda_codec_cleanup_stream(codec, hinfo->nid);
3137 	return 0;
3138 }
3139 
3140 static int set_pcm_default_values(struct hda_codec *codec,
3141 				  struct hda_pcm_stream *info)
3142 {
3143 	int err;
3144 
3145 	/* query support PCM information from the given NID */
3146 	if (info->nid && (!info->rates || !info->formats)) {
3147 		err = snd_hda_query_supported_pcm(codec, info->nid,
3148 				info->rates ? NULL : &info->rates,
3149 				info->formats ? NULL : &info->formats,
3150 				info->subformats ? NULL : &info->subformats,
3151 				info->maxbps ? NULL : &info->maxbps);
3152 		if (err < 0)
3153 			return err;
3154 	}
3155 	if (info->ops.open == NULL)
3156 		info->ops.open = hda_pcm_default_open_close;
3157 	if (info->ops.close == NULL)
3158 		info->ops.close = hda_pcm_default_open_close;
3159 	if (info->ops.prepare == NULL) {
3160 		if (snd_BUG_ON(!info->nid))
3161 			return -EINVAL;
3162 		info->ops.prepare = hda_pcm_default_prepare;
3163 	}
3164 	if (info->ops.cleanup == NULL) {
3165 		if (snd_BUG_ON(!info->nid))
3166 			return -EINVAL;
3167 		info->ops.cleanup = hda_pcm_default_cleanup;
3168 	}
3169 	return 0;
3170 }
3171 
3172 /*
3173  * codec prepare/cleanup entries
3174  */
3175 /**
3176  * snd_hda_codec_prepare - Prepare a stream
3177  * @codec: the HDA codec
3178  * @hinfo: PCM information
3179  * @stream: stream tag to assign
3180  * @format: format id to assign
3181  * @substream: PCM substream to assign
3182  *
3183  * Calls the prepare callback set by the codec with the given arguments.
3184  * Clean up the inactive streams when successful.
3185  */
3186 int snd_hda_codec_prepare(struct hda_codec *codec,
3187 			  struct hda_pcm_stream *hinfo,
3188 			  unsigned int stream,
3189 			  unsigned int format,
3190 			  struct snd_pcm_substream *substream)
3191 {
3192 	int ret;
3193 
3194 	guard(mutex)(&codec->bus->prepare_mutex);
3195 	if (hinfo->ops.prepare)
3196 		ret = hinfo->ops.prepare(hinfo, codec, stream, format,
3197 					 substream);
3198 	else
3199 		ret = -ENODEV;
3200 	if (ret >= 0)
3201 		purify_inactive_streams(codec);
3202 	return ret;
3203 }
3204 EXPORT_SYMBOL_GPL(snd_hda_codec_prepare);
3205 
3206 /**
3207  * snd_hda_codec_cleanup - Clean up stream resources
3208  * @codec: the HDA codec
3209  * @hinfo: PCM information
3210  * @substream: PCM substream
3211  *
3212  * Calls the cleanup callback set by the codec with the given arguments.
3213  */
3214 void snd_hda_codec_cleanup(struct hda_codec *codec,
3215 			   struct hda_pcm_stream *hinfo,
3216 			   struct snd_pcm_substream *substream)
3217 {
3218 	guard(mutex)(&codec->bus->prepare_mutex);
3219 	if (hinfo->ops.cleanup)
3220 		hinfo->ops.cleanup(hinfo, codec, substream);
3221 }
3222 EXPORT_SYMBOL_GPL(snd_hda_codec_cleanup);
3223 
3224 /* global */
3225 const char *snd_hda_pcm_type_name[HDA_PCM_NTYPES] = {
3226 	"Audio", "SPDIF", "HDMI", "Modem"
3227 };
3228 
3229 /*
3230  * get the empty PCM device number to assign
3231  */
3232 static int get_empty_pcm_device(struct hda_bus *bus, unsigned int type)
3233 {
3234 	/* audio device indices; not linear to keep compatibility */
3235 	/* assigned to static slots up to dev#10; if more needed, assign
3236 	 * the later slot dynamically (when CONFIG_SND_DYNAMIC_MINORS=y)
3237 	 */
3238 	static const int audio_idx[HDA_PCM_NTYPES][5] = {
3239 		[HDA_PCM_TYPE_AUDIO] = { 0, 2, 4, 5, -1 },
3240 		[HDA_PCM_TYPE_SPDIF] = { 1, -1 },
3241 		[HDA_PCM_TYPE_HDMI]  = { 3, 7, 8, 9, -1 },
3242 		[HDA_PCM_TYPE_MODEM] = { 6, -1 },
3243 	};
3244 	int i;
3245 
3246 	if (type >= HDA_PCM_NTYPES) {
3247 		dev_err(bus->card->dev, "Invalid PCM type %d\n", type);
3248 		return -EINVAL;
3249 	}
3250 
3251 	for (i = 0; audio_idx[type][i] >= 0; i++) {
3252 #ifndef CONFIG_SND_DYNAMIC_MINORS
3253 		if (audio_idx[type][i] >= 8)
3254 			break;
3255 #endif
3256 		if (!test_and_set_bit(audio_idx[type][i], bus->pcm_dev_bits))
3257 			return audio_idx[type][i];
3258 	}
3259 
3260 #ifdef CONFIG_SND_DYNAMIC_MINORS
3261 	/* non-fixed slots starting from 10 */
3262 	for (i = 10; i < 32; i++) {
3263 		if (!test_and_set_bit(i, bus->pcm_dev_bits))
3264 			return i;
3265 	}
3266 #endif
3267 
3268 	dev_warn(bus->card->dev, "Too many %s devices\n",
3269 		snd_hda_pcm_type_name[type]);
3270 #ifndef CONFIG_SND_DYNAMIC_MINORS
3271 	dev_warn(bus->card->dev,
3272 		 "Consider building the kernel with CONFIG_SND_DYNAMIC_MINORS=y\n");
3273 #endif
3274 	return -EAGAIN;
3275 }
3276 
3277 /* call build_pcms ops of the given codec and set up the default parameters */
3278 int snd_hda_codec_parse_pcms(struct hda_codec *codec)
3279 {
3280 	struct hda_codec_driver *driver = hda_codec_to_driver(codec);
3281 	struct hda_pcm *cpcm;
3282 	int err;
3283 
3284 	if (!list_empty(&codec->pcm_list_head))
3285 		return 0; /* already parsed */
3286 
3287 	if (!driver->ops->build_pcms)
3288 		return 0;
3289 
3290 	err = driver->ops->build_pcms(codec);
3291 	if (err < 0) {
3292 		codec_err(codec, "cannot build PCMs for #%d (error %d)\n",
3293 			  codec->core.addr, err);
3294 		return err;
3295 	}
3296 
3297 	list_for_each_entry(cpcm, &codec->pcm_list_head, list) {
3298 		int stream;
3299 
3300 		for_each_pcm_streams(stream) {
3301 			struct hda_pcm_stream *info = &cpcm->stream[stream];
3302 
3303 			if (!info->substreams)
3304 				continue;
3305 			err = set_pcm_default_values(codec, info);
3306 			if (err < 0) {
3307 				codec_warn(codec,
3308 					   "fail to setup default for PCM %s\n",
3309 					   cpcm->name);
3310 				return err;
3311 			}
3312 		}
3313 	}
3314 
3315 	return 0;
3316 }
3317 EXPORT_SYMBOL_GPL(snd_hda_codec_parse_pcms);
3318 
3319 /* assign all PCMs of the given codec */
3320 int snd_hda_codec_build_pcms(struct hda_codec *codec)
3321 {
3322 	struct hda_bus *bus = codec->bus;
3323 	struct hda_pcm *cpcm;
3324 	int dev, err;
3325 
3326 	err = snd_hda_codec_parse_pcms(codec);
3327 	if (err < 0)
3328 		return err;
3329 
3330 	/* attach a new PCM streams */
3331 	list_for_each_entry(cpcm, &codec->pcm_list_head, list) {
3332 		if (cpcm->pcm)
3333 			continue; /* already attached */
3334 		if (!cpcm->stream[0].substreams && !cpcm->stream[1].substreams)
3335 			continue; /* no substreams assigned */
3336 
3337 		dev = get_empty_pcm_device(bus, cpcm->pcm_type);
3338 		if (dev < 0) {
3339 			cpcm->device = SNDRV_PCM_INVALID_DEVICE;
3340 			continue; /* no fatal error */
3341 		}
3342 		cpcm->device = dev;
3343 		err =  snd_hda_attach_pcm_stream(bus, codec, cpcm);
3344 		if (err < 0) {
3345 			codec_err(codec,
3346 				  "cannot attach PCM stream %d for codec #%d\n",
3347 				  dev, codec->core.addr);
3348 			continue; /* no fatal error */
3349 		}
3350 	}
3351 
3352 	return 0;
3353 }
3354 
3355 /**
3356  * snd_hda_add_new_ctls - create controls from the array
3357  * @codec: the HDA codec
3358  * @knew: the array of struct snd_kcontrol_new
3359  *
3360  * This helper function creates and add new controls in the given array.
3361  * The array must be terminated with an empty entry as terminator.
3362  *
3363  * Returns 0 if successful, or a negative error code.
3364  */
3365 int snd_hda_add_new_ctls(struct hda_codec *codec,
3366 			 const struct snd_kcontrol_new *knew)
3367 {
3368 	int err;
3369 
3370 	for (; knew->name; knew++) {
3371 		struct snd_kcontrol *kctl;
3372 		int addr = 0, idx = 0;
3373 		if (knew->iface == (__force snd_ctl_elem_iface_t)-1)
3374 			continue; /* skip this codec private value */
3375 		for (;;) {
3376 			kctl = snd_ctl_new1(knew, codec);
3377 			if (!kctl)
3378 				return -ENOMEM;
3379 			/* Do not use the id.device field for MIXER elements.
3380 			 * This field is for real device numbers (like PCM) but codecs
3381 			 * are hidden components from the user space view (unrelated
3382 			 * to the mixer element identification).
3383 			 */
3384 			if (addr > 0 && codec->ctl_dev_id)
3385 				kctl->id.device = addr;
3386 			if (idx > 0)
3387 				kctl->id.index = idx;
3388 			err = snd_hda_ctl_add(codec, 0, kctl);
3389 			if (!err)
3390 				break;
3391 			/* try first with another device index corresponding to
3392 			 * the codec addr; if it still fails (or it's the
3393 			 * primary codec), then try another control index
3394 			 */
3395 			if (!addr && codec->core.addr) {
3396 				addr = codec->core.addr;
3397 				if (!codec->ctl_dev_id)
3398 					idx += 10 * addr;
3399 			} else if (!idx && !knew->index) {
3400 				idx = find_empty_mixer_ctl_idx(codec,
3401 							       knew->name, 0);
3402 				if (idx <= 0)
3403 					return err;
3404 			} else
3405 				return err;
3406 		}
3407 	}
3408 	return 0;
3409 }
3410 EXPORT_SYMBOL_GPL(snd_hda_add_new_ctls);
3411 
3412 /**
3413  * snd_hda_codec_set_power_save - Configure codec's runtime PM
3414  * @codec: codec device to configure
3415  * @delay: autosuspend delay
3416  */
3417 void snd_hda_codec_set_power_save(struct hda_codec *codec, int delay)
3418 {
3419 	struct device *dev = hda_codec_dev(codec);
3420 
3421 	if (delay == 0 && codec->auto_runtime_pm)
3422 		delay = 3000;
3423 
3424 	if (delay > 0) {
3425 		pm_runtime_set_autosuspend_delay(dev, delay);
3426 		pm_runtime_use_autosuspend(dev);
3427 		pm_runtime_allow(dev);
3428 		if (!pm_runtime_suspended(dev))
3429 			pm_runtime_mark_last_busy(dev);
3430 	} else {
3431 		pm_runtime_dont_use_autosuspend(dev);
3432 		pm_runtime_forbid(dev);
3433 	}
3434 }
3435 EXPORT_SYMBOL_GPL(snd_hda_codec_set_power_save);
3436 
3437 /**
3438  * snd_hda_set_power_save - reprogram autosuspend for the given delay
3439  * @bus: HD-audio bus
3440  * @delay: autosuspend delay in msec, 0 = off
3441  *
3442  * Synchronize the runtime PM autosuspend state from the power_save option.
3443  */
3444 void snd_hda_set_power_save(struct hda_bus *bus, int delay)
3445 {
3446 	struct hda_codec *c;
3447 
3448 	list_for_each_codec(c, bus)
3449 		snd_hda_codec_set_power_save(c, delay);
3450 }
3451 EXPORT_SYMBOL_GPL(snd_hda_set_power_save);
3452 
3453 /**
3454  * snd_hda_check_amp_list_power - Check the amp list and update the power
3455  * @codec: HD-audio codec
3456  * @check: the object containing an AMP list and the status
3457  * @nid: NID to check / update
3458  *
3459  * Check whether the given NID is in the amp list.  If it's in the list,
3460  * check the current AMP status, and update the power-status according
3461  * to the mute status.
3462  *
3463  * This function is supposed to be set or called from the check_power_status
3464  * patch ops.
3465  */
3466 int snd_hda_check_amp_list_power(struct hda_codec *codec,
3467 				 struct hda_loopback_check *check,
3468 				 hda_nid_t nid)
3469 {
3470 	const struct hda_amp_list *p;
3471 	int ch, v;
3472 
3473 	if (!check->amplist)
3474 		return 0;
3475 	for (p = check->amplist; p->nid; p++) {
3476 		if (p->nid == nid)
3477 			break;
3478 	}
3479 	if (!p->nid)
3480 		return 0; /* nothing changed */
3481 
3482 	for (p = check->amplist; p->nid; p++) {
3483 		for (ch = 0; ch < 2; ch++) {
3484 			v = snd_hda_codec_amp_read(codec, p->nid, ch, p->dir,
3485 						   p->idx);
3486 			if (!(v & HDA_AMP_MUTE) && v > 0) {
3487 				if (!check->power_on) {
3488 					check->power_on = 1;
3489 					snd_hda_power_up_pm(codec);
3490 				}
3491 				return 1;
3492 			}
3493 		}
3494 	}
3495 	if (check->power_on) {
3496 		check->power_on = 0;
3497 		snd_hda_power_down_pm(codec);
3498 	}
3499 	return 0;
3500 }
3501 EXPORT_SYMBOL_GPL(snd_hda_check_amp_list_power);
3502 
3503 /*
3504  * input MUX helper
3505  */
3506 
3507 /**
3508  * snd_hda_input_mux_info - Info callback helper for the input-mux enum
3509  * @imux: imux helper object
3510  * @uinfo: pointer to get/store the data
3511  */
3512 int snd_hda_input_mux_info(const struct hda_input_mux *imux,
3513 			   struct snd_ctl_elem_info *uinfo)
3514 {
3515 	unsigned int index;
3516 
3517 	uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
3518 	uinfo->count = 1;
3519 	uinfo->value.enumerated.items = imux->num_items;
3520 	if (!imux->num_items)
3521 		return 0;
3522 	index = uinfo->value.enumerated.item;
3523 	if (index >= imux->num_items)
3524 		index = imux->num_items - 1;
3525 	strscpy(uinfo->value.enumerated.name, imux->items[index].label);
3526 	return 0;
3527 }
3528 EXPORT_SYMBOL_GPL(snd_hda_input_mux_info);
3529 
3530 /**
3531  * snd_hda_input_mux_put - Put callback helper for the input-mux enum
3532  * @codec: the HDA codec
3533  * @imux: imux helper object
3534  * @ucontrol: pointer to get/store the data
3535  * @nid: input mux NID
3536  * @cur_val: pointer to get/store the current imux value
3537  */
3538 int snd_hda_input_mux_put(struct hda_codec *codec,
3539 			  const struct hda_input_mux *imux,
3540 			  struct snd_ctl_elem_value *ucontrol,
3541 			  hda_nid_t nid,
3542 			  unsigned int *cur_val)
3543 {
3544 	unsigned int idx;
3545 
3546 	if (!imux->num_items)
3547 		return 0;
3548 	idx = ucontrol->value.enumerated.item[0];
3549 	if (idx >= imux->num_items)
3550 		idx = imux->num_items - 1;
3551 	if (*cur_val == idx)
3552 		return 0;
3553 	snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_CONNECT_SEL,
3554 				  imux->items[idx].index);
3555 	*cur_val = idx;
3556 	return 1;
3557 }
3558 EXPORT_SYMBOL_GPL(snd_hda_input_mux_put);
3559 
3560 
3561 /**
3562  * snd_hda_enum_helper_info - Helper for simple enum ctls
3563  * @kcontrol: ctl element
3564  * @uinfo: pointer to get/store the data
3565  * @num_items: number of enum items
3566  * @texts: enum item string array
3567  *
3568  * process kcontrol info callback of a simple string enum array
3569  * when @num_items is 0 or @texts is NULL, assume a boolean enum array
3570  */
3571 int snd_hda_enum_helper_info(struct snd_kcontrol *kcontrol,
3572 			     struct snd_ctl_elem_info *uinfo,
3573 			     int num_items, const char * const *texts)
3574 {
3575 	static const char * const texts_default[] = {
3576 		"Disabled", "Enabled"
3577 	};
3578 
3579 	if (!texts || !num_items) {
3580 		num_items = 2;
3581 		texts = texts_default;
3582 	}
3583 
3584 	return snd_ctl_enum_info(uinfo, 1, num_items, texts);
3585 }
3586 EXPORT_SYMBOL_GPL(snd_hda_enum_helper_info);
3587 
3588 /*
3589  * Multi-channel / digital-out PCM helper functions
3590  */
3591 
3592 /* setup SPDIF output stream */
3593 static void setup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid,
3594 				 unsigned int stream_tag, unsigned int format)
3595 {
3596 	struct hda_spdif_out *spdif;
3597 	unsigned int curr_fmt;
3598 	bool reset;
3599 
3600 	spdif = snd_hda_spdif_out_of_nid(codec, nid);
3601 	/* Add sanity check to pass klockwork check.
3602 	 * This should never happen.
3603 	 */
3604 	if (WARN_ON(spdif == NULL))
3605 		return;
3606 
3607 	curr_fmt = snd_hda_codec_read(codec, nid, 0,
3608 				      AC_VERB_GET_STREAM_FORMAT, 0);
3609 	reset = codec->spdif_status_reset &&
3610 		(spdif->ctls & AC_DIG1_ENABLE) &&
3611 		curr_fmt != format;
3612 
3613 	/* turn off SPDIF if needed; otherwise the IEC958 bits won't be
3614 	   updated */
3615 	if (reset)
3616 		set_dig_out_convert(codec, nid,
3617 				    spdif->ctls & ~AC_DIG1_ENABLE & 0xff,
3618 				    -1);
3619 	snd_hda_codec_setup_stream(codec, nid, stream_tag, 0, format);
3620 	if (codec->follower_dig_outs) {
3621 		const hda_nid_t *d;
3622 		for (d = codec->follower_dig_outs; *d; d++)
3623 			snd_hda_codec_setup_stream(codec, *d, stream_tag, 0,
3624 						   format);
3625 	}
3626 	/* turn on again (if needed) */
3627 	if (reset)
3628 		set_dig_out_convert(codec, nid,
3629 				    spdif->ctls & 0xff, -1);
3630 }
3631 
3632 static void cleanup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid)
3633 {
3634 	snd_hda_codec_cleanup_stream(codec, nid);
3635 	if (codec->follower_dig_outs) {
3636 		const hda_nid_t *d;
3637 		for (d = codec->follower_dig_outs; *d; d++)
3638 			snd_hda_codec_cleanup_stream(codec, *d);
3639 	}
3640 }
3641 
3642 /**
3643  * snd_hda_multi_out_dig_open - open the digital out in the exclusive mode
3644  * @codec: the HDA codec
3645  * @mout: hda_multi_out object
3646  */
3647 int snd_hda_multi_out_dig_open(struct hda_codec *codec,
3648 			       struct hda_multi_out *mout)
3649 {
3650 	guard(mutex)(&codec->spdif_mutex);
3651 	if (mout->dig_out_used == HDA_DIG_ANALOG_DUP)
3652 		/* already opened as analog dup; reset it once */
3653 		cleanup_dig_out_stream(codec, mout->dig_out_nid);
3654 	mout->dig_out_used = HDA_DIG_EXCLUSIVE;
3655 	return 0;
3656 }
3657 EXPORT_SYMBOL_GPL(snd_hda_multi_out_dig_open);
3658 
3659 /**
3660  * snd_hda_multi_out_dig_prepare - prepare the digital out stream
3661  * @codec: the HDA codec
3662  * @mout: hda_multi_out object
3663  * @stream_tag: stream tag to assign
3664  * @format: format id to assign
3665  * @substream: PCM substream to assign
3666  */
3667 int snd_hda_multi_out_dig_prepare(struct hda_codec *codec,
3668 				  struct hda_multi_out *mout,
3669 				  unsigned int stream_tag,
3670 				  unsigned int format,
3671 				  struct snd_pcm_substream *substream)
3672 {
3673 	guard(mutex)(&codec->spdif_mutex);
3674 	setup_dig_out_stream(codec, mout->dig_out_nid, stream_tag, format);
3675 	return 0;
3676 }
3677 EXPORT_SYMBOL_GPL(snd_hda_multi_out_dig_prepare);
3678 
3679 /**
3680  * snd_hda_multi_out_dig_cleanup - clean-up the digital out stream
3681  * @codec: the HDA codec
3682  * @mout: hda_multi_out object
3683  */
3684 int snd_hda_multi_out_dig_cleanup(struct hda_codec *codec,
3685 				  struct hda_multi_out *mout)
3686 {
3687 	guard(mutex)(&codec->spdif_mutex);
3688 	cleanup_dig_out_stream(codec, mout->dig_out_nid);
3689 	return 0;
3690 }
3691 EXPORT_SYMBOL_GPL(snd_hda_multi_out_dig_cleanup);
3692 
3693 /**
3694  * snd_hda_multi_out_dig_close - release the digital out stream
3695  * @codec: the HDA codec
3696  * @mout: hda_multi_out object
3697  */
3698 int snd_hda_multi_out_dig_close(struct hda_codec *codec,
3699 				struct hda_multi_out *mout)
3700 {
3701 	guard(mutex)(&codec->spdif_mutex);
3702 	mout->dig_out_used = 0;
3703 	return 0;
3704 }
3705 EXPORT_SYMBOL_GPL(snd_hda_multi_out_dig_close);
3706 
3707 /**
3708  * snd_hda_multi_out_analog_open - open analog outputs
3709  * @codec: the HDA codec
3710  * @mout: hda_multi_out object
3711  * @substream: PCM substream to assign
3712  * @hinfo: PCM information to assign
3713  *
3714  * Open analog outputs and set up the hw-constraints.
3715  * If the digital outputs can be opened as follower, open the digital
3716  * outputs, too.
3717  */
3718 int snd_hda_multi_out_analog_open(struct hda_codec *codec,
3719 				  struct hda_multi_out *mout,
3720 				  struct snd_pcm_substream *substream,
3721 				  struct hda_pcm_stream *hinfo)
3722 {
3723 	struct snd_pcm_runtime *runtime = substream->runtime;
3724 	bool notify_share_sw = false;
3725 
3726 	runtime->hw.channels_max = mout->max_channels;
3727 	if (mout->dig_out_nid) {
3728 		if (!mout->analog_rates) {
3729 			mout->analog_rates = hinfo->rates;
3730 			mout->analog_formats = hinfo->formats;
3731 			mout->analog_maxbps = hinfo->maxbps;
3732 		} else {
3733 			runtime->hw.rates = mout->analog_rates;
3734 			runtime->hw.formats = mout->analog_formats;
3735 			hinfo->maxbps = mout->analog_maxbps;
3736 		}
3737 		if (!mout->spdif_rates) {
3738 			snd_hda_query_supported_pcm(codec, mout->dig_out_nid,
3739 						    &mout->spdif_rates,
3740 						    &mout->spdif_formats,
3741 						    NULL,
3742 						    &mout->spdif_maxbps);
3743 		}
3744 		guard(mutex)(&codec->spdif_mutex);
3745 		if (mout->share_spdif) {
3746 			if ((runtime->hw.rates & mout->spdif_rates) &&
3747 			    (runtime->hw.formats & mout->spdif_formats)) {
3748 				runtime->hw.rates &= mout->spdif_rates;
3749 				runtime->hw.formats &= mout->spdif_formats;
3750 				if (mout->spdif_maxbps < hinfo->maxbps)
3751 					hinfo->maxbps = mout->spdif_maxbps;
3752 			} else {
3753 				mout->share_spdif = 0;
3754 				notify_share_sw = true;
3755 			}
3756 		}
3757 	}
3758 	if (notify_share_sw)
3759 		notify_spdif_share_sw(codec, mout);
3760 	return snd_pcm_hw_constraint_step(substream->runtime, 0,
3761 					  SNDRV_PCM_HW_PARAM_CHANNELS, 2);
3762 }
3763 EXPORT_SYMBOL_GPL(snd_hda_multi_out_analog_open);
3764 
3765 /**
3766  * snd_hda_multi_out_analog_prepare - Preapre the analog outputs.
3767  * @codec: the HDA codec
3768  * @mout: hda_multi_out object
3769  * @stream_tag: stream tag to assign
3770  * @format: format id to assign
3771  * @substream: PCM substream to assign
3772  *
3773  * Set up the i/o for analog out.
3774  * When the digital out is available, copy the front out to digital out, too.
3775  */
3776 int snd_hda_multi_out_analog_prepare(struct hda_codec *codec,
3777 				     struct hda_multi_out *mout,
3778 				     unsigned int stream_tag,
3779 				     unsigned int format,
3780 				     struct snd_pcm_substream *substream)
3781 {
3782 	const hda_nid_t *nids = mout->dac_nids;
3783 	int chs = substream->runtime->channels;
3784 	struct hda_spdif_out *spdif;
3785 	int i;
3786 
3787 	scoped_guard(mutex, &codec->spdif_mutex) {
3788 		spdif = snd_hda_spdif_out_of_nid(codec, mout->dig_out_nid);
3789 		if (mout->dig_out_nid && mout->share_spdif &&
3790 		    mout->dig_out_used != HDA_DIG_EXCLUSIVE) {
3791 			if (chs == 2 && spdif != NULL &&
3792 			    snd_hda_is_supported_format(codec, mout->dig_out_nid,
3793 							format) &&
3794 			    !(spdif->status & IEC958_AES0_NONAUDIO)) {
3795 				mout->dig_out_used = HDA_DIG_ANALOG_DUP;
3796 				setup_dig_out_stream(codec, mout->dig_out_nid,
3797 						     stream_tag, format);
3798 			} else {
3799 				mout->dig_out_used = 0;
3800 				cleanup_dig_out_stream(codec, mout->dig_out_nid);
3801 			}
3802 		}
3803 	}
3804 
3805 	/* front */
3806 	snd_hda_codec_setup_stream(codec, nids[HDA_FRONT], stream_tag,
3807 				   0, format);
3808 	if (!mout->no_share_stream &&
3809 	    mout->hp_nid && mout->hp_nid != nids[HDA_FRONT])
3810 		/* headphone out will just decode front left/right (stereo) */
3811 		snd_hda_codec_setup_stream(codec, mout->hp_nid, stream_tag,
3812 					   0, format);
3813 	/* extra outputs copied from front */
3814 	for (i = 0; i < ARRAY_SIZE(mout->hp_out_nid); i++)
3815 		if (!mout->no_share_stream && mout->hp_out_nid[i])
3816 			snd_hda_codec_setup_stream(codec,
3817 						   mout->hp_out_nid[i],
3818 						   stream_tag, 0, format);
3819 
3820 	/* surrounds */
3821 	for (i = 1; i < mout->num_dacs; i++) {
3822 		if (chs >= (i + 1) * 2) /* independent out */
3823 			snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
3824 						   i * 2, format);
3825 		else if (!mout->no_share_stream) /* copy front */
3826 			snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
3827 						   0, format);
3828 	}
3829 
3830 	/* extra surrounds */
3831 	for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++) {
3832 		int ch = 0;
3833 		if (!mout->extra_out_nid[i])
3834 			break;
3835 		if (chs >= (i + 1) * 2)
3836 			ch = i * 2;
3837 		else if (!mout->no_share_stream)
3838 			break;
3839 		snd_hda_codec_setup_stream(codec, mout->extra_out_nid[i],
3840 					   stream_tag, ch, format);
3841 	}
3842 
3843 	return 0;
3844 }
3845 EXPORT_SYMBOL_GPL(snd_hda_multi_out_analog_prepare);
3846 
3847 /**
3848  * snd_hda_multi_out_analog_cleanup - clean up the setting for analog out
3849  * @codec: the HDA codec
3850  * @mout: hda_multi_out object
3851  */
3852 int snd_hda_multi_out_analog_cleanup(struct hda_codec *codec,
3853 				     struct hda_multi_out *mout)
3854 {
3855 	const hda_nid_t *nids = mout->dac_nids;
3856 	int i;
3857 
3858 	for (i = 0; i < mout->num_dacs; i++)
3859 		snd_hda_codec_cleanup_stream(codec, nids[i]);
3860 	if (mout->hp_nid)
3861 		snd_hda_codec_cleanup_stream(codec, mout->hp_nid);
3862 	for (i = 0; i < ARRAY_SIZE(mout->hp_out_nid); i++)
3863 		if (mout->hp_out_nid[i])
3864 			snd_hda_codec_cleanup_stream(codec,
3865 						     mout->hp_out_nid[i]);
3866 	for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
3867 		if (mout->extra_out_nid[i])
3868 			snd_hda_codec_cleanup_stream(codec,
3869 						     mout->extra_out_nid[i]);
3870 	guard(mutex)(&codec->spdif_mutex);
3871 	if (mout->dig_out_nid && mout->dig_out_used == HDA_DIG_ANALOG_DUP) {
3872 		cleanup_dig_out_stream(codec, mout->dig_out_nid);
3873 		mout->dig_out_used = 0;
3874 	}
3875 	return 0;
3876 }
3877 EXPORT_SYMBOL_GPL(snd_hda_multi_out_analog_cleanup);
3878 
3879 /**
3880  * snd_hda_get_default_vref - Get the default (mic) VREF pin bits
3881  * @codec: the HDA codec
3882  * @pin: referred pin NID
3883  *
3884  * Guess the suitable VREF pin bits to be set as the pin-control value.
3885  * Note: the function doesn't set the AC_PINCTL_IN_EN bit.
3886  */
3887 unsigned int snd_hda_get_default_vref(struct hda_codec *codec, hda_nid_t pin)
3888 {
3889 	unsigned int pincap;
3890 	unsigned int oldval;
3891 	oldval = snd_hda_codec_read(codec, pin, 0,
3892 				    AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
3893 	pincap = snd_hda_query_pin_caps(codec, pin);
3894 	pincap = (pincap & AC_PINCAP_VREF) >> AC_PINCAP_VREF_SHIFT;
3895 	/* Exception: if the default pin setup is vref50, we give it priority */
3896 	if ((pincap & AC_PINCAP_VREF_80) && oldval != PIN_VREF50)
3897 		return AC_PINCTL_VREF_80;
3898 	else if (pincap & AC_PINCAP_VREF_50)
3899 		return AC_PINCTL_VREF_50;
3900 	else if (pincap & AC_PINCAP_VREF_100)
3901 		return AC_PINCTL_VREF_100;
3902 	else if (pincap & AC_PINCAP_VREF_GRD)
3903 		return AC_PINCTL_VREF_GRD;
3904 	return AC_PINCTL_VREF_HIZ;
3905 }
3906 EXPORT_SYMBOL_GPL(snd_hda_get_default_vref);
3907 
3908 /**
3909  * snd_hda_correct_pin_ctl - correct the pin ctl value for matching with the pin cap
3910  * @codec: the HDA codec
3911  * @pin: referred pin NID
3912  * @val: pin ctl value to audit
3913  */
3914 unsigned int snd_hda_correct_pin_ctl(struct hda_codec *codec,
3915 				     hda_nid_t pin, unsigned int val)
3916 {
3917 	static const unsigned int cap_lists[][2] = {
3918 		{ AC_PINCTL_VREF_100, AC_PINCAP_VREF_100 },
3919 		{ AC_PINCTL_VREF_80, AC_PINCAP_VREF_80 },
3920 		{ AC_PINCTL_VREF_50, AC_PINCAP_VREF_50 },
3921 		{ AC_PINCTL_VREF_GRD, AC_PINCAP_VREF_GRD },
3922 	};
3923 	unsigned int cap;
3924 
3925 	if (!val)
3926 		return 0;
3927 	cap = snd_hda_query_pin_caps(codec, pin);
3928 	if (!cap)
3929 		return val; /* don't know what to do... */
3930 
3931 	if (val & AC_PINCTL_OUT_EN) {
3932 		if (!(cap & AC_PINCAP_OUT))
3933 			val &= ~(AC_PINCTL_OUT_EN | AC_PINCTL_HP_EN);
3934 		else if ((val & AC_PINCTL_HP_EN) && !(cap & AC_PINCAP_HP_DRV))
3935 			val &= ~AC_PINCTL_HP_EN;
3936 	}
3937 
3938 	if (val & AC_PINCTL_IN_EN) {
3939 		if (!(cap & AC_PINCAP_IN))
3940 			val &= ~(AC_PINCTL_IN_EN | AC_PINCTL_VREFEN);
3941 		else {
3942 			unsigned int vcap, vref;
3943 			int i;
3944 			vcap = (cap & AC_PINCAP_VREF) >> AC_PINCAP_VREF_SHIFT;
3945 			vref = val & AC_PINCTL_VREFEN;
3946 			for (i = 0; i < ARRAY_SIZE(cap_lists); i++) {
3947 				if (vref == cap_lists[i][0] &&
3948 				    !(vcap & cap_lists[i][1])) {
3949 					if (i == ARRAY_SIZE(cap_lists) - 1)
3950 						vref = AC_PINCTL_VREF_HIZ;
3951 					else
3952 						vref = cap_lists[i + 1][0];
3953 				}
3954 			}
3955 			val &= ~AC_PINCTL_VREFEN;
3956 			val |= vref;
3957 		}
3958 	}
3959 
3960 	return val;
3961 }
3962 EXPORT_SYMBOL_GPL(snd_hda_correct_pin_ctl);
3963 
3964 /**
3965  * _snd_hda_set_pin_ctl - Helper to set pin ctl value
3966  * @codec: the HDA codec
3967  * @pin: referred pin NID
3968  * @val: pin control value to set
3969  * @cached: access over codec pinctl cache or direct write
3970  *
3971  * This function is a helper to set a pin ctl value more safely.
3972  * It corrects the pin ctl value via snd_hda_correct_pin_ctl(), stores the
3973  * value in pin target array via snd_hda_codec_set_pin_target(), then
3974  * actually writes the value via either snd_hda_codec_write_cache() or
3975  * snd_hda_codec_write() depending on @cached flag.
3976  */
3977 int _snd_hda_set_pin_ctl(struct hda_codec *codec, hda_nid_t pin,
3978 			 unsigned int val, bool cached)
3979 {
3980 	val = snd_hda_correct_pin_ctl(codec, pin, val);
3981 	snd_hda_codec_set_pin_target(codec, pin, val);
3982 	if (cached)
3983 		return snd_hda_codec_write_cache(codec, pin, 0,
3984 				AC_VERB_SET_PIN_WIDGET_CONTROL, val);
3985 	else
3986 		return snd_hda_codec_write(codec, pin, 0,
3987 					   AC_VERB_SET_PIN_WIDGET_CONTROL, val);
3988 }
3989 EXPORT_SYMBOL_GPL(_snd_hda_set_pin_ctl);
3990 
3991 /**
3992  * snd_hda_add_imux_item - Add an item to input_mux
3993  * @codec: the HDA codec
3994  * @imux: imux helper object
3995  * @label: the name of imux item to assign
3996  * @index: index number of imux item to assign
3997  * @type_idx: pointer to store the resultant label index
3998  *
3999  * When the same label is used already in the existing items, the number
4000  * suffix is appended to the label.  This label index number is stored
4001  * to type_idx when non-NULL pointer is given.
4002  */
4003 int snd_hda_add_imux_item(struct hda_codec *codec,
4004 			  struct hda_input_mux *imux, const char *label,
4005 			  int index, int *type_idx)
4006 {
4007 	int i, label_idx = 0;
4008 	if (imux->num_items >= HDA_MAX_NUM_INPUTS) {
4009 		codec_err(codec, "hda_codec: Too many imux items!\n");
4010 		return -EINVAL;
4011 	}
4012 	for (i = 0; i < imux->num_items; i++) {
4013 		if (!strncmp(label, imux->items[i].label, strlen(label)))
4014 			label_idx++;
4015 	}
4016 	if (type_idx)
4017 		*type_idx = label_idx;
4018 	if (label_idx > 0)
4019 		snprintf(imux->items[imux->num_items].label,
4020 			 sizeof(imux->items[imux->num_items].label),
4021 			 "%s %d", label, label_idx);
4022 	else
4023 		strscpy(imux->items[imux->num_items].label, label,
4024 			sizeof(imux->items[imux->num_items].label));
4025 	imux->items[imux->num_items].index = index;
4026 	imux->num_items++;
4027 	return 0;
4028 }
4029 EXPORT_SYMBOL_GPL(snd_hda_add_imux_item);
4030 
4031 /**
4032  * snd_hda_bus_reset_codecs - Reset the bus
4033  * @bus: HD-audio bus
4034  */
4035 void snd_hda_bus_reset_codecs(struct hda_bus *bus)
4036 {
4037 	struct hda_codec *codec;
4038 
4039 	list_for_each_codec(codec, bus) {
4040 		/* FIXME: maybe a better way needed for forced reset */
4041 		if (current_work() != &codec->jackpoll_work.work)
4042 			cancel_delayed_work_sync(&codec->jackpoll_work);
4043 		if (hda_codec_is_power_on(codec)) {
4044 			hda_call_codec_suspend(codec);
4045 			hda_call_codec_resume(codec);
4046 		}
4047 	}
4048 }
4049 
4050 /**
4051  * snd_hda_codec_set_gpio - Set up GPIO bits for AFG
4052  * @codec: the HDA codec
4053  * @mask: GPIO bitmask
4054  * @dir: GPIO direction bits
4055  * @data: GPIO data bits
4056  * @delay: the delay in msec before writing GPIO data bits
4057  */
4058 void snd_hda_codec_set_gpio(struct hda_codec *codec, unsigned int mask,
4059 			    unsigned int dir, unsigned int data,
4060 			    unsigned int delay)
4061 {
4062 	snd_hda_codec_write(codec, codec->core.afg, 0,
4063 			    AC_VERB_SET_GPIO_MASK, mask);
4064 	if (delay) {
4065 		snd_hda_codec_write_sync(codec, codec->core.afg, 0,
4066 					 AC_VERB_SET_GPIO_DIRECTION, dir);
4067 		msleep(delay);
4068 		snd_hda_codec_write_sync(codec, codec->core.afg, 0,
4069 					 AC_VERB_SET_GPIO_DATA, data);
4070 	} else {
4071 		snd_hda_codec_write(codec, codec->core.afg, 0,
4072 				    AC_VERB_SET_GPIO_DIRECTION, dir);
4073 		snd_hda_codec_write(codec, codec->core.afg, 0,
4074 				    AC_VERB_SET_GPIO_DATA, data);
4075 	}
4076 }
4077 EXPORT_SYMBOL_GPL(snd_hda_codec_set_gpio);
4078 
4079 /**
4080  * snd_print_pcm_bits - Print the supported PCM fmt bits to the string buffer
4081  * @pcm: PCM caps bits
4082  * @buf: the string buffer to write
4083  * @buflen: the max buffer length
4084  *
4085  * used by hda_proc.c and hda_eld.c
4086  */
4087 void snd_print_pcm_bits(int pcm, char *buf, int buflen)
4088 {
4089 	static const unsigned int bits[] = { 8, 16, 20, 24, 32 };
4090 	int i, j;
4091 
4092 	for (i = 0, j = 0; i < ARRAY_SIZE(bits); i++)
4093 		if (pcm & (AC_SUPPCM_BITS_8 << i))
4094 			j += scnprintf(buf + j, buflen - j,  " %d", bits[i]);
4095 
4096 	buf[j] = '\0'; /* necessary when j == 0 */
4097 }
4098 EXPORT_SYMBOL_GPL(snd_print_pcm_bits);
4099 
4100 MODULE_DESCRIPTION("HDA codec core");
4101 MODULE_LICENSE("GPL");
4102