[ALSA] Fix/add support of Realtek ALC883 / ALC888 and ALC861 codecs
[linux-2.6] / sound / pci / hda / hda_codec.c
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 <sound/driver.h>
23 #include <linux/init.h>
24 #include <linux/delay.h>
25 #include <linux/slab.h>
26 #include <linux/pci.h>
27 #include <linux/moduleparam.h>
28 #include <linux/mutex.h>
29 #include <sound/core.h>
30 #include "hda_codec.h"
31 #include <sound/asoundef.h>
32 #include <sound/initval.h>
33 #include "hda_local.h"
34
35
36 MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
37 MODULE_DESCRIPTION("Universal interface for High Definition Audio Codec");
38 MODULE_LICENSE("GPL");
39
40
41 /*
42  * vendor / preset table
43  */
44
45 struct hda_vendor_id {
46         unsigned int id;
47         const char *name;
48 };
49
50 /* codec vendor labels */
51 static struct hda_vendor_id hda_vendor_ids[] = {
52         { 0x10ec, "Realtek" },
53         { 0x11d4, "Analog Devices" },
54         { 0x13f6, "C-Media" },
55         { 0x434d, "C-Media" },
56         { 0x8384, "SigmaTel" },
57         {} /* terminator */
58 };
59
60 /* codec presets */
61 #include "hda_patch.h"
62
63
64 /**
65  * snd_hda_codec_read - send a command and get the response
66  * @codec: the HDA codec
67  * @nid: NID to send the command
68  * @direct: direct flag
69  * @verb: the verb to send
70  * @parm: the parameter for the verb
71  *
72  * Send a single command and read the corresponding response.
73  *
74  * Returns the obtained response value, or -1 for an error.
75  */
76 unsigned int snd_hda_codec_read(struct hda_codec *codec, hda_nid_t nid, int direct,
77                                 unsigned int verb, unsigned int parm)
78 {
79         unsigned int res;
80         mutex_lock(&codec->bus->cmd_mutex);
81         if (! codec->bus->ops.command(codec, nid, direct, verb, parm))
82                 res = codec->bus->ops.get_response(codec);
83         else
84                 res = (unsigned int)-1;
85         mutex_unlock(&codec->bus->cmd_mutex);
86         return res;
87 }
88
89 EXPORT_SYMBOL(snd_hda_codec_read);
90
91 /**
92  * snd_hda_codec_write - send a single command without waiting for response
93  * @codec: the HDA codec
94  * @nid: NID to send the command
95  * @direct: direct flag
96  * @verb: the verb to send
97  * @parm: the parameter for the verb
98  *
99  * Send a single command without waiting for response.
100  *
101  * Returns 0 if successful, or a negative error code.
102  */
103 int snd_hda_codec_write(struct hda_codec *codec, hda_nid_t nid, int direct,
104                          unsigned int verb, unsigned int parm)
105 {
106         int err;
107         mutex_lock(&codec->bus->cmd_mutex);
108         err = codec->bus->ops.command(codec, nid, direct, verb, parm);
109         mutex_unlock(&codec->bus->cmd_mutex);
110         return err;
111 }
112
113 EXPORT_SYMBOL(snd_hda_codec_write);
114
115 /**
116  * snd_hda_sequence_write - sequence writes
117  * @codec: the HDA codec
118  * @seq: VERB array to send
119  *
120  * Send the commands sequentially from the given array.
121  * The array must be terminated with NID=0.
122  */
123 void snd_hda_sequence_write(struct hda_codec *codec, const struct hda_verb *seq)
124 {
125         for (; seq->nid; seq++)
126                 snd_hda_codec_write(codec, seq->nid, 0, seq->verb, seq->param);
127 }
128
129 EXPORT_SYMBOL(snd_hda_sequence_write);
130
131 /**
132  * snd_hda_get_sub_nodes - get the range of sub nodes
133  * @codec: the HDA codec
134  * @nid: NID to parse
135  * @start_id: the pointer to store the start NID
136  *
137  * Parse the NID and store the start NID of its sub-nodes.
138  * Returns the number of sub-nodes.
139  */
140 int snd_hda_get_sub_nodes(struct hda_codec *codec, hda_nid_t nid, hda_nid_t *start_id)
141 {
142         unsigned int parm;
143
144         parm = snd_hda_param_read(codec, nid, AC_PAR_NODE_COUNT);
145         *start_id = (parm >> 16) & 0x7fff;
146         return (int)(parm & 0x7fff);
147 }
148
149 EXPORT_SYMBOL(snd_hda_get_sub_nodes);
150
151 /**
152  * snd_hda_get_connections - get connection list
153  * @codec: the HDA codec
154  * @nid: NID to parse
155  * @conn_list: connection list array
156  * @max_conns: max. number of connections to store
157  *
158  * Parses the connection list of the given widget and stores the list
159  * of NIDs.
160  *
161  * Returns the number of connections, or a negative error code.
162  */
163 int snd_hda_get_connections(struct hda_codec *codec, hda_nid_t nid,
164                             hda_nid_t *conn_list, int max_conns)
165 {
166         unsigned int parm;
167         int i, conn_len, conns;
168         unsigned int shift, num_elems, mask;
169         hda_nid_t prev_nid;
170
171         snd_assert(conn_list && max_conns > 0, return -EINVAL);
172
173         parm = snd_hda_param_read(codec, nid, AC_PAR_CONNLIST_LEN);
174         if (parm & AC_CLIST_LONG) {
175                 /* long form */
176                 shift = 16;
177                 num_elems = 2;
178         } else {
179                 /* short form */
180                 shift = 8;
181                 num_elems = 4;
182         }
183         conn_len = parm & AC_CLIST_LENGTH;
184         mask = (1 << (shift-1)) - 1;
185
186         if (! conn_len)
187                 return 0; /* no connection */
188
189         if (conn_len == 1) {
190                 /* single connection */
191                 parm = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_CONNECT_LIST, 0);
192                 conn_list[0] = parm & mask;
193                 return 1;
194         }
195
196         /* multi connection */
197         conns = 0;
198         prev_nid = 0;
199         for (i = 0; i < conn_len; i++) {
200                 int range_val;
201                 hda_nid_t val, n;
202
203                 if (i % num_elems == 0)
204                         parm = snd_hda_codec_read(codec, nid, 0,
205                                                   AC_VERB_GET_CONNECT_LIST, i);
206                 range_val = !! (parm & (1 << (shift-1))); /* ranges */
207                 val = parm & mask;
208                 parm >>= shift;
209                 if (range_val) {
210                         /* ranges between the previous and this one */
211                         if (! prev_nid || prev_nid >= val) {
212                                 snd_printk(KERN_WARNING "hda_codec: invalid dep_range_val %x:%x\n", prev_nid, val);
213                                 continue;
214                         }
215                         for (n = prev_nid + 1; n <= val; n++) {
216                                 if (conns >= max_conns) {
217                                         snd_printk(KERN_ERR "Too many connections\n");
218                                         return -EINVAL;
219                                 }
220                                 conn_list[conns++] = n;
221                         }
222                 } else {
223                         if (conns >= max_conns) {
224                                 snd_printk(KERN_ERR "Too many connections\n");
225                                 return -EINVAL;
226                         }
227                         conn_list[conns++] = val;
228                 }
229                 prev_nid = val;
230         }
231         return conns;
232 }
233
234
235 /**
236  * snd_hda_queue_unsol_event - add an unsolicited event to queue
237  * @bus: the BUS
238  * @res: unsolicited event (lower 32bit of RIRB entry)
239  * @res_ex: codec addr and flags (upper 32bit or RIRB entry)
240  *
241  * Adds the given event to the queue.  The events are processed in
242  * the workqueue asynchronously.  Call this function in the interrupt
243  * hanlder when RIRB receives an unsolicited event.
244  *
245  * Returns 0 if successful, or a negative error code.
246  */
247 int snd_hda_queue_unsol_event(struct hda_bus *bus, u32 res, u32 res_ex)
248 {
249         struct hda_bus_unsolicited *unsol;
250         unsigned int wp;
251
252         if ((unsol = bus->unsol) == NULL)
253                 return 0;
254
255         wp = (unsol->wp + 1) % HDA_UNSOL_QUEUE_SIZE;
256         unsol->wp = wp;
257
258         wp <<= 1;
259         unsol->queue[wp] = res;
260         unsol->queue[wp + 1] = res_ex;
261
262         queue_work(unsol->workq, &unsol->work);
263
264         return 0;
265 }
266
267 EXPORT_SYMBOL(snd_hda_queue_unsol_event);
268
269 /*
270  * process queueud unsolicited events
271  */
272 static void process_unsol_events(void *data)
273 {
274         struct hda_bus *bus = data;
275         struct hda_bus_unsolicited *unsol = bus->unsol;
276         struct hda_codec *codec;
277         unsigned int rp, caddr, res;
278
279         while (unsol->rp != unsol->wp) {
280                 rp = (unsol->rp + 1) % HDA_UNSOL_QUEUE_SIZE;
281                 unsol->rp = rp;
282                 rp <<= 1;
283                 res = unsol->queue[rp];
284                 caddr = unsol->queue[rp + 1];
285                 if (! (caddr & (1 << 4))) /* no unsolicited event? */
286                         continue;
287                 codec = bus->caddr_tbl[caddr & 0x0f];
288                 if (codec && codec->patch_ops.unsol_event)
289                         codec->patch_ops.unsol_event(codec, res);
290         }
291 }
292
293 /*
294  * initialize unsolicited queue
295  */
296 static int init_unsol_queue(struct hda_bus *bus)
297 {
298         struct hda_bus_unsolicited *unsol;
299
300         if (bus->unsol) /* already initialized */
301                 return 0;
302
303         unsol = kzalloc(sizeof(*unsol), GFP_KERNEL);
304         if (! unsol) {
305                 snd_printk(KERN_ERR "hda_codec: can't allocate unsolicited queue\n");
306                 return -ENOMEM;
307         }
308         unsol->workq = create_singlethread_workqueue("hda_codec");
309         if (! unsol->workq) {
310                 snd_printk(KERN_ERR "hda_codec: can't create workqueue\n");
311                 kfree(unsol);
312                 return -ENOMEM;
313         }
314         INIT_WORK(&unsol->work, process_unsol_events, bus);
315         bus->unsol = unsol;
316         return 0;
317 }
318
319 /*
320  * destructor
321  */
322 static void snd_hda_codec_free(struct hda_codec *codec);
323
324 static int snd_hda_bus_free(struct hda_bus *bus)
325 {
326         struct list_head *p, *n;
327
328         if (! bus)
329                 return 0;
330         if (bus->unsol) {
331                 destroy_workqueue(bus->unsol->workq);
332                 kfree(bus->unsol);
333         }
334         list_for_each_safe(p, n, &bus->codec_list) {
335                 struct hda_codec *codec = list_entry(p, struct hda_codec, list);
336                 snd_hda_codec_free(codec);
337         }
338         if (bus->ops.private_free)
339                 bus->ops.private_free(bus);
340         kfree(bus);
341         return 0;
342 }
343
344 static int snd_hda_bus_dev_free(struct snd_device *device)
345 {
346         struct hda_bus *bus = device->device_data;
347         return snd_hda_bus_free(bus);
348 }
349
350 /**
351  * snd_hda_bus_new - create a HDA bus
352  * @card: the card entry
353  * @temp: the template for hda_bus information
354  * @busp: the pointer to store the created bus instance
355  *
356  * Returns 0 if successful, or a negative error code.
357  */
358 int snd_hda_bus_new(struct snd_card *card, const struct hda_bus_template *temp,
359                     struct hda_bus **busp)
360 {
361         struct hda_bus *bus;
362         int err;
363         static struct snd_device_ops dev_ops = {
364                 .dev_free = snd_hda_bus_dev_free,
365         };
366
367         snd_assert(temp, return -EINVAL);
368         snd_assert(temp->ops.command && temp->ops.get_response, return -EINVAL);
369
370         if (busp)
371                 *busp = NULL;
372
373         bus = kzalloc(sizeof(*bus), GFP_KERNEL);
374         if (bus == NULL) {
375                 snd_printk(KERN_ERR "can't allocate struct hda_bus\n");
376                 return -ENOMEM;
377         }
378
379         bus->card = card;
380         bus->private_data = temp->private_data;
381         bus->pci = temp->pci;
382         bus->modelname = temp->modelname;
383         bus->ops = temp->ops;
384
385         mutex_init(&bus->cmd_mutex);
386         INIT_LIST_HEAD(&bus->codec_list);
387
388         if ((err = snd_device_new(card, SNDRV_DEV_BUS, bus, &dev_ops)) < 0) {
389                 snd_hda_bus_free(bus);
390                 return err;
391         }
392         if (busp)
393                 *busp = bus;
394         return 0;
395 }
396
397 EXPORT_SYMBOL(snd_hda_bus_new);
398
399 /*
400  * find a matching codec preset
401  */
402 static const struct hda_codec_preset *find_codec_preset(struct hda_codec *codec)
403 {
404         const struct hda_codec_preset **tbl, *preset;
405
406         for (tbl = hda_preset_tables; *tbl; tbl++) {
407                 for (preset = *tbl; preset->id; preset++) {
408                         u32 mask = preset->mask;
409                         if (! mask)
410                                 mask = ~0;
411                         if (preset->id == (codec->vendor_id & mask) &&
412                             (! preset->rev ||
413                              preset->rev == codec->revision_id))
414                                 return preset;
415                 }
416         }
417         return NULL;
418 }
419
420 /*
421  * snd_hda_get_codec_name - store the codec name
422  */
423 void snd_hda_get_codec_name(struct hda_codec *codec,
424                             char *name, int namelen)
425 {
426         const struct hda_vendor_id *c;
427         const char *vendor = NULL;
428         u16 vendor_id = codec->vendor_id >> 16;
429         char tmp[16];
430
431         for (c = hda_vendor_ids; c->id; c++) {
432                 if (c->id == vendor_id) {
433                         vendor = c->name;
434                         break;
435                 }
436         }
437         if (! vendor) {
438                 sprintf(tmp, "Generic %04x", vendor_id);
439                 vendor = tmp;
440         }
441         if (codec->preset && codec->preset->name)
442                 snprintf(name, namelen, "%s %s", vendor, codec->preset->name);
443         else
444                 snprintf(name, namelen, "%s ID %x", vendor, codec->vendor_id & 0xffff);
445 }
446
447 /*
448  * look for an AFG and MFG nodes
449  */
450 static void setup_fg_nodes(struct hda_codec *codec)
451 {
452         int i, total_nodes;
453         hda_nid_t nid;
454
455         total_nodes = snd_hda_get_sub_nodes(codec, AC_NODE_ROOT, &nid);
456         for (i = 0; i < total_nodes; i++, nid++) {
457                 switch((snd_hda_param_read(codec, nid, AC_PAR_FUNCTION_TYPE) & 0xff)) {
458                 case AC_GRP_AUDIO_FUNCTION:
459                         codec->afg = nid;
460                         break;
461                 case AC_GRP_MODEM_FUNCTION:
462                         codec->mfg = nid;
463                         break;
464                 default:
465                         break;
466                 }
467         }
468 }
469
470 /*
471  * read widget caps for each widget and store in cache
472  */
473 static int read_widget_caps(struct hda_codec *codec, hda_nid_t fg_node)
474 {
475         int i;
476         hda_nid_t nid;
477
478         codec->num_nodes = snd_hda_get_sub_nodes(codec, fg_node,
479                                                  &codec->start_nid);
480         codec->wcaps = kmalloc(codec->num_nodes * 4, GFP_KERNEL);
481         if (! codec->wcaps)
482                 return -ENOMEM;
483         nid = codec->start_nid;
484         for (i = 0; i < codec->num_nodes; i++, nid++)
485                 codec->wcaps[i] = snd_hda_param_read(codec, nid,
486                                                      AC_PAR_AUDIO_WIDGET_CAP);
487         return 0;
488 }
489
490
491 /*
492  * codec destructor
493  */
494 static void snd_hda_codec_free(struct hda_codec *codec)
495 {
496         if (! codec)
497                 return;
498         list_del(&codec->list);
499         codec->bus->caddr_tbl[codec->addr] = NULL;
500         if (codec->patch_ops.free)
501                 codec->patch_ops.free(codec);
502         kfree(codec->amp_info);
503         kfree(codec->wcaps);
504         kfree(codec);
505 }
506
507 static void init_amp_hash(struct hda_codec *codec);
508
509 /**
510  * snd_hda_codec_new - create a HDA codec
511  * @bus: the bus to assign
512  * @codec_addr: the codec address
513  * @codecp: the pointer to store the generated codec
514  *
515  * Returns 0 if successful, or a negative error code.
516  */
517 int snd_hda_codec_new(struct hda_bus *bus, unsigned int codec_addr,
518                       struct hda_codec **codecp)
519 {
520         struct hda_codec *codec;
521         char component[13];
522         int err;
523
524         snd_assert(bus, return -EINVAL);
525         snd_assert(codec_addr <= HDA_MAX_CODEC_ADDRESS, return -EINVAL);
526
527         if (bus->caddr_tbl[codec_addr]) {
528                 snd_printk(KERN_ERR "hda_codec: address 0x%x is already occupied\n", codec_addr);
529                 return -EBUSY;
530         }
531
532         codec = kzalloc(sizeof(*codec), GFP_KERNEL);
533         if (codec == NULL) {
534                 snd_printk(KERN_ERR "can't allocate struct hda_codec\n");
535                 return -ENOMEM;
536         }
537
538         codec->bus = bus;
539         codec->addr = codec_addr;
540         mutex_init(&codec->spdif_mutex);
541         init_amp_hash(codec);
542
543         list_add_tail(&codec->list, &bus->codec_list);
544         bus->caddr_tbl[codec_addr] = codec;
545
546         codec->vendor_id = snd_hda_param_read(codec, AC_NODE_ROOT, AC_PAR_VENDOR_ID);
547         if (codec->vendor_id == -1)
548                 /* read again, hopefully the access method was corrected
549                  * in the last read...
550                  */
551                 codec->vendor_id = snd_hda_param_read(codec, AC_NODE_ROOT,
552                                                       AC_PAR_VENDOR_ID);
553         codec->subsystem_id = snd_hda_param_read(codec, AC_NODE_ROOT, AC_PAR_SUBSYSTEM_ID);
554         codec->revision_id = snd_hda_param_read(codec, AC_NODE_ROOT, AC_PAR_REV_ID);
555
556         setup_fg_nodes(codec);
557         if (! codec->afg && ! codec->mfg) {
558                 snd_printdd("hda_codec: no AFG or MFG node found\n");
559                 snd_hda_codec_free(codec);
560                 return -ENODEV;
561         }
562
563         if (read_widget_caps(codec, codec->afg ? codec->afg : codec->mfg) < 0) {
564                 snd_printk(KERN_ERR "hda_codec: cannot malloc\n");
565                 snd_hda_codec_free(codec);
566                 return -ENOMEM;
567         }
568
569         if (! codec->subsystem_id) {
570                 hda_nid_t nid = codec->afg ? codec->afg : codec->mfg;
571                 codec->subsystem_id = snd_hda_codec_read(codec, nid, 0,
572                                                          AC_VERB_GET_SUBSYSTEM_ID,
573                                                          0);
574         }
575
576         codec->preset = find_codec_preset(codec);
577         if (! *bus->card->mixername)
578                 snd_hda_get_codec_name(codec, bus->card->mixername,
579                                        sizeof(bus->card->mixername));
580
581         if (codec->preset && codec->preset->patch)
582                 err = codec->preset->patch(codec);
583         else
584                 err = snd_hda_parse_generic_codec(codec);
585         if (err < 0) {
586                 snd_hda_codec_free(codec);
587                 return err;
588         }
589
590         if (codec->patch_ops.unsol_event)
591                 init_unsol_queue(bus);
592
593         snd_hda_codec_proc_new(codec);
594
595         sprintf(component, "HDA:%08x", codec->vendor_id);
596         snd_component_add(codec->bus->card, component);
597
598         if (codecp)
599                 *codecp = codec;
600         return 0;
601 }
602
603 EXPORT_SYMBOL(snd_hda_codec_new);
604
605 /**
606  * snd_hda_codec_setup_stream - set up the codec for streaming
607  * @codec: the CODEC to set up
608  * @nid: the NID to set up
609  * @stream_tag: stream tag to pass, it's between 0x1 and 0xf.
610  * @channel_id: channel id to pass, zero based.
611  * @format: stream format.
612  */
613 void snd_hda_codec_setup_stream(struct hda_codec *codec, hda_nid_t nid, u32 stream_tag,
614                                 int channel_id, int format)
615 {
616         if (! nid)
617                 return;
618
619         snd_printdd("hda_codec_setup_stream: NID=0x%x, stream=0x%x, channel=%d, format=0x%x\n",
620                     nid, stream_tag, channel_id, format);
621         snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_CHANNEL_STREAMID,
622                             (stream_tag << 4) | channel_id);
623         msleep(1);
624         snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_STREAM_FORMAT, format);
625 }
626
627 EXPORT_SYMBOL(snd_hda_codec_setup_stream);
628
629 /*
630  * amp access functions
631  */
632
633 /* FIXME: more better hash key? */
634 #define HDA_HASH_KEY(nid,dir,idx) (u32)((nid) + ((idx) << 16) + ((dir) << 24))
635 #define INFO_AMP_CAPS   (1<<0)
636 #define INFO_AMP_VOL(ch)        (1 << (1 + (ch)))
637
638 /* initialize the hash table */
639 static void init_amp_hash(struct hda_codec *codec)
640 {
641         memset(codec->amp_hash, 0xff, sizeof(codec->amp_hash));
642         codec->num_amp_entries = 0;
643         codec->amp_info_size = 0;
644         codec->amp_info = NULL;
645 }
646
647 /* query the hash.  allocate an entry if not found. */
648 static struct hda_amp_info *get_alloc_amp_hash(struct hda_codec *codec, u32 key)
649 {
650         u16 idx = key % (u16)ARRAY_SIZE(codec->amp_hash);
651         u16 cur = codec->amp_hash[idx];
652         struct hda_amp_info *info;
653
654         while (cur != 0xffff) {
655                 info = &codec->amp_info[cur];
656                 if (info->key == key)
657                         return info;
658                 cur = info->next;
659         }
660
661         /* add a new hash entry */
662         if (codec->num_amp_entries >= codec->amp_info_size) {
663                 /* reallocate the array */
664                 int new_size = codec->amp_info_size + 64;
665                 struct hda_amp_info *new_info = kcalloc(new_size, sizeof(struct hda_amp_info),
666                                                         GFP_KERNEL);
667                 if (! new_info) {
668                         snd_printk(KERN_ERR "hda_codec: can't malloc amp_info\n");
669                         return NULL;
670                 }
671                 if (codec->amp_info) {
672                         memcpy(new_info, codec->amp_info,
673                                codec->amp_info_size * sizeof(struct hda_amp_info));
674                         kfree(codec->amp_info);
675                 }
676                 codec->amp_info_size = new_size;
677                 codec->amp_info = new_info;
678         }
679         cur = codec->num_amp_entries++;
680         info = &codec->amp_info[cur];
681         info->key = key;
682         info->status = 0; /* not initialized yet */
683         info->next = codec->amp_hash[idx];
684         codec->amp_hash[idx] = cur;
685
686         return info;
687 }
688
689 /*
690  * query AMP capabilities for the given widget and direction
691  */
692 static u32 query_amp_caps(struct hda_codec *codec, hda_nid_t nid, int direction)
693 {
694         struct hda_amp_info *info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, direction, 0));
695
696         if (! info)
697                 return 0;
698         if (! (info->status & INFO_AMP_CAPS)) {
699                 if (! (get_wcaps(codec, nid) & AC_WCAP_AMP_OVRD))
700                         nid = codec->afg;
701                 info->amp_caps = snd_hda_param_read(codec, nid, direction == HDA_OUTPUT ?
702                                                     AC_PAR_AMP_OUT_CAP : AC_PAR_AMP_IN_CAP);
703                 info->status |= INFO_AMP_CAPS;
704         }
705         return info->amp_caps;
706 }
707
708 /*
709  * read the current volume to info
710  * if the cache exists, read the cache value.
711  */
712 static unsigned int get_vol_mute(struct hda_codec *codec, struct hda_amp_info *info,
713                          hda_nid_t nid, int ch, int direction, int index)
714 {
715         u32 val, parm;
716
717         if (info->status & INFO_AMP_VOL(ch))
718                 return info->vol[ch];
719
720         parm = ch ? AC_AMP_GET_RIGHT : AC_AMP_GET_LEFT;
721         parm |= direction == HDA_OUTPUT ? AC_AMP_GET_OUTPUT : AC_AMP_GET_INPUT;
722         parm |= index;
723         val = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_AMP_GAIN_MUTE, parm);
724         info->vol[ch] = val & 0xff;
725         info->status |= INFO_AMP_VOL(ch);
726         return info->vol[ch];
727 }
728
729 /*
730  * write the current volume in info to the h/w and update the cache
731  */
732 static void put_vol_mute(struct hda_codec *codec, struct hda_amp_info *info,
733                          hda_nid_t nid, int ch, int direction, int index, int val)
734 {
735         u32 parm;
736
737         parm = ch ? AC_AMP_SET_RIGHT : AC_AMP_SET_LEFT;
738         parm |= direction == HDA_OUTPUT ? AC_AMP_SET_OUTPUT : AC_AMP_SET_INPUT;
739         parm |= index << AC_AMP_SET_INDEX_SHIFT;
740         parm |= val;
741         snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_AMP_GAIN_MUTE, parm);
742         info->vol[ch] = val;
743 }
744
745 /*
746  * read AMP value.  The volume is between 0 to 0x7f, 0x80 = mute bit.
747  */
748 int snd_hda_codec_amp_read(struct hda_codec *codec, hda_nid_t nid, int ch,
749                            int direction, int index)
750 {
751         struct hda_amp_info *info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, direction, index));
752         if (! info)
753                 return 0;
754         return get_vol_mute(codec, info, nid, ch, direction, index);
755 }
756
757 /*
758  * update the AMP value, mask = bit mask to set, val = the value
759  */
760 int snd_hda_codec_amp_update(struct hda_codec *codec, hda_nid_t nid, int ch,
761                              int direction, int idx, int mask, int val)
762 {
763         struct hda_amp_info *info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, direction, idx));
764
765         if (! info)
766                 return 0;
767         val &= mask;
768         val |= get_vol_mute(codec, info, nid, ch, direction, idx) & ~mask;
769         if (info->vol[ch] == val && ! codec->in_resume)
770                 return 0;
771         put_vol_mute(codec, info, nid, ch, direction, idx, val);
772         return 1;
773 }
774
775
776 /*
777  * AMP control callbacks
778  */
779 /* retrieve parameters from private_value */
780 #define get_amp_nid(kc)         ((kc)->private_value & 0xffff)
781 #define get_amp_channels(kc)    (((kc)->private_value >> 16) & 0x3)
782 #define get_amp_direction(kc)   (((kc)->private_value >> 18) & 0x1)
783 #define get_amp_index(kc)       (((kc)->private_value >> 19) & 0xf)
784
785 /* volume */
786 int snd_hda_mixer_amp_volume_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
787 {
788         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
789         u16 nid = get_amp_nid(kcontrol);
790         u8 chs = get_amp_channels(kcontrol);
791         int dir = get_amp_direction(kcontrol);
792         u32 caps;
793
794         caps = query_amp_caps(codec, nid, dir);
795         caps = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT; /* num steps */
796         if (! caps) {
797                 printk(KERN_WARNING "hda_codec: num_steps = 0 for NID=0x%x\n", nid);
798                 return -EINVAL;
799         }
800         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
801         uinfo->count = chs == 3 ? 2 : 1;
802         uinfo->value.integer.min = 0;
803         uinfo->value.integer.max = caps;
804         return 0;
805 }
806
807 int snd_hda_mixer_amp_volume_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
808 {
809         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
810         hda_nid_t nid = get_amp_nid(kcontrol);
811         int chs = get_amp_channels(kcontrol);
812         int dir = get_amp_direction(kcontrol);
813         int idx = get_amp_index(kcontrol);
814         long *valp = ucontrol->value.integer.value;
815
816         if (chs & 1)
817                 *valp++ = snd_hda_codec_amp_read(codec, nid, 0, dir, idx) & 0x7f;
818         if (chs & 2)
819                 *valp = snd_hda_codec_amp_read(codec, nid, 1, dir, idx) & 0x7f;
820         return 0;
821 }
822
823 int snd_hda_mixer_amp_volume_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
824 {
825         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
826         hda_nid_t nid = get_amp_nid(kcontrol);
827         int chs = get_amp_channels(kcontrol);
828         int dir = get_amp_direction(kcontrol);
829         int idx = get_amp_index(kcontrol);
830         long *valp = ucontrol->value.integer.value;
831         int change = 0;
832
833         if (chs & 1) {
834                 change = snd_hda_codec_amp_update(codec, nid, 0, dir, idx,
835                                                   0x7f, *valp);
836                 valp++;
837         }
838         if (chs & 2)
839                 change |= snd_hda_codec_amp_update(codec, nid, 1, dir, idx,
840                                                    0x7f, *valp);
841         return change;
842 }
843
844 /* switch */
845 int snd_hda_mixer_amp_switch_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
846 {
847         int chs = get_amp_channels(kcontrol);
848
849         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
850         uinfo->count = chs == 3 ? 2 : 1;
851         uinfo->value.integer.min = 0;
852         uinfo->value.integer.max = 1;
853         return 0;
854 }
855
856 int snd_hda_mixer_amp_switch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
857 {
858         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
859         hda_nid_t nid = get_amp_nid(kcontrol);
860         int chs = get_amp_channels(kcontrol);
861         int dir = get_amp_direction(kcontrol);
862         int idx = get_amp_index(kcontrol);
863         long *valp = ucontrol->value.integer.value;
864
865         if (chs & 1)
866                 *valp++ = (snd_hda_codec_amp_read(codec, nid, 0, dir, idx) & 0x80) ? 0 : 1;
867         if (chs & 2)
868                 *valp = (snd_hda_codec_amp_read(codec, nid, 1, dir, idx) & 0x80) ? 0 : 1;
869         return 0;
870 }
871
872 int snd_hda_mixer_amp_switch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
873 {
874         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
875         hda_nid_t nid = get_amp_nid(kcontrol);
876         int chs = get_amp_channels(kcontrol);
877         int dir = get_amp_direction(kcontrol);
878         int idx = get_amp_index(kcontrol);
879         long *valp = ucontrol->value.integer.value;
880         int change = 0;
881
882         if (chs & 1) {
883                 change = snd_hda_codec_amp_update(codec, nid, 0, dir, idx,
884                                                   0x80, *valp ? 0 : 0x80);
885                 valp++;
886         }
887         if (chs & 2)
888                 change |= snd_hda_codec_amp_update(codec, nid, 1, dir, idx,
889                                                    0x80, *valp ? 0 : 0x80);
890         
891         return change;
892 }
893
894 /*
895  * bound volume controls
896  *
897  * bind multiple volumes (# indices, from 0)
898  */
899
900 #define AMP_VAL_IDX_SHIFT       19
901 #define AMP_VAL_IDX_MASK        (0x0f<<19)
902
903 int snd_hda_mixer_bind_switch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
904 {
905         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
906         unsigned long pval;
907         int err;
908
909         mutex_lock(&codec->spdif_mutex); /* reuse spdif_mutex */
910         pval = kcontrol->private_value;
911         kcontrol->private_value = pval & ~AMP_VAL_IDX_MASK; /* index 0 */
912         err = snd_hda_mixer_amp_switch_get(kcontrol, ucontrol);
913         kcontrol->private_value = pval;
914         mutex_unlock(&codec->spdif_mutex);
915         return err;
916 }
917
918 int snd_hda_mixer_bind_switch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
919 {
920         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
921         unsigned long pval;
922         int i, indices, err = 0, change = 0;
923
924         mutex_lock(&codec->spdif_mutex); /* reuse spdif_mutex */
925         pval = kcontrol->private_value;
926         indices = (pval & AMP_VAL_IDX_MASK) >> AMP_VAL_IDX_SHIFT;
927         for (i = 0; i < indices; i++) {
928                 kcontrol->private_value = (pval & ~AMP_VAL_IDX_MASK) | (i << AMP_VAL_IDX_SHIFT);
929                 err = snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
930                 if (err < 0)
931                         break;
932                 change |= err;
933         }
934         kcontrol->private_value = pval;
935         mutex_unlock(&codec->spdif_mutex);
936         return err < 0 ? err : change;
937 }
938
939 /*
940  * SPDIF out controls
941  */
942
943 static int snd_hda_spdif_mask_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
944 {
945         uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
946         uinfo->count = 1;
947         return 0;
948 }
949
950 static int snd_hda_spdif_cmask_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
951 {
952         ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
953                                            IEC958_AES0_NONAUDIO |
954                                            IEC958_AES0_CON_EMPHASIS_5015 |
955                                            IEC958_AES0_CON_NOT_COPYRIGHT;
956         ucontrol->value.iec958.status[1] = IEC958_AES1_CON_CATEGORY |
957                                            IEC958_AES1_CON_ORIGINAL;
958         return 0;
959 }
960
961 static int snd_hda_spdif_pmask_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
962 {
963         ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
964                                            IEC958_AES0_NONAUDIO |
965                                            IEC958_AES0_PRO_EMPHASIS_5015;
966         return 0;
967 }
968
969 static int snd_hda_spdif_default_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
970 {
971         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
972
973         ucontrol->value.iec958.status[0] = codec->spdif_status & 0xff;
974         ucontrol->value.iec958.status[1] = (codec->spdif_status >> 8) & 0xff;
975         ucontrol->value.iec958.status[2] = (codec->spdif_status >> 16) & 0xff;
976         ucontrol->value.iec958.status[3] = (codec->spdif_status >> 24) & 0xff;
977
978         return 0;
979 }
980
981 /* convert from SPDIF status bits to HDA SPDIF bits
982  * bit 0 (DigEn) is always set zero (to be filled later)
983  */
984 static unsigned short convert_from_spdif_status(unsigned int sbits)
985 {
986         unsigned short val = 0;
987
988         if (sbits & IEC958_AES0_PROFESSIONAL)
989                 val |= 1 << 6;
990         if (sbits & IEC958_AES0_NONAUDIO)
991                 val |= 1 << 5;
992         if (sbits & IEC958_AES0_PROFESSIONAL) {
993                 if ((sbits & IEC958_AES0_PRO_EMPHASIS) == IEC958_AES0_PRO_EMPHASIS_5015)
994                         val |= 1 << 3;
995         } else {
996                 if ((sbits & IEC958_AES0_CON_EMPHASIS) == IEC958_AES0_CON_EMPHASIS_5015)
997                         val |= 1 << 3;
998                 if (! (sbits & IEC958_AES0_CON_NOT_COPYRIGHT))
999                         val |= 1 << 4;
1000                 if (sbits & (IEC958_AES1_CON_ORIGINAL << 8))
1001                         val |= 1 << 7;
1002                 val |= sbits & (IEC958_AES1_CON_CATEGORY << 8);
1003         }
1004         return val;
1005 }
1006
1007 /* convert to SPDIF status bits from HDA SPDIF bits
1008  */
1009 static unsigned int convert_to_spdif_status(unsigned short val)
1010 {
1011         unsigned int sbits = 0;
1012
1013         if (val & (1 << 5))
1014                 sbits |= IEC958_AES0_NONAUDIO;
1015         if (val & (1 << 6))
1016                 sbits |= IEC958_AES0_PROFESSIONAL;
1017         if (sbits & IEC958_AES0_PROFESSIONAL) {
1018                 if (sbits & (1 << 3))
1019                         sbits |= IEC958_AES0_PRO_EMPHASIS_5015;
1020         } else {
1021                 if (val & (1 << 3))
1022                         sbits |= IEC958_AES0_CON_EMPHASIS_5015;
1023                 if (! (val & (1 << 4)))
1024                         sbits |= IEC958_AES0_CON_NOT_COPYRIGHT;
1025                 if (val & (1 << 7))
1026                         sbits |= (IEC958_AES1_CON_ORIGINAL << 8);
1027                 sbits |= val & (0x7f << 8);
1028         }
1029         return sbits;
1030 }
1031
1032 static int snd_hda_spdif_default_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1033 {
1034         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1035         hda_nid_t nid = kcontrol->private_value;
1036         unsigned short val;
1037         int change;
1038
1039         mutex_lock(&codec->spdif_mutex);
1040         codec->spdif_status = ucontrol->value.iec958.status[0] |
1041                 ((unsigned int)ucontrol->value.iec958.status[1] << 8) |
1042                 ((unsigned int)ucontrol->value.iec958.status[2] << 16) |
1043                 ((unsigned int)ucontrol->value.iec958.status[3] << 24);
1044         val = convert_from_spdif_status(codec->spdif_status);
1045         val |= codec->spdif_ctls & 1;
1046         change = codec->spdif_ctls != val;
1047         codec->spdif_ctls = val;
1048
1049         if (change || codec->in_resume) {
1050                 snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_DIGI_CONVERT_1, val & 0xff);
1051                 snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_DIGI_CONVERT_2, val >> 8);
1052         }
1053
1054         mutex_unlock(&codec->spdif_mutex);
1055         return change;
1056 }
1057
1058 static int snd_hda_spdif_out_switch_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
1059 {
1060         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
1061         uinfo->count = 1;
1062         uinfo->value.integer.min = 0;
1063         uinfo->value.integer.max = 1;
1064         return 0;
1065 }
1066
1067 static int snd_hda_spdif_out_switch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1068 {
1069         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1070
1071         ucontrol->value.integer.value[0] = codec->spdif_ctls & 1;
1072         return 0;
1073 }
1074
1075 static int snd_hda_spdif_out_switch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1076 {
1077         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1078         hda_nid_t nid = kcontrol->private_value;
1079         unsigned short val;
1080         int change;
1081
1082         mutex_lock(&codec->spdif_mutex);
1083         val = codec->spdif_ctls & ~1;
1084         if (ucontrol->value.integer.value[0])
1085                 val |= 1;
1086         change = codec->spdif_ctls != val;
1087         if (change || codec->in_resume) {
1088                 codec->spdif_ctls = val;
1089                 snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_DIGI_CONVERT_1, val & 0xff);
1090                 snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_AMP_GAIN_MUTE,
1091                                     AC_AMP_SET_RIGHT | AC_AMP_SET_LEFT |
1092                                     AC_AMP_SET_OUTPUT | ((val & 1) ? 0 : 0x80));
1093         }
1094         mutex_unlock(&codec->spdif_mutex);
1095         return change;
1096 }
1097
1098 static struct snd_kcontrol_new dig_mixes[] = {
1099         {
1100                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
1101                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1102                 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,CON_MASK),
1103                 .info = snd_hda_spdif_mask_info,
1104                 .get = snd_hda_spdif_cmask_get,
1105         },
1106         {
1107                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
1108                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1109                 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PRO_MASK),
1110                 .info = snd_hda_spdif_mask_info,
1111                 .get = snd_hda_spdif_pmask_get,
1112         },
1113         {
1114                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1115                 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
1116                 .info = snd_hda_spdif_mask_info,
1117                 .get = snd_hda_spdif_default_get,
1118                 .put = snd_hda_spdif_default_put,
1119         },
1120         {
1121                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1122                 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,SWITCH),
1123                 .info = snd_hda_spdif_out_switch_info,
1124                 .get = snd_hda_spdif_out_switch_get,
1125                 .put = snd_hda_spdif_out_switch_put,
1126         },
1127         { } /* end */
1128 };
1129
1130 /**
1131  * snd_hda_create_spdif_out_ctls - create Output SPDIF-related controls
1132  * @codec: the HDA codec
1133  * @nid: audio out widget NID
1134  *
1135  * Creates controls related with the SPDIF output.
1136  * Called from each patch supporting the SPDIF out.
1137  *
1138  * Returns 0 if successful, or a negative error code.
1139  */
1140 int snd_hda_create_spdif_out_ctls(struct hda_codec *codec, hda_nid_t nid)
1141 {
1142         int err;
1143         struct snd_kcontrol *kctl;
1144         struct snd_kcontrol_new *dig_mix;
1145
1146         for (dig_mix = dig_mixes; dig_mix->name; dig_mix++) {
1147                 kctl = snd_ctl_new1(dig_mix, codec);
1148                 kctl->private_value = nid;
1149                 if ((err = snd_ctl_add(codec->bus->card, kctl)) < 0)
1150                         return err;
1151         }
1152         codec->spdif_ctls = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_DIGI_CONVERT, 0);
1153         codec->spdif_status = convert_to_spdif_status(codec->spdif_ctls);
1154         return 0;
1155 }
1156
1157 /*
1158  * SPDIF input
1159  */
1160
1161 #define snd_hda_spdif_in_switch_info    snd_hda_spdif_out_switch_info
1162
1163 static int snd_hda_spdif_in_switch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1164 {
1165         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1166
1167         ucontrol->value.integer.value[0] = codec->spdif_in_enable;
1168         return 0;
1169 }
1170
1171 static int snd_hda_spdif_in_switch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1172 {
1173         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1174         hda_nid_t nid = kcontrol->private_value;
1175         unsigned int val = !!ucontrol->value.integer.value[0];
1176         int change;
1177
1178         mutex_lock(&codec->spdif_mutex);
1179         change = codec->spdif_in_enable != val;
1180         if (change || codec->in_resume) {
1181                 codec->spdif_in_enable = val;
1182                 snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_DIGI_CONVERT_1, val);
1183         }
1184         mutex_unlock(&codec->spdif_mutex);
1185         return change;
1186 }
1187
1188 static int snd_hda_spdif_in_status_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1189 {
1190         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1191         hda_nid_t nid = kcontrol->private_value;
1192         unsigned short val;
1193         unsigned int sbits;
1194
1195         val = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_DIGI_CONVERT, 0);
1196         sbits = convert_to_spdif_status(val);
1197         ucontrol->value.iec958.status[0] = sbits;
1198         ucontrol->value.iec958.status[1] = sbits >> 8;
1199         ucontrol->value.iec958.status[2] = sbits >> 16;
1200         ucontrol->value.iec958.status[3] = sbits >> 24;
1201         return 0;
1202 }
1203
1204 static struct snd_kcontrol_new dig_in_ctls[] = {
1205         {
1206                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1207                 .name = SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH),
1208                 .info = snd_hda_spdif_in_switch_info,
1209                 .get = snd_hda_spdif_in_switch_get,
1210                 .put = snd_hda_spdif_in_switch_put,
1211         },
1212         {
1213                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
1214                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1215                 .name = SNDRV_CTL_NAME_IEC958("",CAPTURE,DEFAULT),
1216                 .info = snd_hda_spdif_mask_info,
1217                 .get = snd_hda_spdif_in_status_get,
1218         },
1219         { } /* end */
1220 };
1221
1222 /**
1223  * snd_hda_create_spdif_in_ctls - create Input SPDIF-related controls
1224  * @codec: the HDA codec
1225  * @nid: audio in widget NID
1226  *
1227  * Creates controls related with the SPDIF input.
1228  * Called from each patch supporting the SPDIF in.
1229  *
1230  * Returns 0 if successful, or a negative error code.
1231  */
1232 int snd_hda_create_spdif_in_ctls(struct hda_codec *codec, hda_nid_t nid)
1233 {
1234         int err;
1235         struct snd_kcontrol *kctl;
1236         struct snd_kcontrol_new *dig_mix;
1237
1238         for (dig_mix = dig_in_ctls; dig_mix->name; dig_mix++) {
1239                 kctl = snd_ctl_new1(dig_mix, codec);
1240                 kctl->private_value = nid;
1241                 if ((err = snd_ctl_add(codec->bus->card, kctl)) < 0)
1242                         return err;
1243         }
1244         codec->spdif_in_enable = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_DIGI_CONVERT, 0) & 1;
1245         return 0;
1246 }
1247
1248
1249 /*
1250  * set power state of the codec
1251  */
1252 static void hda_set_power_state(struct hda_codec *codec, hda_nid_t fg,
1253                                 unsigned int power_state)
1254 {
1255         hda_nid_t nid, nid_start;
1256         int nodes;
1257
1258         snd_hda_codec_write(codec, fg, 0, AC_VERB_SET_POWER_STATE,
1259                             power_state);
1260
1261         nodes = snd_hda_get_sub_nodes(codec, fg, &nid_start);
1262         for (nid = nid_start; nid < nodes + nid_start; nid++) {
1263                 if (get_wcaps(codec, nid) & AC_WCAP_POWER)
1264                         snd_hda_codec_write(codec, nid, 0,
1265                                             AC_VERB_SET_POWER_STATE,
1266                                             power_state);
1267         }
1268
1269         if (power_state == AC_PWRST_D0)
1270                 msleep(10);
1271 }
1272
1273
1274 /**
1275  * snd_hda_build_controls - build mixer controls
1276  * @bus: the BUS
1277  *
1278  * Creates mixer controls for each codec included in the bus.
1279  *
1280  * Returns 0 if successful, otherwise a negative error code.
1281  */
1282 int snd_hda_build_controls(struct hda_bus *bus)
1283 {
1284         struct list_head *p;
1285
1286         /* build controls */
1287         list_for_each(p, &bus->codec_list) {
1288                 struct hda_codec *codec = list_entry(p, struct hda_codec, list);
1289                 int err;
1290                 if (! codec->patch_ops.build_controls)
1291                         continue;
1292                 err = codec->patch_ops.build_controls(codec);
1293                 if (err < 0)
1294                         return err;
1295         }
1296
1297         /* initialize */
1298         list_for_each(p, &bus->codec_list) {
1299                 struct hda_codec *codec = list_entry(p, struct hda_codec, list);
1300                 int err;
1301                 hda_set_power_state(codec,
1302                                     codec->afg ? codec->afg : codec->mfg,
1303                                     AC_PWRST_D0);
1304                 if (! codec->patch_ops.init)
1305                         continue;
1306                 err = codec->patch_ops.init(codec);
1307                 if (err < 0)
1308                         return err;
1309         }
1310         return 0;
1311 }
1312
1313 EXPORT_SYMBOL(snd_hda_build_controls);
1314
1315 /*
1316  * stream formats
1317  */
1318 struct hda_rate_tbl {
1319         unsigned int hz;
1320         unsigned int alsa_bits;
1321         unsigned int hda_fmt;
1322 };
1323
1324 static struct hda_rate_tbl rate_bits[] = {
1325         /* rate in Hz, ALSA rate bitmask, HDA format value */
1326
1327         /* autodetected value used in snd_hda_query_supported_pcm */
1328         { 8000, SNDRV_PCM_RATE_8000, 0x0500 }, /* 1/6 x 48 */
1329         { 11025, SNDRV_PCM_RATE_11025, 0x4300 }, /* 1/4 x 44 */
1330         { 16000, SNDRV_PCM_RATE_16000, 0x0200 }, /* 1/3 x 48 */
1331         { 22050, SNDRV_PCM_RATE_22050, 0x4100 }, /* 1/2 x 44 */
1332         { 32000, SNDRV_PCM_RATE_32000, 0x0a00 }, /* 2/3 x 48 */
1333         { 44100, SNDRV_PCM_RATE_44100, 0x4000 }, /* 44 */
1334         { 48000, SNDRV_PCM_RATE_48000, 0x0000 }, /* 48 */
1335         { 88200, SNDRV_PCM_RATE_88200, 0x4800 }, /* 2 x 44 */
1336         { 96000, SNDRV_PCM_RATE_96000, 0x0800 }, /* 2 x 48 */
1337         { 176400, SNDRV_PCM_RATE_176400, 0x5800 },/* 4 x 44 */
1338         { 192000, SNDRV_PCM_RATE_192000, 0x1800 }, /* 4 x 48 */
1339
1340         /* not autodetected value */
1341         { 9600, SNDRV_PCM_RATE_KNOT, 0x0400 }, /* 1/5 x 48 */
1342
1343         { 0 } /* terminator */
1344 };
1345
1346 /**
1347  * snd_hda_calc_stream_format - calculate format bitset
1348  * @rate: the sample rate
1349  * @channels: the number of channels
1350  * @format: the PCM format (SNDRV_PCM_FORMAT_XXX)
1351  * @maxbps: the max. bps
1352  *
1353  * Calculate the format bitset from the given rate, channels and th PCM format.
1354  *
1355  * Return zero if invalid.
1356  */
1357 unsigned int snd_hda_calc_stream_format(unsigned int rate,
1358                                         unsigned int channels,
1359                                         unsigned int format,
1360                                         unsigned int maxbps)
1361 {
1362         int i;
1363         unsigned int val = 0;
1364
1365         for (i = 0; rate_bits[i].hz; i++)
1366                 if (rate_bits[i].hz == rate) {
1367                         val = rate_bits[i].hda_fmt;
1368                         break;
1369                 }
1370         if (! rate_bits[i].hz) {
1371                 snd_printdd("invalid rate %d\n", rate);
1372                 return 0;
1373         }
1374
1375         if (channels == 0 || channels > 8) {
1376                 snd_printdd("invalid channels %d\n", channels);
1377                 return 0;
1378         }
1379         val |= channels - 1;
1380
1381         switch (snd_pcm_format_width(format)) {
1382         case 8:  val |= 0x00; break;
1383         case 16: val |= 0x10; break;
1384         case 20:
1385         case 24:
1386         case 32:
1387                 if (maxbps >= 32)
1388                         val |= 0x40;
1389                 else if (maxbps >= 24)
1390                         val |= 0x30;
1391                 else
1392                         val |= 0x20;
1393                 break;
1394         default:
1395                 snd_printdd("invalid format width %d\n", snd_pcm_format_width(format));
1396                 return 0;
1397         }
1398
1399         return val;
1400 }
1401
1402 EXPORT_SYMBOL(snd_hda_calc_stream_format);
1403
1404 /**
1405  * snd_hda_query_supported_pcm - query the supported PCM rates and formats
1406  * @codec: the HDA codec
1407  * @nid: NID to query
1408  * @ratesp: the pointer to store the detected rate bitflags
1409  * @formatsp: the pointer to store the detected formats
1410  * @bpsp: the pointer to store the detected format widths
1411  *
1412  * Queries the supported PCM rates and formats.  The NULL @ratesp, @formatsp
1413  * or @bsps argument is ignored.
1414  *
1415  * Returns 0 if successful, otherwise a negative error code.
1416  */
1417 int snd_hda_query_supported_pcm(struct hda_codec *codec, hda_nid_t nid,
1418                                 u32 *ratesp, u64 *formatsp, unsigned int *bpsp)
1419 {
1420         int i;
1421         unsigned int val, streams;
1422
1423         val = 0;
1424         if (nid != codec->afg &&
1425             (get_wcaps(codec, nid) & AC_WCAP_FORMAT_OVRD)) {
1426                 val = snd_hda_param_read(codec, nid, AC_PAR_PCM);
1427                 if (val == -1)
1428                         return -EIO;
1429         }
1430         if (! val)
1431                 val = snd_hda_param_read(codec, codec->afg, AC_PAR_PCM);
1432
1433         if (ratesp) {
1434                 u32 rates = 0;
1435                 for (i = 0; rate_bits[i].hz; i++) {
1436                         if (val & (1 << i))
1437                                 rates |= rate_bits[i].alsa_bits;
1438                 }
1439                 *ratesp = rates;
1440         }
1441
1442         if (formatsp || bpsp) {
1443                 u64 formats = 0;
1444                 unsigned int bps;
1445                 unsigned int wcaps;
1446
1447                 wcaps = get_wcaps(codec, nid);
1448                 streams = snd_hda_param_read(codec, nid, AC_PAR_STREAM);
1449                 if (streams == -1)
1450                         return -EIO;
1451                 if (! streams) {
1452                         streams = snd_hda_param_read(codec, codec->afg, AC_PAR_STREAM);
1453                         if (streams == -1)
1454                                 return -EIO;
1455                 }
1456
1457                 bps = 0;
1458                 if (streams & AC_SUPFMT_PCM) {
1459                         if (val & AC_SUPPCM_BITS_8) {
1460                                 formats |= SNDRV_PCM_FMTBIT_U8;
1461                                 bps = 8;
1462                         }
1463                         if (val & AC_SUPPCM_BITS_16) {
1464                                 formats |= SNDRV_PCM_FMTBIT_S16_LE;
1465                                 bps = 16;
1466                         }
1467                         if (wcaps & AC_WCAP_DIGITAL) {
1468                                 if (val & AC_SUPPCM_BITS_32)
1469                                         formats |= SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE;
1470                                 if (val & (AC_SUPPCM_BITS_20|AC_SUPPCM_BITS_24))
1471                                         formats |= SNDRV_PCM_FMTBIT_S32_LE;
1472                                 if (val & AC_SUPPCM_BITS_24)
1473                                         bps = 24;
1474                                 else if (val & AC_SUPPCM_BITS_20)
1475                                         bps = 20;
1476                         } else if (val & (AC_SUPPCM_BITS_20|AC_SUPPCM_BITS_24|AC_SUPPCM_BITS_32)) {
1477                                 formats |= SNDRV_PCM_FMTBIT_S32_LE;
1478                                 if (val & AC_SUPPCM_BITS_32)
1479                                         bps = 32;
1480                                 else if (val & AC_SUPPCM_BITS_20)
1481                                         bps = 20;
1482                                 else if (val & AC_SUPPCM_BITS_24)
1483                                         bps = 24;
1484                         }
1485                 }
1486                 else if (streams == AC_SUPFMT_FLOAT32) { /* should be exclusive */
1487                         formats |= SNDRV_PCM_FMTBIT_FLOAT_LE;
1488                         bps = 32;
1489                 } else if (streams == AC_SUPFMT_AC3) { /* should be exclusive */
1490                         /* temporary hack: we have still no proper support
1491                          * for the direct AC3 stream...
1492                          */
1493                         formats |= SNDRV_PCM_FMTBIT_U8;
1494                         bps = 8;
1495                 }
1496                 if (formatsp)
1497                         *formatsp = formats;
1498                 if (bpsp)
1499                         *bpsp = bps;
1500         }
1501
1502         return 0;
1503 }
1504
1505 /**
1506  * snd_hda_is_supported_format - check whether the given node supports the format val
1507  *
1508  * Returns 1 if supported, 0 if not.
1509  */
1510 int snd_hda_is_supported_format(struct hda_codec *codec, hda_nid_t nid,
1511                                 unsigned int format)
1512 {
1513         int i;
1514         unsigned int val = 0, rate, stream;
1515
1516         if (nid != codec->afg &&
1517             (get_wcaps(codec, nid) & AC_WCAP_FORMAT_OVRD)) {
1518                 val = snd_hda_param_read(codec, nid, AC_PAR_PCM);
1519                 if (val == -1)
1520                         return 0;
1521         }
1522         if (! val) {
1523                 val = snd_hda_param_read(codec, codec->afg, AC_PAR_PCM);
1524                 if (val == -1)
1525                         return 0;
1526         }
1527
1528         rate = format & 0xff00;
1529         for (i = 0; rate_bits[i].hz; i++)
1530                 if (rate_bits[i].hda_fmt == rate) {
1531                         if (val & (1 << i))
1532                                 break;
1533                         return 0;
1534                 }
1535         if (! rate_bits[i].hz)
1536                 return 0;
1537
1538         stream = snd_hda_param_read(codec, nid, AC_PAR_STREAM);
1539         if (stream == -1)
1540                 return 0;
1541         if (! stream && nid != codec->afg)
1542                 stream = snd_hda_param_read(codec, codec->afg, AC_PAR_STREAM);
1543         if (! stream || stream == -1)
1544                 return 0;
1545
1546         if (stream & AC_SUPFMT_PCM) {
1547                 switch (format & 0xf0) {
1548                 case 0x00:
1549                         if (! (val & AC_SUPPCM_BITS_8))
1550                                 return 0;
1551                         break;
1552                 case 0x10:
1553                         if (! (val & AC_SUPPCM_BITS_16))
1554                                 return 0;
1555                         break;
1556                 case 0x20:
1557                         if (! (val & AC_SUPPCM_BITS_20))
1558                                 return 0;
1559                         break;
1560                 case 0x30:
1561                         if (! (val & AC_SUPPCM_BITS_24))
1562                                 return 0;
1563                         break;
1564                 case 0x40:
1565                         if (! (val & AC_SUPPCM_BITS_32))
1566                                 return 0;
1567                         break;
1568                 default:
1569                         return 0;
1570                 }
1571         } else {
1572                 /* FIXME: check for float32 and AC3? */
1573         }
1574
1575         return 1;
1576 }
1577
1578 /*
1579  * PCM stuff
1580  */
1581 static int hda_pcm_default_open_close(struct hda_pcm_stream *hinfo,
1582                                       struct hda_codec *codec,
1583                                       struct snd_pcm_substream *substream)
1584 {
1585         return 0;
1586 }
1587
1588 static int hda_pcm_default_prepare(struct hda_pcm_stream *hinfo,
1589                                    struct hda_codec *codec,
1590                                    unsigned int stream_tag,
1591                                    unsigned int format,
1592                                    struct snd_pcm_substream *substream)
1593 {
1594         snd_hda_codec_setup_stream(codec, hinfo->nid, stream_tag, 0, format);
1595         return 0;
1596 }
1597
1598 static int hda_pcm_default_cleanup(struct hda_pcm_stream *hinfo,
1599                                    struct hda_codec *codec,
1600                                    struct snd_pcm_substream *substream)
1601 {
1602         snd_hda_codec_setup_stream(codec, hinfo->nid, 0, 0, 0);
1603         return 0;
1604 }
1605
1606 static int set_pcm_default_values(struct hda_codec *codec, struct hda_pcm_stream *info)
1607 {
1608         if (info->nid) {
1609                 /* query support PCM information from the given NID */
1610                 if (! info->rates || ! info->formats)
1611                         snd_hda_query_supported_pcm(codec, info->nid,
1612                                                     info->rates ? NULL : &info->rates,
1613                                                     info->formats ? NULL : &info->formats,
1614                                                     info->maxbps ? NULL : &info->maxbps);
1615         }
1616         if (info->ops.open == NULL)
1617                 info->ops.open = hda_pcm_default_open_close;
1618         if (info->ops.close == NULL)
1619                 info->ops.close = hda_pcm_default_open_close;
1620         if (info->ops.prepare == NULL) {
1621                 snd_assert(info->nid, return -EINVAL);
1622                 info->ops.prepare = hda_pcm_default_prepare;
1623         }
1624         if (info->ops.cleanup == NULL) {
1625                 snd_assert(info->nid, return -EINVAL);
1626                 info->ops.cleanup = hda_pcm_default_cleanup;
1627         }
1628         return 0;
1629 }
1630
1631 /**
1632  * snd_hda_build_pcms - build PCM information
1633  * @bus: the BUS
1634  *
1635  * Create PCM information for each codec included in the bus.
1636  *
1637  * The build_pcms codec patch is requested to set up codec->num_pcms and
1638  * codec->pcm_info properly.  The array is referred by the top-level driver
1639  * to create its PCM instances.
1640  * The allocated codec->pcm_info should be released in codec->patch_ops.free
1641  * callback.
1642  *
1643  * At least, substreams, channels_min and channels_max must be filled for
1644  * each stream.  substreams = 0 indicates that the stream doesn't exist.
1645  * When rates and/or formats are zero, the supported values are queried
1646  * from the given nid.  The nid is used also by the default ops.prepare
1647  * and ops.cleanup callbacks.
1648  *
1649  * The driver needs to call ops.open in its open callback.  Similarly,
1650  * ops.close is supposed to be called in the close callback.
1651  * ops.prepare should be called in the prepare or hw_params callback
1652  * with the proper parameters for set up.
1653  * ops.cleanup should be called in hw_free for clean up of streams.
1654  *
1655  * This function returns 0 if successfull, or a negative error code.
1656  */
1657 int snd_hda_build_pcms(struct hda_bus *bus)
1658 {
1659         struct list_head *p;
1660
1661         list_for_each(p, &bus->codec_list) {
1662                 struct hda_codec *codec = list_entry(p, struct hda_codec, list);
1663                 unsigned int pcm, s;
1664                 int err;
1665                 if (! codec->patch_ops.build_pcms)
1666                         continue;
1667                 err = codec->patch_ops.build_pcms(codec);
1668                 if (err < 0)
1669                         return err;
1670                 for (pcm = 0; pcm < codec->num_pcms; pcm++) {
1671                         for (s = 0; s < 2; s++) {
1672                                 struct hda_pcm_stream *info;
1673                                 info = &codec->pcm_info[pcm].stream[s];
1674                                 if (! info->substreams)
1675                                         continue;
1676                                 err = set_pcm_default_values(codec, info);
1677                                 if (err < 0)
1678                                         return err;
1679                         }
1680                 }
1681         }
1682         return 0;
1683 }
1684
1685 EXPORT_SYMBOL(snd_hda_build_pcms);
1686
1687 /**
1688  * snd_hda_check_board_config - compare the current codec with the config table
1689  * @codec: the HDA codec
1690  * @tbl: configuration table, terminated by null entries
1691  *
1692  * Compares the modelname or PCI subsystem id of the current codec with the
1693  * given configuration table.  If a matching entry is found, returns its
1694  * config value (supposed to be 0 or positive).
1695  *
1696  * If no entries are matching, the function returns a negative value.
1697  */
1698 int snd_hda_check_board_config(struct hda_codec *codec, const struct hda_board_config *tbl)
1699 {
1700         const struct hda_board_config *c;
1701
1702         if (codec->bus->modelname) {
1703                 for (c = tbl; c->modelname || c->pci_subvendor; c++) {
1704                         if (c->modelname &&
1705                             ! strcmp(codec->bus->modelname, c->modelname)) {
1706                                 snd_printd(KERN_INFO "hda_codec: model '%s' is selected\n", c->modelname);
1707                                 return c->config;
1708                         }
1709                 }
1710         }
1711
1712         if (codec->bus->pci) {
1713                 u16 subsystem_vendor, subsystem_device;
1714                 pci_read_config_word(codec->bus->pci, PCI_SUBSYSTEM_VENDOR_ID, &subsystem_vendor);
1715                 pci_read_config_word(codec->bus->pci, PCI_SUBSYSTEM_ID, &subsystem_device);
1716                 for (c = tbl; c->modelname || c->pci_subvendor; c++) {
1717                         if (c->pci_subvendor == subsystem_vendor &&
1718                             (! c->pci_subdevice /* all match */||
1719                              (c->pci_subdevice == subsystem_device))) {
1720                                 snd_printdd(KERN_INFO "hda_codec: PCI %x:%x, codec config %d is selected\n",
1721                                             subsystem_vendor, subsystem_device, c->config);
1722                                 return c->config;
1723                         }
1724                 }
1725         }
1726         return -1;
1727 }
1728
1729 /**
1730  * snd_hda_add_new_ctls - create controls from the array
1731  * @codec: the HDA codec
1732  * @knew: the array of struct snd_kcontrol_new
1733  *
1734  * This helper function creates and add new controls in the given array.
1735  * The array must be terminated with an empty entry as terminator.
1736  *
1737  * Returns 0 if successful, or a negative error code.
1738  */
1739 int snd_hda_add_new_ctls(struct hda_codec *codec, struct snd_kcontrol_new *knew)
1740 {
1741         int err;
1742
1743         for (; knew->name; knew++) {
1744                 struct snd_kcontrol *kctl;
1745                 kctl = snd_ctl_new1(knew, codec);
1746                 if (! kctl)
1747                         return -ENOMEM;
1748                 err = snd_ctl_add(codec->bus->card, kctl);
1749                 if (err < 0) {
1750                         if (! codec->addr)
1751                                 return err;
1752                         kctl = snd_ctl_new1(knew, codec);
1753                         if (! kctl)
1754                                 return -ENOMEM;
1755                         kctl->id.device = codec->addr;
1756                         if ((err = snd_ctl_add(codec->bus->card, kctl)) < 0)
1757                                 return err;
1758                 }
1759         }
1760         return 0;
1761 }
1762
1763
1764 /*
1765  * Channel mode helper
1766  */
1767 int snd_hda_ch_mode_info(struct hda_codec *codec, struct snd_ctl_elem_info *uinfo,
1768                          const struct hda_channel_mode *chmode, int num_chmodes)
1769 {
1770         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
1771         uinfo->count = 1;
1772         uinfo->value.enumerated.items = num_chmodes;
1773         if (uinfo->value.enumerated.item >= num_chmodes)
1774                 uinfo->value.enumerated.item = num_chmodes - 1;
1775         sprintf(uinfo->value.enumerated.name, "%dch",
1776                 chmode[uinfo->value.enumerated.item].channels);
1777         return 0;
1778 }
1779
1780 int snd_hda_ch_mode_get(struct hda_codec *codec, struct snd_ctl_elem_value *ucontrol,
1781                         const struct hda_channel_mode *chmode, int num_chmodes,
1782                         int max_channels)
1783 {
1784         int i;
1785
1786         for (i = 0; i < num_chmodes; i++) {
1787                 if (max_channels == chmode[i].channels) {
1788                         ucontrol->value.enumerated.item[0] = i;
1789                         break;
1790                 }
1791         }
1792         return 0;
1793 }
1794
1795 int snd_hda_ch_mode_put(struct hda_codec *codec, struct snd_ctl_elem_value *ucontrol,
1796                         const struct hda_channel_mode *chmode, int num_chmodes,
1797                         int *max_channelsp)
1798 {
1799         unsigned int mode;
1800
1801         mode = ucontrol->value.enumerated.item[0];
1802         snd_assert(mode < num_chmodes, return -EINVAL);
1803         if (*max_channelsp == chmode[mode].channels && ! codec->in_resume)
1804                 return 0;
1805         /* change the current channel setting */
1806         *max_channelsp = chmode[mode].channels;
1807         if (chmode[mode].sequence)
1808                 snd_hda_sequence_write(codec, chmode[mode].sequence);
1809         return 1;
1810 }
1811
1812 /*
1813  * input MUX helper
1814  */
1815 int snd_hda_input_mux_info(const struct hda_input_mux *imux, struct snd_ctl_elem_info *uinfo)
1816 {
1817         unsigned int index;
1818
1819         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
1820         uinfo->count = 1;
1821         uinfo->value.enumerated.items = imux->num_items;
1822         index = uinfo->value.enumerated.item;
1823         if (index >= imux->num_items)
1824                 index = imux->num_items - 1;
1825         strcpy(uinfo->value.enumerated.name, imux->items[index].label);
1826         return 0;
1827 }
1828
1829 int snd_hda_input_mux_put(struct hda_codec *codec, const struct hda_input_mux *imux,
1830                           struct snd_ctl_elem_value *ucontrol, hda_nid_t nid,
1831                           unsigned int *cur_val)
1832 {
1833         unsigned int idx;
1834
1835         idx = ucontrol->value.enumerated.item[0];
1836         if (idx >= imux->num_items)
1837                 idx = imux->num_items - 1;
1838         if (*cur_val == idx && ! codec->in_resume)
1839                 return 0;
1840         snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_CONNECT_SEL,
1841                             imux->items[idx].index);
1842         *cur_val = idx;
1843         return 1;
1844 }
1845
1846
1847 /*
1848  * Multi-channel / digital-out PCM helper functions
1849  */
1850
1851 /*
1852  * open the digital out in the exclusive mode
1853  */
1854 int snd_hda_multi_out_dig_open(struct hda_codec *codec, struct hda_multi_out *mout)
1855 {
1856         mutex_lock(&codec->spdif_mutex);
1857         if (mout->dig_out_used) {
1858                 mutex_unlock(&codec->spdif_mutex);
1859                 return -EBUSY; /* already being used */
1860         }
1861         mout->dig_out_used = HDA_DIG_EXCLUSIVE;
1862         mutex_unlock(&codec->spdif_mutex);
1863         return 0;
1864 }
1865
1866 /*
1867  * release the digital out
1868  */
1869 int snd_hda_multi_out_dig_close(struct hda_codec *codec, struct hda_multi_out *mout)
1870 {
1871         mutex_lock(&codec->spdif_mutex);
1872         mout->dig_out_used = 0;
1873         mutex_unlock(&codec->spdif_mutex);
1874         return 0;
1875 }
1876
1877 /*
1878  * set up more restrictions for analog out
1879  */
1880 int snd_hda_multi_out_analog_open(struct hda_codec *codec, struct hda_multi_out *mout,
1881                                   struct snd_pcm_substream *substream)
1882 {
1883         substream->runtime->hw.channels_max = mout->max_channels;
1884         return snd_pcm_hw_constraint_step(substream->runtime, 0,
1885                                           SNDRV_PCM_HW_PARAM_CHANNELS, 2);
1886 }
1887
1888 /*
1889  * set up the i/o for analog out
1890  * when the digital out is available, copy the front out to digital out, too.
1891  */
1892 int snd_hda_multi_out_analog_prepare(struct hda_codec *codec, struct hda_multi_out *mout,
1893                                      unsigned int stream_tag,
1894                                      unsigned int format,
1895                                      struct snd_pcm_substream *substream)
1896 {
1897         hda_nid_t *nids = mout->dac_nids;
1898         int chs = substream->runtime->channels;
1899         int i;
1900
1901         mutex_lock(&codec->spdif_mutex);
1902         if (mout->dig_out_nid && mout->dig_out_used != HDA_DIG_EXCLUSIVE) {
1903                 if (chs == 2 &&
1904                     snd_hda_is_supported_format(codec, mout->dig_out_nid, format) &&
1905                     ! (codec->spdif_status & IEC958_AES0_NONAUDIO)) {
1906                         mout->dig_out_used = HDA_DIG_ANALOG_DUP;
1907                         /* setup digital receiver */
1908                         snd_hda_codec_setup_stream(codec, mout->dig_out_nid,
1909                                                    stream_tag, 0, format);
1910                 } else {
1911                         mout->dig_out_used = 0;
1912                         snd_hda_codec_setup_stream(codec, mout->dig_out_nid, 0, 0, 0);
1913                 }
1914         }
1915         mutex_unlock(&codec->spdif_mutex);
1916
1917         /* front */
1918         snd_hda_codec_setup_stream(codec, nids[HDA_FRONT], stream_tag, 0, format);
1919         if (mout->hp_nid)
1920                 /* headphone out will just decode front left/right (stereo) */
1921                 snd_hda_codec_setup_stream(codec, mout->hp_nid, stream_tag, 0, format);
1922         /* extra outputs copied from front */
1923         for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
1924                 if (mout->extra_out_nid[i])
1925                         snd_hda_codec_setup_stream(codec,
1926                                                    mout->extra_out_nid[i],
1927                                                    stream_tag, 0, format);
1928
1929         /* surrounds */
1930         for (i = 1; i < mout->num_dacs; i++) {
1931                 if (chs >= (i + 1) * 2) /* independent out */
1932                         snd_hda_codec_setup_stream(codec, nids[i], stream_tag, i * 2,
1933                                                    format);
1934                 else /* copy front */
1935                         snd_hda_codec_setup_stream(codec, nids[i], stream_tag, 0,
1936                                                    format);
1937         }
1938         return 0;
1939 }
1940
1941 /*
1942  * clean up the setting for analog out
1943  */
1944 int snd_hda_multi_out_analog_cleanup(struct hda_codec *codec, struct hda_multi_out *mout)
1945 {
1946         hda_nid_t *nids = mout->dac_nids;
1947         int i;
1948
1949         for (i = 0; i < mout->num_dacs; i++)
1950                 snd_hda_codec_setup_stream(codec, nids[i], 0, 0, 0);
1951         if (mout->hp_nid)
1952                 snd_hda_codec_setup_stream(codec, mout->hp_nid, 0, 0, 0);
1953         for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
1954                 if (mout->extra_out_nid[i])
1955                         snd_hda_codec_setup_stream(codec,
1956                                                    mout->extra_out_nid[i],
1957                                                    0, 0, 0);
1958         mutex_lock(&codec->spdif_mutex);
1959         if (mout->dig_out_nid && mout->dig_out_used == HDA_DIG_ANALOG_DUP) {
1960                 snd_hda_codec_setup_stream(codec, mout->dig_out_nid, 0, 0, 0);
1961                 mout->dig_out_used = 0;
1962         }
1963         mutex_unlock(&codec->spdif_mutex);
1964         return 0;
1965 }
1966
1967 /*
1968  * Helper for automatic ping configuration
1969  */
1970
1971 static int is_in_nid_list(hda_nid_t nid, hda_nid_t *list)
1972 {
1973         for (; *list; list++)
1974                 if (*list == nid)
1975                         return 1;
1976         return 0;
1977 }
1978
1979 /*
1980  * Parse all pin widgets and store the useful pin nids to cfg
1981  *
1982  * The number of line-outs or any primary output is stored in line_outs,
1983  * and the corresponding output pins are assigned to line_out_pins[],
1984  * in the order of front, rear, CLFE, side, ...
1985  *
1986  * If more extra outputs (speaker and headphone) are found, the pins are
1987  * assisnged to hp_pin and speaker_pins[], respectively.  If no line-out jack
1988  * is detected, one of speaker of HP pins is assigned as the primary
1989  * output, i.e. to line_out_pins[0].  So, line_outs is always positive
1990  * if any analog output exists.
1991  * 
1992  * The analog input pins are assigned to input_pins array.
1993  * The digital input/output pins are assigned to dig_in_pin and dig_out_pin,
1994  * respectively.
1995  */
1996 int snd_hda_parse_pin_def_config(struct hda_codec *codec, struct auto_pin_cfg *cfg,
1997                                  hda_nid_t *ignore_nids)
1998 {
1999         hda_nid_t nid, nid_start;
2000         int i, j, nodes;
2001         short seq, assoc_line_out, sequences[ARRAY_SIZE(cfg->line_out_pins)];
2002
2003         memset(cfg, 0, sizeof(*cfg));
2004
2005         memset(sequences, 0, sizeof(sequences));
2006         assoc_line_out = 0;
2007
2008         nodes = snd_hda_get_sub_nodes(codec, codec->afg, &nid_start);
2009         for (nid = nid_start; nid < nodes + nid_start; nid++) {
2010                 unsigned int wid_caps = get_wcaps(codec, nid);
2011                 unsigned int wid_type = (wid_caps & AC_WCAP_TYPE) >> AC_WCAP_TYPE_SHIFT;
2012                 unsigned int def_conf;
2013                 short assoc, loc;
2014
2015                 /* read all default configuration for pin complex */
2016                 if (wid_type != AC_WID_PIN)
2017                         continue;
2018                 /* ignore the given nids (e.g. pc-beep returns error) */
2019                 if (ignore_nids && is_in_nid_list(nid, ignore_nids))
2020                         continue;
2021
2022                 def_conf = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_CONFIG_DEFAULT, 0);
2023                 if (get_defcfg_connect(def_conf) == AC_JACK_PORT_NONE)
2024                         continue;
2025                 loc = get_defcfg_location(def_conf);
2026                 switch (get_defcfg_device(def_conf)) {
2027                 case AC_JACK_LINE_OUT:
2028                         seq = get_defcfg_sequence(def_conf);
2029                         assoc = get_defcfg_association(def_conf);
2030                         if (! assoc)
2031                                 continue;
2032                         if (! assoc_line_out)
2033                                 assoc_line_out = assoc;
2034                         else if (assoc_line_out != assoc)
2035                                 continue;
2036                         if (cfg->line_outs >= ARRAY_SIZE(cfg->line_out_pins))
2037                                 continue;
2038                         cfg->line_out_pins[cfg->line_outs] = nid;
2039                         sequences[cfg->line_outs] = seq;
2040                         cfg->line_outs++;
2041                         break;
2042                 case AC_JACK_SPEAKER:
2043                         if (cfg->speaker_outs >= ARRAY_SIZE(cfg->speaker_pins))
2044                                 continue;
2045                         cfg->speaker_pins[cfg->speaker_outs] = nid;
2046                         cfg->speaker_outs++;
2047                         break;
2048                 case AC_JACK_HP_OUT:
2049                         cfg->hp_pin = nid;
2050                         break;
2051                 case AC_JACK_MIC_IN:
2052                         if (loc == AC_JACK_LOC_FRONT)
2053                                 cfg->input_pins[AUTO_PIN_FRONT_MIC] = nid;
2054                         else
2055                                 cfg->input_pins[AUTO_PIN_MIC] = nid;
2056                         break;
2057                 case AC_JACK_LINE_IN:
2058                         if (loc == AC_JACK_LOC_FRONT)
2059                                 cfg->input_pins[AUTO_PIN_FRONT_LINE] = nid;
2060                         else
2061                                 cfg->input_pins[AUTO_PIN_LINE] = nid;
2062                         break;
2063                 case AC_JACK_CD:
2064                         cfg->input_pins[AUTO_PIN_CD] = nid;
2065                         break;
2066                 case AC_JACK_AUX:
2067                         cfg->input_pins[AUTO_PIN_AUX] = nid;
2068                         break;
2069                 case AC_JACK_SPDIF_OUT:
2070                         cfg->dig_out_pin = nid;
2071                         break;
2072                 case AC_JACK_SPDIF_IN:
2073                         cfg->dig_in_pin = nid;
2074                         break;
2075                 }
2076         }
2077
2078         /* sort by sequence */
2079         for (i = 0; i < cfg->line_outs; i++)
2080                 for (j = i + 1; j < cfg->line_outs; j++)
2081                         if (sequences[i] > sequences[j]) {
2082                                 seq = sequences[i];
2083                                 sequences[i] = sequences[j];
2084                                 sequences[j] = seq;
2085                                 nid = cfg->line_out_pins[i];
2086                                 cfg->line_out_pins[i] = cfg->line_out_pins[j];
2087                                 cfg->line_out_pins[j] = nid;
2088                         }
2089
2090         /* Reorder the surround channels
2091          * ALSA sequence is front/surr/clfe/side
2092          * HDA sequence is:
2093          *    4-ch: front/surr  =>  OK as it is
2094          *    6-ch: front/clfe/surr
2095          *    8-ch: front/clfe/side/surr
2096          */
2097         switch (cfg->line_outs) {
2098         case 3:
2099                 nid = cfg->line_out_pins[1];
2100                 cfg->line_out_pins[1] = cfg->line_out_pins[2];
2101                 cfg->line_out_pins[2] = nid;
2102                 break;
2103         case 4:
2104                 nid = cfg->line_out_pins[1];
2105                 cfg->line_out_pins[1] = cfg->line_out_pins[3];
2106                 cfg->line_out_pins[3] = cfg->line_out_pins[2];
2107                 cfg->line_out_pins[2] = nid;
2108                 break;
2109         }
2110
2111         /*
2112          * debug prints of the parsed results
2113          */
2114         snd_printd("autoconfig: line_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x)\n",
2115                    cfg->line_outs, cfg->line_out_pins[0], cfg->line_out_pins[1],
2116                    cfg->line_out_pins[2], cfg->line_out_pins[3],
2117                    cfg->line_out_pins[4]);
2118         snd_printd("   speaker_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x)\n",
2119                    cfg->speaker_outs, cfg->speaker_pins[0],
2120                    cfg->speaker_pins[1], cfg->speaker_pins[2],
2121                    cfg->speaker_pins[3], cfg->speaker_pins[4]);
2122         snd_printd("   hp=0x%x, dig_out=0x%x, din_in=0x%x\n",
2123                    cfg->hp_pin, cfg->dig_out_pin, cfg->dig_in_pin);
2124         snd_printd("   inputs: mic=0x%x, fmic=0x%x, line=0x%x, fline=0x%x,"
2125                    " cd=0x%x, aux=0x%x\n",
2126                    cfg->input_pins[AUTO_PIN_MIC],
2127                    cfg->input_pins[AUTO_PIN_FRONT_MIC],
2128                    cfg->input_pins[AUTO_PIN_LINE],
2129                    cfg->input_pins[AUTO_PIN_FRONT_LINE],
2130                    cfg->input_pins[AUTO_PIN_CD],
2131                    cfg->input_pins[AUTO_PIN_AUX]);
2132
2133         /*
2134          * FIX-UP: if no line-outs are detected, try to use speaker or HP pin
2135          * as a primary output
2136          */
2137         if (! cfg->line_outs) {
2138                 if (cfg->speaker_outs) {
2139                         cfg->line_outs = cfg->speaker_outs;
2140                         memcpy(cfg->line_out_pins, cfg->speaker_pins,
2141                                sizeof(cfg->speaker_pins));
2142                         cfg->speaker_outs = 0;
2143                         memset(cfg->speaker_pins, 0, sizeof(cfg->speaker_pins));
2144                 } else if (cfg->hp_pin) {
2145                         cfg->line_outs = 1;
2146                         cfg->line_out_pins[0] = cfg->hp_pin;
2147                         cfg->hp_pin = 0;
2148                 }
2149         }
2150
2151         return 0;
2152 }
2153
2154 /* labels for input pins */
2155 const char *auto_pin_cfg_labels[AUTO_PIN_LAST] = {
2156         "Mic", "Front Mic", "Line", "Front Line", "CD", "Aux"
2157 };
2158
2159
2160 #ifdef CONFIG_PM
2161 /*
2162  * power management
2163  */
2164
2165 /**
2166  * snd_hda_suspend - suspend the codecs
2167  * @bus: the HDA bus
2168  * @state: suspsend state
2169  *
2170  * Returns 0 if successful.
2171  */
2172 int snd_hda_suspend(struct hda_bus *bus, pm_message_t state)
2173 {
2174         struct list_head *p;
2175
2176         /* FIXME: should handle power widget capabilities */
2177         list_for_each(p, &bus->codec_list) {
2178                 struct hda_codec *codec = list_entry(p, struct hda_codec, list);
2179                 if (codec->patch_ops.suspend)
2180                         codec->patch_ops.suspend(codec, state);
2181                 hda_set_power_state(codec,
2182                                     codec->afg ? codec->afg : codec->mfg,
2183                                     AC_PWRST_D3);
2184         }
2185         return 0;
2186 }
2187
2188 EXPORT_SYMBOL(snd_hda_suspend);
2189
2190 /**
2191  * snd_hda_resume - resume the codecs
2192  * @bus: the HDA bus
2193  * @state: resume state
2194  *
2195  * Returns 0 if successful.
2196  */
2197 int snd_hda_resume(struct hda_bus *bus)
2198 {
2199         struct list_head *p;
2200
2201         list_for_each(p, &bus->codec_list) {
2202                 struct hda_codec *codec = list_entry(p, struct hda_codec, list);
2203                 hda_set_power_state(codec,
2204                                     codec->afg ? codec->afg : codec->mfg,
2205                                     AC_PWRST_D0);
2206                 if (codec->patch_ops.resume)
2207                         codec->patch_ops.resume(codec);
2208         }
2209         return 0;
2210 }
2211
2212 EXPORT_SYMBOL(snd_hda_resume);
2213
2214 /**
2215  * snd_hda_resume_ctls - resume controls in the new control list
2216  * @codec: the HDA codec
2217  * @knew: the array of struct snd_kcontrol_new
2218  *
2219  * This function resumes the mixer controls in the struct snd_kcontrol_new array,
2220  * originally for snd_hda_add_new_ctls().
2221  * The array must be terminated with an empty entry as terminator.
2222  */
2223 int snd_hda_resume_ctls(struct hda_codec *codec, struct snd_kcontrol_new *knew)
2224 {
2225         struct snd_ctl_elem_value *val;
2226
2227         val = kmalloc(sizeof(*val), GFP_KERNEL);
2228         if (! val)
2229                 return -ENOMEM;
2230         codec->in_resume = 1;
2231         for (; knew->name; knew++) {
2232                 int i, count;
2233                 count = knew->count ? knew->count : 1;
2234                 for (i = 0; i < count; i++) {
2235                         memset(val, 0, sizeof(*val));
2236                         val->id.iface = knew->iface;
2237                         val->id.device = knew->device;
2238                         val->id.subdevice = knew->subdevice;
2239                         strcpy(val->id.name, knew->name);
2240                         val->id.index = knew->index ? knew->index : i;
2241                         /* Assume that get callback reads only from cache,
2242                          * not accessing to the real hardware
2243                          */
2244                         if (snd_ctl_elem_read(codec->bus->card, val) < 0)
2245                                 continue;
2246                         snd_ctl_elem_write(codec->bus->card, NULL, val);
2247                 }
2248         }
2249         codec->in_resume = 0;
2250         kfree(val);
2251         return 0;
2252 }
2253
2254 /**
2255  * snd_hda_resume_spdif_out - resume the digital out
2256  * @codec: the HDA codec
2257  */
2258 int snd_hda_resume_spdif_out(struct hda_codec *codec)
2259 {
2260         return snd_hda_resume_ctls(codec, dig_mixes);
2261 }
2262
2263 /**
2264  * snd_hda_resume_spdif_in - resume the digital in
2265  * @codec: the HDA codec
2266  */
2267 int snd_hda_resume_spdif_in(struct hda_codec *codec)
2268 {
2269         return snd_hda_resume_ctls(codec, dig_in_ctls);
2270 }
2271 #endif
2272
2273 /*
2274  *  INIT part
2275  */
2276
2277 static int __init alsa_hda_init(void)
2278 {
2279         return 0;
2280 }
2281
2282 static void __exit alsa_hda_exit(void)
2283 {
2284 }
2285
2286 module_init(alsa_hda_init)
2287 module_exit(alsa_hda_exit)