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