xref: /openbmc/linux/sound/pci/hda/hda_codec.c (revision c4ee0af3)
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/pci.h>
27 #include <linux/mutex.h>
28 #include <linux/module.h>
29 #include <sound/core.h>
30 #include "hda_codec.h"
31 #include <sound/asoundef.h>
32 #include <sound/tlv.h>
33 #include <sound/initval.h>
34 #include <sound/jack.h>
35 #include "hda_local.h"
36 #include "hda_beep.h"
37 #include "hda_jack.h"
38 #include <sound/hda_hwdep.h>
39 
40 #define CREATE_TRACE_POINTS
41 #include "hda_trace.h"
42 
43 /*
44  * vendor / preset table
45  */
46 
47 struct hda_vendor_id {
48 	unsigned int id;
49 	const char *name;
50 };
51 
52 /* codec vendor labels */
53 static struct hda_vendor_id hda_vendor_ids[] = {
54 	{ 0x1002, "ATI" },
55 	{ 0x1013, "Cirrus Logic" },
56 	{ 0x1057, "Motorola" },
57 	{ 0x1095, "Silicon Image" },
58 	{ 0x10de, "Nvidia" },
59 	{ 0x10ec, "Realtek" },
60 	{ 0x1102, "Creative" },
61 	{ 0x1106, "VIA" },
62 	{ 0x111d, "IDT" },
63 	{ 0x11c1, "LSI" },
64 	{ 0x11d4, "Analog Devices" },
65 	{ 0x13f6, "C-Media" },
66 	{ 0x14f1, "Conexant" },
67 	{ 0x17e8, "Chrontel" },
68 	{ 0x1854, "LG" },
69 	{ 0x1aec, "Wolfson Microelectronics" },
70 	{ 0x434d, "C-Media" },
71 	{ 0x8086, "Intel" },
72 	{ 0x8384, "SigmaTel" },
73 	{} /* terminator */
74 };
75 
76 static DEFINE_MUTEX(preset_mutex);
77 static LIST_HEAD(hda_preset_tables);
78 
79 int snd_hda_add_codec_preset(struct hda_codec_preset_list *preset)
80 {
81 	mutex_lock(&preset_mutex);
82 	list_add_tail(&preset->list, &hda_preset_tables);
83 	mutex_unlock(&preset_mutex);
84 	return 0;
85 }
86 EXPORT_SYMBOL_HDA(snd_hda_add_codec_preset);
87 
88 int snd_hda_delete_codec_preset(struct hda_codec_preset_list *preset)
89 {
90 	mutex_lock(&preset_mutex);
91 	list_del(&preset->list);
92 	mutex_unlock(&preset_mutex);
93 	return 0;
94 }
95 EXPORT_SYMBOL_HDA(snd_hda_delete_codec_preset);
96 
97 #ifdef CONFIG_PM
98 #define codec_in_pm(codec)	((codec)->in_pm)
99 static void hda_power_work(struct work_struct *work);
100 static void hda_keep_power_on(struct hda_codec *codec);
101 #define hda_codec_is_power_on(codec)	((codec)->power_on)
102 static inline void hda_call_pm_notify(struct hda_bus *bus, bool power_up)
103 {
104 	if (bus->ops.pm_notify)
105 		bus->ops.pm_notify(bus, power_up);
106 }
107 #else
108 #define codec_in_pm(codec)	0
109 static inline void hda_keep_power_on(struct hda_codec *codec) {}
110 #define hda_codec_is_power_on(codec)	1
111 #define hda_call_pm_notify(bus, state) {}
112 #endif
113 
114 /**
115  * snd_hda_get_jack_location - Give a location string of the jack
116  * @cfg: pin default config value
117  *
118  * Parse the pin default config value and returns the string of the
119  * jack location, e.g. "Rear", "Front", etc.
120  */
121 const char *snd_hda_get_jack_location(u32 cfg)
122 {
123 	static char *bases[7] = {
124 		"N/A", "Rear", "Front", "Left", "Right", "Top", "Bottom",
125 	};
126 	static unsigned char specials_idx[] = {
127 		0x07, 0x08,
128 		0x17, 0x18, 0x19,
129 		0x37, 0x38
130 	};
131 	static char *specials[] = {
132 		"Rear Panel", "Drive Bar",
133 		"Riser", "HDMI", "ATAPI",
134 		"Mobile-In", "Mobile-Out"
135 	};
136 	int i;
137 	cfg = (cfg & AC_DEFCFG_LOCATION) >> AC_DEFCFG_LOCATION_SHIFT;
138 	if ((cfg & 0x0f) < 7)
139 		return bases[cfg & 0x0f];
140 	for (i = 0; i < ARRAY_SIZE(specials_idx); i++) {
141 		if (cfg == specials_idx[i])
142 			return specials[i];
143 	}
144 	return "UNKNOWN";
145 }
146 EXPORT_SYMBOL_HDA(snd_hda_get_jack_location);
147 
148 /**
149  * snd_hda_get_jack_connectivity - Give a connectivity string of the jack
150  * @cfg: pin default config value
151  *
152  * Parse the pin default config value and returns the string of the
153  * jack connectivity, i.e. external or internal connection.
154  */
155 const char *snd_hda_get_jack_connectivity(u32 cfg)
156 {
157 	static char *jack_locations[4] = { "Ext", "Int", "Sep", "Oth" };
158 
159 	return jack_locations[(cfg >> (AC_DEFCFG_LOCATION_SHIFT + 4)) & 3];
160 }
161 EXPORT_SYMBOL_HDA(snd_hda_get_jack_connectivity);
162 
163 /**
164  * snd_hda_get_jack_type - Give a type string of the jack
165  * @cfg: pin default config value
166  *
167  * Parse the pin default config value and returns the string of the
168  * jack type, i.e. the purpose of the jack, such as Line-Out or CD.
169  */
170 const char *snd_hda_get_jack_type(u32 cfg)
171 {
172 	static char *jack_types[16] = {
173 		"Line Out", "Speaker", "HP Out", "CD",
174 		"SPDIF Out", "Digital Out", "Modem Line", "Modem Hand",
175 		"Line In", "Aux", "Mic", "Telephony",
176 		"SPDIF In", "Digital In", "Reserved", "Other"
177 	};
178 
179 	return jack_types[(cfg & AC_DEFCFG_DEVICE)
180 				>> AC_DEFCFG_DEVICE_SHIFT];
181 }
182 EXPORT_SYMBOL_HDA(snd_hda_get_jack_type);
183 
184 /*
185  * Compose a 32bit command word to be sent to the HD-audio controller
186  */
187 static inline unsigned int
188 make_codec_cmd(struct hda_codec *codec, hda_nid_t nid, int flags,
189 	       unsigned int verb, unsigned int parm)
190 {
191 	u32 val;
192 
193 	if ((codec->addr & ~0xf) || (nid & ~0x7f) ||
194 	    (verb & ~0xfff) || (parm & ~0xffff)) {
195 		printk(KERN_ERR "hda-codec: out of range cmd %x:%x:%x:%x\n",
196 		       codec->addr, nid, verb, parm);
197 		return ~0;
198 	}
199 
200 	val = (u32)codec->addr << 28;
201 	val |= (u32)nid << 20;
202 	val |= verb << 8;
203 	val |= parm;
204 	return val;
205 }
206 
207 /*
208  * Send and receive a verb
209  */
210 static int codec_exec_verb(struct hda_codec *codec, unsigned int cmd,
211 			   int flags, unsigned int *res)
212 {
213 	struct hda_bus *bus = codec->bus;
214 	int err;
215 
216 	if (cmd == ~0)
217 		return -1;
218 
219 	if (res)
220 		*res = -1;
221  again:
222 	snd_hda_power_up(codec);
223 	mutex_lock(&bus->cmd_mutex);
224 	if (flags & HDA_RW_NO_RESPONSE_FALLBACK)
225 		bus->no_response_fallback = 1;
226 	for (;;) {
227 		trace_hda_send_cmd(codec, cmd);
228 		err = bus->ops.command(bus, cmd);
229 		if (err != -EAGAIN)
230 			break;
231 		/* process pending verbs */
232 		bus->ops.get_response(bus, codec->addr);
233 	}
234 	if (!err && res) {
235 		*res = bus->ops.get_response(bus, codec->addr);
236 		trace_hda_get_response(codec, *res);
237 	}
238 	bus->no_response_fallback = 0;
239 	mutex_unlock(&bus->cmd_mutex);
240 	snd_hda_power_down(codec);
241 	if (!codec_in_pm(codec) && res && *res == -1 && bus->rirb_error) {
242 		if (bus->response_reset) {
243 			snd_printd("hda_codec: resetting BUS due to "
244 				   "fatal communication error\n");
245 			trace_hda_bus_reset(bus);
246 			bus->ops.bus_reset(bus);
247 		}
248 		goto again;
249 	}
250 	/* clear reset-flag when the communication gets recovered */
251 	if (!err || codec_in_pm(codec))
252 		bus->response_reset = 0;
253 	return err;
254 }
255 
256 /**
257  * snd_hda_codec_read - send a command and get the response
258  * @codec: the HDA codec
259  * @nid: NID to send the command
260  * @flags: optional bit flags
261  * @verb: the verb to send
262  * @parm: the parameter for the verb
263  *
264  * Send a single command and read the corresponding response.
265  *
266  * Returns the obtained response value, or -1 for an error.
267  */
268 unsigned int snd_hda_codec_read(struct hda_codec *codec, hda_nid_t nid,
269 				int flags,
270 				unsigned int verb, unsigned int parm)
271 {
272 	unsigned cmd = make_codec_cmd(codec, nid, flags, verb, parm);
273 	unsigned int res;
274 	if (codec_exec_verb(codec, cmd, flags, &res))
275 		return -1;
276 	return res;
277 }
278 EXPORT_SYMBOL_HDA(snd_hda_codec_read);
279 
280 /**
281  * snd_hda_codec_write - send a single command without waiting for response
282  * @codec: the HDA codec
283  * @nid: NID to send the command
284  * @flags: optional bit flags
285  * @verb: the verb to send
286  * @parm: the parameter for the verb
287  *
288  * Send a single command without waiting for response.
289  *
290  * Returns 0 if successful, or a negative error code.
291  */
292 int snd_hda_codec_write(struct hda_codec *codec, hda_nid_t nid, int flags,
293 			unsigned int verb, unsigned int parm)
294 {
295 	unsigned int cmd = make_codec_cmd(codec, nid, flags, verb, parm);
296 	unsigned int res;
297 	return codec_exec_verb(codec, cmd, flags,
298 			       codec->bus->sync_write ? &res : NULL);
299 }
300 EXPORT_SYMBOL_HDA(snd_hda_codec_write);
301 
302 /**
303  * snd_hda_sequence_write - sequence writes
304  * @codec: the HDA codec
305  * @seq: VERB array to send
306  *
307  * Send the commands sequentially from the given array.
308  * The array must be terminated with NID=0.
309  */
310 void snd_hda_sequence_write(struct hda_codec *codec, const struct hda_verb *seq)
311 {
312 	for (; seq->nid; seq++)
313 		snd_hda_codec_write(codec, seq->nid, 0, seq->verb, seq->param);
314 }
315 EXPORT_SYMBOL_HDA(snd_hda_sequence_write);
316 
317 /**
318  * snd_hda_get_sub_nodes - get the range of sub nodes
319  * @codec: the HDA codec
320  * @nid: NID to parse
321  * @start_id: the pointer to store the start NID
322  *
323  * Parse the NID and store the start NID of its sub-nodes.
324  * Returns the number of sub-nodes.
325  */
326 int snd_hda_get_sub_nodes(struct hda_codec *codec, hda_nid_t nid,
327 			  hda_nid_t *start_id)
328 {
329 	unsigned int parm;
330 
331 	parm = snd_hda_param_read(codec, nid, AC_PAR_NODE_COUNT);
332 	if (parm == -1)
333 		return 0;
334 	*start_id = (parm >> 16) & 0x7fff;
335 	return (int)(parm & 0x7fff);
336 }
337 EXPORT_SYMBOL_HDA(snd_hda_get_sub_nodes);
338 
339 /* connection list element */
340 struct hda_conn_list {
341 	struct list_head list;
342 	int len;
343 	hda_nid_t nid;
344 	hda_nid_t conns[0];
345 };
346 
347 /* look up the cached results */
348 static struct hda_conn_list *
349 lookup_conn_list(struct hda_codec *codec, hda_nid_t nid)
350 {
351 	struct hda_conn_list *p;
352 	list_for_each_entry(p, &codec->conn_list, list) {
353 		if (p->nid == nid)
354 			return p;
355 	}
356 	return NULL;
357 }
358 
359 static int add_conn_list(struct hda_codec *codec, hda_nid_t nid, int len,
360 			 const hda_nid_t *list)
361 {
362 	struct hda_conn_list *p;
363 
364 	p = kmalloc(sizeof(*p) + len * sizeof(hda_nid_t), GFP_KERNEL);
365 	if (!p)
366 		return -ENOMEM;
367 	p->len = len;
368 	p->nid = nid;
369 	memcpy(p->conns, list, len * sizeof(hda_nid_t));
370 	list_add(&p->list, &codec->conn_list);
371 	return 0;
372 }
373 
374 static void remove_conn_list(struct hda_codec *codec)
375 {
376 	while (!list_empty(&codec->conn_list)) {
377 		struct hda_conn_list *p;
378 		p = list_first_entry(&codec->conn_list, typeof(*p), list);
379 		list_del(&p->list);
380 		kfree(p);
381 	}
382 }
383 
384 /* read the connection and add to the cache */
385 static int read_and_add_raw_conns(struct hda_codec *codec, hda_nid_t nid)
386 {
387 	hda_nid_t list[32];
388 	hda_nid_t *result = list;
389 	int len;
390 
391 	len = snd_hda_get_raw_connections(codec, nid, list, ARRAY_SIZE(list));
392 	if (len == -ENOSPC) {
393 		len = snd_hda_get_num_raw_conns(codec, nid);
394 		result = kmalloc(sizeof(hda_nid_t) * len, GFP_KERNEL);
395 		if (!result)
396 			return -ENOMEM;
397 		len = snd_hda_get_raw_connections(codec, nid, result, len);
398 	}
399 	if (len >= 0)
400 		len = snd_hda_override_conn_list(codec, nid, len, result);
401 	if (result != list)
402 		kfree(result);
403 	return len;
404 }
405 
406 /**
407  * snd_hda_get_conn_list - get connection list
408  * @codec: the HDA codec
409  * @nid: NID to parse
410  * @len: number of connection list entries
411  * @listp: the pointer to store NID list
412  *
413  * Parses the connection list of the given widget and stores the pointer
414  * to the list of NIDs.
415  *
416  * Returns the number of connections, or a negative error code.
417  *
418  * Note that the returned pointer isn't protected against the list
419  * modification.  If snd_hda_override_conn_list() might be called
420  * concurrently, protect with a mutex appropriately.
421  */
422 int snd_hda_get_conn_list(struct hda_codec *codec, hda_nid_t nid,
423 			  const hda_nid_t **listp)
424 {
425 	bool added = false;
426 
427 	for (;;) {
428 		int err;
429 		const struct hda_conn_list *p;
430 
431 		/* if the connection-list is already cached, read it */
432 		p = lookup_conn_list(codec, nid);
433 		if (p) {
434 			if (listp)
435 				*listp = p->conns;
436 			return p->len;
437 		}
438 		if (snd_BUG_ON(added))
439 			return -EINVAL;
440 
441 		err = read_and_add_raw_conns(codec, nid);
442 		if (err < 0)
443 			return err;
444 		added = true;
445 	}
446 }
447 EXPORT_SYMBOL_HDA(snd_hda_get_conn_list);
448 
449 /**
450  * snd_hda_get_connections - copy connection list
451  * @codec: the HDA codec
452  * @nid: NID to parse
453  * @conn_list: connection list array; when NULL, checks only the size
454  * @max_conns: max. number of connections to store
455  *
456  * Parses the connection list of the given widget and stores the list
457  * of NIDs.
458  *
459  * Returns the number of connections, or a negative error code.
460  */
461 int snd_hda_get_connections(struct hda_codec *codec, hda_nid_t nid,
462 			    hda_nid_t *conn_list, int max_conns)
463 {
464 	const hda_nid_t *list;
465 	int len = snd_hda_get_conn_list(codec, nid, &list);
466 
467 	if (len > 0 && conn_list) {
468 		if (len > max_conns) {
469 			snd_printk(KERN_ERR "hda_codec: "
470 				   "Too many connections %d for NID 0x%x\n",
471 				   len, nid);
472 			return -EINVAL;
473 		}
474 		memcpy(conn_list, list, len * sizeof(hda_nid_t));
475 	}
476 
477 	return len;
478 }
479 EXPORT_SYMBOL_HDA(snd_hda_get_connections);
480 
481 /* return CONNLIST_LEN parameter of the given widget */
482 static unsigned int get_num_conns(struct hda_codec *codec, hda_nid_t nid)
483 {
484 	unsigned int wcaps = get_wcaps(codec, nid);
485 	unsigned int parm;
486 
487 	if (!(wcaps & AC_WCAP_CONN_LIST) &&
488 	    get_wcaps_type(wcaps) != AC_WID_VOL_KNB)
489 		return 0;
490 
491 	parm = snd_hda_param_read(codec, nid, AC_PAR_CONNLIST_LEN);
492 	if (parm == -1)
493 		parm = 0;
494 	return parm;
495 }
496 
497 int snd_hda_get_num_raw_conns(struct hda_codec *codec, hda_nid_t nid)
498 {
499 	return snd_hda_get_raw_connections(codec, nid, NULL, 0);
500 }
501 
502 /**
503  * snd_hda_get_raw_connections - copy connection list without cache
504  * @codec: the HDA codec
505  * @nid: NID to parse
506  * @conn_list: connection list array
507  * @max_conns: max. number of connections to store
508  *
509  * Like snd_hda_get_connections(), copy the connection list but without
510  * checking through the connection-list cache.
511  * Currently called only from hda_proc.c, so not exported.
512  */
513 int snd_hda_get_raw_connections(struct hda_codec *codec, hda_nid_t nid,
514 				hda_nid_t *conn_list, int max_conns)
515 {
516 	unsigned int parm;
517 	int i, conn_len, conns;
518 	unsigned int shift, num_elems, mask;
519 	hda_nid_t prev_nid;
520 	int null_count = 0;
521 
522 	parm = get_num_conns(codec, nid);
523 	if (!parm)
524 		return 0;
525 
526 	if (parm & AC_CLIST_LONG) {
527 		/* long form */
528 		shift = 16;
529 		num_elems = 2;
530 	} else {
531 		/* short form */
532 		shift = 8;
533 		num_elems = 4;
534 	}
535 	conn_len = parm & AC_CLIST_LENGTH;
536 	mask = (1 << (shift-1)) - 1;
537 
538 	if (!conn_len)
539 		return 0; /* no connection */
540 
541 	if (conn_len == 1) {
542 		/* single connection */
543 		parm = snd_hda_codec_read(codec, nid, 0,
544 					  AC_VERB_GET_CONNECT_LIST, 0);
545 		if (parm == -1 && codec->bus->rirb_error)
546 			return -EIO;
547 		if (conn_list)
548 			conn_list[0] = parm & mask;
549 		return 1;
550 	}
551 
552 	/* multi connection */
553 	conns = 0;
554 	prev_nid = 0;
555 	for (i = 0; i < conn_len; i++) {
556 		int range_val;
557 		hda_nid_t val, n;
558 
559 		if (i % num_elems == 0) {
560 			parm = snd_hda_codec_read(codec, nid, 0,
561 						  AC_VERB_GET_CONNECT_LIST, i);
562 			if (parm == -1 && codec->bus->rirb_error)
563 				return -EIO;
564 		}
565 		range_val = !!(parm & (1 << (shift-1))); /* ranges */
566 		val = parm & mask;
567 		if (val == 0 && null_count++) {  /* no second chance */
568 			snd_printdd("hda_codec: "
569 				   "invalid CONNECT_LIST verb %x[%i]:%x\n",
570 				    nid, i, parm);
571 			return 0;
572 		}
573 		parm >>= shift;
574 		if (range_val) {
575 			/* ranges between the previous and this one */
576 			if (!prev_nid || prev_nid >= val) {
577 				snd_printk(KERN_WARNING "hda_codec: "
578 					   "invalid dep_range_val %x:%x\n",
579 					   prev_nid, val);
580 				continue;
581 			}
582 			for (n = prev_nid + 1; n <= val; n++) {
583 				if (conn_list) {
584 					if (conns >= max_conns)
585 						return -ENOSPC;
586 					conn_list[conns] = n;
587 				}
588 				conns++;
589 			}
590 		} else {
591 			if (conn_list) {
592 				if (conns >= max_conns)
593 					return -ENOSPC;
594 				conn_list[conns] = val;
595 			}
596 			conns++;
597 		}
598 		prev_nid = val;
599 	}
600 	return conns;
601 }
602 
603 /**
604  * snd_hda_override_conn_list - add/modify the connection-list to cache
605  * @codec: the HDA codec
606  * @nid: NID to parse
607  * @len: number of connection list entries
608  * @list: the list of connection entries
609  *
610  * Add or modify the given connection-list to the cache.  If the corresponding
611  * cache already exists, invalidate it and append a new one.
612  *
613  * Returns zero or a negative error code.
614  */
615 int snd_hda_override_conn_list(struct hda_codec *codec, hda_nid_t nid, int len,
616 			       const hda_nid_t *list)
617 {
618 	struct hda_conn_list *p;
619 
620 	p = lookup_conn_list(codec, nid);
621 	if (p) {
622 		list_del(&p->list);
623 		kfree(p);
624 	}
625 
626 	return add_conn_list(codec, nid, len, list);
627 }
628 EXPORT_SYMBOL_HDA(snd_hda_override_conn_list);
629 
630 /**
631  * snd_hda_get_conn_index - get the connection index of the given NID
632  * @codec: the HDA codec
633  * @mux: NID containing the list
634  * @nid: NID to select
635  * @recursive: 1 when searching NID recursively, otherwise 0
636  *
637  * Parses the connection list of the widget @mux and checks whether the
638  * widget @nid is present.  If it is, return the connection index.
639  * Otherwise it returns -1.
640  */
641 int snd_hda_get_conn_index(struct hda_codec *codec, hda_nid_t mux,
642 			   hda_nid_t nid, int recursive)
643 {
644 	const hda_nid_t *conn;
645 	int i, nums;
646 
647 	nums = snd_hda_get_conn_list(codec, mux, &conn);
648 	for (i = 0; i < nums; i++)
649 		if (conn[i] == nid)
650 			return i;
651 	if (!recursive)
652 		return -1;
653 	if (recursive > 10) {
654 		snd_printd("hda_codec: too deep connection for 0x%x\n", nid);
655 		return -1;
656 	}
657 	recursive++;
658 	for (i = 0; i < nums; i++) {
659 		unsigned int type = get_wcaps_type(get_wcaps(codec, conn[i]));
660 		if (type == AC_WID_PIN || type == AC_WID_AUD_OUT)
661 			continue;
662 		if (snd_hda_get_conn_index(codec, conn[i], nid, recursive) >= 0)
663 			return i;
664 	}
665 	return -1;
666 }
667 EXPORT_SYMBOL_HDA(snd_hda_get_conn_index);
668 
669 
670 /* return DEVLIST_LEN parameter of the given widget */
671 static unsigned int get_num_devices(struct hda_codec *codec, hda_nid_t nid)
672 {
673 	unsigned int wcaps = get_wcaps(codec, nid);
674 	unsigned int parm;
675 
676 	if (!codec->dp_mst || !(wcaps & AC_WCAP_DIGITAL) ||
677 	    get_wcaps_type(wcaps) != AC_WID_PIN)
678 		return 0;
679 
680 	parm = snd_hda_param_read(codec, nid, AC_PAR_DEVLIST_LEN);
681 	if (parm == -1 && codec->bus->rirb_error)
682 		parm = 0;
683 	return parm & AC_DEV_LIST_LEN_MASK;
684 }
685 
686 /**
687  * snd_hda_get_devices - copy device list without cache
688  * @codec: the HDA codec
689  * @nid: NID of the pin to parse
690  * @dev_list: device list array
691  * @max_devices: max. number of devices to store
692  *
693  * Copy the device list. This info is dynamic and so not cached.
694  * Currently called only from hda_proc.c, so not exported.
695  */
696 int snd_hda_get_devices(struct hda_codec *codec, hda_nid_t nid,
697 			u8 *dev_list, int max_devices)
698 {
699 	unsigned int parm;
700 	int i, dev_len, devices;
701 
702 	parm = get_num_devices(codec, nid);
703 	if (!parm)	/* not multi-stream capable */
704 		return 0;
705 
706 	dev_len = parm + 1;
707 	dev_len = dev_len < max_devices ? dev_len : max_devices;
708 
709 	devices = 0;
710 	while (devices < dev_len) {
711 		parm = snd_hda_codec_read(codec, nid, 0,
712 					  AC_VERB_GET_DEVICE_LIST, devices);
713 		if (parm == -1 && codec->bus->rirb_error)
714 			break;
715 
716 		for (i = 0; i < 8; i++) {
717 			dev_list[devices] = (u8)parm;
718 			parm >>= 4;
719 			devices++;
720 			if (devices >= dev_len)
721 				break;
722 		}
723 	}
724 	return devices;
725 }
726 
727 /**
728  * snd_hda_queue_unsol_event - add an unsolicited event to queue
729  * @bus: the BUS
730  * @res: unsolicited event (lower 32bit of RIRB entry)
731  * @res_ex: codec addr and flags (upper 32bit or RIRB entry)
732  *
733  * Adds the given event to the queue.  The events are processed in
734  * the workqueue asynchronously.  Call this function in the interrupt
735  * hanlder when RIRB receives an unsolicited event.
736  *
737  * Returns 0 if successful, or a negative error code.
738  */
739 int snd_hda_queue_unsol_event(struct hda_bus *bus, u32 res, u32 res_ex)
740 {
741 	struct hda_bus_unsolicited *unsol;
742 	unsigned int wp;
743 
744 	if (!bus || !bus->workq)
745 		return 0;
746 
747 	trace_hda_unsol_event(bus, res, res_ex);
748 	unsol = bus->unsol;
749 	if (!unsol)
750 		return 0;
751 
752 	wp = (unsol->wp + 1) % HDA_UNSOL_QUEUE_SIZE;
753 	unsol->wp = wp;
754 
755 	wp <<= 1;
756 	unsol->queue[wp] = res;
757 	unsol->queue[wp + 1] = res_ex;
758 
759 	queue_work(bus->workq, &unsol->work);
760 
761 	return 0;
762 }
763 EXPORT_SYMBOL_HDA(snd_hda_queue_unsol_event);
764 
765 /*
766  * process queued unsolicited events
767  */
768 static void process_unsol_events(struct work_struct *work)
769 {
770 	struct hda_bus_unsolicited *unsol =
771 		container_of(work, struct hda_bus_unsolicited, work);
772 	struct hda_bus *bus = unsol->bus;
773 	struct hda_codec *codec;
774 	unsigned int rp, caddr, res;
775 
776 	while (unsol->rp != unsol->wp) {
777 		rp = (unsol->rp + 1) % HDA_UNSOL_QUEUE_SIZE;
778 		unsol->rp = rp;
779 		rp <<= 1;
780 		res = unsol->queue[rp];
781 		caddr = unsol->queue[rp + 1];
782 		if (!(caddr & (1 << 4))) /* no unsolicited event? */
783 			continue;
784 		codec = bus->caddr_tbl[caddr & 0x0f];
785 		if (codec && codec->patch_ops.unsol_event)
786 			codec->patch_ops.unsol_event(codec, res);
787 	}
788 }
789 
790 /*
791  * initialize unsolicited queue
792  */
793 static int init_unsol_queue(struct hda_bus *bus)
794 {
795 	struct hda_bus_unsolicited *unsol;
796 
797 	if (bus->unsol) /* already initialized */
798 		return 0;
799 
800 	unsol = kzalloc(sizeof(*unsol), GFP_KERNEL);
801 	if (!unsol) {
802 		snd_printk(KERN_ERR "hda_codec: "
803 			   "can't allocate unsolicited queue\n");
804 		return -ENOMEM;
805 	}
806 	INIT_WORK(&unsol->work, process_unsol_events);
807 	unsol->bus = bus;
808 	bus->unsol = unsol;
809 	return 0;
810 }
811 
812 /*
813  * destructor
814  */
815 static void snd_hda_codec_free(struct hda_codec *codec);
816 
817 static int snd_hda_bus_free(struct hda_bus *bus)
818 {
819 	struct hda_codec *codec, *n;
820 
821 	if (!bus)
822 		return 0;
823 	if (bus->workq)
824 		flush_workqueue(bus->workq);
825 	if (bus->unsol)
826 		kfree(bus->unsol);
827 	list_for_each_entry_safe(codec, n, &bus->codec_list, list) {
828 		snd_hda_codec_free(codec);
829 	}
830 	if (bus->ops.private_free)
831 		bus->ops.private_free(bus);
832 	if (bus->workq)
833 		destroy_workqueue(bus->workq);
834 	kfree(bus);
835 	return 0;
836 }
837 
838 static int snd_hda_bus_dev_free(struct snd_device *device)
839 {
840 	struct hda_bus *bus = device->device_data;
841 	bus->shutdown = 1;
842 	return snd_hda_bus_free(bus);
843 }
844 
845 #ifdef CONFIG_SND_HDA_HWDEP
846 static int snd_hda_bus_dev_register(struct snd_device *device)
847 {
848 	struct hda_bus *bus = device->device_data;
849 	struct hda_codec *codec;
850 	list_for_each_entry(codec, &bus->codec_list, list) {
851 		snd_hda_hwdep_add_sysfs(codec);
852 		snd_hda_hwdep_add_power_sysfs(codec);
853 	}
854 	return 0;
855 }
856 #else
857 #define snd_hda_bus_dev_register	NULL
858 #endif
859 
860 /**
861  * snd_hda_bus_new - create a HDA bus
862  * @card: the card entry
863  * @temp: the template for hda_bus information
864  * @busp: the pointer to store the created bus instance
865  *
866  * Returns 0 if successful, or a negative error code.
867  */
868 int snd_hda_bus_new(struct snd_card *card,
869 			      const struct hda_bus_template *temp,
870 			      struct hda_bus **busp)
871 {
872 	struct hda_bus *bus;
873 	int err;
874 	static struct snd_device_ops dev_ops = {
875 		.dev_register = snd_hda_bus_dev_register,
876 		.dev_free = snd_hda_bus_dev_free,
877 	};
878 
879 	if (snd_BUG_ON(!temp))
880 		return -EINVAL;
881 	if (snd_BUG_ON(!temp->ops.command || !temp->ops.get_response))
882 		return -EINVAL;
883 
884 	if (busp)
885 		*busp = NULL;
886 
887 	bus = kzalloc(sizeof(*bus), GFP_KERNEL);
888 	if (bus == NULL) {
889 		snd_printk(KERN_ERR "can't allocate struct hda_bus\n");
890 		return -ENOMEM;
891 	}
892 
893 	bus->card = card;
894 	bus->private_data = temp->private_data;
895 	bus->pci = temp->pci;
896 	bus->modelname = temp->modelname;
897 	bus->power_save = temp->power_save;
898 	bus->ops = temp->ops;
899 
900 	mutex_init(&bus->cmd_mutex);
901 	mutex_init(&bus->prepare_mutex);
902 	INIT_LIST_HEAD(&bus->codec_list);
903 
904 	snprintf(bus->workq_name, sizeof(bus->workq_name),
905 		 "hd-audio%d", card->number);
906 	bus->workq = create_singlethread_workqueue(bus->workq_name);
907 	if (!bus->workq) {
908 		snd_printk(KERN_ERR "cannot create workqueue %s\n",
909 			   bus->workq_name);
910 		kfree(bus);
911 		return -ENOMEM;
912 	}
913 
914 	err = snd_device_new(card, SNDRV_DEV_BUS, bus, &dev_ops);
915 	if (err < 0) {
916 		snd_hda_bus_free(bus);
917 		return err;
918 	}
919 	if (busp)
920 		*busp = bus;
921 	return 0;
922 }
923 EXPORT_SYMBOL_HDA(snd_hda_bus_new);
924 
925 #ifdef CONFIG_SND_HDA_GENERIC
926 #define is_generic_config(codec) \
927 	(codec->modelname && !strcmp(codec->modelname, "generic"))
928 #else
929 #define is_generic_config(codec)	0
930 #endif
931 
932 #ifdef MODULE
933 #define HDA_MODREQ_MAX_COUNT	2	/* two request_modules()'s */
934 #else
935 #define HDA_MODREQ_MAX_COUNT	0	/* all presets are statically linked */
936 #endif
937 
938 /*
939  * find a matching codec preset
940  */
941 static const struct hda_codec_preset *
942 find_codec_preset(struct hda_codec *codec)
943 {
944 	struct hda_codec_preset_list *tbl;
945 	const struct hda_codec_preset *preset;
946 	unsigned int mod_requested = 0;
947 
948 	if (is_generic_config(codec))
949 		return NULL; /* use the generic parser */
950 
951  again:
952 	mutex_lock(&preset_mutex);
953 	list_for_each_entry(tbl, &hda_preset_tables, list) {
954 		if (!try_module_get(tbl->owner)) {
955 			snd_printk(KERN_ERR "hda_codec: cannot module_get\n");
956 			continue;
957 		}
958 		for (preset = tbl->preset; preset->id; preset++) {
959 			u32 mask = preset->mask;
960 			if (preset->afg && preset->afg != codec->afg)
961 				continue;
962 			if (preset->mfg && preset->mfg != codec->mfg)
963 				continue;
964 			if (!mask)
965 				mask = ~0;
966 			if (preset->id == (codec->vendor_id & mask) &&
967 			    (!preset->rev ||
968 			     preset->rev == codec->revision_id)) {
969 				mutex_unlock(&preset_mutex);
970 				codec->owner = tbl->owner;
971 				return preset;
972 			}
973 		}
974 		module_put(tbl->owner);
975 	}
976 	mutex_unlock(&preset_mutex);
977 
978 	if (mod_requested < HDA_MODREQ_MAX_COUNT) {
979 		char name[32];
980 		if (!mod_requested)
981 			snprintf(name, sizeof(name), "snd-hda-codec-id:%08x",
982 				 codec->vendor_id);
983 		else
984 			snprintf(name, sizeof(name), "snd-hda-codec-id:%04x*",
985 				 (codec->vendor_id >> 16) & 0xffff);
986 		request_module(name);
987 		mod_requested++;
988 		goto again;
989 	}
990 	return NULL;
991 }
992 
993 /*
994  * get_codec_name - store the codec name
995  */
996 static int get_codec_name(struct hda_codec *codec)
997 {
998 	const struct hda_vendor_id *c;
999 	const char *vendor = NULL;
1000 	u16 vendor_id = codec->vendor_id >> 16;
1001 	char tmp[16];
1002 
1003 	if (codec->vendor_name)
1004 		goto get_chip_name;
1005 
1006 	for (c = hda_vendor_ids; c->id; c++) {
1007 		if (c->id == vendor_id) {
1008 			vendor = c->name;
1009 			break;
1010 		}
1011 	}
1012 	if (!vendor) {
1013 		sprintf(tmp, "Generic %04x", vendor_id);
1014 		vendor = tmp;
1015 	}
1016 	codec->vendor_name = kstrdup(vendor, GFP_KERNEL);
1017 	if (!codec->vendor_name)
1018 		return -ENOMEM;
1019 
1020  get_chip_name:
1021 	if (codec->chip_name)
1022 		return 0;
1023 
1024 	if (codec->preset && codec->preset->name)
1025 		codec->chip_name = kstrdup(codec->preset->name, GFP_KERNEL);
1026 	else {
1027 		sprintf(tmp, "ID %x", codec->vendor_id & 0xffff);
1028 		codec->chip_name = kstrdup(tmp, GFP_KERNEL);
1029 	}
1030 	if (!codec->chip_name)
1031 		return -ENOMEM;
1032 	return 0;
1033 }
1034 
1035 /*
1036  * look for an AFG and MFG nodes
1037  */
1038 static void setup_fg_nodes(struct hda_codec *codec)
1039 {
1040 	int i, total_nodes, function_id;
1041 	hda_nid_t nid;
1042 
1043 	total_nodes = snd_hda_get_sub_nodes(codec, AC_NODE_ROOT, &nid);
1044 	for (i = 0; i < total_nodes; i++, nid++) {
1045 		function_id = snd_hda_param_read(codec, nid,
1046 						AC_PAR_FUNCTION_TYPE);
1047 		switch (function_id & 0xff) {
1048 		case AC_GRP_AUDIO_FUNCTION:
1049 			codec->afg = nid;
1050 			codec->afg_function_id = function_id & 0xff;
1051 			codec->afg_unsol = (function_id >> 8) & 1;
1052 			break;
1053 		case AC_GRP_MODEM_FUNCTION:
1054 			codec->mfg = nid;
1055 			codec->mfg_function_id = function_id & 0xff;
1056 			codec->mfg_unsol = (function_id >> 8) & 1;
1057 			break;
1058 		default:
1059 			break;
1060 		}
1061 	}
1062 }
1063 
1064 /*
1065  * read widget caps for each widget and store in cache
1066  */
1067 static int read_widget_caps(struct hda_codec *codec, hda_nid_t fg_node)
1068 {
1069 	int i;
1070 	hda_nid_t nid;
1071 
1072 	codec->num_nodes = snd_hda_get_sub_nodes(codec, fg_node,
1073 						 &codec->start_nid);
1074 	codec->wcaps = kmalloc(codec->num_nodes * 4, GFP_KERNEL);
1075 	if (!codec->wcaps)
1076 		return -ENOMEM;
1077 	nid = codec->start_nid;
1078 	for (i = 0; i < codec->num_nodes; i++, nid++)
1079 		codec->wcaps[i] = snd_hda_param_read(codec, nid,
1080 						     AC_PAR_AUDIO_WIDGET_CAP);
1081 	return 0;
1082 }
1083 
1084 /* read all pin default configurations and save codec->init_pins */
1085 static int read_pin_defaults(struct hda_codec *codec)
1086 {
1087 	int i;
1088 	hda_nid_t nid = codec->start_nid;
1089 
1090 	for (i = 0; i < codec->num_nodes; i++, nid++) {
1091 		struct hda_pincfg *pin;
1092 		unsigned int wcaps = get_wcaps(codec, nid);
1093 		unsigned int wid_type = get_wcaps_type(wcaps);
1094 		if (wid_type != AC_WID_PIN)
1095 			continue;
1096 		pin = snd_array_new(&codec->init_pins);
1097 		if (!pin)
1098 			return -ENOMEM;
1099 		pin->nid = nid;
1100 		pin->cfg = snd_hda_codec_read(codec, nid, 0,
1101 					      AC_VERB_GET_CONFIG_DEFAULT, 0);
1102 		pin->ctrl = snd_hda_codec_read(codec, nid, 0,
1103 					       AC_VERB_GET_PIN_WIDGET_CONTROL,
1104 					       0);
1105 	}
1106 	return 0;
1107 }
1108 
1109 /* look up the given pin config list and return the item matching with NID */
1110 static struct hda_pincfg *look_up_pincfg(struct hda_codec *codec,
1111 					 struct snd_array *array,
1112 					 hda_nid_t nid)
1113 {
1114 	int i;
1115 	for (i = 0; i < array->used; i++) {
1116 		struct hda_pincfg *pin = snd_array_elem(array, i);
1117 		if (pin->nid == nid)
1118 			return pin;
1119 	}
1120 	return NULL;
1121 }
1122 
1123 /* set the current pin config value for the given NID.
1124  * the value is cached, and read via snd_hda_codec_get_pincfg()
1125  */
1126 int snd_hda_add_pincfg(struct hda_codec *codec, struct snd_array *list,
1127 		       hda_nid_t nid, unsigned int cfg)
1128 {
1129 	struct hda_pincfg *pin;
1130 
1131 	/* the check below may be invalid when pins are added by a fixup
1132 	 * dynamically (e.g. via snd_hda_codec_update_widgets()), so disabled
1133 	 * for now
1134 	 */
1135 	/*
1136 	if (get_wcaps_type(get_wcaps(codec, nid)) != AC_WID_PIN)
1137 		return -EINVAL;
1138 	*/
1139 
1140 	pin = look_up_pincfg(codec, list, nid);
1141 	if (!pin) {
1142 		pin = snd_array_new(list);
1143 		if (!pin)
1144 			return -ENOMEM;
1145 		pin->nid = nid;
1146 	}
1147 	pin->cfg = cfg;
1148 	return 0;
1149 }
1150 
1151 /**
1152  * snd_hda_codec_set_pincfg - Override a pin default configuration
1153  * @codec: the HDA codec
1154  * @nid: NID to set the pin config
1155  * @cfg: the pin default config value
1156  *
1157  * Override a pin default configuration value in the cache.
1158  * This value can be read by snd_hda_codec_get_pincfg() in a higher
1159  * priority than the real hardware value.
1160  */
1161 int snd_hda_codec_set_pincfg(struct hda_codec *codec,
1162 			     hda_nid_t nid, unsigned int cfg)
1163 {
1164 	return snd_hda_add_pincfg(codec, &codec->driver_pins, nid, cfg);
1165 }
1166 EXPORT_SYMBOL_HDA(snd_hda_codec_set_pincfg);
1167 
1168 /**
1169  * snd_hda_codec_get_pincfg - Obtain a pin-default configuration
1170  * @codec: the HDA codec
1171  * @nid: NID to get the pin config
1172  *
1173  * Get the current pin config value of the given pin NID.
1174  * If the pincfg value is cached or overridden via sysfs or driver,
1175  * returns the cached value.
1176  */
1177 unsigned int snd_hda_codec_get_pincfg(struct hda_codec *codec, hda_nid_t nid)
1178 {
1179 	struct hda_pincfg *pin;
1180 
1181 #ifdef CONFIG_SND_HDA_HWDEP
1182 	{
1183 		unsigned int cfg = 0;
1184 		mutex_lock(&codec->user_mutex);
1185 		pin = look_up_pincfg(codec, &codec->user_pins, nid);
1186 		if (pin)
1187 			cfg = pin->cfg;
1188 		mutex_unlock(&codec->user_mutex);
1189 		if (cfg)
1190 			return cfg;
1191 	}
1192 #endif
1193 	pin = look_up_pincfg(codec, &codec->driver_pins, nid);
1194 	if (pin)
1195 		return pin->cfg;
1196 	pin = look_up_pincfg(codec, &codec->init_pins, nid);
1197 	if (pin)
1198 		return pin->cfg;
1199 	return 0;
1200 }
1201 EXPORT_SYMBOL_HDA(snd_hda_codec_get_pincfg);
1202 
1203 /* remember the current pinctl target value */
1204 int snd_hda_codec_set_pin_target(struct hda_codec *codec, hda_nid_t nid,
1205 				 unsigned int val)
1206 {
1207 	struct hda_pincfg *pin;
1208 
1209 	pin = look_up_pincfg(codec, &codec->init_pins, nid);
1210 	if (!pin)
1211 		return -EINVAL;
1212 	pin->target = val;
1213 	return 0;
1214 }
1215 EXPORT_SYMBOL_HDA(snd_hda_codec_set_pin_target);
1216 
1217 /* return the current pinctl target value */
1218 int snd_hda_codec_get_pin_target(struct hda_codec *codec, hda_nid_t nid)
1219 {
1220 	struct hda_pincfg *pin;
1221 
1222 	pin = look_up_pincfg(codec, &codec->init_pins, nid);
1223 	if (!pin)
1224 		return 0;
1225 	return pin->target;
1226 }
1227 EXPORT_SYMBOL_HDA(snd_hda_codec_get_pin_target);
1228 
1229 /**
1230  * snd_hda_shutup_pins - Shut up all pins
1231  * @codec: the HDA codec
1232  *
1233  * Clear all pin controls to shup up before suspend for avoiding click noise.
1234  * The controls aren't cached so that they can be resumed properly.
1235  */
1236 void snd_hda_shutup_pins(struct hda_codec *codec)
1237 {
1238 	int i;
1239 	/* don't shut up pins when unloading the driver; otherwise it breaks
1240 	 * the default pin setup at the next load of the driver
1241 	 */
1242 	if (codec->bus->shutdown)
1243 		return;
1244 	for (i = 0; i < codec->init_pins.used; i++) {
1245 		struct hda_pincfg *pin = snd_array_elem(&codec->init_pins, i);
1246 		/* use read here for syncing after issuing each verb */
1247 		snd_hda_codec_read(codec, pin->nid, 0,
1248 				   AC_VERB_SET_PIN_WIDGET_CONTROL, 0);
1249 	}
1250 	codec->pins_shutup = 1;
1251 }
1252 EXPORT_SYMBOL_HDA(snd_hda_shutup_pins);
1253 
1254 #ifdef CONFIG_PM
1255 /* Restore the pin controls cleared previously via snd_hda_shutup_pins() */
1256 static void restore_shutup_pins(struct hda_codec *codec)
1257 {
1258 	int i;
1259 	if (!codec->pins_shutup)
1260 		return;
1261 	if (codec->bus->shutdown)
1262 		return;
1263 	for (i = 0; i < codec->init_pins.used; i++) {
1264 		struct hda_pincfg *pin = snd_array_elem(&codec->init_pins, i);
1265 		snd_hda_codec_write(codec, pin->nid, 0,
1266 				    AC_VERB_SET_PIN_WIDGET_CONTROL,
1267 				    pin->ctrl);
1268 	}
1269 	codec->pins_shutup = 0;
1270 }
1271 #endif
1272 
1273 static void hda_jackpoll_work(struct work_struct *work)
1274 {
1275 	struct hda_codec *codec =
1276 		container_of(work, struct hda_codec, jackpoll_work.work);
1277 
1278 	snd_hda_jack_set_dirty_all(codec);
1279 	snd_hda_jack_poll_all(codec);
1280 
1281 	if (!codec->jackpoll_interval)
1282 		return;
1283 
1284 	queue_delayed_work(codec->bus->workq, &codec->jackpoll_work,
1285 			   codec->jackpoll_interval);
1286 }
1287 
1288 static void init_hda_cache(struct hda_cache_rec *cache,
1289 			   unsigned int record_size);
1290 static void free_hda_cache(struct hda_cache_rec *cache);
1291 
1292 /* release all pincfg lists */
1293 static void free_init_pincfgs(struct hda_codec *codec)
1294 {
1295 	snd_array_free(&codec->driver_pins);
1296 #ifdef CONFIG_SND_HDA_HWDEP
1297 	snd_array_free(&codec->user_pins);
1298 #endif
1299 	snd_array_free(&codec->init_pins);
1300 }
1301 
1302 /*
1303  * audio-converter setup caches
1304  */
1305 struct hda_cvt_setup {
1306 	hda_nid_t nid;
1307 	u8 stream_tag;
1308 	u8 channel_id;
1309 	u16 format_id;
1310 	unsigned char active;	/* cvt is currently used */
1311 	unsigned char dirty;	/* setups should be cleared */
1312 };
1313 
1314 /* get or create a cache entry for the given audio converter NID */
1315 static struct hda_cvt_setup *
1316 get_hda_cvt_setup(struct hda_codec *codec, hda_nid_t nid)
1317 {
1318 	struct hda_cvt_setup *p;
1319 	int i;
1320 
1321 	for (i = 0; i < codec->cvt_setups.used; i++) {
1322 		p = snd_array_elem(&codec->cvt_setups, i);
1323 		if (p->nid == nid)
1324 			return p;
1325 	}
1326 	p = snd_array_new(&codec->cvt_setups);
1327 	if (p)
1328 		p->nid = nid;
1329 	return p;
1330 }
1331 
1332 /*
1333  * codec destructor
1334  */
1335 static void snd_hda_codec_free(struct hda_codec *codec)
1336 {
1337 	if (!codec)
1338 		return;
1339 	cancel_delayed_work_sync(&codec->jackpoll_work);
1340 	snd_hda_jack_tbl_clear(codec);
1341 	free_init_pincfgs(codec);
1342 #ifdef CONFIG_PM
1343 	cancel_delayed_work(&codec->power_work);
1344 	flush_workqueue(codec->bus->workq);
1345 #endif
1346 	list_del(&codec->list);
1347 	snd_array_free(&codec->mixers);
1348 	snd_array_free(&codec->nids);
1349 	snd_array_free(&codec->cvt_setups);
1350 	snd_array_free(&codec->spdif_out);
1351 	remove_conn_list(codec);
1352 	codec->bus->caddr_tbl[codec->addr] = NULL;
1353 	if (codec->patch_ops.free)
1354 		codec->patch_ops.free(codec);
1355 #ifdef CONFIG_PM
1356 	if (!codec->pm_down_notified) /* cancel leftover refcounts */
1357 		hda_call_pm_notify(codec->bus, false);
1358 #endif
1359 	module_put(codec->owner);
1360 	free_hda_cache(&codec->amp_cache);
1361 	free_hda_cache(&codec->cmd_cache);
1362 	kfree(codec->vendor_name);
1363 	kfree(codec->chip_name);
1364 	kfree(codec->modelname);
1365 	kfree(codec->wcaps);
1366 	kfree(codec);
1367 }
1368 
1369 static bool snd_hda_codec_get_supported_ps(struct hda_codec *codec,
1370 				hda_nid_t fg, unsigned int power_state);
1371 
1372 static unsigned int hda_set_power_state(struct hda_codec *codec,
1373 				unsigned int power_state);
1374 
1375 /**
1376  * snd_hda_codec_new - create a HDA codec
1377  * @bus: the bus to assign
1378  * @codec_addr: the codec address
1379  * @codecp: the pointer to store the generated codec
1380  *
1381  * Returns 0 if successful, or a negative error code.
1382  */
1383 int snd_hda_codec_new(struct hda_bus *bus,
1384 				unsigned int codec_addr,
1385 				struct hda_codec **codecp)
1386 {
1387 	struct hda_codec *codec;
1388 	char component[31];
1389 	hda_nid_t fg;
1390 	int err;
1391 
1392 	if (snd_BUG_ON(!bus))
1393 		return -EINVAL;
1394 	if (snd_BUG_ON(codec_addr > HDA_MAX_CODEC_ADDRESS))
1395 		return -EINVAL;
1396 
1397 	if (bus->caddr_tbl[codec_addr]) {
1398 		snd_printk(KERN_ERR "hda_codec: "
1399 			   "address 0x%x is already occupied\n", codec_addr);
1400 		return -EBUSY;
1401 	}
1402 
1403 	codec = kzalloc(sizeof(*codec), GFP_KERNEL);
1404 	if (codec == NULL) {
1405 		snd_printk(KERN_ERR "can't allocate struct hda_codec\n");
1406 		return -ENOMEM;
1407 	}
1408 
1409 	codec->bus = bus;
1410 	codec->addr = codec_addr;
1411 	mutex_init(&codec->spdif_mutex);
1412 	mutex_init(&codec->control_mutex);
1413 	mutex_init(&codec->hash_mutex);
1414 	init_hda_cache(&codec->amp_cache, sizeof(struct hda_amp_info));
1415 	init_hda_cache(&codec->cmd_cache, sizeof(struct hda_cache_head));
1416 	snd_array_init(&codec->mixers, sizeof(struct hda_nid_item), 32);
1417 	snd_array_init(&codec->nids, sizeof(struct hda_nid_item), 32);
1418 	snd_array_init(&codec->init_pins, sizeof(struct hda_pincfg), 16);
1419 	snd_array_init(&codec->driver_pins, sizeof(struct hda_pincfg), 16);
1420 	snd_array_init(&codec->cvt_setups, sizeof(struct hda_cvt_setup), 8);
1421 	snd_array_init(&codec->spdif_out, sizeof(struct hda_spdif_out), 16);
1422 	snd_array_init(&codec->jacktbl, sizeof(struct hda_jack_tbl), 16);
1423 	snd_array_init(&codec->verbs, sizeof(struct hda_verb *), 8);
1424 	INIT_LIST_HEAD(&codec->conn_list);
1425 
1426 	INIT_DELAYED_WORK(&codec->jackpoll_work, hda_jackpoll_work);
1427 
1428 #ifdef CONFIG_PM
1429 	spin_lock_init(&codec->power_lock);
1430 	INIT_DELAYED_WORK(&codec->power_work, hda_power_work);
1431 	/* snd_hda_codec_new() marks the codec as power-up, and leave it as is.
1432 	 * the caller has to power down appropriatley after initialization
1433 	 * phase.
1434 	 */
1435 	hda_keep_power_on(codec);
1436 	hda_call_pm_notify(bus, true);
1437 #endif
1438 
1439 	if (codec->bus->modelname) {
1440 		codec->modelname = kstrdup(codec->bus->modelname, GFP_KERNEL);
1441 		if (!codec->modelname) {
1442 			snd_hda_codec_free(codec);
1443 			return -ENODEV;
1444 		}
1445 	}
1446 
1447 	list_add_tail(&codec->list, &bus->codec_list);
1448 	bus->caddr_tbl[codec_addr] = codec;
1449 
1450 	codec->vendor_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1451 					      AC_PAR_VENDOR_ID);
1452 	if (codec->vendor_id == -1)
1453 		/* read again, hopefully the access method was corrected
1454 		 * in the last read...
1455 		 */
1456 		codec->vendor_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1457 						      AC_PAR_VENDOR_ID);
1458 	codec->subsystem_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1459 						 AC_PAR_SUBSYSTEM_ID);
1460 	codec->revision_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1461 						AC_PAR_REV_ID);
1462 
1463 	setup_fg_nodes(codec);
1464 	if (!codec->afg && !codec->mfg) {
1465 		snd_printdd("hda_codec: no AFG or MFG node found\n");
1466 		err = -ENODEV;
1467 		goto error;
1468 	}
1469 
1470 	fg = codec->afg ? codec->afg : codec->mfg;
1471 	err = read_widget_caps(codec, fg);
1472 	if (err < 0) {
1473 		snd_printk(KERN_ERR "hda_codec: cannot malloc\n");
1474 		goto error;
1475 	}
1476 	err = read_pin_defaults(codec);
1477 	if (err < 0)
1478 		goto error;
1479 
1480 	if (!codec->subsystem_id) {
1481 		codec->subsystem_id =
1482 			snd_hda_codec_read(codec, fg, 0,
1483 					   AC_VERB_GET_SUBSYSTEM_ID, 0);
1484 	}
1485 
1486 #ifdef CONFIG_PM
1487 	codec->d3_stop_clk = snd_hda_codec_get_supported_ps(codec, fg,
1488 					AC_PWRST_CLKSTOP);
1489 	if (!codec->d3_stop_clk)
1490 		bus->power_keep_link_on = 1;
1491 #endif
1492 	codec->epss = snd_hda_codec_get_supported_ps(codec, fg,
1493 					AC_PWRST_EPSS);
1494 
1495 	/* power-up all before initialization */
1496 	hda_set_power_state(codec, AC_PWRST_D0);
1497 
1498 	snd_hda_codec_proc_new(codec);
1499 
1500 	snd_hda_create_hwdep(codec);
1501 
1502 	sprintf(component, "HDA:%08x,%08x,%08x", codec->vendor_id,
1503 		codec->subsystem_id, codec->revision_id);
1504 	snd_component_add(codec->bus->card, component);
1505 
1506 	if (codecp)
1507 		*codecp = codec;
1508 	return 0;
1509 
1510  error:
1511 	snd_hda_codec_free(codec);
1512 	return err;
1513 }
1514 EXPORT_SYMBOL_HDA(snd_hda_codec_new);
1515 
1516 int snd_hda_codec_update_widgets(struct hda_codec *codec)
1517 {
1518 	hda_nid_t fg;
1519 	int err;
1520 
1521 	/* Assume the function group node does not change,
1522 	 * only the widget nodes may change.
1523 	 */
1524 	kfree(codec->wcaps);
1525 	fg = codec->afg ? codec->afg : codec->mfg;
1526 	err = read_widget_caps(codec, fg);
1527 	if (err < 0) {
1528 		snd_printk(KERN_ERR "hda_codec: cannot malloc\n");
1529 		return err;
1530 	}
1531 
1532 	snd_array_free(&codec->init_pins);
1533 	err = read_pin_defaults(codec);
1534 
1535 	return err;
1536 }
1537 EXPORT_SYMBOL_HDA(snd_hda_codec_update_widgets);
1538 
1539 
1540 /**
1541  * snd_hda_codec_configure - (Re-)configure the HD-audio codec
1542  * @codec: the HDA codec
1543  *
1544  * Start parsing of the given codec tree and (re-)initialize the whole
1545  * patch instance.
1546  *
1547  * Returns 0 if successful or a negative error code.
1548  */
1549 int snd_hda_codec_configure(struct hda_codec *codec)
1550 {
1551 	int err;
1552 
1553 	codec->preset = find_codec_preset(codec);
1554 	if (!codec->vendor_name || !codec->chip_name) {
1555 		err = get_codec_name(codec);
1556 		if (err < 0)
1557 			return err;
1558 	}
1559 
1560 	if (is_generic_config(codec)) {
1561 		err = snd_hda_parse_generic_codec(codec);
1562 		goto patched;
1563 	}
1564 	if (codec->preset && codec->preset->patch) {
1565 		err = codec->preset->patch(codec);
1566 		goto patched;
1567 	}
1568 
1569 	/* call the default parser */
1570 	err = snd_hda_parse_generic_codec(codec);
1571 	if (err < 0)
1572 		printk(KERN_ERR "hda-codec: No codec parser is available\n");
1573 
1574  patched:
1575 	if (!err && codec->patch_ops.unsol_event)
1576 		err = init_unsol_queue(codec->bus);
1577 	/* audio codec should override the mixer name */
1578 	if (!err && (codec->afg || !*codec->bus->card->mixername))
1579 		snprintf(codec->bus->card->mixername,
1580 			 sizeof(codec->bus->card->mixername),
1581 			 "%s %s", codec->vendor_name, codec->chip_name);
1582 	return err;
1583 }
1584 EXPORT_SYMBOL_HDA(snd_hda_codec_configure);
1585 
1586 /* update the stream-id if changed */
1587 static void update_pcm_stream_id(struct hda_codec *codec,
1588 				 struct hda_cvt_setup *p, hda_nid_t nid,
1589 				 u32 stream_tag, int channel_id)
1590 {
1591 	unsigned int oldval, newval;
1592 
1593 	if (p->stream_tag != stream_tag || p->channel_id != channel_id) {
1594 		oldval = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_CONV, 0);
1595 		newval = (stream_tag << 4) | channel_id;
1596 		if (oldval != newval)
1597 			snd_hda_codec_write(codec, nid, 0,
1598 					    AC_VERB_SET_CHANNEL_STREAMID,
1599 					    newval);
1600 		p->stream_tag = stream_tag;
1601 		p->channel_id = channel_id;
1602 	}
1603 }
1604 
1605 /* update the format-id if changed */
1606 static void update_pcm_format(struct hda_codec *codec, struct hda_cvt_setup *p,
1607 			      hda_nid_t nid, int format)
1608 {
1609 	unsigned int oldval;
1610 
1611 	if (p->format_id != format) {
1612 		oldval = snd_hda_codec_read(codec, nid, 0,
1613 					    AC_VERB_GET_STREAM_FORMAT, 0);
1614 		if (oldval != format) {
1615 			msleep(1);
1616 			snd_hda_codec_write(codec, nid, 0,
1617 					    AC_VERB_SET_STREAM_FORMAT,
1618 					    format);
1619 		}
1620 		p->format_id = format;
1621 	}
1622 }
1623 
1624 /**
1625  * snd_hda_codec_setup_stream - set up the codec for streaming
1626  * @codec: the CODEC to set up
1627  * @nid: the NID to set up
1628  * @stream_tag: stream tag to pass, it's between 0x1 and 0xf.
1629  * @channel_id: channel id to pass, zero based.
1630  * @format: stream format.
1631  */
1632 void snd_hda_codec_setup_stream(struct hda_codec *codec, hda_nid_t nid,
1633 				u32 stream_tag,
1634 				int channel_id, int format)
1635 {
1636 	struct hda_codec *c;
1637 	struct hda_cvt_setup *p;
1638 	int type;
1639 	int i;
1640 
1641 	if (!nid)
1642 		return;
1643 
1644 	snd_printdd("hda_codec_setup_stream: "
1645 		    "NID=0x%x, stream=0x%x, channel=%d, format=0x%x\n",
1646 		    nid, stream_tag, channel_id, format);
1647 	p = get_hda_cvt_setup(codec, nid);
1648 	if (!p)
1649 		return;
1650 
1651 	if (codec->pcm_format_first)
1652 		update_pcm_format(codec, p, nid, format);
1653 	update_pcm_stream_id(codec, p, nid, stream_tag, channel_id);
1654 	if (!codec->pcm_format_first)
1655 		update_pcm_format(codec, p, nid, format);
1656 
1657 	p->active = 1;
1658 	p->dirty = 0;
1659 
1660 	/* make other inactive cvts with the same stream-tag dirty */
1661 	type = get_wcaps_type(get_wcaps(codec, nid));
1662 	list_for_each_entry(c, &codec->bus->codec_list, list) {
1663 		for (i = 0; i < c->cvt_setups.used; i++) {
1664 			p = snd_array_elem(&c->cvt_setups, i);
1665 			if (!p->active && p->stream_tag == stream_tag &&
1666 			    get_wcaps_type(get_wcaps(c, p->nid)) == type)
1667 				p->dirty = 1;
1668 		}
1669 	}
1670 }
1671 EXPORT_SYMBOL_HDA(snd_hda_codec_setup_stream);
1672 
1673 static void really_cleanup_stream(struct hda_codec *codec,
1674 				  struct hda_cvt_setup *q);
1675 
1676 /**
1677  * __snd_hda_codec_cleanup_stream - clean up the codec for closing
1678  * @codec: the CODEC to clean up
1679  * @nid: the NID to clean up
1680  * @do_now: really clean up the stream instead of clearing the active flag
1681  */
1682 void __snd_hda_codec_cleanup_stream(struct hda_codec *codec, hda_nid_t nid,
1683 				    int do_now)
1684 {
1685 	struct hda_cvt_setup *p;
1686 
1687 	if (!nid)
1688 		return;
1689 
1690 	if (codec->no_sticky_stream)
1691 		do_now = 1;
1692 
1693 	snd_printdd("hda_codec_cleanup_stream: NID=0x%x\n", nid);
1694 	p = get_hda_cvt_setup(codec, nid);
1695 	if (p) {
1696 		/* here we just clear the active flag when do_now isn't set;
1697 		 * actual clean-ups will be done later in
1698 		 * purify_inactive_streams() called from snd_hda_codec_prpapre()
1699 		 */
1700 		if (do_now)
1701 			really_cleanup_stream(codec, p);
1702 		else
1703 			p->active = 0;
1704 	}
1705 }
1706 EXPORT_SYMBOL_HDA(__snd_hda_codec_cleanup_stream);
1707 
1708 static void really_cleanup_stream(struct hda_codec *codec,
1709 				  struct hda_cvt_setup *q)
1710 {
1711 	hda_nid_t nid = q->nid;
1712 	if (q->stream_tag || q->channel_id)
1713 		snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_CHANNEL_STREAMID, 0);
1714 	if (q->format_id)
1715 		snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_STREAM_FORMAT, 0
1716 );
1717 	memset(q, 0, sizeof(*q));
1718 	q->nid = nid;
1719 }
1720 
1721 /* clean up the all conflicting obsolete streams */
1722 static void purify_inactive_streams(struct hda_codec *codec)
1723 {
1724 	struct hda_codec *c;
1725 	int i;
1726 
1727 	list_for_each_entry(c, &codec->bus->codec_list, list) {
1728 		for (i = 0; i < c->cvt_setups.used; i++) {
1729 			struct hda_cvt_setup *p;
1730 			p = snd_array_elem(&c->cvt_setups, i);
1731 			if (p->dirty)
1732 				really_cleanup_stream(c, p);
1733 		}
1734 	}
1735 }
1736 
1737 #ifdef CONFIG_PM
1738 /* clean up all streams; called from suspend */
1739 static void hda_cleanup_all_streams(struct hda_codec *codec)
1740 {
1741 	int i;
1742 
1743 	for (i = 0; i < codec->cvt_setups.used; i++) {
1744 		struct hda_cvt_setup *p = snd_array_elem(&codec->cvt_setups, i);
1745 		if (p->stream_tag)
1746 			really_cleanup_stream(codec, p);
1747 	}
1748 }
1749 #endif
1750 
1751 /*
1752  * amp access functions
1753  */
1754 
1755 /* FIXME: more better hash key? */
1756 #define HDA_HASH_KEY(nid, dir, idx) (u32)((nid) + ((idx) << 16) + ((dir) << 24))
1757 #define HDA_HASH_PINCAP_KEY(nid) (u32)((nid) + (0x02 << 24))
1758 #define HDA_HASH_PARPCM_KEY(nid) (u32)((nid) + (0x03 << 24))
1759 #define HDA_HASH_PARSTR_KEY(nid) (u32)((nid) + (0x04 << 24))
1760 #define INFO_AMP_CAPS	(1<<0)
1761 #define INFO_AMP_VOL(ch)	(1 << (1 + (ch)))
1762 
1763 /* initialize the hash table */
1764 static void init_hda_cache(struct hda_cache_rec *cache,
1765 				     unsigned int record_size)
1766 {
1767 	memset(cache, 0, sizeof(*cache));
1768 	memset(cache->hash, 0xff, sizeof(cache->hash));
1769 	snd_array_init(&cache->buf, record_size, 64);
1770 }
1771 
1772 static void free_hda_cache(struct hda_cache_rec *cache)
1773 {
1774 	snd_array_free(&cache->buf);
1775 }
1776 
1777 /* query the hash.  allocate an entry if not found. */
1778 static struct hda_cache_head  *get_hash(struct hda_cache_rec *cache, u32 key)
1779 {
1780 	u16 idx = key % (u16)ARRAY_SIZE(cache->hash);
1781 	u16 cur = cache->hash[idx];
1782 	struct hda_cache_head *info;
1783 
1784 	while (cur != 0xffff) {
1785 		info = snd_array_elem(&cache->buf, cur);
1786 		if (info->key == key)
1787 			return info;
1788 		cur = info->next;
1789 	}
1790 	return NULL;
1791 }
1792 
1793 /* query the hash.  allocate an entry if not found. */
1794 static struct hda_cache_head  *get_alloc_hash(struct hda_cache_rec *cache,
1795 					      u32 key)
1796 {
1797 	struct hda_cache_head *info = get_hash(cache, key);
1798 	if (!info) {
1799 		u16 idx, cur;
1800 		/* add a new hash entry */
1801 		info = snd_array_new(&cache->buf);
1802 		if (!info)
1803 			return NULL;
1804 		cur = snd_array_index(&cache->buf, info);
1805 		info->key = key;
1806 		info->val = 0;
1807 		info->dirty = 0;
1808 		idx = key % (u16)ARRAY_SIZE(cache->hash);
1809 		info->next = cache->hash[idx];
1810 		cache->hash[idx] = cur;
1811 	}
1812 	return info;
1813 }
1814 
1815 /* query and allocate an amp hash entry */
1816 static inline struct hda_amp_info *
1817 get_alloc_amp_hash(struct hda_codec *codec, u32 key)
1818 {
1819 	return (struct hda_amp_info *)get_alloc_hash(&codec->amp_cache, key);
1820 }
1821 
1822 /* overwrite the value with the key in the caps hash */
1823 static int write_caps_hash(struct hda_codec *codec, u32 key, unsigned int val)
1824 {
1825 	struct hda_amp_info *info;
1826 
1827 	mutex_lock(&codec->hash_mutex);
1828 	info = get_alloc_amp_hash(codec, key);
1829 	if (!info) {
1830 		mutex_unlock(&codec->hash_mutex);
1831 		return -EINVAL;
1832 	}
1833 	info->amp_caps = val;
1834 	info->head.val |= INFO_AMP_CAPS;
1835 	mutex_unlock(&codec->hash_mutex);
1836 	return 0;
1837 }
1838 
1839 /* query the value from the caps hash; if not found, fetch the current
1840  * value from the given function and store in the hash
1841  */
1842 static unsigned int
1843 query_caps_hash(struct hda_codec *codec, hda_nid_t nid, int dir, u32 key,
1844 		unsigned int (*func)(struct hda_codec *, hda_nid_t, int))
1845 {
1846 	struct hda_amp_info *info;
1847 	unsigned int val;
1848 
1849 	mutex_lock(&codec->hash_mutex);
1850 	info = get_alloc_amp_hash(codec, key);
1851 	if (!info) {
1852 		mutex_unlock(&codec->hash_mutex);
1853 		return 0;
1854 	}
1855 	if (!(info->head.val & INFO_AMP_CAPS)) {
1856 		mutex_unlock(&codec->hash_mutex); /* for reentrance */
1857 		val = func(codec, nid, dir);
1858 		write_caps_hash(codec, key, val);
1859 	} else {
1860 		val = info->amp_caps;
1861 		mutex_unlock(&codec->hash_mutex);
1862 	}
1863 	return val;
1864 }
1865 
1866 static unsigned int read_amp_cap(struct hda_codec *codec, hda_nid_t nid,
1867 				 int direction)
1868 {
1869 	if (!(get_wcaps(codec, nid) & AC_WCAP_AMP_OVRD))
1870 		nid = codec->afg;
1871 	return snd_hda_param_read(codec, nid,
1872 				  direction == HDA_OUTPUT ?
1873 				  AC_PAR_AMP_OUT_CAP : AC_PAR_AMP_IN_CAP);
1874 }
1875 
1876 /**
1877  * query_amp_caps - query AMP capabilities
1878  * @codec: the HD-auio codec
1879  * @nid: the NID to query
1880  * @direction: either #HDA_INPUT or #HDA_OUTPUT
1881  *
1882  * Query AMP capabilities for the given widget and direction.
1883  * Returns the obtained capability bits.
1884  *
1885  * When cap bits have been already read, this doesn't read again but
1886  * returns the cached value.
1887  */
1888 u32 query_amp_caps(struct hda_codec *codec, hda_nid_t nid, int direction)
1889 {
1890 	return query_caps_hash(codec, nid, direction,
1891 			       HDA_HASH_KEY(nid, direction, 0),
1892 			       read_amp_cap);
1893 }
1894 EXPORT_SYMBOL_HDA(query_amp_caps);
1895 
1896 /**
1897  * snd_hda_override_amp_caps - Override the AMP capabilities
1898  * @codec: the CODEC to clean up
1899  * @nid: the NID to clean up
1900  * @direction: either #HDA_INPUT or #HDA_OUTPUT
1901  * @caps: the capability bits to set
1902  *
1903  * Override the cached AMP caps bits value by the given one.
1904  * This function is useful if the driver needs to adjust the AMP ranges,
1905  * e.g. limit to 0dB, etc.
1906  *
1907  * Returns zero if successful or a negative error code.
1908  */
1909 int snd_hda_override_amp_caps(struct hda_codec *codec, hda_nid_t nid, int dir,
1910 			      unsigned int caps)
1911 {
1912 	return write_caps_hash(codec, HDA_HASH_KEY(nid, dir, 0), caps);
1913 }
1914 EXPORT_SYMBOL_HDA(snd_hda_override_amp_caps);
1915 
1916 static unsigned int read_pin_cap(struct hda_codec *codec, hda_nid_t nid,
1917 				 int dir)
1918 {
1919 	return snd_hda_param_read(codec, nid, AC_PAR_PIN_CAP);
1920 }
1921 
1922 /**
1923  * snd_hda_query_pin_caps - Query PIN capabilities
1924  * @codec: the HD-auio codec
1925  * @nid: the NID to query
1926  *
1927  * Query PIN capabilities for the given widget.
1928  * Returns the obtained capability bits.
1929  *
1930  * When cap bits have been already read, this doesn't read again but
1931  * returns the cached value.
1932  */
1933 u32 snd_hda_query_pin_caps(struct hda_codec *codec, hda_nid_t nid)
1934 {
1935 	return query_caps_hash(codec, nid, 0, HDA_HASH_PINCAP_KEY(nid),
1936 			       read_pin_cap);
1937 }
1938 EXPORT_SYMBOL_HDA(snd_hda_query_pin_caps);
1939 
1940 /**
1941  * snd_hda_override_pin_caps - Override the pin capabilities
1942  * @codec: the CODEC
1943  * @nid: the NID to override
1944  * @caps: the capability bits to set
1945  *
1946  * Override the cached PIN capabilitiy bits value by the given one.
1947  *
1948  * Returns zero if successful or a negative error code.
1949  */
1950 int snd_hda_override_pin_caps(struct hda_codec *codec, hda_nid_t nid,
1951 			      unsigned int caps)
1952 {
1953 	return write_caps_hash(codec, HDA_HASH_PINCAP_KEY(nid), caps);
1954 }
1955 EXPORT_SYMBOL_HDA(snd_hda_override_pin_caps);
1956 
1957 /* read or sync the hash value with the current value;
1958  * call within hash_mutex
1959  */
1960 static struct hda_amp_info *
1961 update_amp_hash(struct hda_codec *codec, hda_nid_t nid, int ch,
1962 		int direction, int index, bool init_only)
1963 {
1964 	struct hda_amp_info *info;
1965 	unsigned int parm, val = 0;
1966 	bool val_read = false;
1967 
1968  retry:
1969 	info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, direction, index));
1970 	if (!info)
1971 		return NULL;
1972 	if (!(info->head.val & INFO_AMP_VOL(ch))) {
1973 		if (!val_read) {
1974 			mutex_unlock(&codec->hash_mutex);
1975 			parm = ch ? AC_AMP_GET_RIGHT : AC_AMP_GET_LEFT;
1976 			parm |= direction == HDA_OUTPUT ?
1977 				AC_AMP_GET_OUTPUT : AC_AMP_GET_INPUT;
1978 			parm |= index;
1979 			val = snd_hda_codec_read(codec, nid, 0,
1980 				 AC_VERB_GET_AMP_GAIN_MUTE, parm);
1981 			val &= 0xff;
1982 			val_read = true;
1983 			mutex_lock(&codec->hash_mutex);
1984 			goto retry;
1985 		}
1986 		info->vol[ch] = val;
1987 		info->head.val |= INFO_AMP_VOL(ch);
1988 	} else if (init_only)
1989 		return NULL;
1990 	return info;
1991 }
1992 
1993 /*
1994  * write the current volume in info to the h/w
1995  */
1996 static void put_vol_mute(struct hda_codec *codec, unsigned int amp_caps,
1997 			 hda_nid_t nid, int ch, int direction, int index,
1998 			 int val)
1999 {
2000 	u32 parm;
2001 
2002 	parm = ch ? AC_AMP_SET_RIGHT : AC_AMP_SET_LEFT;
2003 	parm |= direction == HDA_OUTPUT ? AC_AMP_SET_OUTPUT : AC_AMP_SET_INPUT;
2004 	parm |= index << AC_AMP_SET_INDEX_SHIFT;
2005 	if ((val & HDA_AMP_MUTE) && !(amp_caps & AC_AMPCAP_MUTE) &&
2006 	    (amp_caps & AC_AMPCAP_MIN_MUTE))
2007 		; /* set the zero value as a fake mute */
2008 	else
2009 		parm |= val;
2010 	snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_AMP_GAIN_MUTE, parm);
2011 }
2012 
2013 /**
2014  * snd_hda_codec_amp_read - Read AMP value
2015  * @codec: HD-audio codec
2016  * @nid: NID to read the AMP value
2017  * @ch: channel (left=0 or right=1)
2018  * @direction: #HDA_INPUT or #HDA_OUTPUT
2019  * @index: the index value (only for input direction)
2020  *
2021  * Read AMP value.  The volume is between 0 to 0x7f, 0x80 = mute bit.
2022  */
2023 int snd_hda_codec_amp_read(struct hda_codec *codec, hda_nid_t nid, int ch,
2024 			   int direction, int index)
2025 {
2026 	struct hda_amp_info *info;
2027 	unsigned int val = 0;
2028 
2029 	mutex_lock(&codec->hash_mutex);
2030 	info = update_amp_hash(codec, nid, ch, direction, index, false);
2031 	if (info)
2032 		val = info->vol[ch];
2033 	mutex_unlock(&codec->hash_mutex);
2034 	return val;
2035 }
2036 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_read);
2037 
2038 static int codec_amp_update(struct hda_codec *codec, hda_nid_t nid, int ch,
2039 			    int direction, int idx, int mask, int val,
2040 			    bool init_only)
2041 {
2042 	struct hda_amp_info *info;
2043 	unsigned int caps;
2044 	unsigned int cache_only;
2045 
2046 	if (snd_BUG_ON(mask & ~0xff))
2047 		mask &= 0xff;
2048 	val &= mask;
2049 
2050 	mutex_lock(&codec->hash_mutex);
2051 	info = update_amp_hash(codec, nid, ch, direction, idx, init_only);
2052 	if (!info) {
2053 		mutex_unlock(&codec->hash_mutex);
2054 		return 0;
2055 	}
2056 	val |= info->vol[ch] & ~mask;
2057 	if (info->vol[ch] == val) {
2058 		mutex_unlock(&codec->hash_mutex);
2059 		return 0;
2060 	}
2061 	info->vol[ch] = val;
2062 	cache_only = info->head.dirty = codec->cached_write;
2063 	caps = info->amp_caps;
2064 	mutex_unlock(&codec->hash_mutex);
2065 	if (!cache_only)
2066 		put_vol_mute(codec, caps, nid, ch, direction, idx, val);
2067 	return 1;
2068 }
2069 
2070 /**
2071  * snd_hda_codec_amp_update - update the AMP value
2072  * @codec: HD-audio codec
2073  * @nid: NID to read the AMP value
2074  * @ch: channel (left=0 or right=1)
2075  * @direction: #HDA_INPUT or #HDA_OUTPUT
2076  * @idx: the index value (only for input direction)
2077  * @mask: bit mask to set
2078  * @val: the bits value to set
2079  *
2080  * Update the AMP value with a bit mask.
2081  * Returns 0 if the value is unchanged, 1 if changed.
2082  */
2083 int snd_hda_codec_amp_update(struct hda_codec *codec, hda_nid_t nid, int ch,
2084 			     int direction, int idx, int mask, int val)
2085 {
2086 	return codec_amp_update(codec, nid, ch, direction, idx, mask, val, false);
2087 }
2088 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_update);
2089 
2090 /**
2091  * snd_hda_codec_amp_stereo - update the AMP stereo values
2092  * @codec: HD-audio codec
2093  * @nid: NID to read the AMP value
2094  * @direction: #HDA_INPUT or #HDA_OUTPUT
2095  * @idx: the index value (only for input direction)
2096  * @mask: bit mask to set
2097  * @val: the bits value to set
2098  *
2099  * Update the AMP values like snd_hda_codec_amp_update(), but for a
2100  * stereo widget with the same mask and value.
2101  */
2102 int snd_hda_codec_amp_stereo(struct hda_codec *codec, hda_nid_t nid,
2103 			     int direction, int idx, int mask, int val)
2104 {
2105 	int ch, ret = 0;
2106 
2107 	if (snd_BUG_ON(mask & ~0xff))
2108 		mask &= 0xff;
2109 	for (ch = 0; ch < 2; ch++)
2110 		ret |= snd_hda_codec_amp_update(codec, nid, ch, direction,
2111 						idx, mask, val);
2112 	return ret;
2113 }
2114 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_stereo);
2115 
2116 /* Works like snd_hda_codec_amp_update() but it writes the value only at
2117  * the first access.  If the amp was already initialized / updated beforehand,
2118  * this does nothing.
2119  */
2120 int snd_hda_codec_amp_init(struct hda_codec *codec, hda_nid_t nid, int ch,
2121 			   int dir, int idx, int mask, int val)
2122 {
2123 	return codec_amp_update(codec, nid, ch, dir, idx, mask, val, true);
2124 }
2125 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_init);
2126 
2127 int snd_hda_codec_amp_init_stereo(struct hda_codec *codec, hda_nid_t nid,
2128 				  int dir, int idx, int mask, int val)
2129 {
2130 	int ch, ret = 0;
2131 
2132 	if (snd_BUG_ON(mask & ~0xff))
2133 		mask &= 0xff;
2134 	for (ch = 0; ch < 2; ch++)
2135 		ret |= snd_hda_codec_amp_init(codec, nid, ch, dir,
2136 					      idx, mask, val);
2137 	return ret;
2138 }
2139 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_init_stereo);
2140 
2141 /**
2142  * snd_hda_codec_resume_amp - Resume all AMP commands from the cache
2143  * @codec: HD-audio codec
2144  *
2145  * Resume the all amp commands from the cache.
2146  */
2147 void snd_hda_codec_resume_amp(struct hda_codec *codec)
2148 {
2149 	int i;
2150 
2151 	mutex_lock(&codec->hash_mutex);
2152 	codec->cached_write = 0;
2153 	for (i = 0; i < codec->amp_cache.buf.used; i++) {
2154 		struct hda_amp_info *buffer;
2155 		u32 key;
2156 		hda_nid_t nid;
2157 		unsigned int idx, dir, ch;
2158 		struct hda_amp_info info;
2159 
2160 		buffer = snd_array_elem(&codec->amp_cache.buf, i);
2161 		if (!buffer->head.dirty)
2162 			continue;
2163 		buffer->head.dirty = 0;
2164 		info = *buffer;
2165 		key = info.head.key;
2166 		if (!key)
2167 			continue;
2168 		nid = key & 0xff;
2169 		idx = (key >> 16) & 0xff;
2170 		dir = (key >> 24) & 0xff;
2171 		for (ch = 0; ch < 2; ch++) {
2172 			if (!(info.head.val & INFO_AMP_VOL(ch)))
2173 				continue;
2174 			mutex_unlock(&codec->hash_mutex);
2175 			put_vol_mute(codec, info.amp_caps, nid, ch, dir, idx,
2176 				     info.vol[ch]);
2177 			mutex_lock(&codec->hash_mutex);
2178 		}
2179 	}
2180 	mutex_unlock(&codec->hash_mutex);
2181 }
2182 EXPORT_SYMBOL_HDA(snd_hda_codec_resume_amp);
2183 
2184 static u32 get_amp_max_value(struct hda_codec *codec, hda_nid_t nid, int dir,
2185 			     unsigned int ofs)
2186 {
2187 	u32 caps = query_amp_caps(codec, nid, dir);
2188 	/* get num steps */
2189 	caps = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
2190 	if (ofs < caps)
2191 		caps -= ofs;
2192 	return caps;
2193 }
2194 
2195 /**
2196  * snd_hda_mixer_amp_volume_info - Info callback for a standard AMP mixer
2197  *
2198  * The control element is supposed to have the private_value field
2199  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2200  */
2201 int snd_hda_mixer_amp_volume_info(struct snd_kcontrol *kcontrol,
2202 				  struct snd_ctl_elem_info *uinfo)
2203 {
2204 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2205 	u16 nid = get_amp_nid(kcontrol);
2206 	u8 chs = get_amp_channels(kcontrol);
2207 	int dir = get_amp_direction(kcontrol);
2208 	unsigned int ofs = get_amp_offset(kcontrol);
2209 
2210 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
2211 	uinfo->count = chs == 3 ? 2 : 1;
2212 	uinfo->value.integer.min = 0;
2213 	uinfo->value.integer.max = get_amp_max_value(codec, nid, dir, ofs);
2214 	if (!uinfo->value.integer.max) {
2215 		printk(KERN_WARNING "hda_codec: "
2216 		       "num_steps = 0 for NID=0x%x (ctl = %s)\n", nid,
2217 		       kcontrol->id.name);
2218 		return -EINVAL;
2219 	}
2220 	return 0;
2221 }
2222 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_volume_info);
2223 
2224 
2225 static inline unsigned int
2226 read_amp_value(struct hda_codec *codec, hda_nid_t nid,
2227 	       int ch, int dir, int idx, unsigned int ofs)
2228 {
2229 	unsigned int val;
2230 	val = snd_hda_codec_amp_read(codec, nid, ch, dir, idx);
2231 	val &= HDA_AMP_VOLMASK;
2232 	if (val >= ofs)
2233 		val -= ofs;
2234 	else
2235 		val = 0;
2236 	return val;
2237 }
2238 
2239 static inline int
2240 update_amp_value(struct hda_codec *codec, hda_nid_t nid,
2241 		 int ch, int dir, int idx, unsigned int ofs,
2242 		 unsigned int val)
2243 {
2244 	unsigned int maxval;
2245 
2246 	if (val > 0)
2247 		val += ofs;
2248 	/* ofs = 0: raw max value */
2249 	maxval = get_amp_max_value(codec, nid, dir, 0);
2250 	if (val > maxval)
2251 		val = maxval;
2252 	return snd_hda_codec_amp_update(codec, nid, ch, dir, idx,
2253 					HDA_AMP_VOLMASK, val);
2254 }
2255 
2256 /**
2257  * snd_hda_mixer_amp_volume_get - Get callback for a standard AMP mixer volume
2258  *
2259  * The control element is supposed to have the private_value field
2260  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2261  */
2262 int snd_hda_mixer_amp_volume_get(struct snd_kcontrol *kcontrol,
2263 				 struct snd_ctl_elem_value *ucontrol)
2264 {
2265 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2266 	hda_nid_t nid = get_amp_nid(kcontrol);
2267 	int chs = get_amp_channels(kcontrol);
2268 	int dir = get_amp_direction(kcontrol);
2269 	int idx = get_amp_index(kcontrol);
2270 	unsigned int ofs = get_amp_offset(kcontrol);
2271 	long *valp = ucontrol->value.integer.value;
2272 
2273 	if (chs & 1)
2274 		*valp++ = read_amp_value(codec, nid, 0, dir, idx, ofs);
2275 	if (chs & 2)
2276 		*valp = read_amp_value(codec, nid, 1, dir, idx, ofs);
2277 	return 0;
2278 }
2279 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_volume_get);
2280 
2281 /**
2282  * snd_hda_mixer_amp_volume_put - Put callback for a standard AMP mixer volume
2283  *
2284  * The control element is supposed to have the private_value field
2285  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2286  */
2287 int snd_hda_mixer_amp_volume_put(struct snd_kcontrol *kcontrol,
2288 				 struct snd_ctl_elem_value *ucontrol)
2289 {
2290 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2291 	hda_nid_t nid = get_amp_nid(kcontrol);
2292 	int chs = get_amp_channels(kcontrol);
2293 	int dir = get_amp_direction(kcontrol);
2294 	int idx = get_amp_index(kcontrol);
2295 	unsigned int ofs = get_amp_offset(kcontrol);
2296 	long *valp = ucontrol->value.integer.value;
2297 	int change = 0;
2298 
2299 	snd_hda_power_up(codec);
2300 	if (chs & 1) {
2301 		change = update_amp_value(codec, nid, 0, dir, idx, ofs, *valp);
2302 		valp++;
2303 	}
2304 	if (chs & 2)
2305 		change |= update_amp_value(codec, nid, 1, dir, idx, ofs, *valp);
2306 	snd_hda_power_down(codec);
2307 	return change;
2308 }
2309 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_volume_put);
2310 
2311 /**
2312  * snd_hda_mixer_amp_volume_put - TLV callback for a standard AMP mixer volume
2313  *
2314  * The control element is supposed to have the private_value field
2315  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2316  */
2317 int snd_hda_mixer_amp_tlv(struct snd_kcontrol *kcontrol, int op_flag,
2318 			  unsigned int size, unsigned int __user *_tlv)
2319 {
2320 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2321 	hda_nid_t nid = get_amp_nid(kcontrol);
2322 	int dir = get_amp_direction(kcontrol);
2323 	unsigned int ofs = get_amp_offset(kcontrol);
2324 	bool min_mute = get_amp_min_mute(kcontrol);
2325 	u32 caps, val1, val2;
2326 
2327 	if (size < 4 * sizeof(unsigned int))
2328 		return -ENOMEM;
2329 	caps = query_amp_caps(codec, nid, dir);
2330 	val2 = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT;
2331 	val2 = (val2 + 1) * 25;
2332 	val1 = -((caps & AC_AMPCAP_OFFSET) >> AC_AMPCAP_OFFSET_SHIFT);
2333 	val1 += ofs;
2334 	val1 = ((int)val1) * ((int)val2);
2335 	if (min_mute || (caps & AC_AMPCAP_MIN_MUTE))
2336 		val2 |= TLV_DB_SCALE_MUTE;
2337 	if (put_user(SNDRV_CTL_TLVT_DB_SCALE, _tlv))
2338 		return -EFAULT;
2339 	if (put_user(2 * sizeof(unsigned int), _tlv + 1))
2340 		return -EFAULT;
2341 	if (put_user(val1, _tlv + 2))
2342 		return -EFAULT;
2343 	if (put_user(val2, _tlv + 3))
2344 		return -EFAULT;
2345 	return 0;
2346 }
2347 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_tlv);
2348 
2349 /**
2350  * snd_hda_set_vmaster_tlv - Set TLV for a virtual master control
2351  * @codec: HD-audio codec
2352  * @nid: NID of a reference widget
2353  * @dir: #HDA_INPUT or #HDA_OUTPUT
2354  * @tlv: TLV data to be stored, at least 4 elements
2355  *
2356  * Set (static) TLV data for a virtual master volume using the AMP caps
2357  * obtained from the reference NID.
2358  * The volume range is recalculated as if the max volume is 0dB.
2359  */
2360 void snd_hda_set_vmaster_tlv(struct hda_codec *codec, hda_nid_t nid, int dir,
2361 			     unsigned int *tlv)
2362 {
2363 	u32 caps;
2364 	int nums, step;
2365 
2366 	caps = query_amp_caps(codec, nid, dir);
2367 	nums = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
2368 	step = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT;
2369 	step = (step + 1) * 25;
2370 	tlv[0] = SNDRV_CTL_TLVT_DB_SCALE;
2371 	tlv[1] = 2 * sizeof(unsigned int);
2372 	tlv[2] = -nums * step;
2373 	tlv[3] = step;
2374 }
2375 EXPORT_SYMBOL_HDA(snd_hda_set_vmaster_tlv);
2376 
2377 /* find a mixer control element with the given name */
2378 static struct snd_kcontrol *
2379 find_mixer_ctl(struct hda_codec *codec, const char *name, int dev, int idx)
2380 {
2381 	struct snd_ctl_elem_id id;
2382 	memset(&id, 0, sizeof(id));
2383 	id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
2384 	id.device = dev;
2385 	id.index = idx;
2386 	if (snd_BUG_ON(strlen(name) >= sizeof(id.name)))
2387 		return NULL;
2388 	strcpy(id.name, name);
2389 	return snd_ctl_find_id(codec->bus->card, &id);
2390 }
2391 
2392 /**
2393  * snd_hda_find_mixer_ctl - Find a mixer control element with the given name
2394  * @codec: HD-audio codec
2395  * @name: ctl id name string
2396  *
2397  * Get the control element with the given id string and IFACE_MIXER.
2398  */
2399 struct snd_kcontrol *snd_hda_find_mixer_ctl(struct hda_codec *codec,
2400 					    const char *name)
2401 {
2402 	return find_mixer_ctl(codec, name, 0, 0);
2403 }
2404 EXPORT_SYMBOL_HDA(snd_hda_find_mixer_ctl);
2405 
2406 static int find_empty_mixer_ctl_idx(struct hda_codec *codec, const char *name,
2407 				    int start_idx)
2408 {
2409 	int i, idx;
2410 	/* 16 ctlrs should be large enough */
2411 	for (i = 0, idx = start_idx; i < 16; i++, idx++) {
2412 		if (!find_mixer_ctl(codec, name, 0, idx))
2413 			return idx;
2414 	}
2415 	return -EBUSY;
2416 }
2417 
2418 /**
2419  * snd_hda_ctl_add - Add a control element and assign to the codec
2420  * @codec: HD-audio codec
2421  * @nid: corresponding NID (optional)
2422  * @kctl: the control element to assign
2423  *
2424  * Add the given control element to an array inside the codec instance.
2425  * All control elements belonging to a codec are supposed to be added
2426  * by this function so that a proper clean-up works at the free or
2427  * reconfiguration time.
2428  *
2429  * If non-zero @nid is passed, the NID is assigned to the control element.
2430  * The assignment is shown in the codec proc file.
2431  *
2432  * snd_hda_ctl_add() checks the control subdev id field whether
2433  * #HDA_SUBDEV_NID_FLAG bit is set.  If set (and @nid is zero), the lower
2434  * bits value is taken as the NID to assign. The #HDA_NID_ITEM_AMP bit
2435  * specifies if kctl->private_value is a HDA amplifier value.
2436  */
2437 int snd_hda_ctl_add(struct hda_codec *codec, hda_nid_t nid,
2438 		    struct snd_kcontrol *kctl)
2439 {
2440 	int err;
2441 	unsigned short flags = 0;
2442 	struct hda_nid_item *item;
2443 
2444 	if (kctl->id.subdevice & HDA_SUBDEV_AMP_FLAG) {
2445 		flags |= HDA_NID_ITEM_AMP;
2446 		if (nid == 0)
2447 			nid = get_amp_nid_(kctl->private_value);
2448 	}
2449 	if ((kctl->id.subdevice & HDA_SUBDEV_NID_FLAG) != 0 && nid == 0)
2450 		nid = kctl->id.subdevice & 0xffff;
2451 	if (kctl->id.subdevice & (HDA_SUBDEV_NID_FLAG|HDA_SUBDEV_AMP_FLAG))
2452 		kctl->id.subdevice = 0;
2453 	err = snd_ctl_add(codec->bus->card, kctl);
2454 	if (err < 0)
2455 		return err;
2456 	item = snd_array_new(&codec->mixers);
2457 	if (!item)
2458 		return -ENOMEM;
2459 	item->kctl = kctl;
2460 	item->nid = nid;
2461 	item->flags = flags;
2462 	return 0;
2463 }
2464 EXPORT_SYMBOL_HDA(snd_hda_ctl_add);
2465 
2466 /**
2467  * snd_hda_add_nid - Assign a NID to a control element
2468  * @codec: HD-audio codec
2469  * @nid: corresponding NID (optional)
2470  * @kctl: the control element to assign
2471  * @index: index to kctl
2472  *
2473  * Add the given control element to an array inside the codec instance.
2474  * This function is used when #snd_hda_ctl_add cannot be used for 1:1
2475  * NID:KCTL mapping - for example "Capture Source" selector.
2476  */
2477 int snd_hda_add_nid(struct hda_codec *codec, struct snd_kcontrol *kctl,
2478 		    unsigned int index, hda_nid_t nid)
2479 {
2480 	struct hda_nid_item *item;
2481 
2482 	if (nid > 0) {
2483 		item = snd_array_new(&codec->nids);
2484 		if (!item)
2485 			return -ENOMEM;
2486 		item->kctl = kctl;
2487 		item->index = index;
2488 		item->nid = nid;
2489 		return 0;
2490 	}
2491 	printk(KERN_ERR "hda-codec: no NID for mapping control %s:%d:%d\n",
2492 	       kctl->id.name, kctl->id.index, index);
2493 	return -EINVAL;
2494 }
2495 EXPORT_SYMBOL_HDA(snd_hda_add_nid);
2496 
2497 /**
2498  * snd_hda_ctls_clear - Clear all controls assigned to the given codec
2499  * @codec: HD-audio codec
2500  */
2501 void snd_hda_ctls_clear(struct hda_codec *codec)
2502 {
2503 	int i;
2504 	struct hda_nid_item *items = codec->mixers.list;
2505 	for (i = 0; i < codec->mixers.used; i++)
2506 		snd_ctl_remove(codec->bus->card, items[i].kctl);
2507 	snd_array_free(&codec->mixers);
2508 	snd_array_free(&codec->nids);
2509 }
2510 
2511 /* pseudo device locking
2512  * toggle card->shutdown to allow/disallow the device access (as a hack)
2513  */
2514 int snd_hda_lock_devices(struct hda_bus *bus)
2515 {
2516 	struct snd_card *card = bus->card;
2517 	struct hda_codec *codec;
2518 
2519 	spin_lock(&card->files_lock);
2520 	if (card->shutdown)
2521 		goto err_unlock;
2522 	card->shutdown = 1;
2523 	if (!list_empty(&card->ctl_files))
2524 		goto err_clear;
2525 
2526 	list_for_each_entry(codec, &bus->codec_list, list) {
2527 		int pcm;
2528 		for (pcm = 0; pcm < codec->num_pcms; pcm++) {
2529 			struct hda_pcm *cpcm = &codec->pcm_info[pcm];
2530 			if (!cpcm->pcm)
2531 				continue;
2532 			if (cpcm->pcm->streams[0].substream_opened ||
2533 			    cpcm->pcm->streams[1].substream_opened)
2534 				goto err_clear;
2535 		}
2536 	}
2537 	spin_unlock(&card->files_lock);
2538 	return 0;
2539 
2540  err_clear:
2541 	card->shutdown = 0;
2542  err_unlock:
2543 	spin_unlock(&card->files_lock);
2544 	return -EINVAL;
2545 }
2546 EXPORT_SYMBOL_HDA(snd_hda_lock_devices);
2547 
2548 void snd_hda_unlock_devices(struct hda_bus *bus)
2549 {
2550 	struct snd_card *card = bus->card;
2551 
2552 	card = bus->card;
2553 	spin_lock(&card->files_lock);
2554 	card->shutdown = 0;
2555 	spin_unlock(&card->files_lock);
2556 }
2557 EXPORT_SYMBOL_HDA(snd_hda_unlock_devices);
2558 
2559 /**
2560  * snd_hda_codec_reset - Clear all objects assigned to the codec
2561  * @codec: HD-audio codec
2562  *
2563  * This frees the all PCM and control elements assigned to the codec, and
2564  * clears the caches and restores the pin default configurations.
2565  *
2566  * When a device is being used, it returns -EBSY.  If successfully freed,
2567  * returns zero.
2568  */
2569 int snd_hda_codec_reset(struct hda_codec *codec)
2570 {
2571 	struct hda_bus *bus = codec->bus;
2572 	struct snd_card *card = bus->card;
2573 	int i;
2574 
2575 	if (snd_hda_lock_devices(bus) < 0)
2576 		return -EBUSY;
2577 
2578 	/* OK, let it free */
2579 	cancel_delayed_work_sync(&codec->jackpoll_work);
2580 #ifdef CONFIG_PM
2581 	cancel_delayed_work_sync(&codec->power_work);
2582 	flush_workqueue(bus->workq);
2583 #endif
2584 	snd_hda_ctls_clear(codec);
2585 	/* release PCMs */
2586 	for (i = 0; i < codec->num_pcms; i++) {
2587 		if (codec->pcm_info[i].pcm) {
2588 			snd_device_free(card, codec->pcm_info[i].pcm);
2589 			clear_bit(codec->pcm_info[i].device,
2590 				  bus->pcm_dev_bits);
2591 		}
2592 	}
2593 	if (codec->patch_ops.free)
2594 		codec->patch_ops.free(codec);
2595 	memset(&codec->patch_ops, 0, sizeof(codec->patch_ops));
2596 	snd_hda_jack_tbl_clear(codec);
2597 	codec->proc_widget_hook = NULL;
2598 	codec->spec = NULL;
2599 	free_hda_cache(&codec->amp_cache);
2600 	free_hda_cache(&codec->cmd_cache);
2601 	init_hda_cache(&codec->amp_cache, sizeof(struct hda_amp_info));
2602 	init_hda_cache(&codec->cmd_cache, sizeof(struct hda_cache_head));
2603 	/* free only driver_pins so that init_pins + user_pins are restored */
2604 	snd_array_free(&codec->driver_pins);
2605 	snd_array_free(&codec->cvt_setups);
2606 	snd_array_free(&codec->spdif_out);
2607 	snd_array_free(&codec->verbs);
2608 	codec->num_pcms = 0;
2609 	codec->pcm_info = NULL;
2610 	codec->preset = NULL;
2611 	codec->slave_dig_outs = NULL;
2612 	codec->spdif_status_reset = 0;
2613 	module_put(codec->owner);
2614 	codec->owner = NULL;
2615 
2616 	/* allow device access again */
2617 	snd_hda_unlock_devices(bus);
2618 	return 0;
2619 }
2620 
2621 typedef int (*map_slave_func_t)(void *, struct snd_kcontrol *);
2622 
2623 /* apply the function to all matching slave ctls in the mixer list */
2624 static int map_slaves(struct hda_codec *codec, const char * const *slaves,
2625 		      const char *suffix, map_slave_func_t func, void *data)
2626 {
2627 	struct hda_nid_item *items;
2628 	const char * const *s;
2629 	int i, err;
2630 
2631 	items = codec->mixers.list;
2632 	for (i = 0; i < codec->mixers.used; i++) {
2633 		struct snd_kcontrol *sctl = items[i].kctl;
2634 		if (!sctl || sctl->id.iface != SNDRV_CTL_ELEM_IFACE_MIXER)
2635 			continue;
2636 		for (s = slaves; *s; s++) {
2637 			char tmpname[sizeof(sctl->id.name)];
2638 			const char *name = *s;
2639 			if (suffix) {
2640 				snprintf(tmpname, sizeof(tmpname), "%s %s",
2641 					 name, suffix);
2642 				name = tmpname;
2643 			}
2644 			if (!strcmp(sctl->id.name, name)) {
2645 				err = func(data, sctl);
2646 				if (err)
2647 					return err;
2648 				break;
2649 			}
2650 		}
2651 	}
2652 	return 0;
2653 }
2654 
2655 static int check_slave_present(void *data, struct snd_kcontrol *sctl)
2656 {
2657 	return 1;
2658 }
2659 
2660 /* guess the value corresponding to 0dB */
2661 static int get_kctl_0dB_offset(struct snd_kcontrol *kctl, int *step_to_check)
2662 {
2663 	int _tlv[4];
2664 	const int *tlv = NULL;
2665 	int val = -1;
2666 
2667 	if (kctl->vd[0].access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) {
2668 		/* FIXME: set_fs() hack for obtaining user-space TLV data */
2669 		mm_segment_t fs = get_fs();
2670 		set_fs(get_ds());
2671 		if (!kctl->tlv.c(kctl, 0, sizeof(_tlv), _tlv))
2672 			tlv = _tlv;
2673 		set_fs(fs);
2674 	} else if (kctl->vd[0].access & SNDRV_CTL_ELEM_ACCESS_TLV_READ)
2675 		tlv = kctl->tlv.p;
2676 	if (tlv && tlv[0] == SNDRV_CTL_TLVT_DB_SCALE) {
2677 		int step = tlv[3];
2678 		step &= ~TLV_DB_SCALE_MUTE;
2679 		if (!step)
2680 			return -1;
2681 		if (*step_to_check && *step_to_check != step) {
2682 			snd_printk(KERN_ERR "hda_codec: Mismatching dB step for vmaster slave (%d!=%d)\n",
2683 				   *step_to_check, step);
2684 			return -1;
2685 		}
2686 		*step_to_check = step;
2687 		val = -tlv[2] / step;
2688 	}
2689 	return val;
2690 }
2691 
2692 /* call kctl->put with the given value(s) */
2693 static int put_kctl_with_value(struct snd_kcontrol *kctl, int val)
2694 {
2695 	struct snd_ctl_elem_value *ucontrol;
2696 	ucontrol = kzalloc(sizeof(*ucontrol), GFP_KERNEL);
2697 	if (!ucontrol)
2698 		return -ENOMEM;
2699 	ucontrol->value.integer.value[0] = val;
2700 	ucontrol->value.integer.value[1] = val;
2701 	kctl->put(kctl, ucontrol);
2702 	kfree(ucontrol);
2703 	return 0;
2704 }
2705 
2706 /* initialize the slave volume with 0dB */
2707 static int init_slave_0dB(void *data, struct snd_kcontrol *slave)
2708 {
2709 	int offset = get_kctl_0dB_offset(slave, data);
2710 	if (offset > 0)
2711 		put_kctl_with_value(slave, offset);
2712 	return 0;
2713 }
2714 
2715 /* unmute the slave */
2716 static int init_slave_unmute(void *data, struct snd_kcontrol *slave)
2717 {
2718 	return put_kctl_with_value(slave, 1);
2719 }
2720 
2721 /**
2722  * snd_hda_add_vmaster - create a virtual master control and add slaves
2723  * @codec: HD-audio codec
2724  * @name: vmaster control name
2725  * @tlv: TLV data (optional)
2726  * @slaves: slave control names (optional)
2727  * @suffix: suffix string to each slave name (optional)
2728  * @init_slave_vol: initialize slaves to unmute/0dB
2729  * @ctl_ret: store the vmaster kcontrol in return
2730  *
2731  * Create a virtual master control with the given name.  The TLV data
2732  * must be either NULL or a valid data.
2733  *
2734  * @slaves is a NULL-terminated array of strings, each of which is a
2735  * slave control name.  All controls with these names are assigned to
2736  * the new virtual master control.
2737  *
2738  * This function returns zero if successful or a negative error code.
2739  */
2740 int __snd_hda_add_vmaster(struct hda_codec *codec, char *name,
2741 			unsigned int *tlv, const char * const *slaves,
2742 			  const char *suffix, bool init_slave_vol,
2743 			  struct snd_kcontrol **ctl_ret)
2744 {
2745 	struct snd_kcontrol *kctl;
2746 	int err;
2747 
2748 	if (ctl_ret)
2749 		*ctl_ret = NULL;
2750 
2751 	err = map_slaves(codec, slaves, suffix, check_slave_present, NULL);
2752 	if (err != 1) {
2753 		snd_printdd("No slave found for %s\n", name);
2754 		return 0;
2755 	}
2756 	kctl = snd_ctl_make_virtual_master(name, tlv);
2757 	if (!kctl)
2758 		return -ENOMEM;
2759 	err = snd_hda_ctl_add(codec, 0, kctl);
2760 	if (err < 0)
2761 		return err;
2762 
2763 	err = map_slaves(codec, slaves, suffix,
2764 			 (map_slave_func_t)snd_ctl_add_slave, kctl);
2765 	if (err < 0)
2766 		return err;
2767 
2768 	/* init with master mute & zero volume */
2769 	put_kctl_with_value(kctl, 0);
2770 	if (init_slave_vol) {
2771 		int step = 0;
2772 		map_slaves(codec, slaves, suffix,
2773 			   tlv ? init_slave_0dB : init_slave_unmute, &step);
2774 	}
2775 
2776 	if (ctl_ret)
2777 		*ctl_ret = kctl;
2778 	return 0;
2779 }
2780 EXPORT_SYMBOL_HDA(__snd_hda_add_vmaster);
2781 
2782 /*
2783  * mute-LED control using vmaster
2784  */
2785 static int vmaster_mute_mode_info(struct snd_kcontrol *kcontrol,
2786 				  struct snd_ctl_elem_info *uinfo)
2787 {
2788 	static const char * const texts[] = {
2789 		"On", "Off", "Follow Master"
2790 	};
2791 	unsigned int index;
2792 
2793 	uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
2794 	uinfo->count = 1;
2795 	uinfo->value.enumerated.items = 3;
2796 	index = uinfo->value.enumerated.item;
2797 	if (index >= 3)
2798 		index = 2;
2799 	strcpy(uinfo->value.enumerated.name, texts[index]);
2800 	return 0;
2801 }
2802 
2803 static int vmaster_mute_mode_get(struct snd_kcontrol *kcontrol,
2804 				 struct snd_ctl_elem_value *ucontrol)
2805 {
2806 	struct hda_vmaster_mute_hook *hook = snd_kcontrol_chip(kcontrol);
2807 	ucontrol->value.enumerated.item[0] = hook->mute_mode;
2808 	return 0;
2809 }
2810 
2811 static int vmaster_mute_mode_put(struct snd_kcontrol *kcontrol,
2812 				 struct snd_ctl_elem_value *ucontrol)
2813 {
2814 	struct hda_vmaster_mute_hook *hook = snd_kcontrol_chip(kcontrol);
2815 	unsigned int old_mode = hook->mute_mode;
2816 
2817 	hook->mute_mode = ucontrol->value.enumerated.item[0];
2818 	if (hook->mute_mode > HDA_VMUTE_FOLLOW_MASTER)
2819 		hook->mute_mode = HDA_VMUTE_FOLLOW_MASTER;
2820 	if (old_mode == hook->mute_mode)
2821 		return 0;
2822 	snd_hda_sync_vmaster_hook(hook);
2823 	return 1;
2824 }
2825 
2826 static struct snd_kcontrol_new vmaster_mute_mode = {
2827 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2828 	.name = "Mute-LED Mode",
2829 	.info = vmaster_mute_mode_info,
2830 	.get = vmaster_mute_mode_get,
2831 	.put = vmaster_mute_mode_put,
2832 };
2833 
2834 /*
2835  * Add a mute-LED hook with the given vmaster switch kctl
2836  * "Mute-LED Mode" control is automatically created and associated with
2837  * the given hook.
2838  */
2839 int snd_hda_add_vmaster_hook(struct hda_codec *codec,
2840 			     struct hda_vmaster_mute_hook *hook,
2841 			     bool expose_enum_ctl)
2842 {
2843 	struct snd_kcontrol *kctl;
2844 
2845 	if (!hook->hook || !hook->sw_kctl)
2846 		return 0;
2847 	snd_ctl_add_vmaster_hook(hook->sw_kctl, hook->hook, codec);
2848 	hook->codec = codec;
2849 	hook->mute_mode = HDA_VMUTE_FOLLOW_MASTER;
2850 	if (!expose_enum_ctl)
2851 		return 0;
2852 	kctl = snd_ctl_new1(&vmaster_mute_mode, hook);
2853 	if (!kctl)
2854 		return -ENOMEM;
2855 	return snd_hda_ctl_add(codec, 0, kctl);
2856 }
2857 EXPORT_SYMBOL_HDA(snd_hda_add_vmaster_hook);
2858 
2859 /*
2860  * Call the hook with the current value for synchronization
2861  * Should be called in init callback
2862  */
2863 void snd_hda_sync_vmaster_hook(struct hda_vmaster_mute_hook *hook)
2864 {
2865 	if (!hook->hook || !hook->codec)
2866 		return;
2867 	/* don't call vmaster hook in the destructor since it might have
2868 	 * been already destroyed
2869 	 */
2870 	if (hook->codec->bus->shutdown)
2871 		return;
2872 	switch (hook->mute_mode) {
2873 	case HDA_VMUTE_FOLLOW_MASTER:
2874 		snd_ctl_sync_vmaster_hook(hook->sw_kctl);
2875 		break;
2876 	default:
2877 		hook->hook(hook->codec, hook->mute_mode);
2878 		break;
2879 	}
2880 }
2881 EXPORT_SYMBOL_HDA(snd_hda_sync_vmaster_hook);
2882 
2883 
2884 /**
2885  * snd_hda_mixer_amp_switch_info - Info callback for a standard AMP mixer switch
2886  *
2887  * The control element is supposed to have the private_value field
2888  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2889  */
2890 int snd_hda_mixer_amp_switch_info(struct snd_kcontrol *kcontrol,
2891 				  struct snd_ctl_elem_info *uinfo)
2892 {
2893 	int chs = get_amp_channels(kcontrol);
2894 
2895 	uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2896 	uinfo->count = chs == 3 ? 2 : 1;
2897 	uinfo->value.integer.min = 0;
2898 	uinfo->value.integer.max = 1;
2899 	return 0;
2900 }
2901 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_info);
2902 
2903 /**
2904  * snd_hda_mixer_amp_switch_get - Get callback for a standard AMP mixer switch
2905  *
2906  * The control element is supposed to have the private_value field
2907  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2908  */
2909 int snd_hda_mixer_amp_switch_get(struct snd_kcontrol *kcontrol,
2910 				 struct snd_ctl_elem_value *ucontrol)
2911 {
2912 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2913 	hda_nid_t nid = get_amp_nid(kcontrol);
2914 	int chs = get_amp_channels(kcontrol);
2915 	int dir = get_amp_direction(kcontrol);
2916 	int idx = get_amp_index(kcontrol);
2917 	long *valp = ucontrol->value.integer.value;
2918 
2919 	if (chs & 1)
2920 		*valp++ = (snd_hda_codec_amp_read(codec, nid, 0, dir, idx) &
2921 			   HDA_AMP_MUTE) ? 0 : 1;
2922 	if (chs & 2)
2923 		*valp = (snd_hda_codec_amp_read(codec, nid, 1, dir, idx) &
2924 			 HDA_AMP_MUTE) ? 0 : 1;
2925 	return 0;
2926 }
2927 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_get);
2928 
2929 /**
2930  * snd_hda_mixer_amp_switch_put - Put callback for a standard AMP mixer switch
2931  *
2932  * The control element is supposed to have the private_value field
2933  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2934  */
2935 int snd_hda_mixer_amp_switch_put(struct snd_kcontrol *kcontrol,
2936 				 struct snd_ctl_elem_value *ucontrol)
2937 {
2938 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2939 	hda_nid_t nid = get_amp_nid(kcontrol);
2940 	int chs = get_amp_channels(kcontrol);
2941 	int dir = get_amp_direction(kcontrol);
2942 	int idx = get_amp_index(kcontrol);
2943 	long *valp = ucontrol->value.integer.value;
2944 	int change = 0;
2945 
2946 	snd_hda_power_up(codec);
2947 	if (chs & 1) {
2948 		change = snd_hda_codec_amp_update(codec, nid, 0, dir, idx,
2949 						  HDA_AMP_MUTE,
2950 						  *valp ? 0 : HDA_AMP_MUTE);
2951 		valp++;
2952 	}
2953 	if (chs & 2)
2954 		change |= snd_hda_codec_amp_update(codec, nid, 1, dir, idx,
2955 						   HDA_AMP_MUTE,
2956 						   *valp ? 0 : HDA_AMP_MUTE);
2957 	hda_call_check_power_status(codec, nid);
2958 	snd_hda_power_down(codec);
2959 	return change;
2960 }
2961 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_put);
2962 
2963 /*
2964  * bound volume controls
2965  *
2966  * bind multiple volumes (# indices, from 0)
2967  */
2968 
2969 #define AMP_VAL_IDX_SHIFT	19
2970 #define AMP_VAL_IDX_MASK	(0x0f<<19)
2971 
2972 /**
2973  * snd_hda_mixer_bind_switch_get - Get callback for a bound volume control
2974  *
2975  * The control element is supposed to have the private_value field
2976  * set up via HDA_BIND_MUTE*() macros.
2977  */
2978 int snd_hda_mixer_bind_switch_get(struct snd_kcontrol *kcontrol,
2979 				  struct snd_ctl_elem_value *ucontrol)
2980 {
2981 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2982 	unsigned long pval;
2983 	int err;
2984 
2985 	mutex_lock(&codec->control_mutex);
2986 	pval = kcontrol->private_value;
2987 	kcontrol->private_value = pval & ~AMP_VAL_IDX_MASK; /* index 0 */
2988 	err = snd_hda_mixer_amp_switch_get(kcontrol, ucontrol);
2989 	kcontrol->private_value = pval;
2990 	mutex_unlock(&codec->control_mutex);
2991 	return err;
2992 }
2993 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_switch_get);
2994 
2995 /**
2996  * snd_hda_mixer_bind_switch_put - Put callback for a bound volume control
2997  *
2998  * The control element is supposed to have the private_value field
2999  * set up via HDA_BIND_MUTE*() macros.
3000  */
3001 int snd_hda_mixer_bind_switch_put(struct snd_kcontrol *kcontrol,
3002 				  struct snd_ctl_elem_value *ucontrol)
3003 {
3004 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3005 	unsigned long pval;
3006 	int i, indices, err = 0, change = 0;
3007 
3008 	mutex_lock(&codec->control_mutex);
3009 	pval = kcontrol->private_value;
3010 	indices = (pval & AMP_VAL_IDX_MASK) >> AMP_VAL_IDX_SHIFT;
3011 	for (i = 0; i < indices; i++) {
3012 		kcontrol->private_value = (pval & ~AMP_VAL_IDX_MASK) |
3013 			(i << AMP_VAL_IDX_SHIFT);
3014 		err = snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
3015 		if (err < 0)
3016 			break;
3017 		change |= err;
3018 	}
3019 	kcontrol->private_value = pval;
3020 	mutex_unlock(&codec->control_mutex);
3021 	return err < 0 ? err : change;
3022 }
3023 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_switch_put);
3024 
3025 /**
3026  * snd_hda_mixer_bind_ctls_info - Info callback for a generic bound control
3027  *
3028  * The control element is supposed to have the private_value field
3029  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
3030  */
3031 int snd_hda_mixer_bind_ctls_info(struct snd_kcontrol *kcontrol,
3032 				 struct snd_ctl_elem_info *uinfo)
3033 {
3034 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3035 	struct hda_bind_ctls *c;
3036 	int err;
3037 
3038 	mutex_lock(&codec->control_mutex);
3039 	c = (struct hda_bind_ctls *)kcontrol->private_value;
3040 	kcontrol->private_value = *c->values;
3041 	err = c->ops->info(kcontrol, uinfo);
3042 	kcontrol->private_value = (long)c;
3043 	mutex_unlock(&codec->control_mutex);
3044 	return err;
3045 }
3046 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_ctls_info);
3047 
3048 /**
3049  * snd_hda_mixer_bind_ctls_get - Get callback for a generic bound control
3050  *
3051  * The control element is supposed to have the private_value field
3052  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
3053  */
3054 int snd_hda_mixer_bind_ctls_get(struct snd_kcontrol *kcontrol,
3055 				struct snd_ctl_elem_value *ucontrol)
3056 {
3057 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3058 	struct hda_bind_ctls *c;
3059 	int err;
3060 
3061 	mutex_lock(&codec->control_mutex);
3062 	c = (struct hda_bind_ctls *)kcontrol->private_value;
3063 	kcontrol->private_value = *c->values;
3064 	err = c->ops->get(kcontrol, ucontrol);
3065 	kcontrol->private_value = (long)c;
3066 	mutex_unlock(&codec->control_mutex);
3067 	return err;
3068 }
3069 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_ctls_get);
3070 
3071 /**
3072  * snd_hda_mixer_bind_ctls_put - Put callback for a generic bound control
3073  *
3074  * The control element is supposed to have the private_value field
3075  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
3076  */
3077 int snd_hda_mixer_bind_ctls_put(struct snd_kcontrol *kcontrol,
3078 				struct snd_ctl_elem_value *ucontrol)
3079 {
3080 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3081 	struct hda_bind_ctls *c;
3082 	unsigned long *vals;
3083 	int err = 0, change = 0;
3084 
3085 	mutex_lock(&codec->control_mutex);
3086 	c = (struct hda_bind_ctls *)kcontrol->private_value;
3087 	for (vals = c->values; *vals; vals++) {
3088 		kcontrol->private_value = *vals;
3089 		err = c->ops->put(kcontrol, ucontrol);
3090 		if (err < 0)
3091 			break;
3092 		change |= err;
3093 	}
3094 	kcontrol->private_value = (long)c;
3095 	mutex_unlock(&codec->control_mutex);
3096 	return err < 0 ? err : change;
3097 }
3098 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_ctls_put);
3099 
3100 /**
3101  * snd_hda_mixer_bind_tlv - TLV callback for a generic bound control
3102  *
3103  * The control element is supposed to have the private_value field
3104  * set up via HDA_BIND_VOL() macro.
3105  */
3106 int snd_hda_mixer_bind_tlv(struct snd_kcontrol *kcontrol, int op_flag,
3107 			   unsigned int size, unsigned int __user *tlv)
3108 {
3109 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3110 	struct hda_bind_ctls *c;
3111 	int err;
3112 
3113 	mutex_lock(&codec->control_mutex);
3114 	c = (struct hda_bind_ctls *)kcontrol->private_value;
3115 	kcontrol->private_value = *c->values;
3116 	err = c->ops->tlv(kcontrol, op_flag, size, tlv);
3117 	kcontrol->private_value = (long)c;
3118 	mutex_unlock(&codec->control_mutex);
3119 	return err;
3120 }
3121 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_tlv);
3122 
3123 struct hda_ctl_ops snd_hda_bind_vol = {
3124 	.info = snd_hda_mixer_amp_volume_info,
3125 	.get = snd_hda_mixer_amp_volume_get,
3126 	.put = snd_hda_mixer_amp_volume_put,
3127 	.tlv = snd_hda_mixer_amp_tlv
3128 };
3129 EXPORT_SYMBOL_HDA(snd_hda_bind_vol);
3130 
3131 struct hda_ctl_ops snd_hda_bind_sw = {
3132 	.info = snd_hda_mixer_amp_switch_info,
3133 	.get = snd_hda_mixer_amp_switch_get,
3134 	.put = snd_hda_mixer_amp_switch_put,
3135 	.tlv = snd_hda_mixer_amp_tlv
3136 };
3137 EXPORT_SYMBOL_HDA(snd_hda_bind_sw);
3138 
3139 /*
3140  * SPDIF out controls
3141  */
3142 
3143 static int snd_hda_spdif_mask_info(struct snd_kcontrol *kcontrol,
3144 				   struct snd_ctl_elem_info *uinfo)
3145 {
3146 	uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
3147 	uinfo->count = 1;
3148 	return 0;
3149 }
3150 
3151 static int snd_hda_spdif_cmask_get(struct snd_kcontrol *kcontrol,
3152 				   struct snd_ctl_elem_value *ucontrol)
3153 {
3154 	ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
3155 					   IEC958_AES0_NONAUDIO |
3156 					   IEC958_AES0_CON_EMPHASIS_5015 |
3157 					   IEC958_AES0_CON_NOT_COPYRIGHT;
3158 	ucontrol->value.iec958.status[1] = IEC958_AES1_CON_CATEGORY |
3159 					   IEC958_AES1_CON_ORIGINAL;
3160 	return 0;
3161 }
3162 
3163 static int snd_hda_spdif_pmask_get(struct snd_kcontrol *kcontrol,
3164 				   struct snd_ctl_elem_value *ucontrol)
3165 {
3166 	ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
3167 					   IEC958_AES0_NONAUDIO |
3168 					   IEC958_AES0_PRO_EMPHASIS_5015;
3169 	return 0;
3170 }
3171 
3172 static int snd_hda_spdif_default_get(struct snd_kcontrol *kcontrol,
3173 				     struct snd_ctl_elem_value *ucontrol)
3174 {
3175 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3176 	int idx = kcontrol->private_value;
3177 	struct hda_spdif_out *spdif;
3178 
3179 	mutex_lock(&codec->spdif_mutex);
3180 	spdif = snd_array_elem(&codec->spdif_out, idx);
3181 	ucontrol->value.iec958.status[0] = spdif->status & 0xff;
3182 	ucontrol->value.iec958.status[1] = (spdif->status >> 8) & 0xff;
3183 	ucontrol->value.iec958.status[2] = (spdif->status >> 16) & 0xff;
3184 	ucontrol->value.iec958.status[3] = (spdif->status >> 24) & 0xff;
3185 	mutex_unlock(&codec->spdif_mutex);
3186 
3187 	return 0;
3188 }
3189 
3190 /* convert from SPDIF status bits to HDA SPDIF bits
3191  * bit 0 (DigEn) is always set zero (to be filled later)
3192  */
3193 static unsigned short convert_from_spdif_status(unsigned int sbits)
3194 {
3195 	unsigned short val = 0;
3196 
3197 	if (sbits & IEC958_AES0_PROFESSIONAL)
3198 		val |= AC_DIG1_PROFESSIONAL;
3199 	if (sbits & IEC958_AES0_NONAUDIO)
3200 		val |= AC_DIG1_NONAUDIO;
3201 	if (sbits & IEC958_AES0_PROFESSIONAL) {
3202 		if ((sbits & IEC958_AES0_PRO_EMPHASIS) ==
3203 		    IEC958_AES0_PRO_EMPHASIS_5015)
3204 			val |= AC_DIG1_EMPHASIS;
3205 	} else {
3206 		if ((sbits & IEC958_AES0_CON_EMPHASIS) ==
3207 		    IEC958_AES0_CON_EMPHASIS_5015)
3208 			val |= AC_DIG1_EMPHASIS;
3209 		if (!(sbits & IEC958_AES0_CON_NOT_COPYRIGHT))
3210 			val |= AC_DIG1_COPYRIGHT;
3211 		if (sbits & (IEC958_AES1_CON_ORIGINAL << 8))
3212 			val |= AC_DIG1_LEVEL;
3213 		val |= sbits & (IEC958_AES1_CON_CATEGORY << 8);
3214 	}
3215 	return val;
3216 }
3217 
3218 /* convert to SPDIF status bits from HDA SPDIF bits
3219  */
3220 static unsigned int convert_to_spdif_status(unsigned short val)
3221 {
3222 	unsigned int sbits = 0;
3223 
3224 	if (val & AC_DIG1_NONAUDIO)
3225 		sbits |= IEC958_AES0_NONAUDIO;
3226 	if (val & AC_DIG1_PROFESSIONAL)
3227 		sbits |= IEC958_AES0_PROFESSIONAL;
3228 	if (sbits & IEC958_AES0_PROFESSIONAL) {
3229 		if (val & AC_DIG1_EMPHASIS)
3230 			sbits |= IEC958_AES0_PRO_EMPHASIS_5015;
3231 	} else {
3232 		if (val & AC_DIG1_EMPHASIS)
3233 			sbits |= IEC958_AES0_CON_EMPHASIS_5015;
3234 		if (!(val & AC_DIG1_COPYRIGHT))
3235 			sbits |= IEC958_AES0_CON_NOT_COPYRIGHT;
3236 		if (val & AC_DIG1_LEVEL)
3237 			sbits |= (IEC958_AES1_CON_ORIGINAL << 8);
3238 		sbits |= val & (0x7f << 8);
3239 	}
3240 	return sbits;
3241 }
3242 
3243 /* set digital convert verbs both for the given NID and its slaves */
3244 static void set_dig_out(struct hda_codec *codec, hda_nid_t nid,
3245 			int verb, int val)
3246 {
3247 	const hda_nid_t *d;
3248 
3249 	snd_hda_codec_write_cache(codec, nid, 0, verb, val);
3250 	d = codec->slave_dig_outs;
3251 	if (!d)
3252 		return;
3253 	for (; *d; d++)
3254 		snd_hda_codec_write_cache(codec, *d, 0, verb, val);
3255 }
3256 
3257 static inline void set_dig_out_convert(struct hda_codec *codec, hda_nid_t nid,
3258 				       int dig1, int dig2)
3259 {
3260 	if (dig1 != -1)
3261 		set_dig_out(codec, nid, AC_VERB_SET_DIGI_CONVERT_1, dig1);
3262 	if (dig2 != -1)
3263 		set_dig_out(codec, nid, AC_VERB_SET_DIGI_CONVERT_2, dig2);
3264 }
3265 
3266 static int snd_hda_spdif_default_put(struct snd_kcontrol *kcontrol,
3267 				     struct snd_ctl_elem_value *ucontrol)
3268 {
3269 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3270 	int idx = kcontrol->private_value;
3271 	struct hda_spdif_out *spdif;
3272 	hda_nid_t nid;
3273 	unsigned short val;
3274 	int change;
3275 
3276 	mutex_lock(&codec->spdif_mutex);
3277 	spdif = snd_array_elem(&codec->spdif_out, idx);
3278 	nid = spdif->nid;
3279 	spdif->status = ucontrol->value.iec958.status[0] |
3280 		((unsigned int)ucontrol->value.iec958.status[1] << 8) |
3281 		((unsigned int)ucontrol->value.iec958.status[2] << 16) |
3282 		((unsigned int)ucontrol->value.iec958.status[3] << 24);
3283 	val = convert_from_spdif_status(spdif->status);
3284 	val |= spdif->ctls & 1;
3285 	change = spdif->ctls != val;
3286 	spdif->ctls = val;
3287 	if (change && nid != (u16)-1)
3288 		set_dig_out_convert(codec, nid, val & 0xff, (val >> 8) & 0xff);
3289 	mutex_unlock(&codec->spdif_mutex);
3290 	return change;
3291 }
3292 
3293 #define snd_hda_spdif_out_switch_info	snd_ctl_boolean_mono_info
3294 
3295 static int snd_hda_spdif_out_switch_get(struct snd_kcontrol *kcontrol,
3296 					struct snd_ctl_elem_value *ucontrol)
3297 {
3298 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3299 	int idx = kcontrol->private_value;
3300 	struct hda_spdif_out *spdif;
3301 
3302 	mutex_lock(&codec->spdif_mutex);
3303 	spdif = snd_array_elem(&codec->spdif_out, idx);
3304 	ucontrol->value.integer.value[0] = spdif->ctls & AC_DIG1_ENABLE;
3305 	mutex_unlock(&codec->spdif_mutex);
3306 	return 0;
3307 }
3308 
3309 static inline void set_spdif_ctls(struct hda_codec *codec, hda_nid_t nid,
3310 				  int dig1, int dig2)
3311 {
3312 	set_dig_out_convert(codec, nid, dig1, dig2);
3313 	/* unmute amp switch (if any) */
3314 	if ((get_wcaps(codec, nid) & AC_WCAP_OUT_AMP) &&
3315 	    (dig1 & AC_DIG1_ENABLE))
3316 		snd_hda_codec_amp_stereo(codec, nid, HDA_OUTPUT, 0,
3317 					    HDA_AMP_MUTE, 0);
3318 }
3319 
3320 static int snd_hda_spdif_out_switch_put(struct snd_kcontrol *kcontrol,
3321 					struct snd_ctl_elem_value *ucontrol)
3322 {
3323 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3324 	int idx = kcontrol->private_value;
3325 	struct hda_spdif_out *spdif;
3326 	hda_nid_t nid;
3327 	unsigned short val;
3328 	int change;
3329 
3330 	mutex_lock(&codec->spdif_mutex);
3331 	spdif = snd_array_elem(&codec->spdif_out, idx);
3332 	nid = spdif->nid;
3333 	val = spdif->ctls & ~AC_DIG1_ENABLE;
3334 	if (ucontrol->value.integer.value[0])
3335 		val |= AC_DIG1_ENABLE;
3336 	change = spdif->ctls != val;
3337 	spdif->ctls = val;
3338 	if (change && nid != (u16)-1)
3339 		set_spdif_ctls(codec, nid, val & 0xff, -1);
3340 	mutex_unlock(&codec->spdif_mutex);
3341 	return change;
3342 }
3343 
3344 static struct snd_kcontrol_new dig_mixes[] = {
3345 	{
3346 		.access = SNDRV_CTL_ELEM_ACCESS_READ,
3347 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3348 		.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, CON_MASK),
3349 		.info = snd_hda_spdif_mask_info,
3350 		.get = snd_hda_spdif_cmask_get,
3351 	},
3352 	{
3353 		.access = SNDRV_CTL_ELEM_ACCESS_READ,
3354 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3355 		.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, PRO_MASK),
3356 		.info = snd_hda_spdif_mask_info,
3357 		.get = snd_hda_spdif_pmask_get,
3358 	},
3359 	{
3360 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3361 		.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, DEFAULT),
3362 		.info = snd_hda_spdif_mask_info,
3363 		.get = snd_hda_spdif_default_get,
3364 		.put = snd_hda_spdif_default_put,
3365 	},
3366 	{
3367 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3368 		.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, SWITCH),
3369 		.info = snd_hda_spdif_out_switch_info,
3370 		.get = snd_hda_spdif_out_switch_get,
3371 		.put = snd_hda_spdif_out_switch_put,
3372 	},
3373 	{ } /* end */
3374 };
3375 
3376 /**
3377  * snd_hda_create_dig_out_ctls - create Output SPDIF-related controls
3378  * @codec: the HDA codec
3379  * @associated_nid: NID that new ctls associated with
3380  * @cvt_nid: converter NID
3381  * @type: HDA_PCM_TYPE_*
3382  * Creates controls related with the digital output.
3383  * Called from each patch supporting the digital out.
3384  *
3385  * Returns 0 if successful, or a negative error code.
3386  */
3387 int snd_hda_create_dig_out_ctls(struct hda_codec *codec,
3388 				hda_nid_t associated_nid,
3389 				hda_nid_t cvt_nid,
3390 				int type)
3391 {
3392 	int err;
3393 	struct snd_kcontrol *kctl;
3394 	struct snd_kcontrol_new *dig_mix;
3395 	int idx = 0;
3396 	const int spdif_index = 16;
3397 	struct hda_spdif_out *spdif;
3398 	struct hda_bus *bus = codec->bus;
3399 
3400 	if (bus->primary_dig_out_type == HDA_PCM_TYPE_HDMI &&
3401 	    type == HDA_PCM_TYPE_SPDIF) {
3402 		idx = spdif_index;
3403 	} else if (bus->primary_dig_out_type == HDA_PCM_TYPE_SPDIF &&
3404 		   type == HDA_PCM_TYPE_HDMI) {
3405 		/* suppose a single SPDIF device */
3406 		for (dig_mix = dig_mixes; dig_mix->name; dig_mix++) {
3407 			kctl = find_mixer_ctl(codec, dig_mix->name, 0, 0);
3408 			if (!kctl)
3409 				break;
3410 			kctl->id.index = spdif_index;
3411 		}
3412 		bus->primary_dig_out_type = HDA_PCM_TYPE_HDMI;
3413 	}
3414 	if (!bus->primary_dig_out_type)
3415 		bus->primary_dig_out_type = type;
3416 
3417 	idx = find_empty_mixer_ctl_idx(codec, "IEC958 Playback Switch", idx);
3418 	if (idx < 0) {
3419 		printk(KERN_ERR "hda_codec: too many IEC958 outputs\n");
3420 		return -EBUSY;
3421 	}
3422 	spdif = snd_array_new(&codec->spdif_out);
3423 	if (!spdif)
3424 		return -ENOMEM;
3425 	for (dig_mix = dig_mixes; dig_mix->name; dig_mix++) {
3426 		kctl = snd_ctl_new1(dig_mix, codec);
3427 		if (!kctl)
3428 			return -ENOMEM;
3429 		kctl->id.index = idx;
3430 		kctl->private_value = codec->spdif_out.used - 1;
3431 		err = snd_hda_ctl_add(codec, associated_nid, kctl);
3432 		if (err < 0)
3433 			return err;
3434 	}
3435 	spdif->nid = cvt_nid;
3436 	spdif->ctls = snd_hda_codec_read(codec, cvt_nid, 0,
3437 					 AC_VERB_GET_DIGI_CONVERT_1, 0);
3438 	spdif->status = convert_to_spdif_status(spdif->ctls);
3439 	return 0;
3440 }
3441 EXPORT_SYMBOL_HDA(snd_hda_create_dig_out_ctls);
3442 
3443 /* get the hda_spdif_out entry from the given NID
3444  * call within spdif_mutex lock
3445  */
3446 struct hda_spdif_out *snd_hda_spdif_out_of_nid(struct hda_codec *codec,
3447 					       hda_nid_t nid)
3448 {
3449 	int i;
3450 	for (i = 0; i < codec->spdif_out.used; i++) {
3451 		struct hda_spdif_out *spdif =
3452 				snd_array_elem(&codec->spdif_out, i);
3453 		if (spdif->nid == nid)
3454 			return spdif;
3455 	}
3456 	return NULL;
3457 }
3458 EXPORT_SYMBOL_HDA(snd_hda_spdif_out_of_nid);
3459 
3460 void snd_hda_spdif_ctls_unassign(struct hda_codec *codec, int idx)
3461 {
3462 	struct hda_spdif_out *spdif;
3463 
3464 	mutex_lock(&codec->spdif_mutex);
3465 	spdif = snd_array_elem(&codec->spdif_out, idx);
3466 	spdif->nid = (u16)-1;
3467 	mutex_unlock(&codec->spdif_mutex);
3468 }
3469 EXPORT_SYMBOL_HDA(snd_hda_spdif_ctls_unassign);
3470 
3471 void snd_hda_spdif_ctls_assign(struct hda_codec *codec, int idx, hda_nid_t nid)
3472 {
3473 	struct hda_spdif_out *spdif;
3474 	unsigned short val;
3475 
3476 	mutex_lock(&codec->spdif_mutex);
3477 	spdif = snd_array_elem(&codec->spdif_out, idx);
3478 	if (spdif->nid != nid) {
3479 		spdif->nid = nid;
3480 		val = spdif->ctls;
3481 		set_spdif_ctls(codec, nid, val & 0xff, (val >> 8) & 0xff);
3482 	}
3483 	mutex_unlock(&codec->spdif_mutex);
3484 }
3485 EXPORT_SYMBOL_HDA(snd_hda_spdif_ctls_assign);
3486 
3487 /*
3488  * SPDIF sharing with analog output
3489  */
3490 static int spdif_share_sw_get(struct snd_kcontrol *kcontrol,
3491 			      struct snd_ctl_elem_value *ucontrol)
3492 {
3493 	struct hda_multi_out *mout = snd_kcontrol_chip(kcontrol);
3494 	ucontrol->value.integer.value[0] = mout->share_spdif;
3495 	return 0;
3496 }
3497 
3498 static int spdif_share_sw_put(struct snd_kcontrol *kcontrol,
3499 			      struct snd_ctl_elem_value *ucontrol)
3500 {
3501 	struct hda_multi_out *mout = snd_kcontrol_chip(kcontrol);
3502 	mout->share_spdif = !!ucontrol->value.integer.value[0];
3503 	return 0;
3504 }
3505 
3506 static struct snd_kcontrol_new spdif_share_sw = {
3507 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3508 	.name = "IEC958 Default PCM Playback Switch",
3509 	.info = snd_ctl_boolean_mono_info,
3510 	.get = spdif_share_sw_get,
3511 	.put = spdif_share_sw_put,
3512 };
3513 
3514 /**
3515  * snd_hda_create_spdif_share_sw - create Default PCM switch
3516  * @codec: the HDA codec
3517  * @mout: multi-out instance
3518  */
3519 int snd_hda_create_spdif_share_sw(struct hda_codec *codec,
3520 				  struct hda_multi_out *mout)
3521 {
3522 	struct snd_kcontrol *kctl;
3523 
3524 	if (!mout->dig_out_nid)
3525 		return 0;
3526 
3527 	kctl = snd_ctl_new1(&spdif_share_sw, mout);
3528 	if (!kctl)
3529 		return -ENOMEM;
3530 	/* ATTENTION: here mout is passed as private_data, instead of codec */
3531 	return snd_hda_ctl_add(codec, mout->dig_out_nid, kctl);
3532 }
3533 EXPORT_SYMBOL_HDA(snd_hda_create_spdif_share_sw);
3534 
3535 /*
3536  * SPDIF input
3537  */
3538 
3539 #define snd_hda_spdif_in_switch_info	snd_hda_spdif_out_switch_info
3540 
3541 static int snd_hda_spdif_in_switch_get(struct snd_kcontrol *kcontrol,
3542 				       struct snd_ctl_elem_value *ucontrol)
3543 {
3544 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3545 
3546 	ucontrol->value.integer.value[0] = codec->spdif_in_enable;
3547 	return 0;
3548 }
3549 
3550 static int snd_hda_spdif_in_switch_put(struct snd_kcontrol *kcontrol,
3551 				       struct snd_ctl_elem_value *ucontrol)
3552 {
3553 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3554 	hda_nid_t nid = kcontrol->private_value;
3555 	unsigned int val = !!ucontrol->value.integer.value[0];
3556 	int change;
3557 
3558 	mutex_lock(&codec->spdif_mutex);
3559 	change = codec->spdif_in_enable != val;
3560 	if (change) {
3561 		codec->spdif_in_enable = val;
3562 		snd_hda_codec_write_cache(codec, nid, 0,
3563 					  AC_VERB_SET_DIGI_CONVERT_1, val);
3564 	}
3565 	mutex_unlock(&codec->spdif_mutex);
3566 	return change;
3567 }
3568 
3569 static int snd_hda_spdif_in_status_get(struct snd_kcontrol *kcontrol,
3570 				       struct snd_ctl_elem_value *ucontrol)
3571 {
3572 	struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3573 	hda_nid_t nid = kcontrol->private_value;
3574 	unsigned short val;
3575 	unsigned int sbits;
3576 
3577 	val = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_DIGI_CONVERT_1, 0);
3578 	sbits = convert_to_spdif_status(val);
3579 	ucontrol->value.iec958.status[0] = sbits;
3580 	ucontrol->value.iec958.status[1] = sbits >> 8;
3581 	ucontrol->value.iec958.status[2] = sbits >> 16;
3582 	ucontrol->value.iec958.status[3] = sbits >> 24;
3583 	return 0;
3584 }
3585 
3586 static struct snd_kcontrol_new dig_in_ctls[] = {
3587 	{
3588 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3589 		.name = SNDRV_CTL_NAME_IEC958("", CAPTURE, SWITCH),
3590 		.info = snd_hda_spdif_in_switch_info,
3591 		.get = snd_hda_spdif_in_switch_get,
3592 		.put = snd_hda_spdif_in_switch_put,
3593 	},
3594 	{
3595 		.access = SNDRV_CTL_ELEM_ACCESS_READ,
3596 		.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3597 		.name = SNDRV_CTL_NAME_IEC958("", CAPTURE, DEFAULT),
3598 		.info = snd_hda_spdif_mask_info,
3599 		.get = snd_hda_spdif_in_status_get,
3600 	},
3601 	{ } /* end */
3602 };
3603 
3604 /**
3605  * snd_hda_create_spdif_in_ctls - create Input SPDIF-related controls
3606  * @codec: the HDA codec
3607  * @nid: audio in widget NID
3608  *
3609  * Creates controls related with the SPDIF input.
3610  * Called from each patch supporting the SPDIF in.
3611  *
3612  * Returns 0 if successful, or a negative error code.
3613  */
3614 int snd_hda_create_spdif_in_ctls(struct hda_codec *codec, hda_nid_t nid)
3615 {
3616 	int err;
3617 	struct snd_kcontrol *kctl;
3618 	struct snd_kcontrol_new *dig_mix;
3619 	int idx;
3620 
3621 	idx = find_empty_mixer_ctl_idx(codec, "IEC958 Capture Switch", 0);
3622 	if (idx < 0) {
3623 		printk(KERN_ERR "hda_codec: too many IEC958 inputs\n");
3624 		return -EBUSY;
3625 	}
3626 	for (dig_mix = dig_in_ctls; dig_mix->name; dig_mix++) {
3627 		kctl = snd_ctl_new1(dig_mix, codec);
3628 		if (!kctl)
3629 			return -ENOMEM;
3630 		kctl->private_value = nid;
3631 		err = snd_hda_ctl_add(codec, nid, kctl);
3632 		if (err < 0)
3633 			return err;
3634 	}
3635 	codec->spdif_in_enable =
3636 		snd_hda_codec_read(codec, nid, 0,
3637 				   AC_VERB_GET_DIGI_CONVERT_1, 0) &
3638 		AC_DIG1_ENABLE;
3639 	return 0;
3640 }
3641 EXPORT_SYMBOL_HDA(snd_hda_create_spdif_in_ctls);
3642 
3643 /*
3644  * command cache
3645  */
3646 
3647 /* build a 31bit cache key with the widget id and the command parameter */
3648 #define build_cmd_cache_key(nid, verb)	((verb << 8) | nid)
3649 #define get_cmd_cache_nid(key)		((key) & 0xff)
3650 #define get_cmd_cache_cmd(key)		(((key) >> 8) & 0xffff)
3651 
3652 /**
3653  * snd_hda_codec_write_cache - send a single command with caching
3654  * @codec: the HDA codec
3655  * @nid: NID to send the command
3656  * @flags: optional bit flags
3657  * @verb: the verb to send
3658  * @parm: the parameter for the verb
3659  *
3660  * Send a single command without waiting for response.
3661  *
3662  * Returns 0 if successful, or a negative error code.
3663  */
3664 int snd_hda_codec_write_cache(struct hda_codec *codec, hda_nid_t nid,
3665 			      int flags, unsigned int verb, unsigned int parm)
3666 {
3667 	int err;
3668 	struct hda_cache_head *c;
3669 	u32 key;
3670 	unsigned int cache_only;
3671 
3672 	cache_only = codec->cached_write;
3673 	if (!cache_only) {
3674 		err = snd_hda_codec_write(codec, nid, flags, verb, parm);
3675 		if (err < 0)
3676 			return err;
3677 	}
3678 
3679 	/* parm may contain the verb stuff for get/set amp */
3680 	verb = verb | (parm >> 8);
3681 	parm &= 0xff;
3682 	key = build_cmd_cache_key(nid, verb);
3683 	mutex_lock(&codec->bus->cmd_mutex);
3684 	c = get_alloc_hash(&codec->cmd_cache, key);
3685 	if (c) {
3686 		c->val = parm;
3687 		c->dirty = cache_only;
3688 	}
3689 	mutex_unlock(&codec->bus->cmd_mutex);
3690 	return 0;
3691 }
3692 EXPORT_SYMBOL_HDA(snd_hda_codec_write_cache);
3693 
3694 /**
3695  * snd_hda_codec_update_cache - check cache and write the cmd only when needed
3696  * @codec: the HDA codec
3697  * @nid: NID to send the command
3698  * @flags: optional bit flags
3699  * @verb: the verb to send
3700  * @parm: the parameter for the verb
3701  *
3702  * This function works like snd_hda_codec_write_cache(), but it doesn't send
3703  * command if the parameter is already identical with the cached value.
3704  * If not, it sends the command and refreshes the cache.
3705  *
3706  * Returns 0 if successful, or a negative error code.
3707  */
3708 int snd_hda_codec_update_cache(struct hda_codec *codec, hda_nid_t nid,
3709 			       int flags, unsigned int verb, unsigned int parm)
3710 {
3711 	struct hda_cache_head *c;
3712 	u32 key;
3713 
3714 	/* parm may contain the verb stuff for get/set amp */
3715 	verb = verb | (parm >> 8);
3716 	parm &= 0xff;
3717 	key = build_cmd_cache_key(nid, verb);
3718 	mutex_lock(&codec->bus->cmd_mutex);
3719 	c = get_hash(&codec->cmd_cache, key);
3720 	if (c && c->val == parm) {
3721 		mutex_unlock(&codec->bus->cmd_mutex);
3722 		return 0;
3723 	}
3724 	mutex_unlock(&codec->bus->cmd_mutex);
3725 	return snd_hda_codec_write_cache(codec, nid, flags, verb, parm);
3726 }
3727 EXPORT_SYMBOL_HDA(snd_hda_codec_update_cache);
3728 
3729 /**
3730  * snd_hda_codec_resume_cache - Resume the all commands from the cache
3731  * @codec: HD-audio codec
3732  *
3733  * Execute all verbs recorded in the command caches to resume.
3734  */
3735 void snd_hda_codec_resume_cache(struct hda_codec *codec)
3736 {
3737 	int i;
3738 
3739 	mutex_lock(&codec->hash_mutex);
3740 	codec->cached_write = 0;
3741 	for (i = 0; i < codec->cmd_cache.buf.used; i++) {
3742 		struct hda_cache_head *buffer;
3743 		u32 key;
3744 
3745 		buffer = snd_array_elem(&codec->cmd_cache.buf, i);
3746 		key = buffer->key;
3747 		if (!key)
3748 			continue;
3749 		if (!buffer->dirty)
3750 			continue;
3751 		buffer->dirty = 0;
3752 		mutex_unlock(&codec->hash_mutex);
3753 		snd_hda_codec_write(codec, get_cmd_cache_nid(key), 0,
3754 				    get_cmd_cache_cmd(key), buffer->val);
3755 		mutex_lock(&codec->hash_mutex);
3756 	}
3757 	mutex_unlock(&codec->hash_mutex);
3758 }
3759 EXPORT_SYMBOL_HDA(snd_hda_codec_resume_cache);
3760 
3761 /**
3762  * snd_hda_sequence_write_cache - sequence writes with caching
3763  * @codec: the HDA codec
3764  * @seq: VERB array to send
3765  *
3766  * Send the commands sequentially from the given array.
3767  * Thte commands are recorded on cache for power-save and resume.
3768  * The array must be terminated with NID=0.
3769  */
3770 void snd_hda_sequence_write_cache(struct hda_codec *codec,
3771 				  const struct hda_verb *seq)
3772 {
3773 	for (; seq->nid; seq++)
3774 		snd_hda_codec_write_cache(codec, seq->nid, 0, seq->verb,
3775 					  seq->param);
3776 }
3777 EXPORT_SYMBOL_HDA(snd_hda_sequence_write_cache);
3778 
3779 /**
3780  * snd_hda_codec_flush_cache - Execute all pending (cached) amps / verbs
3781  * @codec: HD-audio codec
3782  */
3783 void snd_hda_codec_flush_cache(struct hda_codec *codec)
3784 {
3785 	snd_hda_codec_resume_amp(codec);
3786 	snd_hda_codec_resume_cache(codec);
3787 }
3788 EXPORT_SYMBOL_HDA(snd_hda_codec_flush_cache);
3789 
3790 void snd_hda_codec_set_power_to_all(struct hda_codec *codec, hda_nid_t fg,
3791 				    unsigned int power_state)
3792 {
3793 	hda_nid_t nid = codec->start_nid;
3794 	int i;
3795 
3796 	for (i = 0; i < codec->num_nodes; i++, nid++) {
3797 		unsigned int wcaps = get_wcaps(codec, nid);
3798 		unsigned int state = power_state;
3799 		if (!(wcaps & AC_WCAP_POWER))
3800 			continue;
3801 		if (codec->power_filter) {
3802 			state = codec->power_filter(codec, nid, power_state);
3803 			if (state != power_state && power_state == AC_PWRST_D3)
3804 				continue;
3805 		}
3806 		snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_POWER_STATE,
3807 				    state);
3808 	}
3809 }
3810 EXPORT_SYMBOL_HDA(snd_hda_codec_set_power_to_all);
3811 
3812 /*
3813  *  supported power states check
3814  */
3815 static bool snd_hda_codec_get_supported_ps(struct hda_codec *codec, hda_nid_t fg,
3816 				unsigned int power_state)
3817 {
3818 	int sup = snd_hda_param_read(codec, fg, AC_PAR_POWER_STATE);
3819 
3820 	if (sup == -1)
3821 		return false;
3822 	if (sup & power_state)
3823 		return true;
3824 	else
3825 		return false;
3826 }
3827 
3828 /*
3829  * wait until the state is reached, returns the current state
3830  */
3831 static unsigned int hda_sync_power_state(struct hda_codec *codec,
3832 					 hda_nid_t fg,
3833 					 unsigned int power_state)
3834 {
3835 	unsigned long end_time = jiffies + msecs_to_jiffies(500);
3836 	unsigned int state, actual_state;
3837 
3838 	for (;;) {
3839 		state = snd_hda_codec_read(codec, fg, 0,
3840 					   AC_VERB_GET_POWER_STATE, 0);
3841 		if (state & AC_PWRST_ERROR)
3842 			break;
3843 		actual_state = (state >> 4) & 0x0f;
3844 		if (actual_state == power_state)
3845 			break;
3846 		if (time_after_eq(jiffies, end_time))
3847 			break;
3848 		/* wait until the codec reachs to the target state */
3849 		msleep(1);
3850 	}
3851 	return state;
3852 }
3853 
3854 /* don't power down the widget if it controls eapd and EAPD_BTLENABLE is set */
3855 unsigned int snd_hda_codec_eapd_power_filter(struct hda_codec *codec,
3856 					     hda_nid_t nid,
3857 					     unsigned int power_state)
3858 {
3859 	if (power_state == AC_PWRST_D3 &&
3860 	    get_wcaps_type(get_wcaps(codec, nid)) == AC_WID_PIN &&
3861 	    (snd_hda_query_pin_caps(codec, nid) & AC_PINCAP_EAPD)) {
3862 		int eapd = snd_hda_codec_read(codec, nid, 0,
3863 					      AC_VERB_GET_EAPD_BTLENABLE, 0);
3864 		if (eapd & 0x02)
3865 			return AC_PWRST_D0;
3866 	}
3867 	return power_state;
3868 }
3869 EXPORT_SYMBOL_HDA(snd_hda_codec_eapd_power_filter);
3870 
3871 /*
3872  * set power state of the codec, and return the power state
3873  */
3874 static unsigned int hda_set_power_state(struct hda_codec *codec,
3875 					unsigned int power_state)
3876 {
3877 	hda_nid_t fg = codec->afg ? codec->afg : codec->mfg;
3878 	int count;
3879 	unsigned int state;
3880 	int flags = 0;
3881 
3882 	/* this delay seems necessary to avoid click noise at power-down */
3883 	if (power_state == AC_PWRST_D3) {
3884 		/* transition time less than 10ms for power down */
3885 		msleep(codec->epss ? 10 : 100);
3886 		flags = HDA_RW_NO_RESPONSE_FALLBACK;
3887 	}
3888 
3889 	/* repeat power states setting at most 10 times*/
3890 	for (count = 0; count < 10; count++) {
3891 		if (codec->patch_ops.set_power_state)
3892 			codec->patch_ops.set_power_state(codec, fg,
3893 							 power_state);
3894 		else {
3895 			snd_hda_codec_read(codec, fg, flags,
3896 					   AC_VERB_SET_POWER_STATE,
3897 					   power_state);
3898 			snd_hda_codec_set_power_to_all(codec, fg, power_state);
3899 		}
3900 		state = hda_sync_power_state(codec, fg, power_state);
3901 		if (!(state & AC_PWRST_ERROR))
3902 			break;
3903 	}
3904 
3905 	return state;
3906 }
3907 
3908 /* sync power states of all widgets;
3909  * this is called at the end of codec parsing
3910  */
3911 static void sync_power_up_states(struct hda_codec *codec)
3912 {
3913 	hda_nid_t nid = codec->start_nid;
3914 	int i;
3915 
3916 	/* don't care if no filter is used */
3917 	if (!codec->power_filter)
3918 		return;
3919 
3920 	for (i = 0; i < codec->num_nodes; i++, nid++) {
3921 		unsigned int wcaps = get_wcaps(codec, nid);
3922 		unsigned int target;
3923 		if (!(wcaps & AC_WCAP_POWER))
3924 			continue;
3925 		target = codec->power_filter(codec, nid, AC_PWRST_D0);
3926 		if (target == AC_PWRST_D0)
3927 			continue;
3928 		if (!snd_hda_check_power_state(codec, nid, target))
3929 			snd_hda_codec_write(codec, nid, 0,
3930 					    AC_VERB_SET_POWER_STATE, target);
3931 	}
3932 }
3933 
3934 #ifdef CONFIG_SND_HDA_HWDEP
3935 /* execute additional init verbs */
3936 static void hda_exec_init_verbs(struct hda_codec *codec)
3937 {
3938 	if (codec->init_verbs.list)
3939 		snd_hda_sequence_write(codec, codec->init_verbs.list);
3940 }
3941 #else
3942 static inline void hda_exec_init_verbs(struct hda_codec *codec) {}
3943 #endif
3944 
3945 #ifdef CONFIG_PM
3946 /*
3947  * call suspend and power-down; used both from PM and power-save
3948  * this function returns the power state in the end
3949  */
3950 static unsigned int hda_call_codec_suspend(struct hda_codec *codec, bool in_wq)
3951 {
3952 	unsigned int state;
3953 
3954 	codec->in_pm = 1;
3955 
3956 	if (codec->patch_ops.suspend)
3957 		codec->patch_ops.suspend(codec);
3958 	hda_cleanup_all_streams(codec);
3959 	state = hda_set_power_state(codec, AC_PWRST_D3);
3960 	/* Cancel delayed work if we aren't currently running from it. */
3961 	if (!in_wq)
3962 		cancel_delayed_work_sync(&codec->power_work);
3963 	spin_lock(&codec->power_lock);
3964 	snd_hda_update_power_acct(codec);
3965 	trace_hda_power_down(codec);
3966 	codec->power_on = 0;
3967 	codec->power_transition = 0;
3968 	codec->power_jiffies = jiffies;
3969 	spin_unlock(&codec->power_lock);
3970 	codec->in_pm = 0;
3971 	return state;
3972 }
3973 
3974 /* mark all entries of cmd and amp caches dirty */
3975 static void hda_mark_cmd_cache_dirty(struct hda_codec *codec)
3976 {
3977 	int i;
3978 	for (i = 0; i < codec->cmd_cache.buf.used; i++) {
3979 		struct hda_cache_head *cmd;
3980 		cmd = snd_array_elem(&codec->cmd_cache.buf, i);
3981 		cmd->dirty = 1;
3982 	}
3983 	for (i = 0; i < codec->amp_cache.buf.used; i++) {
3984 		struct hda_amp_info *amp;
3985 		amp = snd_array_elem(&codec->amp_cache.buf, i);
3986 		amp->head.dirty = 1;
3987 	}
3988 }
3989 
3990 /*
3991  * kick up codec; used both from PM and power-save
3992  */
3993 static void hda_call_codec_resume(struct hda_codec *codec)
3994 {
3995 	codec->in_pm = 1;
3996 
3997 	hda_mark_cmd_cache_dirty(codec);
3998 
3999 	/* set as if powered on for avoiding re-entering the resume
4000 	 * in the resume / power-save sequence
4001 	 */
4002 	hda_keep_power_on(codec);
4003 	if (codec->pm_down_notified) {
4004 		codec->pm_down_notified = 0;
4005 		hda_call_pm_notify(codec->bus, true);
4006 	}
4007 	hda_set_power_state(codec, AC_PWRST_D0);
4008 	restore_shutup_pins(codec);
4009 	hda_exec_init_verbs(codec);
4010 	snd_hda_jack_set_dirty_all(codec);
4011 	if (codec->patch_ops.resume)
4012 		codec->patch_ops.resume(codec);
4013 	else {
4014 		if (codec->patch_ops.init)
4015 			codec->patch_ops.init(codec);
4016 		snd_hda_codec_resume_amp(codec);
4017 		snd_hda_codec_resume_cache(codec);
4018 	}
4019 
4020 	if (codec->jackpoll_interval)
4021 		hda_jackpoll_work(&codec->jackpoll_work.work);
4022 	else
4023 		snd_hda_jack_report_sync(codec);
4024 
4025 	codec->in_pm = 0;
4026 	snd_hda_power_down(codec); /* flag down before returning */
4027 }
4028 #endif /* CONFIG_PM */
4029 
4030 
4031 /**
4032  * snd_hda_build_controls - build mixer controls
4033  * @bus: the BUS
4034  *
4035  * Creates mixer controls for each codec included in the bus.
4036  *
4037  * Returns 0 if successful, otherwise a negative error code.
4038  */
4039 int snd_hda_build_controls(struct hda_bus *bus)
4040 {
4041 	struct hda_codec *codec;
4042 
4043 	list_for_each_entry(codec, &bus->codec_list, list) {
4044 		int err = snd_hda_codec_build_controls(codec);
4045 		if (err < 0) {
4046 			printk(KERN_ERR "hda_codec: cannot build controls "
4047 			       "for #%d (error %d)\n", codec->addr, err);
4048 			err = snd_hda_codec_reset(codec);
4049 			if (err < 0) {
4050 				printk(KERN_ERR
4051 				       "hda_codec: cannot revert codec\n");
4052 				return err;
4053 			}
4054 		}
4055 	}
4056 	return 0;
4057 }
4058 EXPORT_SYMBOL_HDA(snd_hda_build_controls);
4059 
4060 /*
4061  * add standard channel maps if not specified
4062  */
4063 static int add_std_chmaps(struct hda_codec *codec)
4064 {
4065 	int i, str, err;
4066 
4067 	for (i = 0; i < codec->num_pcms; i++) {
4068 		for (str = 0; str < 2; str++) {
4069 			struct snd_pcm *pcm = codec->pcm_info[i].pcm;
4070 			struct hda_pcm_stream *hinfo =
4071 				&codec->pcm_info[i].stream[str];
4072 			struct snd_pcm_chmap *chmap;
4073 			const struct snd_pcm_chmap_elem *elem;
4074 
4075 			if (codec->pcm_info[i].own_chmap)
4076 				continue;
4077 			if (!pcm || !hinfo->substreams)
4078 				continue;
4079 			elem = hinfo->chmap ? hinfo->chmap : snd_pcm_std_chmaps;
4080 			err = snd_pcm_add_chmap_ctls(pcm, str, elem,
4081 						     hinfo->channels_max,
4082 						     0, &chmap);
4083 			if (err < 0)
4084 				return err;
4085 			chmap->channel_mask = SND_PCM_CHMAP_MASK_2468;
4086 		}
4087 	}
4088 	return 0;
4089 }
4090 
4091 /* default channel maps for 2.1 speakers;
4092  * since HD-audio supports only stereo, odd number channels are omitted
4093  */
4094 const struct snd_pcm_chmap_elem snd_pcm_2_1_chmaps[] = {
4095 	{ .channels = 2,
4096 	  .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR } },
4097 	{ .channels = 4,
4098 	  .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR,
4099 		   SNDRV_CHMAP_LFE, SNDRV_CHMAP_LFE } },
4100 	{ }
4101 };
4102 EXPORT_SYMBOL_GPL(snd_pcm_2_1_chmaps);
4103 
4104 int snd_hda_codec_build_controls(struct hda_codec *codec)
4105 {
4106 	int err = 0;
4107 	hda_exec_init_verbs(codec);
4108 	/* continue to initialize... */
4109 	if (codec->patch_ops.init)
4110 		err = codec->patch_ops.init(codec);
4111 	if (!err && codec->patch_ops.build_controls)
4112 		err = codec->patch_ops.build_controls(codec);
4113 	if (err < 0)
4114 		return err;
4115 
4116 	/* we create chmaps here instead of build_pcms */
4117 	err = add_std_chmaps(codec);
4118 	if (err < 0)
4119 		return err;
4120 
4121 	if (codec->jackpoll_interval)
4122 		hda_jackpoll_work(&codec->jackpoll_work.work);
4123 	else
4124 		snd_hda_jack_report_sync(codec); /* call at the last init point */
4125 	sync_power_up_states(codec);
4126 	return 0;
4127 }
4128 
4129 /*
4130  * stream formats
4131  */
4132 struct hda_rate_tbl {
4133 	unsigned int hz;
4134 	unsigned int alsa_bits;
4135 	unsigned int hda_fmt;
4136 };
4137 
4138 /* rate = base * mult / div */
4139 #define HDA_RATE(base, mult, div) \
4140 	(AC_FMT_BASE_##base##K | (((mult) - 1) << AC_FMT_MULT_SHIFT) | \
4141 	 (((div) - 1) << AC_FMT_DIV_SHIFT))
4142 
4143 static struct hda_rate_tbl rate_bits[] = {
4144 	/* rate in Hz, ALSA rate bitmask, HDA format value */
4145 
4146 	/* autodetected value used in snd_hda_query_supported_pcm */
4147 	{ 8000, SNDRV_PCM_RATE_8000, HDA_RATE(48, 1, 6) },
4148 	{ 11025, SNDRV_PCM_RATE_11025, HDA_RATE(44, 1, 4) },
4149 	{ 16000, SNDRV_PCM_RATE_16000, HDA_RATE(48, 1, 3) },
4150 	{ 22050, SNDRV_PCM_RATE_22050, HDA_RATE(44, 1, 2) },
4151 	{ 32000, SNDRV_PCM_RATE_32000, HDA_RATE(48, 2, 3) },
4152 	{ 44100, SNDRV_PCM_RATE_44100, HDA_RATE(44, 1, 1) },
4153 	{ 48000, SNDRV_PCM_RATE_48000, HDA_RATE(48, 1, 1) },
4154 	{ 88200, SNDRV_PCM_RATE_88200, HDA_RATE(44, 2, 1) },
4155 	{ 96000, SNDRV_PCM_RATE_96000, HDA_RATE(48, 2, 1) },
4156 	{ 176400, SNDRV_PCM_RATE_176400, HDA_RATE(44, 4, 1) },
4157 	{ 192000, SNDRV_PCM_RATE_192000, HDA_RATE(48, 4, 1) },
4158 #define AC_PAR_PCM_RATE_BITS	11
4159 	/* up to bits 10, 384kHZ isn't supported properly */
4160 
4161 	/* not autodetected value */
4162 	{ 9600, SNDRV_PCM_RATE_KNOT, HDA_RATE(48, 1, 5) },
4163 
4164 	{ 0 } /* terminator */
4165 };
4166 
4167 /**
4168  * snd_hda_calc_stream_format - calculate format bitset
4169  * @rate: the sample rate
4170  * @channels: the number of channels
4171  * @format: the PCM format (SNDRV_PCM_FORMAT_XXX)
4172  * @maxbps: the max. bps
4173  *
4174  * Calculate the format bitset from the given rate, channels and th PCM format.
4175  *
4176  * Return zero if invalid.
4177  */
4178 unsigned int snd_hda_calc_stream_format(unsigned int rate,
4179 					unsigned int channels,
4180 					unsigned int format,
4181 					unsigned int maxbps,
4182 					unsigned short spdif_ctls)
4183 {
4184 	int i;
4185 	unsigned int val = 0;
4186 
4187 	for (i = 0; rate_bits[i].hz; i++)
4188 		if (rate_bits[i].hz == rate) {
4189 			val = rate_bits[i].hda_fmt;
4190 			break;
4191 		}
4192 	if (!rate_bits[i].hz) {
4193 		snd_printdd("invalid rate %d\n", rate);
4194 		return 0;
4195 	}
4196 
4197 	if (channels == 0 || channels > 8) {
4198 		snd_printdd("invalid channels %d\n", channels);
4199 		return 0;
4200 	}
4201 	val |= channels - 1;
4202 
4203 	switch (snd_pcm_format_width(format)) {
4204 	case 8:
4205 		val |= AC_FMT_BITS_8;
4206 		break;
4207 	case 16:
4208 		val |= AC_FMT_BITS_16;
4209 		break;
4210 	case 20:
4211 	case 24:
4212 	case 32:
4213 		if (maxbps >= 32 || format == SNDRV_PCM_FORMAT_FLOAT_LE)
4214 			val |= AC_FMT_BITS_32;
4215 		else if (maxbps >= 24)
4216 			val |= AC_FMT_BITS_24;
4217 		else
4218 			val |= AC_FMT_BITS_20;
4219 		break;
4220 	default:
4221 		snd_printdd("invalid format width %d\n",
4222 			    snd_pcm_format_width(format));
4223 		return 0;
4224 	}
4225 
4226 	if (spdif_ctls & AC_DIG1_NONAUDIO)
4227 		val |= AC_FMT_TYPE_NON_PCM;
4228 
4229 	return val;
4230 }
4231 EXPORT_SYMBOL_HDA(snd_hda_calc_stream_format);
4232 
4233 static unsigned int get_pcm_param(struct hda_codec *codec, hda_nid_t nid,
4234 				  int dir)
4235 {
4236 	unsigned int val = 0;
4237 	if (nid != codec->afg &&
4238 	    (get_wcaps(codec, nid) & AC_WCAP_FORMAT_OVRD))
4239 		val = snd_hda_param_read(codec, nid, AC_PAR_PCM);
4240 	if (!val || val == -1)
4241 		val = snd_hda_param_read(codec, codec->afg, AC_PAR_PCM);
4242 	if (!val || val == -1)
4243 		return 0;
4244 	return val;
4245 }
4246 
4247 static unsigned int query_pcm_param(struct hda_codec *codec, hda_nid_t nid)
4248 {
4249 	return query_caps_hash(codec, nid, 0, HDA_HASH_PARPCM_KEY(nid),
4250 			       get_pcm_param);
4251 }
4252 
4253 static unsigned int get_stream_param(struct hda_codec *codec, hda_nid_t nid,
4254 				     int dir)
4255 {
4256 	unsigned int streams = snd_hda_param_read(codec, nid, AC_PAR_STREAM);
4257 	if (!streams || streams == -1)
4258 		streams = snd_hda_param_read(codec, codec->afg, AC_PAR_STREAM);
4259 	if (!streams || streams == -1)
4260 		return 0;
4261 	return streams;
4262 }
4263 
4264 static unsigned int query_stream_param(struct hda_codec *codec, hda_nid_t nid)
4265 {
4266 	return query_caps_hash(codec, nid, 0, HDA_HASH_PARSTR_KEY(nid),
4267 			       get_stream_param);
4268 }
4269 
4270 /**
4271  * snd_hda_query_supported_pcm - query the supported PCM rates and formats
4272  * @codec: the HDA codec
4273  * @nid: NID to query
4274  * @ratesp: the pointer to store the detected rate bitflags
4275  * @formatsp: the pointer to store the detected formats
4276  * @bpsp: the pointer to store the detected format widths
4277  *
4278  * Queries the supported PCM rates and formats.  The NULL @ratesp, @formatsp
4279  * or @bsps argument is ignored.
4280  *
4281  * Returns 0 if successful, otherwise a negative error code.
4282  */
4283 int snd_hda_query_supported_pcm(struct hda_codec *codec, hda_nid_t nid,
4284 				u32 *ratesp, u64 *formatsp, unsigned int *bpsp)
4285 {
4286 	unsigned int i, val, wcaps;
4287 
4288 	wcaps = get_wcaps(codec, nid);
4289 	val = query_pcm_param(codec, nid);
4290 
4291 	if (ratesp) {
4292 		u32 rates = 0;
4293 		for (i = 0; i < AC_PAR_PCM_RATE_BITS; i++) {
4294 			if (val & (1 << i))
4295 				rates |= rate_bits[i].alsa_bits;
4296 		}
4297 		if (rates == 0) {
4298 			snd_printk(KERN_ERR "hda_codec: rates == 0 "
4299 				   "(nid=0x%x, val=0x%x, ovrd=%i)\n",
4300 					nid, val,
4301 					(wcaps & AC_WCAP_FORMAT_OVRD) ? 1 : 0);
4302 			return -EIO;
4303 		}
4304 		*ratesp = rates;
4305 	}
4306 
4307 	if (formatsp || bpsp) {
4308 		u64 formats = 0;
4309 		unsigned int streams, bps;
4310 
4311 		streams = query_stream_param(codec, nid);
4312 		if (!streams)
4313 			return -EIO;
4314 
4315 		bps = 0;
4316 		if (streams & AC_SUPFMT_PCM) {
4317 			if (val & AC_SUPPCM_BITS_8) {
4318 				formats |= SNDRV_PCM_FMTBIT_U8;
4319 				bps = 8;
4320 			}
4321 			if (val & AC_SUPPCM_BITS_16) {
4322 				formats |= SNDRV_PCM_FMTBIT_S16_LE;
4323 				bps = 16;
4324 			}
4325 			if (wcaps & AC_WCAP_DIGITAL) {
4326 				if (val & AC_SUPPCM_BITS_32)
4327 					formats |= SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE;
4328 				if (val & (AC_SUPPCM_BITS_20|AC_SUPPCM_BITS_24))
4329 					formats |= SNDRV_PCM_FMTBIT_S32_LE;
4330 				if (val & AC_SUPPCM_BITS_24)
4331 					bps = 24;
4332 				else if (val & AC_SUPPCM_BITS_20)
4333 					bps = 20;
4334 			} else if (val & (AC_SUPPCM_BITS_20|AC_SUPPCM_BITS_24|
4335 					  AC_SUPPCM_BITS_32)) {
4336 				formats |= SNDRV_PCM_FMTBIT_S32_LE;
4337 				if (val & AC_SUPPCM_BITS_32)
4338 					bps = 32;
4339 				else if (val & AC_SUPPCM_BITS_24)
4340 					bps = 24;
4341 				else if (val & AC_SUPPCM_BITS_20)
4342 					bps = 20;
4343 			}
4344 		}
4345 #if 0 /* FIXME: CS4206 doesn't work, which is the only codec supporting float */
4346 		if (streams & AC_SUPFMT_FLOAT32) {
4347 			formats |= SNDRV_PCM_FMTBIT_FLOAT_LE;
4348 			if (!bps)
4349 				bps = 32;
4350 		}
4351 #endif
4352 		if (streams == AC_SUPFMT_AC3) {
4353 			/* should be exclusive */
4354 			/* temporary hack: we have still no proper support
4355 			 * for the direct AC3 stream...
4356 			 */
4357 			formats |= SNDRV_PCM_FMTBIT_U8;
4358 			bps = 8;
4359 		}
4360 		if (formats == 0) {
4361 			snd_printk(KERN_ERR "hda_codec: formats == 0 "
4362 				   "(nid=0x%x, val=0x%x, ovrd=%i, "
4363 				   "streams=0x%x)\n",
4364 					nid, val,
4365 					(wcaps & AC_WCAP_FORMAT_OVRD) ? 1 : 0,
4366 					streams);
4367 			return -EIO;
4368 		}
4369 		if (formatsp)
4370 			*formatsp = formats;
4371 		if (bpsp)
4372 			*bpsp = bps;
4373 	}
4374 
4375 	return 0;
4376 }
4377 EXPORT_SYMBOL_HDA(snd_hda_query_supported_pcm);
4378 
4379 /**
4380  * snd_hda_is_supported_format - Check the validity of the format
4381  * @codec: HD-audio codec
4382  * @nid: NID to check
4383  * @format: the HD-audio format value to check
4384  *
4385  * Check whether the given node supports the format value.
4386  *
4387  * Returns 1 if supported, 0 if not.
4388  */
4389 int snd_hda_is_supported_format(struct hda_codec *codec, hda_nid_t nid,
4390 				unsigned int format)
4391 {
4392 	int i;
4393 	unsigned int val = 0, rate, stream;
4394 
4395 	val = query_pcm_param(codec, nid);
4396 	if (!val)
4397 		return 0;
4398 
4399 	rate = format & 0xff00;
4400 	for (i = 0; i < AC_PAR_PCM_RATE_BITS; i++)
4401 		if (rate_bits[i].hda_fmt == rate) {
4402 			if (val & (1 << i))
4403 				break;
4404 			return 0;
4405 		}
4406 	if (i >= AC_PAR_PCM_RATE_BITS)
4407 		return 0;
4408 
4409 	stream = query_stream_param(codec, nid);
4410 	if (!stream)
4411 		return 0;
4412 
4413 	if (stream & AC_SUPFMT_PCM) {
4414 		switch (format & 0xf0) {
4415 		case 0x00:
4416 			if (!(val & AC_SUPPCM_BITS_8))
4417 				return 0;
4418 			break;
4419 		case 0x10:
4420 			if (!(val & AC_SUPPCM_BITS_16))
4421 				return 0;
4422 			break;
4423 		case 0x20:
4424 			if (!(val & AC_SUPPCM_BITS_20))
4425 				return 0;
4426 			break;
4427 		case 0x30:
4428 			if (!(val & AC_SUPPCM_BITS_24))
4429 				return 0;
4430 			break;
4431 		case 0x40:
4432 			if (!(val & AC_SUPPCM_BITS_32))
4433 				return 0;
4434 			break;
4435 		default:
4436 			return 0;
4437 		}
4438 	} else {
4439 		/* FIXME: check for float32 and AC3? */
4440 	}
4441 
4442 	return 1;
4443 }
4444 EXPORT_SYMBOL_HDA(snd_hda_is_supported_format);
4445 
4446 /*
4447  * PCM stuff
4448  */
4449 static int hda_pcm_default_open_close(struct hda_pcm_stream *hinfo,
4450 				      struct hda_codec *codec,
4451 				      struct snd_pcm_substream *substream)
4452 {
4453 	return 0;
4454 }
4455 
4456 static int hda_pcm_default_prepare(struct hda_pcm_stream *hinfo,
4457 				   struct hda_codec *codec,
4458 				   unsigned int stream_tag,
4459 				   unsigned int format,
4460 				   struct snd_pcm_substream *substream)
4461 {
4462 	snd_hda_codec_setup_stream(codec, hinfo->nid, stream_tag, 0, format);
4463 	return 0;
4464 }
4465 
4466 static int hda_pcm_default_cleanup(struct hda_pcm_stream *hinfo,
4467 				   struct hda_codec *codec,
4468 				   struct snd_pcm_substream *substream)
4469 {
4470 	snd_hda_codec_cleanup_stream(codec, hinfo->nid);
4471 	return 0;
4472 }
4473 
4474 static int set_pcm_default_values(struct hda_codec *codec,
4475 				  struct hda_pcm_stream *info)
4476 {
4477 	int err;
4478 
4479 	/* query support PCM information from the given NID */
4480 	if (info->nid && (!info->rates || !info->formats)) {
4481 		err = snd_hda_query_supported_pcm(codec, info->nid,
4482 				info->rates ? NULL : &info->rates,
4483 				info->formats ? NULL : &info->formats,
4484 				info->maxbps ? NULL : &info->maxbps);
4485 		if (err < 0)
4486 			return err;
4487 	}
4488 	if (info->ops.open == NULL)
4489 		info->ops.open = hda_pcm_default_open_close;
4490 	if (info->ops.close == NULL)
4491 		info->ops.close = hda_pcm_default_open_close;
4492 	if (info->ops.prepare == NULL) {
4493 		if (snd_BUG_ON(!info->nid))
4494 			return -EINVAL;
4495 		info->ops.prepare = hda_pcm_default_prepare;
4496 	}
4497 	if (info->ops.cleanup == NULL) {
4498 		if (snd_BUG_ON(!info->nid))
4499 			return -EINVAL;
4500 		info->ops.cleanup = hda_pcm_default_cleanup;
4501 	}
4502 	return 0;
4503 }
4504 
4505 /*
4506  * codec prepare/cleanup entries
4507  */
4508 int snd_hda_codec_prepare(struct hda_codec *codec,
4509 			  struct hda_pcm_stream *hinfo,
4510 			  unsigned int stream,
4511 			  unsigned int format,
4512 			  struct snd_pcm_substream *substream)
4513 {
4514 	int ret;
4515 	mutex_lock(&codec->bus->prepare_mutex);
4516 	ret = hinfo->ops.prepare(hinfo, codec, stream, format, substream);
4517 	if (ret >= 0)
4518 		purify_inactive_streams(codec);
4519 	mutex_unlock(&codec->bus->prepare_mutex);
4520 	return ret;
4521 }
4522 EXPORT_SYMBOL_HDA(snd_hda_codec_prepare);
4523 
4524 void snd_hda_codec_cleanup(struct hda_codec *codec,
4525 			   struct hda_pcm_stream *hinfo,
4526 			   struct snd_pcm_substream *substream)
4527 {
4528 	mutex_lock(&codec->bus->prepare_mutex);
4529 	hinfo->ops.cleanup(hinfo, codec, substream);
4530 	mutex_unlock(&codec->bus->prepare_mutex);
4531 }
4532 EXPORT_SYMBOL_HDA(snd_hda_codec_cleanup);
4533 
4534 /* global */
4535 const char *snd_hda_pcm_type_name[HDA_PCM_NTYPES] = {
4536 	"Audio", "SPDIF", "HDMI", "Modem"
4537 };
4538 
4539 /*
4540  * get the empty PCM device number to assign
4541  */
4542 static int get_empty_pcm_device(struct hda_bus *bus, unsigned int type)
4543 {
4544 	/* audio device indices; not linear to keep compatibility */
4545 	/* assigned to static slots up to dev#10; if more needed, assign
4546 	 * the later slot dynamically (when CONFIG_SND_DYNAMIC_MINORS=y)
4547 	 */
4548 	static int audio_idx[HDA_PCM_NTYPES][5] = {
4549 		[HDA_PCM_TYPE_AUDIO] = { 0, 2, 4, 5, -1 },
4550 		[HDA_PCM_TYPE_SPDIF] = { 1, -1 },
4551 		[HDA_PCM_TYPE_HDMI]  = { 3, 7, 8, 9, -1 },
4552 		[HDA_PCM_TYPE_MODEM] = { 6, -1 },
4553 	};
4554 	int i;
4555 
4556 	if (type >= HDA_PCM_NTYPES) {
4557 		snd_printk(KERN_WARNING "Invalid PCM type %d\n", type);
4558 		return -EINVAL;
4559 	}
4560 
4561 	for (i = 0; audio_idx[type][i] >= 0; i++) {
4562 #ifndef CONFIG_SND_DYNAMIC_MINORS
4563 		if (audio_idx[type][i] >= 8)
4564 			break;
4565 #endif
4566 		if (!test_and_set_bit(audio_idx[type][i], bus->pcm_dev_bits))
4567 			return audio_idx[type][i];
4568 	}
4569 
4570 #ifdef CONFIG_SND_DYNAMIC_MINORS
4571 	/* non-fixed slots starting from 10 */
4572 	for (i = 10; i < 32; i++) {
4573 		if (!test_and_set_bit(i, bus->pcm_dev_bits))
4574 			return i;
4575 	}
4576 #endif
4577 
4578 	snd_printk(KERN_WARNING "Too many %s devices\n",
4579 		snd_hda_pcm_type_name[type]);
4580 #ifndef CONFIG_SND_DYNAMIC_MINORS
4581 	snd_printk(KERN_WARNING "Consider building the kernel with CONFIG_SND_DYNAMIC_MINORS=y\n");
4582 #endif
4583 	return -EAGAIN;
4584 }
4585 
4586 /*
4587  * attach a new PCM stream
4588  */
4589 static int snd_hda_attach_pcm(struct hda_codec *codec, struct hda_pcm *pcm)
4590 {
4591 	struct hda_bus *bus = codec->bus;
4592 	struct hda_pcm_stream *info;
4593 	int stream, err;
4594 
4595 	if (snd_BUG_ON(!pcm->name))
4596 		return -EINVAL;
4597 	for (stream = 0; stream < 2; stream++) {
4598 		info = &pcm->stream[stream];
4599 		if (info->substreams) {
4600 			err = set_pcm_default_values(codec, info);
4601 			if (err < 0)
4602 				return err;
4603 		}
4604 	}
4605 	return bus->ops.attach_pcm(bus, codec, pcm);
4606 }
4607 
4608 /* assign all PCMs of the given codec */
4609 int snd_hda_codec_build_pcms(struct hda_codec *codec)
4610 {
4611 	unsigned int pcm;
4612 	int err;
4613 
4614 	if (!codec->num_pcms) {
4615 		if (!codec->patch_ops.build_pcms)
4616 			return 0;
4617 		err = codec->patch_ops.build_pcms(codec);
4618 		if (err < 0) {
4619 			printk(KERN_ERR "hda_codec: cannot build PCMs"
4620 			       "for #%d (error %d)\n", codec->addr, err);
4621 			err = snd_hda_codec_reset(codec);
4622 			if (err < 0) {
4623 				printk(KERN_ERR
4624 				       "hda_codec: cannot revert codec\n");
4625 				return err;
4626 			}
4627 		}
4628 	}
4629 	for (pcm = 0; pcm < codec->num_pcms; pcm++) {
4630 		struct hda_pcm *cpcm = &codec->pcm_info[pcm];
4631 		int dev;
4632 
4633 		if (!cpcm->stream[0].substreams && !cpcm->stream[1].substreams)
4634 			continue; /* no substreams assigned */
4635 
4636 		if (!cpcm->pcm) {
4637 			dev = get_empty_pcm_device(codec->bus, cpcm->pcm_type);
4638 			if (dev < 0)
4639 				continue; /* no fatal error */
4640 			cpcm->device = dev;
4641 			err = snd_hda_attach_pcm(codec, cpcm);
4642 			if (err < 0) {
4643 				printk(KERN_ERR "hda_codec: cannot attach "
4644 				       "PCM stream %d for codec #%d\n",
4645 				       dev, codec->addr);
4646 				continue; /* no fatal error */
4647 			}
4648 		}
4649 	}
4650 	return 0;
4651 }
4652 
4653 /**
4654  * snd_hda_build_pcms - build PCM information
4655  * @bus: the BUS
4656  *
4657  * Create PCM information for each codec included in the bus.
4658  *
4659  * The build_pcms codec patch is requested to set up codec->num_pcms and
4660  * codec->pcm_info properly.  The array is referred by the top-level driver
4661  * to create its PCM instances.
4662  * The allocated codec->pcm_info should be released in codec->patch_ops.free
4663  * callback.
4664  *
4665  * At least, substreams, channels_min and channels_max must be filled for
4666  * each stream.  substreams = 0 indicates that the stream doesn't exist.
4667  * When rates and/or formats are zero, the supported values are queried
4668  * from the given nid.  The nid is used also by the default ops.prepare
4669  * and ops.cleanup callbacks.
4670  *
4671  * The driver needs to call ops.open in its open callback.  Similarly,
4672  * ops.close is supposed to be called in the close callback.
4673  * ops.prepare should be called in the prepare or hw_params callback
4674  * with the proper parameters for set up.
4675  * ops.cleanup should be called in hw_free for clean up of streams.
4676  *
4677  * This function returns 0 if successful, or a negative error code.
4678  */
4679 int snd_hda_build_pcms(struct hda_bus *bus)
4680 {
4681 	struct hda_codec *codec;
4682 
4683 	list_for_each_entry(codec, &bus->codec_list, list) {
4684 		int err = snd_hda_codec_build_pcms(codec);
4685 		if (err < 0)
4686 			return err;
4687 	}
4688 	return 0;
4689 }
4690 EXPORT_SYMBOL_HDA(snd_hda_build_pcms);
4691 
4692 /**
4693  * snd_hda_check_board_config - compare the current codec with the config table
4694  * @codec: the HDA codec
4695  * @num_configs: number of config enums
4696  * @models: array of model name strings
4697  * @tbl: configuration table, terminated by null entries
4698  *
4699  * Compares the modelname or PCI subsystem id of the current codec with the
4700  * given configuration table.  If a matching entry is found, returns its
4701  * config value (supposed to be 0 or positive).
4702  *
4703  * If no entries are matching, the function returns a negative value.
4704  */
4705 int snd_hda_check_board_config(struct hda_codec *codec,
4706 			       int num_configs, const char * const *models,
4707 			       const struct snd_pci_quirk *tbl)
4708 {
4709 	if (codec->modelname && models) {
4710 		int i;
4711 		for (i = 0; i < num_configs; i++) {
4712 			if (models[i] &&
4713 			    !strcmp(codec->modelname, models[i])) {
4714 				snd_printd(KERN_INFO "hda_codec: model '%s' is "
4715 					   "selected\n", models[i]);
4716 				return i;
4717 			}
4718 		}
4719 	}
4720 
4721 	if (!codec->bus->pci || !tbl)
4722 		return -1;
4723 
4724 	tbl = snd_pci_quirk_lookup(codec->bus->pci, tbl);
4725 	if (!tbl)
4726 		return -1;
4727 	if (tbl->value >= 0 && tbl->value < num_configs) {
4728 #ifdef CONFIG_SND_DEBUG_VERBOSE
4729 		char tmp[10];
4730 		const char *model = NULL;
4731 		if (models)
4732 			model = models[tbl->value];
4733 		if (!model) {
4734 			sprintf(tmp, "#%d", tbl->value);
4735 			model = tmp;
4736 		}
4737 		snd_printdd(KERN_INFO "hda_codec: model '%s' is selected "
4738 			    "for config %x:%x (%s)\n",
4739 			    model, tbl->subvendor, tbl->subdevice,
4740 			    (tbl->name ? tbl->name : "Unknown device"));
4741 #endif
4742 		return tbl->value;
4743 	}
4744 	return -1;
4745 }
4746 EXPORT_SYMBOL_HDA(snd_hda_check_board_config);
4747 
4748 /**
4749  * snd_hda_check_board_codec_sid_config - compare the current codec
4750 					subsystem ID with the
4751 					config table
4752 
4753 	   This is important for Gateway notebooks with SB450 HDA Audio
4754 	   where the vendor ID of the PCI device is:
4755 		ATI Technologies Inc SB450 HDA Audio [1002:437b]
4756 	   and the vendor/subvendor are found only at the codec.
4757 
4758  * @codec: the HDA codec
4759  * @num_configs: number of config enums
4760  * @models: array of model name strings
4761  * @tbl: configuration table, terminated by null entries
4762  *
4763  * Compares the modelname or PCI subsystem id of the current codec with the
4764  * given configuration table.  If a matching entry is found, returns its
4765  * config value (supposed to be 0 or positive).
4766  *
4767  * If no entries are matching, the function returns a negative value.
4768  */
4769 int snd_hda_check_board_codec_sid_config(struct hda_codec *codec,
4770 			       int num_configs, const char * const *models,
4771 			       const struct snd_pci_quirk *tbl)
4772 {
4773 	const struct snd_pci_quirk *q;
4774 
4775 	/* Search for codec ID */
4776 	for (q = tbl; q->subvendor; q++) {
4777 		unsigned int mask = 0xffff0000 | q->subdevice_mask;
4778 		unsigned int id = (q->subdevice | (q->subvendor << 16)) & mask;
4779 		if ((codec->subsystem_id & mask) == id)
4780 			break;
4781 	}
4782 
4783 	if (!q->subvendor)
4784 		return -1;
4785 
4786 	tbl = q;
4787 
4788 	if (tbl->value >= 0 && tbl->value < num_configs) {
4789 #ifdef CONFIG_SND_DEBUG_VERBOSE
4790 		char tmp[10];
4791 		const char *model = NULL;
4792 		if (models)
4793 			model = models[tbl->value];
4794 		if (!model) {
4795 			sprintf(tmp, "#%d", tbl->value);
4796 			model = tmp;
4797 		}
4798 		snd_printdd(KERN_INFO "hda_codec: model '%s' is selected "
4799 			    "for config %x:%x (%s)\n",
4800 			    model, tbl->subvendor, tbl->subdevice,
4801 			    (tbl->name ? tbl->name : "Unknown device"));
4802 #endif
4803 		return tbl->value;
4804 	}
4805 	return -1;
4806 }
4807 EXPORT_SYMBOL_HDA(snd_hda_check_board_codec_sid_config);
4808 
4809 /**
4810  * snd_hda_add_new_ctls - create controls from the array
4811  * @codec: the HDA codec
4812  * @knew: the array of struct snd_kcontrol_new
4813  *
4814  * This helper function creates and add new controls in the given array.
4815  * The array must be terminated with an empty entry as terminator.
4816  *
4817  * Returns 0 if successful, or a negative error code.
4818  */
4819 int snd_hda_add_new_ctls(struct hda_codec *codec,
4820 			 const struct snd_kcontrol_new *knew)
4821 {
4822 	int err;
4823 
4824 	for (; knew->name; knew++) {
4825 		struct snd_kcontrol *kctl;
4826 		int addr = 0, idx = 0;
4827 		if (knew->iface == -1)	/* skip this codec private value */
4828 			continue;
4829 		for (;;) {
4830 			kctl = snd_ctl_new1(knew, codec);
4831 			if (!kctl)
4832 				return -ENOMEM;
4833 			if (addr > 0)
4834 				kctl->id.device = addr;
4835 			if (idx > 0)
4836 				kctl->id.index = idx;
4837 			err = snd_hda_ctl_add(codec, 0, kctl);
4838 			if (!err)
4839 				break;
4840 			/* try first with another device index corresponding to
4841 			 * the codec addr; if it still fails (or it's the
4842 			 * primary codec), then try another control index
4843 			 */
4844 			if (!addr && codec->addr)
4845 				addr = codec->addr;
4846 			else if (!idx && !knew->index) {
4847 				idx = find_empty_mixer_ctl_idx(codec,
4848 							       knew->name, 0);
4849 				if (idx <= 0)
4850 					return err;
4851 			} else
4852 				return err;
4853 		}
4854 	}
4855 	return 0;
4856 }
4857 EXPORT_SYMBOL_HDA(snd_hda_add_new_ctls);
4858 
4859 #ifdef CONFIG_PM
4860 static void hda_power_work(struct work_struct *work)
4861 {
4862 	struct hda_codec *codec =
4863 		container_of(work, struct hda_codec, power_work.work);
4864 	struct hda_bus *bus = codec->bus;
4865 	unsigned int state;
4866 
4867 	spin_lock(&codec->power_lock);
4868 	if (codec->power_transition > 0) { /* during power-up sequence? */
4869 		spin_unlock(&codec->power_lock);
4870 		return;
4871 	}
4872 	if (!codec->power_on || codec->power_count) {
4873 		codec->power_transition = 0;
4874 		spin_unlock(&codec->power_lock);
4875 		return;
4876 	}
4877 	spin_unlock(&codec->power_lock);
4878 
4879 	state = hda_call_codec_suspend(codec, true);
4880 	if (!codec->pm_down_notified &&
4881 	    !bus->power_keep_link_on && (state & AC_PWRST_CLK_STOP_OK)) {
4882 		codec->pm_down_notified = 1;
4883 		hda_call_pm_notify(bus, false);
4884 	}
4885 }
4886 
4887 static void hda_keep_power_on(struct hda_codec *codec)
4888 {
4889 	spin_lock(&codec->power_lock);
4890 	codec->power_count++;
4891 	codec->power_on = 1;
4892 	codec->power_jiffies = jiffies;
4893 	spin_unlock(&codec->power_lock);
4894 }
4895 
4896 /* update the power on/off account with the current jiffies */
4897 void snd_hda_update_power_acct(struct hda_codec *codec)
4898 {
4899 	unsigned long delta = jiffies - codec->power_jiffies;
4900 	if (codec->power_on)
4901 		codec->power_on_acct += delta;
4902 	else
4903 		codec->power_off_acct += delta;
4904 	codec->power_jiffies += delta;
4905 }
4906 
4907 /* Transition to powered up, if wait_power_down then wait for a pending
4908  * transition to D3 to complete. A pending D3 transition is indicated
4909  * with power_transition == -1. */
4910 /* call this with codec->power_lock held! */
4911 static void __snd_hda_power_up(struct hda_codec *codec, bool wait_power_down)
4912 {
4913 	struct hda_bus *bus = codec->bus;
4914 
4915 	/* Return if power_on or transitioning to power_on, unless currently
4916 	 * powering down. */
4917 	if ((codec->power_on || codec->power_transition > 0) &&
4918 	    !(wait_power_down && codec->power_transition < 0))
4919 		return;
4920 	spin_unlock(&codec->power_lock);
4921 
4922 	cancel_delayed_work_sync(&codec->power_work);
4923 
4924 	spin_lock(&codec->power_lock);
4925 	/* If the power down delayed work was cancelled above before starting,
4926 	 * then there is no need to go through power up here.
4927 	 */
4928 	if (codec->power_on) {
4929 		if (codec->power_transition < 0)
4930 			codec->power_transition = 0;
4931 		return;
4932 	}
4933 
4934 	trace_hda_power_up(codec);
4935 	snd_hda_update_power_acct(codec);
4936 	codec->power_on = 1;
4937 	codec->power_jiffies = jiffies;
4938 	codec->power_transition = 1; /* avoid reentrance */
4939 	spin_unlock(&codec->power_lock);
4940 
4941 	if (codec->pm_down_notified) {
4942 		codec->pm_down_notified = 0;
4943 		hda_call_pm_notify(bus, true);
4944 	}
4945 
4946 	hda_call_codec_resume(codec);
4947 
4948 	spin_lock(&codec->power_lock);
4949 	codec->power_transition = 0;
4950 }
4951 
4952 #define power_save(codec)	\
4953 	((codec)->bus->power_save ? *(codec)->bus->power_save : 0)
4954 
4955 /* Transition to powered down */
4956 static void __snd_hda_power_down(struct hda_codec *codec)
4957 {
4958 	if (!codec->power_on || codec->power_count || codec->power_transition)
4959 		return;
4960 
4961 	if (power_save(codec)) {
4962 		codec->power_transition = -1; /* avoid reentrance */
4963 		queue_delayed_work(codec->bus->workq, &codec->power_work,
4964 				msecs_to_jiffies(power_save(codec) * 1000));
4965 	}
4966 }
4967 
4968 /**
4969  * snd_hda_power_save - Power-up/down/sync the codec
4970  * @codec: HD-audio codec
4971  * @delta: the counter delta to change
4972  *
4973  * Change the power-up counter via @delta, and power up or down the hardware
4974  * appropriately.  For the power-down, queue to the delayed action.
4975  * Passing zero to @delta means to synchronize the power state.
4976  */
4977 void snd_hda_power_save(struct hda_codec *codec, int delta, bool d3wait)
4978 {
4979 	spin_lock(&codec->power_lock);
4980 	codec->power_count += delta;
4981 	trace_hda_power_count(codec);
4982 	if (delta > 0)
4983 		__snd_hda_power_up(codec, d3wait);
4984 	else
4985 		__snd_hda_power_down(codec);
4986 	spin_unlock(&codec->power_lock);
4987 }
4988 EXPORT_SYMBOL_HDA(snd_hda_power_save);
4989 
4990 /**
4991  * snd_hda_check_amp_list_power - Check the amp list and update the power
4992  * @codec: HD-audio codec
4993  * @check: the object containing an AMP list and the status
4994  * @nid: NID to check / update
4995  *
4996  * Check whether the given NID is in the amp list.  If it's in the list,
4997  * check the current AMP status, and update the the power-status according
4998  * to the mute status.
4999  *
5000  * This function is supposed to be set or called from the check_power_status
5001  * patch ops.
5002  */
5003 int snd_hda_check_amp_list_power(struct hda_codec *codec,
5004 				 struct hda_loopback_check *check,
5005 				 hda_nid_t nid)
5006 {
5007 	const struct hda_amp_list *p;
5008 	int ch, v;
5009 
5010 	if (!check->amplist)
5011 		return 0;
5012 	for (p = check->amplist; p->nid; p++) {
5013 		if (p->nid == nid)
5014 			break;
5015 	}
5016 	if (!p->nid)
5017 		return 0; /* nothing changed */
5018 
5019 	for (p = check->amplist; p->nid; p++) {
5020 		for (ch = 0; ch < 2; ch++) {
5021 			v = snd_hda_codec_amp_read(codec, p->nid, ch, p->dir,
5022 						   p->idx);
5023 			if (!(v & HDA_AMP_MUTE) && v > 0) {
5024 				if (!check->power_on) {
5025 					check->power_on = 1;
5026 					snd_hda_power_up(codec);
5027 				}
5028 				return 1;
5029 			}
5030 		}
5031 	}
5032 	if (check->power_on) {
5033 		check->power_on = 0;
5034 		snd_hda_power_down(codec);
5035 	}
5036 	return 0;
5037 }
5038 EXPORT_SYMBOL_HDA(snd_hda_check_amp_list_power);
5039 #endif
5040 
5041 /*
5042  * Channel mode helper
5043  */
5044 
5045 /**
5046  * snd_hda_ch_mode_info - Info callback helper for the channel mode enum
5047  */
5048 int snd_hda_ch_mode_info(struct hda_codec *codec,
5049 			 struct snd_ctl_elem_info *uinfo,
5050 			 const struct hda_channel_mode *chmode,
5051 			 int num_chmodes)
5052 {
5053 	uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
5054 	uinfo->count = 1;
5055 	uinfo->value.enumerated.items = num_chmodes;
5056 	if (uinfo->value.enumerated.item >= num_chmodes)
5057 		uinfo->value.enumerated.item = num_chmodes - 1;
5058 	sprintf(uinfo->value.enumerated.name, "%dch",
5059 		chmode[uinfo->value.enumerated.item].channels);
5060 	return 0;
5061 }
5062 EXPORT_SYMBOL_HDA(snd_hda_ch_mode_info);
5063 
5064 /**
5065  * snd_hda_ch_mode_get - Get callback helper for the channel mode enum
5066  */
5067 int snd_hda_ch_mode_get(struct hda_codec *codec,
5068 			struct snd_ctl_elem_value *ucontrol,
5069 			const struct hda_channel_mode *chmode,
5070 			int num_chmodes,
5071 			int max_channels)
5072 {
5073 	int i;
5074 
5075 	for (i = 0; i < num_chmodes; i++) {
5076 		if (max_channels == chmode[i].channels) {
5077 			ucontrol->value.enumerated.item[0] = i;
5078 			break;
5079 		}
5080 	}
5081 	return 0;
5082 }
5083 EXPORT_SYMBOL_HDA(snd_hda_ch_mode_get);
5084 
5085 /**
5086  * snd_hda_ch_mode_put - Put callback helper for the channel mode enum
5087  */
5088 int snd_hda_ch_mode_put(struct hda_codec *codec,
5089 			struct snd_ctl_elem_value *ucontrol,
5090 			const struct hda_channel_mode *chmode,
5091 			int num_chmodes,
5092 			int *max_channelsp)
5093 {
5094 	unsigned int mode;
5095 
5096 	mode = ucontrol->value.enumerated.item[0];
5097 	if (mode >= num_chmodes)
5098 		return -EINVAL;
5099 	if (*max_channelsp == chmode[mode].channels)
5100 		return 0;
5101 	/* change the current channel setting */
5102 	*max_channelsp = chmode[mode].channels;
5103 	if (chmode[mode].sequence)
5104 		snd_hda_sequence_write_cache(codec, chmode[mode].sequence);
5105 	return 1;
5106 }
5107 EXPORT_SYMBOL_HDA(snd_hda_ch_mode_put);
5108 
5109 /*
5110  * input MUX helper
5111  */
5112 
5113 /**
5114  * snd_hda_input_mux_info_info - Info callback helper for the input-mux enum
5115  */
5116 int snd_hda_input_mux_info(const struct hda_input_mux *imux,
5117 			   struct snd_ctl_elem_info *uinfo)
5118 {
5119 	unsigned int index;
5120 
5121 	uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
5122 	uinfo->count = 1;
5123 	uinfo->value.enumerated.items = imux->num_items;
5124 	if (!imux->num_items)
5125 		return 0;
5126 	index = uinfo->value.enumerated.item;
5127 	if (index >= imux->num_items)
5128 		index = imux->num_items - 1;
5129 	strcpy(uinfo->value.enumerated.name, imux->items[index].label);
5130 	return 0;
5131 }
5132 EXPORT_SYMBOL_HDA(snd_hda_input_mux_info);
5133 
5134 /**
5135  * snd_hda_input_mux_info_put - Put callback helper for the input-mux enum
5136  */
5137 int snd_hda_input_mux_put(struct hda_codec *codec,
5138 			  const struct hda_input_mux *imux,
5139 			  struct snd_ctl_elem_value *ucontrol,
5140 			  hda_nid_t nid,
5141 			  unsigned int *cur_val)
5142 {
5143 	unsigned int idx;
5144 
5145 	if (!imux->num_items)
5146 		return 0;
5147 	idx = ucontrol->value.enumerated.item[0];
5148 	if (idx >= imux->num_items)
5149 		idx = imux->num_items - 1;
5150 	if (*cur_val == idx)
5151 		return 0;
5152 	snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_CONNECT_SEL,
5153 				  imux->items[idx].index);
5154 	*cur_val = idx;
5155 	return 1;
5156 }
5157 EXPORT_SYMBOL_HDA(snd_hda_input_mux_put);
5158 
5159 
5160 /*
5161  * process kcontrol info callback of a simple string enum array
5162  * when @num_items is 0 or @texts is NULL, assume a boolean enum array
5163  */
5164 int snd_hda_enum_helper_info(struct snd_kcontrol *kcontrol,
5165 			     struct snd_ctl_elem_info *uinfo,
5166 			     int num_items, const char * const *texts)
5167 {
5168 	static const char * const texts_default[] = {
5169 		"Disabled", "Enabled"
5170 	};
5171 
5172 	if (!texts || !num_items) {
5173 		num_items = 2;
5174 		texts = texts_default;
5175 	}
5176 
5177 	uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
5178 	uinfo->count = 1;
5179 	uinfo->value.enumerated.items = num_items;
5180 	if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items)
5181 		uinfo->value.enumerated.item = uinfo->value.enumerated.items - 1;
5182 	strcpy(uinfo->value.enumerated.name,
5183 	       texts[uinfo->value.enumerated.item]);
5184 	return 0;
5185 }
5186 EXPORT_SYMBOL_HDA(snd_hda_enum_helper_info);
5187 
5188 /*
5189  * Multi-channel / digital-out PCM helper functions
5190  */
5191 
5192 /* setup SPDIF output stream */
5193 static void setup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid,
5194 				 unsigned int stream_tag, unsigned int format)
5195 {
5196 	struct hda_spdif_out *spdif;
5197 	unsigned int curr_fmt;
5198 	bool reset;
5199 
5200 	spdif = snd_hda_spdif_out_of_nid(codec, nid);
5201 	curr_fmt = snd_hda_codec_read(codec, nid, 0,
5202 				      AC_VERB_GET_STREAM_FORMAT, 0);
5203 	reset = codec->spdif_status_reset &&
5204 		(spdif->ctls & AC_DIG1_ENABLE) &&
5205 		curr_fmt != format;
5206 
5207 	/* turn off SPDIF if needed; otherwise the IEC958 bits won't be
5208 	   updated */
5209 	if (reset)
5210 		set_dig_out_convert(codec, nid,
5211 				    spdif->ctls & ~AC_DIG1_ENABLE & 0xff,
5212 				    -1);
5213 	snd_hda_codec_setup_stream(codec, nid, stream_tag, 0, format);
5214 	if (codec->slave_dig_outs) {
5215 		const hda_nid_t *d;
5216 		for (d = codec->slave_dig_outs; *d; d++)
5217 			snd_hda_codec_setup_stream(codec, *d, stream_tag, 0,
5218 						   format);
5219 	}
5220 	/* turn on again (if needed) */
5221 	if (reset)
5222 		set_dig_out_convert(codec, nid,
5223 				    spdif->ctls & 0xff, -1);
5224 }
5225 
5226 static void cleanup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid)
5227 {
5228 	snd_hda_codec_cleanup_stream(codec, nid);
5229 	if (codec->slave_dig_outs) {
5230 		const hda_nid_t *d;
5231 		for (d = codec->slave_dig_outs; *d; d++)
5232 			snd_hda_codec_cleanup_stream(codec, *d);
5233 	}
5234 }
5235 
5236 /**
5237  * snd_hda_bus_reboot_notify - call the reboot notifier of each codec
5238  * @bus: HD-audio bus
5239  */
5240 void snd_hda_bus_reboot_notify(struct hda_bus *bus)
5241 {
5242 	struct hda_codec *codec;
5243 
5244 	if (!bus)
5245 		return;
5246 	list_for_each_entry(codec, &bus->codec_list, list) {
5247 		if (hda_codec_is_power_on(codec) &&
5248 		    codec->patch_ops.reboot_notify)
5249 			codec->patch_ops.reboot_notify(codec);
5250 	}
5251 }
5252 EXPORT_SYMBOL_HDA(snd_hda_bus_reboot_notify);
5253 
5254 /**
5255  * snd_hda_multi_out_dig_open - open the digital out in the exclusive mode
5256  */
5257 int snd_hda_multi_out_dig_open(struct hda_codec *codec,
5258 			       struct hda_multi_out *mout)
5259 {
5260 	mutex_lock(&codec->spdif_mutex);
5261 	if (mout->dig_out_used == HDA_DIG_ANALOG_DUP)
5262 		/* already opened as analog dup; reset it once */
5263 		cleanup_dig_out_stream(codec, mout->dig_out_nid);
5264 	mout->dig_out_used = HDA_DIG_EXCLUSIVE;
5265 	mutex_unlock(&codec->spdif_mutex);
5266 	return 0;
5267 }
5268 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_open);
5269 
5270 /**
5271  * snd_hda_multi_out_dig_prepare - prepare the digital out stream
5272  */
5273 int snd_hda_multi_out_dig_prepare(struct hda_codec *codec,
5274 				  struct hda_multi_out *mout,
5275 				  unsigned int stream_tag,
5276 				  unsigned int format,
5277 				  struct snd_pcm_substream *substream)
5278 {
5279 	mutex_lock(&codec->spdif_mutex);
5280 	setup_dig_out_stream(codec, mout->dig_out_nid, stream_tag, format);
5281 	mutex_unlock(&codec->spdif_mutex);
5282 	return 0;
5283 }
5284 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_prepare);
5285 
5286 /**
5287  * snd_hda_multi_out_dig_cleanup - clean-up the digital out stream
5288  */
5289 int snd_hda_multi_out_dig_cleanup(struct hda_codec *codec,
5290 				  struct hda_multi_out *mout)
5291 {
5292 	mutex_lock(&codec->spdif_mutex);
5293 	cleanup_dig_out_stream(codec, mout->dig_out_nid);
5294 	mutex_unlock(&codec->spdif_mutex);
5295 	return 0;
5296 }
5297 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_cleanup);
5298 
5299 /**
5300  * snd_hda_multi_out_dig_close - release the digital out stream
5301  */
5302 int snd_hda_multi_out_dig_close(struct hda_codec *codec,
5303 				struct hda_multi_out *mout)
5304 {
5305 	mutex_lock(&codec->spdif_mutex);
5306 	mout->dig_out_used = 0;
5307 	mutex_unlock(&codec->spdif_mutex);
5308 	return 0;
5309 }
5310 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_close);
5311 
5312 /**
5313  * snd_hda_multi_out_analog_open - open analog outputs
5314  *
5315  * Open analog outputs and set up the hw-constraints.
5316  * If the digital outputs can be opened as slave, open the digital
5317  * outputs, too.
5318  */
5319 int snd_hda_multi_out_analog_open(struct hda_codec *codec,
5320 				  struct hda_multi_out *mout,
5321 				  struct snd_pcm_substream *substream,
5322 				  struct hda_pcm_stream *hinfo)
5323 {
5324 	struct snd_pcm_runtime *runtime = substream->runtime;
5325 	runtime->hw.channels_max = mout->max_channels;
5326 	if (mout->dig_out_nid) {
5327 		if (!mout->analog_rates) {
5328 			mout->analog_rates = hinfo->rates;
5329 			mout->analog_formats = hinfo->formats;
5330 			mout->analog_maxbps = hinfo->maxbps;
5331 		} else {
5332 			runtime->hw.rates = mout->analog_rates;
5333 			runtime->hw.formats = mout->analog_formats;
5334 			hinfo->maxbps = mout->analog_maxbps;
5335 		}
5336 		if (!mout->spdif_rates) {
5337 			snd_hda_query_supported_pcm(codec, mout->dig_out_nid,
5338 						    &mout->spdif_rates,
5339 						    &mout->spdif_formats,
5340 						    &mout->spdif_maxbps);
5341 		}
5342 		mutex_lock(&codec->spdif_mutex);
5343 		if (mout->share_spdif) {
5344 			if ((runtime->hw.rates & mout->spdif_rates) &&
5345 			    (runtime->hw.formats & mout->spdif_formats)) {
5346 				runtime->hw.rates &= mout->spdif_rates;
5347 				runtime->hw.formats &= mout->spdif_formats;
5348 				if (mout->spdif_maxbps < hinfo->maxbps)
5349 					hinfo->maxbps = mout->spdif_maxbps;
5350 			} else {
5351 				mout->share_spdif = 0;
5352 				/* FIXME: need notify? */
5353 			}
5354 		}
5355 		mutex_unlock(&codec->spdif_mutex);
5356 	}
5357 	return snd_pcm_hw_constraint_step(substream->runtime, 0,
5358 					  SNDRV_PCM_HW_PARAM_CHANNELS, 2);
5359 }
5360 EXPORT_SYMBOL_HDA(snd_hda_multi_out_analog_open);
5361 
5362 /**
5363  * snd_hda_multi_out_analog_prepare - Preapre the analog outputs.
5364  *
5365  * Set up the i/o for analog out.
5366  * When the digital out is available, copy the front out to digital out, too.
5367  */
5368 int snd_hda_multi_out_analog_prepare(struct hda_codec *codec,
5369 				     struct hda_multi_out *mout,
5370 				     unsigned int stream_tag,
5371 				     unsigned int format,
5372 				     struct snd_pcm_substream *substream)
5373 {
5374 	const hda_nid_t *nids = mout->dac_nids;
5375 	int chs = substream->runtime->channels;
5376 	struct hda_spdif_out *spdif;
5377 	int i;
5378 
5379 	mutex_lock(&codec->spdif_mutex);
5380 	spdif = snd_hda_spdif_out_of_nid(codec, mout->dig_out_nid);
5381 	if (mout->dig_out_nid && mout->share_spdif &&
5382 	    mout->dig_out_used != HDA_DIG_EXCLUSIVE) {
5383 		if (chs == 2 &&
5384 		    snd_hda_is_supported_format(codec, mout->dig_out_nid,
5385 						format) &&
5386 		    !(spdif->status & IEC958_AES0_NONAUDIO)) {
5387 			mout->dig_out_used = HDA_DIG_ANALOG_DUP;
5388 			setup_dig_out_stream(codec, mout->dig_out_nid,
5389 					     stream_tag, format);
5390 		} else {
5391 			mout->dig_out_used = 0;
5392 			cleanup_dig_out_stream(codec, mout->dig_out_nid);
5393 		}
5394 	}
5395 	mutex_unlock(&codec->spdif_mutex);
5396 
5397 	/* front */
5398 	snd_hda_codec_setup_stream(codec, nids[HDA_FRONT], stream_tag,
5399 				   0, format);
5400 	if (!mout->no_share_stream &&
5401 	    mout->hp_nid && mout->hp_nid != nids[HDA_FRONT])
5402 		/* headphone out will just decode front left/right (stereo) */
5403 		snd_hda_codec_setup_stream(codec, mout->hp_nid, stream_tag,
5404 					   0, format);
5405 	/* extra outputs copied from front */
5406 	for (i = 0; i < ARRAY_SIZE(mout->hp_out_nid); i++)
5407 		if (!mout->no_share_stream && mout->hp_out_nid[i])
5408 			snd_hda_codec_setup_stream(codec,
5409 						   mout->hp_out_nid[i],
5410 						   stream_tag, 0, format);
5411 
5412 	/* surrounds */
5413 	for (i = 1; i < mout->num_dacs; i++) {
5414 		if (chs >= (i + 1) * 2) /* independent out */
5415 			snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
5416 						   i * 2, format);
5417 		else if (!mout->no_share_stream) /* copy front */
5418 			snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
5419 						   0, format);
5420 	}
5421 
5422 	/* extra surrounds */
5423 	for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++) {
5424 		int ch = 0;
5425 		if (!mout->extra_out_nid[i])
5426 			break;
5427 		if (chs >= (i + 1) * 2)
5428 			ch = i * 2;
5429 		else if (!mout->no_share_stream)
5430 			break;
5431 		snd_hda_codec_setup_stream(codec, mout->extra_out_nid[i],
5432 					   stream_tag, ch, format);
5433 	}
5434 
5435 	return 0;
5436 }
5437 EXPORT_SYMBOL_HDA(snd_hda_multi_out_analog_prepare);
5438 
5439 /**
5440  * snd_hda_multi_out_analog_cleanup - clean up the setting for analog out
5441  */
5442 int snd_hda_multi_out_analog_cleanup(struct hda_codec *codec,
5443 				     struct hda_multi_out *mout)
5444 {
5445 	const hda_nid_t *nids = mout->dac_nids;
5446 	int i;
5447 
5448 	for (i = 0; i < mout->num_dacs; i++)
5449 		snd_hda_codec_cleanup_stream(codec, nids[i]);
5450 	if (mout->hp_nid)
5451 		snd_hda_codec_cleanup_stream(codec, mout->hp_nid);
5452 	for (i = 0; i < ARRAY_SIZE(mout->hp_out_nid); i++)
5453 		if (mout->hp_out_nid[i])
5454 			snd_hda_codec_cleanup_stream(codec,
5455 						     mout->hp_out_nid[i]);
5456 	for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
5457 		if (mout->extra_out_nid[i])
5458 			snd_hda_codec_cleanup_stream(codec,
5459 						     mout->extra_out_nid[i]);
5460 	mutex_lock(&codec->spdif_mutex);
5461 	if (mout->dig_out_nid && mout->dig_out_used == HDA_DIG_ANALOG_DUP) {
5462 		cleanup_dig_out_stream(codec, mout->dig_out_nid);
5463 		mout->dig_out_used = 0;
5464 	}
5465 	mutex_unlock(&codec->spdif_mutex);
5466 	return 0;
5467 }
5468 EXPORT_SYMBOL_HDA(snd_hda_multi_out_analog_cleanup);
5469 
5470 /**
5471  * snd_hda_get_default_vref - Get the default (mic) VREF pin bits
5472  *
5473  * Guess the suitable VREF pin bits to be set as the pin-control value.
5474  * Note: the function doesn't set the AC_PINCTL_IN_EN bit.
5475  */
5476 unsigned int snd_hda_get_default_vref(struct hda_codec *codec, hda_nid_t pin)
5477 {
5478 	unsigned int pincap;
5479 	unsigned int oldval;
5480 	oldval = snd_hda_codec_read(codec, pin, 0,
5481 				    AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
5482 	pincap = snd_hda_query_pin_caps(codec, pin);
5483 	pincap = (pincap & AC_PINCAP_VREF) >> AC_PINCAP_VREF_SHIFT;
5484 	/* Exception: if the default pin setup is vref50, we give it priority */
5485 	if ((pincap & AC_PINCAP_VREF_80) && oldval != PIN_VREF50)
5486 		return AC_PINCTL_VREF_80;
5487 	else if (pincap & AC_PINCAP_VREF_50)
5488 		return AC_PINCTL_VREF_50;
5489 	else if (pincap & AC_PINCAP_VREF_100)
5490 		return AC_PINCTL_VREF_100;
5491 	else if (pincap & AC_PINCAP_VREF_GRD)
5492 		return AC_PINCTL_VREF_GRD;
5493 	return AC_PINCTL_VREF_HIZ;
5494 }
5495 EXPORT_SYMBOL_HDA(snd_hda_get_default_vref);
5496 
5497 /* correct the pin ctl value for matching with the pin cap */
5498 unsigned int snd_hda_correct_pin_ctl(struct hda_codec *codec,
5499 				     hda_nid_t pin, unsigned int val)
5500 {
5501 	static unsigned int cap_lists[][2] = {
5502 		{ AC_PINCTL_VREF_100, AC_PINCAP_VREF_100 },
5503 		{ AC_PINCTL_VREF_80, AC_PINCAP_VREF_80 },
5504 		{ AC_PINCTL_VREF_50, AC_PINCAP_VREF_50 },
5505 		{ AC_PINCTL_VREF_GRD, AC_PINCAP_VREF_GRD },
5506 	};
5507 	unsigned int cap;
5508 
5509 	if (!val)
5510 		return 0;
5511 	cap = snd_hda_query_pin_caps(codec, pin);
5512 	if (!cap)
5513 		return val; /* don't know what to do... */
5514 
5515 	if (val & AC_PINCTL_OUT_EN) {
5516 		if (!(cap & AC_PINCAP_OUT))
5517 			val &= ~(AC_PINCTL_OUT_EN | AC_PINCTL_HP_EN);
5518 		else if ((val & AC_PINCTL_HP_EN) && !(cap & AC_PINCAP_HP_DRV))
5519 			val &= ~AC_PINCTL_HP_EN;
5520 	}
5521 
5522 	if (val & AC_PINCTL_IN_EN) {
5523 		if (!(cap & AC_PINCAP_IN))
5524 			val &= ~(AC_PINCTL_IN_EN | AC_PINCTL_VREFEN);
5525 		else {
5526 			unsigned int vcap, vref;
5527 			int i;
5528 			vcap = (cap & AC_PINCAP_VREF) >> AC_PINCAP_VREF_SHIFT;
5529 			vref = val & AC_PINCTL_VREFEN;
5530 			for (i = 0; i < ARRAY_SIZE(cap_lists); i++) {
5531 				if (vref == cap_lists[i][0] &&
5532 				    !(vcap & cap_lists[i][1])) {
5533 					if (i == ARRAY_SIZE(cap_lists) - 1)
5534 						vref = AC_PINCTL_VREF_HIZ;
5535 					else
5536 						vref = cap_lists[i + 1][0];
5537 				}
5538 			}
5539 			val &= ~AC_PINCTL_VREFEN;
5540 			val |= vref;
5541 		}
5542 	}
5543 
5544 	return val;
5545 }
5546 EXPORT_SYMBOL_HDA(snd_hda_correct_pin_ctl);
5547 
5548 int _snd_hda_set_pin_ctl(struct hda_codec *codec, hda_nid_t pin,
5549 			 unsigned int val, bool cached)
5550 {
5551 	val = snd_hda_correct_pin_ctl(codec, pin, val);
5552 	snd_hda_codec_set_pin_target(codec, pin, val);
5553 	if (cached)
5554 		return snd_hda_codec_update_cache(codec, pin, 0,
5555 				AC_VERB_SET_PIN_WIDGET_CONTROL, val);
5556 	else
5557 		return snd_hda_codec_write(codec, pin, 0,
5558 					   AC_VERB_SET_PIN_WIDGET_CONTROL, val);
5559 }
5560 EXPORT_SYMBOL_HDA(_snd_hda_set_pin_ctl);
5561 
5562 /**
5563  * snd_hda_add_imux_item - Add an item to input_mux
5564  *
5565  * When the same label is used already in the existing items, the number
5566  * suffix is appended to the label.  This label index number is stored
5567  * to type_idx when non-NULL pointer is given.
5568  */
5569 int snd_hda_add_imux_item(struct hda_input_mux *imux, const char *label,
5570 			  int index, int *type_idx)
5571 {
5572 	int i, label_idx = 0;
5573 	if (imux->num_items >= HDA_MAX_NUM_INPUTS) {
5574 		snd_printd(KERN_ERR "hda_codec: Too many imux items!\n");
5575 		return -EINVAL;
5576 	}
5577 	for (i = 0; i < imux->num_items; i++) {
5578 		if (!strncmp(label, imux->items[i].label, strlen(label)))
5579 			label_idx++;
5580 	}
5581 	if (type_idx)
5582 		*type_idx = label_idx;
5583 	if (label_idx > 0)
5584 		snprintf(imux->items[imux->num_items].label,
5585 			 sizeof(imux->items[imux->num_items].label),
5586 			 "%s %d", label, label_idx);
5587 	else
5588 		strlcpy(imux->items[imux->num_items].label, label,
5589 			sizeof(imux->items[imux->num_items].label));
5590 	imux->items[imux->num_items].index = index;
5591 	imux->num_items++;
5592 	return 0;
5593 }
5594 EXPORT_SYMBOL_HDA(snd_hda_add_imux_item);
5595 
5596 
5597 #ifdef CONFIG_PM
5598 /*
5599  * power management
5600  */
5601 
5602 /**
5603  * snd_hda_suspend - suspend the codecs
5604  * @bus: the HDA bus
5605  *
5606  * Returns 0 if successful.
5607  */
5608 int snd_hda_suspend(struct hda_bus *bus)
5609 {
5610 	struct hda_codec *codec;
5611 
5612 	list_for_each_entry(codec, &bus->codec_list, list) {
5613 		cancel_delayed_work_sync(&codec->jackpoll_work);
5614 		if (hda_codec_is_power_on(codec))
5615 			hda_call_codec_suspend(codec, false);
5616 	}
5617 	return 0;
5618 }
5619 EXPORT_SYMBOL_HDA(snd_hda_suspend);
5620 
5621 /**
5622  * snd_hda_resume - resume the codecs
5623  * @bus: the HDA bus
5624  *
5625  * Returns 0 if successful.
5626  */
5627 int snd_hda_resume(struct hda_bus *bus)
5628 {
5629 	struct hda_codec *codec;
5630 
5631 	list_for_each_entry(codec, &bus->codec_list, list) {
5632 		hda_call_codec_resume(codec);
5633 	}
5634 	return 0;
5635 }
5636 EXPORT_SYMBOL_HDA(snd_hda_resume);
5637 #endif /* CONFIG_PM */
5638 
5639 /*
5640  * generic arrays
5641  */
5642 
5643 /**
5644  * snd_array_new - get a new element from the given array
5645  * @array: the array object
5646  *
5647  * Get a new element from the given array.  If it exceeds the
5648  * pre-allocated array size, re-allocate the array.
5649  *
5650  * Returns NULL if allocation failed.
5651  */
5652 void *snd_array_new(struct snd_array *array)
5653 {
5654 	if (snd_BUG_ON(!array->elem_size))
5655 		return NULL;
5656 	if (array->used >= array->alloced) {
5657 		int num = array->alloced + array->alloc_align;
5658 		int size = (num + 1) * array->elem_size;
5659 		void *nlist;
5660 		if (snd_BUG_ON(num >= 4096))
5661 			return NULL;
5662 		nlist = krealloc(array->list, size, GFP_KERNEL | __GFP_ZERO);
5663 		if (!nlist)
5664 			return NULL;
5665 		array->list = nlist;
5666 		array->alloced = num;
5667 	}
5668 	return snd_array_elem(array, array->used++);
5669 }
5670 EXPORT_SYMBOL_HDA(snd_array_new);
5671 
5672 /**
5673  * snd_array_free - free the given array elements
5674  * @array: the array object
5675  */
5676 void snd_array_free(struct snd_array *array)
5677 {
5678 	kfree(array->list);
5679 	array->used = 0;
5680 	array->alloced = 0;
5681 	array->list = NULL;
5682 }
5683 EXPORT_SYMBOL_HDA(snd_array_free);
5684 
5685 /**
5686  * snd_print_pcm_bits - Print the supported PCM fmt bits to the string buffer
5687  * @pcm: PCM caps bits
5688  * @buf: the string buffer to write
5689  * @buflen: the max buffer length
5690  *
5691  * used by hda_proc.c and hda_eld.c
5692  */
5693 void snd_print_pcm_bits(int pcm, char *buf, int buflen)
5694 {
5695 	static unsigned int bits[] = { 8, 16, 20, 24, 32 };
5696 	int i, j;
5697 
5698 	for (i = 0, j = 0; i < ARRAY_SIZE(bits); i++)
5699 		if (pcm & (AC_SUPPCM_BITS_8 << i))
5700 			j += snprintf(buf + j, buflen - j,  " %d", bits[i]);
5701 
5702 	buf[j] = '\0'; /* necessary when j == 0 */
5703 }
5704 EXPORT_SYMBOL_HDA(snd_print_pcm_bits);
5705 
5706 MODULE_DESCRIPTION("HDA codec core");
5707 MODULE_LICENSE("GPL");
5708