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