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