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