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