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