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