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