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