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