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