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