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