ALSA: hda - Move power_save option to hda_intel.c
[safe/jmp/linux-2.6] / sound / pci / hda / hda_codec.c
1 /*
2  * Universal Interface for Intel High Definition Audio Codec
3  *
4  * Copyright (c) 2004 Takashi Iwai <tiwai@suse.de>
5  *
6  *
7  *  This driver is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This driver is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20  */
21
22 #include <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 /* Clear all controls assigned to the given codec */
1210 void snd_hda_ctls_clear(struct hda_codec *codec)
1211 {
1212         int i;
1213         struct snd_kcontrol **kctls = codec->mixers.list;
1214         for (i = 0; i < codec->mixers.used; i++)
1215                 snd_ctl_remove(codec->bus->card, kctls[i]);
1216         snd_array_free(&codec->mixers);
1217 }
1218
1219 void snd_hda_codec_reset(struct hda_codec *codec)
1220 {
1221         int i;
1222
1223 #ifdef CONFIG_SND_HDA_POWER_SAVE
1224         cancel_delayed_work(&codec->power_work);
1225         flush_scheduled_work();
1226 #endif
1227         snd_hda_ctls_clear(codec);
1228         /* relase PCMs */
1229         for (i = 0; i < codec->num_pcms; i++) {
1230                 if (codec->pcm_info[i].pcm)
1231                         snd_device_free(codec->bus->card,
1232                                         codec->pcm_info[i].pcm);
1233         }
1234         if (codec->patch_ops.free)
1235                 codec->patch_ops.free(codec);
1236         codec->spec = NULL;
1237         free_hda_cache(&codec->amp_cache);
1238         free_hda_cache(&codec->cmd_cache);
1239         codec->num_pcms = 0;
1240         codec->pcm_info = NULL;
1241         codec->preset = NULL;
1242 }
1243
1244 /* create a virtual master control and add slaves */
1245 int snd_hda_add_vmaster(struct hda_codec *codec, char *name,
1246                         unsigned int *tlv, const char **slaves)
1247 {
1248         struct snd_kcontrol *kctl;
1249         const char **s;
1250         int err;
1251
1252         for (s = slaves; *s && !snd_hda_find_mixer_ctl(codec, *s); s++)
1253                 ;
1254         if (!*s) {
1255                 snd_printdd("No slave found for %s\n", name);
1256                 return 0;
1257         }
1258         kctl = snd_ctl_make_virtual_master(name, tlv);
1259         if (!kctl)
1260                 return -ENOMEM;
1261         err = snd_hda_ctl_add(codec, kctl);
1262         if (err < 0)
1263                 return err;
1264         
1265         for (s = slaves; *s; s++) {
1266                 struct snd_kcontrol *sctl;
1267
1268                 sctl = snd_hda_find_mixer_ctl(codec, *s);
1269                 if (!sctl) {
1270                         snd_printdd("Cannot find slave %s, skipped\n", *s);
1271                         continue;
1272                 }
1273                 err = snd_ctl_add_slave(kctl, sctl);
1274                 if (err < 0)
1275                         return err;
1276         }
1277         return 0;
1278 }
1279
1280 /* switch */
1281 int snd_hda_mixer_amp_switch_info(struct snd_kcontrol *kcontrol,
1282                                   struct snd_ctl_elem_info *uinfo)
1283 {
1284         int chs = get_amp_channels(kcontrol);
1285
1286         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
1287         uinfo->count = chs == 3 ? 2 : 1;
1288         uinfo->value.integer.min = 0;
1289         uinfo->value.integer.max = 1;
1290         return 0;
1291 }
1292
1293 int snd_hda_mixer_amp_switch_get(struct snd_kcontrol *kcontrol,
1294                                  struct snd_ctl_elem_value *ucontrol)
1295 {
1296         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1297         hda_nid_t nid = get_amp_nid(kcontrol);
1298         int chs = get_amp_channels(kcontrol);
1299         int dir = get_amp_direction(kcontrol);
1300         int idx = get_amp_index(kcontrol);
1301         long *valp = ucontrol->value.integer.value;
1302
1303         if (chs & 1)
1304                 *valp++ = (snd_hda_codec_amp_read(codec, nid, 0, dir, idx) &
1305                            HDA_AMP_MUTE) ? 0 : 1;
1306         if (chs & 2)
1307                 *valp = (snd_hda_codec_amp_read(codec, nid, 1, dir, idx) &
1308                          HDA_AMP_MUTE) ? 0 : 1;
1309         return 0;
1310 }
1311
1312 int snd_hda_mixer_amp_switch_put(struct snd_kcontrol *kcontrol,
1313                                  struct snd_ctl_elem_value *ucontrol)
1314 {
1315         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1316         hda_nid_t nid = get_amp_nid(kcontrol);
1317         int chs = get_amp_channels(kcontrol);
1318         int dir = get_amp_direction(kcontrol);
1319         int idx = get_amp_index(kcontrol);
1320         long *valp = ucontrol->value.integer.value;
1321         int change = 0;
1322
1323         snd_hda_power_up(codec);
1324         if (chs & 1) {
1325                 change = snd_hda_codec_amp_update(codec, nid, 0, dir, idx,
1326                                                   HDA_AMP_MUTE,
1327                                                   *valp ? 0 : HDA_AMP_MUTE);
1328                 valp++;
1329         }
1330         if (chs & 2)
1331                 change |= snd_hda_codec_amp_update(codec, nid, 1, dir, idx,
1332                                                    HDA_AMP_MUTE,
1333                                                    *valp ? 0 : HDA_AMP_MUTE);
1334 #ifdef CONFIG_SND_HDA_POWER_SAVE
1335         if (codec->patch_ops.check_power_status)
1336                 codec->patch_ops.check_power_status(codec, nid);
1337 #endif
1338         snd_hda_power_down(codec);
1339         return change;
1340 }
1341
1342 /*
1343  * bound volume controls
1344  *
1345  * bind multiple volumes (# indices, from 0)
1346  */
1347
1348 #define AMP_VAL_IDX_SHIFT       19
1349 #define AMP_VAL_IDX_MASK        (0x0f<<19)
1350
1351 int snd_hda_mixer_bind_switch_get(struct snd_kcontrol *kcontrol,
1352                                   struct snd_ctl_elem_value *ucontrol)
1353 {
1354         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1355         unsigned long pval;
1356         int err;
1357
1358         mutex_lock(&codec->spdif_mutex); /* reuse spdif_mutex */
1359         pval = kcontrol->private_value;
1360         kcontrol->private_value = pval & ~AMP_VAL_IDX_MASK; /* index 0 */
1361         err = snd_hda_mixer_amp_switch_get(kcontrol, ucontrol);
1362         kcontrol->private_value = pval;
1363         mutex_unlock(&codec->spdif_mutex);
1364         return err;
1365 }
1366
1367 int snd_hda_mixer_bind_switch_put(struct snd_kcontrol *kcontrol,
1368                                   struct snd_ctl_elem_value *ucontrol)
1369 {
1370         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1371         unsigned long pval;
1372         int i, indices, err = 0, change = 0;
1373
1374         mutex_lock(&codec->spdif_mutex); /* reuse spdif_mutex */
1375         pval = kcontrol->private_value;
1376         indices = (pval & AMP_VAL_IDX_MASK) >> AMP_VAL_IDX_SHIFT;
1377         for (i = 0; i < indices; i++) {
1378                 kcontrol->private_value = (pval & ~AMP_VAL_IDX_MASK) |
1379                         (i << AMP_VAL_IDX_SHIFT);
1380                 err = snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
1381                 if (err < 0)
1382                         break;
1383                 change |= err;
1384         }
1385         kcontrol->private_value = pval;
1386         mutex_unlock(&codec->spdif_mutex);
1387         return err < 0 ? err : change;
1388 }
1389
1390 /*
1391  * generic bound volume/swtich controls
1392  */
1393 int snd_hda_mixer_bind_ctls_info(struct snd_kcontrol *kcontrol,
1394                                  struct snd_ctl_elem_info *uinfo)
1395 {
1396         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1397         struct hda_bind_ctls *c;
1398         int err;
1399
1400         mutex_lock(&codec->spdif_mutex); /* reuse spdif_mutex */
1401         c = (struct hda_bind_ctls *)kcontrol->private_value;
1402         kcontrol->private_value = *c->values;
1403         err = c->ops->info(kcontrol, uinfo);
1404         kcontrol->private_value = (long)c;
1405         mutex_unlock(&codec->spdif_mutex);
1406         return err;
1407 }
1408
1409 int snd_hda_mixer_bind_ctls_get(struct snd_kcontrol *kcontrol,
1410                                 struct snd_ctl_elem_value *ucontrol)
1411 {
1412         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1413         struct hda_bind_ctls *c;
1414         int err;
1415
1416         mutex_lock(&codec->spdif_mutex); /* reuse spdif_mutex */
1417         c = (struct hda_bind_ctls *)kcontrol->private_value;
1418         kcontrol->private_value = *c->values;
1419         err = c->ops->get(kcontrol, ucontrol);
1420         kcontrol->private_value = (long)c;
1421         mutex_unlock(&codec->spdif_mutex);
1422         return err;
1423 }
1424
1425 int snd_hda_mixer_bind_ctls_put(struct snd_kcontrol *kcontrol,
1426                                 struct snd_ctl_elem_value *ucontrol)
1427 {
1428         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1429         struct hda_bind_ctls *c;
1430         unsigned long *vals;
1431         int err = 0, change = 0;
1432
1433         mutex_lock(&codec->spdif_mutex); /* reuse spdif_mutex */
1434         c = (struct hda_bind_ctls *)kcontrol->private_value;
1435         for (vals = c->values; *vals; vals++) {
1436                 kcontrol->private_value = *vals;
1437                 err = c->ops->put(kcontrol, ucontrol);
1438                 if (err < 0)
1439                         break;
1440                 change |= err;
1441         }
1442         kcontrol->private_value = (long)c;
1443         mutex_unlock(&codec->spdif_mutex);
1444         return err < 0 ? err : change;
1445 }
1446
1447 int snd_hda_mixer_bind_tlv(struct snd_kcontrol *kcontrol, int op_flag,
1448                            unsigned int size, unsigned int __user *tlv)
1449 {
1450         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1451         struct hda_bind_ctls *c;
1452         int err;
1453
1454         mutex_lock(&codec->spdif_mutex); /* reuse spdif_mutex */
1455         c = (struct hda_bind_ctls *)kcontrol->private_value;
1456         kcontrol->private_value = *c->values;
1457         err = c->ops->tlv(kcontrol, op_flag, size, tlv);
1458         kcontrol->private_value = (long)c;
1459         mutex_unlock(&codec->spdif_mutex);
1460         return err;
1461 }
1462
1463 struct hda_ctl_ops snd_hda_bind_vol = {
1464         .info = snd_hda_mixer_amp_volume_info,
1465         .get = snd_hda_mixer_amp_volume_get,
1466         .put = snd_hda_mixer_amp_volume_put,
1467         .tlv = snd_hda_mixer_amp_tlv
1468 };
1469
1470 struct hda_ctl_ops snd_hda_bind_sw = {
1471         .info = snd_hda_mixer_amp_switch_info,
1472         .get = snd_hda_mixer_amp_switch_get,
1473         .put = snd_hda_mixer_amp_switch_put,
1474         .tlv = snd_hda_mixer_amp_tlv
1475 };
1476
1477 /*
1478  * SPDIF out controls
1479  */
1480
1481 static int snd_hda_spdif_mask_info(struct snd_kcontrol *kcontrol,
1482                                    struct snd_ctl_elem_info *uinfo)
1483 {
1484         uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
1485         uinfo->count = 1;
1486         return 0;
1487 }
1488
1489 static int snd_hda_spdif_cmask_get(struct snd_kcontrol *kcontrol,
1490                                    struct snd_ctl_elem_value *ucontrol)
1491 {
1492         ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
1493                                            IEC958_AES0_NONAUDIO |
1494                                            IEC958_AES0_CON_EMPHASIS_5015 |
1495                                            IEC958_AES0_CON_NOT_COPYRIGHT;
1496         ucontrol->value.iec958.status[1] = IEC958_AES1_CON_CATEGORY |
1497                                            IEC958_AES1_CON_ORIGINAL;
1498         return 0;
1499 }
1500
1501 static int snd_hda_spdif_pmask_get(struct snd_kcontrol *kcontrol,
1502                                    struct snd_ctl_elem_value *ucontrol)
1503 {
1504         ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
1505                                            IEC958_AES0_NONAUDIO |
1506                                            IEC958_AES0_PRO_EMPHASIS_5015;
1507         return 0;
1508 }
1509
1510 static int snd_hda_spdif_default_get(struct snd_kcontrol *kcontrol,
1511                                      struct snd_ctl_elem_value *ucontrol)
1512 {
1513         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1514
1515         ucontrol->value.iec958.status[0] = codec->spdif_status & 0xff;
1516         ucontrol->value.iec958.status[1] = (codec->spdif_status >> 8) & 0xff;
1517         ucontrol->value.iec958.status[2] = (codec->spdif_status >> 16) & 0xff;
1518         ucontrol->value.iec958.status[3] = (codec->spdif_status >> 24) & 0xff;
1519
1520         return 0;
1521 }
1522
1523 /* convert from SPDIF status bits to HDA SPDIF bits
1524  * bit 0 (DigEn) is always set zero (to be filled later)
1525  */
1526 static unsigned short convert_from_spdif_status(unsigned int sbits)
1527 {
1528         unsigned short val = 0;
1529
1530         if (sbits & IEC958_AES0_PROFESSIONAL)
1531                 val |= AC_DIG1_PROFESSIONAL;
1532         if (sbits & IEC958_AES0_NONAUDIO)
1533                 val |= AC_DIG1_NONAUDIO;
1534         if (sbits & IEC958_AES0_PROFESSIONAL) {
1535                 if ((sbits & IEC958_AES0_PRO_EMPHASIS) ==
1536                     IEC958_AES0_PRO_EMPHASIS_5015)
1537                         val |= AC_DIG1_EMPHASIS;
1538         } else {
1539                 if ((sbits & IEC958_AES0_CON_EMPHASIS) ==
1540                     IEC958_AES0_CON_EMPHASIS_5015)
1541                         val |= AC_DIG1_EMPHASIS;
1542                 if (!(sbits & IEC958_AES0_CON_NOT_COPYRIGHT))
1543                         val |= AC_DIG1_COPYRIGHT;
1544                 if (sbits & (IEC958_AES1_CON_ORIGINAL << 8))
1545                         val |= AC_DIG1_LEVEL;
1546                 val |= sbits & (IEC958_AES1_CON_CATEGORY << 8);
1547         }
1548         return val;
1549 }
1550
1551 /* convert to SPDIF status bits from HDA SPDIF bits
1552  */
1553 static unsigned int convert_to_spdif_status(unsigned short val)
1554 {
1555         unsigned int sbits = 0;
1556
1557         if (val & AC_DIG1_NONAUDIO)
1558                 sbits |= IEC958_AES0_NONAUDIO;
1559         if (val & AC_DIG1_PROFESSIONAL)
1560                 sbits |= IEC958_AES0_PROFESSIONAL;
1561         if (sbits & IEC958_AES0_PROFESSIONAL) {
1562                 if (sbits & AC_DIG1_EMPHASIS)
1563                         sbits |= IEC958_AES0_PRO_EMPHASIS_5015;
1564         } else {
1565                 if (val & AC_DIG1_EMPHASIS)
1566                         sbits |= IEC958_AES0_CON_EMPHASIS_5015;
1567                 if (!(val & AC_DIG1_COPYRIGHT))
1568                         sbits |= IEC958_AES0_CON_NOT_COPYRIGHT;
1569                 if (val & AC_DIG1_LEVEL)
1570                         sbits |= (IEC958_AES1_CON_ORIGINAL << 8);
1571                 sbits |= val & (0x7f << 8);
1572         }
1573         return sbits;
1574 }
1575
1576 /* set digital convert verbs both for the given NID and its slaves */
1577 static void set_dig_out(struct hda_codec *codec, hda_nid_t nid,
1578                         int verb, int val)
1579 {
1580         hda_nid_t *d;
1581
1582         snd_hda_codec_write_cache(codec, nid, 0, verb, val);
1583         d = codec->slave_dig_outs;
1584         if (!d)
1585                 return;
1586         for (; *d; d++)
1587                 snd_hda_codec_write_cache(codec, *d, 0, verb, val);
1588 }
1589
1590 static inline void set_dig_out_convert(struct hda_codec *codec, hda_nid_t nid,
1591                                        int dig1, int dig2)
1592 {
1593         if (dig1 != -1)
1594                 set_dig_out(codec, nid, AC_VERB_SET_DIGI_CONVERT_1, dig1);
1595         if (dig2 != -1)
1596                 set_dig_out(codec, nid, AC_VERB_SET_DIGI_CONVERT_2, dig2);
1597 }
1598
1599 static int snd_hda_spdif_default_put(struct snd_kcontrol *kcontrol,
1600                                      struct snd_ctl_elem_value *ucontrol)
1601 {
1602         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1603         hda_nid_t nid = kcontrol->private_value;
1604         unsigned short val;
1605         int change;
1606
1607         mutex_lock(&codec->spdif_mutex);
1608         codec->spdif_status = ucontrol->value.iec958.status[0] |
1609                 ((unsigned int)ucontrol->value.iec958.status[1] << 8) |
1610                 ((unsigned int)ucontrol->value.iec958.status[2] << 16) |
1611                 ((unsigned int)ucontrol->value.iec958.status[3] << 24);
1612         val = convert_from_spdif_status(codec->spdif_status);
1613         val |= codec->spdif_ctls & 1;
1614         change = codec->spdif_ctls != val;
1615         codec->spdif_ctls = val;
1616
1617         if (change)
1618                 set_dig_out_convert(codec, nid, val & 0xff, (val >> 8) & 0xff);
1619
1620         mutex_unlock(&codec->spdif_mutex);
1621         return change;
1622 }
1623
1624 #define snd_hda_spdif_out_switch_info   snd_ctl_boolean_mono_info
1625
1626 static int snd_hda_spdif_out_switch_get(struct snd_kcontrol *kcontrol,
1627                                         struct snd_ctl_elem_value *ucontrol)
1628 {
1629         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1630
1631         ucontrol->value.integer.value[0] = codec->spdif_ctls & AC_DIG1_ENABLE;
1632         return 0;
1633 }
1634
1635 static int snd_hda_spdif_out_switch_put(struct snd_kcontrol *kcontrol,
1636                                         struct snd_ctl_elem_value *ucontrol)
1637 {
1638         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1639         hda_nid_t nid = kcontrol->private_value;
1640         unsigned short val;
1641         int change;
1642
1643         mutex_lock(&codec->spdif_mutex);
1644         val = codec->spdif_ctls & ~AC_DIG1_ENABLE;
1645         if (ucontrol->value.integer.value[0])
1646                 val |= AC_DIG1_ENABLE;
1647         change = codec->spdif_ctls != val;
1648         if (change) {
1649                 codec->spdif_ctls = val;
1650                 set_dig_out_convert(codec, nid, val & 0xff, -1);
1651                 /* unmute amp switch (if any) */
1652                 if ((get_wcaps(codec, nid) & AC_WCAP_OUT_AMP) &&
1653                     (val & AC_DIG1_ENABLE))
1654                         snd_hda_codec_amp_stereo(codec, nid, HDA_OUTPUT, 0,
1655                                                  HDA_AMP_MUTE, 0);
1656         }
1657         mutex_unlock(&codec->spdif_mutex);
1658         return change;
1659 }
1660
1661 static struct snd_kcontrol_new dig_mixes[] = {
1662         {
1663                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
1664                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1665                 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,CON_MASK),
1666                 .info = snd_hda_spdif_mask_info,
1667                 .get = snd_hda_spdif_cmask_get,
1668         },
1669         {
1670                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
1671                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1672                 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PRO_MASK),
1673                 .info = snd_hda_spdif_mask_info,
1674                 .get = snd_hda_spdif_pmask_get,
1675         },
1676         {
1677                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1678                 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
1679                 .info = snd_hda_spdif_mask_info,
1680                 .get = snd_hda_spdif_default_get,
1681                 .put = snd_hda_spdif_default_put,
1682         },
1683         {
1684                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1685                 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,SWITCH),
1686                 .info = snd_hda_spdif_out_switch_info,
1687                 .get = snd_hda_spdif_out_switch_get,
1688                 .put = snd_hda_spdif_out_switch_put,
1689         },
1690         { } /* end */
1691 };
1692
1693 #define SPDIF_MAX_IDX   4       /* 4 instances should be enough to probe */
1694
1695 /**
1696  * snd_hda_create_spdif_out_ctls - create Output SPDIF-related controls
1697  * @codec: the HDA codec
1698  * @nid: audio out widget NID
1699  *
1700  * Creates controls related with the SPDIF output.
1701  * Called from each patch supporting the SPDIF out.
1702  *
1703  * Returns 0 if successful, or a negative error code.
1704  */
1705 int snd_hda_create_spdif_out_ctls(struct hda_codec *codec, hda_nid_t nid)
1706 {
1707         int err;
1708         struct snd_kcontrol *kctl;
1709         struct snd_kcontrol_new *dig_mix;
1710         int idx;
1711
1712         for (idx = 0; idx < SPDIF_MAX_IDX; idx++) {
1713                 if (!_snd_hda_find_mixer_ctl(codec, "IEC958 Playback Switch",
1714                                              idx))
1715                         break;
1716         }
1717         if (idx >= SPDIF_MAX_IDX) {
1718                 printk(KERN_ERR "hda_codec: too many IEC958 outputs\n");
1719                 return -EBUSY;
1720         }
1721         for (dig_mix = dig_mixes; dig_mix->name; dig_mix++) {
1722                 kctl = snd_ctl_new1(dig_mix, codec);
1723                 if (!kctl)
1724                         return -ENOMEM;
1725                 kctl->id.index = idx;
1726                 kctl->private_value = nid;
1727                 err = snd_hda_ctl_add(codec, kctl);
1728                 if (err < 0)
1729                         return err;
1730         }
1731         codec->spdif_ctls =
1732                 snd_hda_codec_read(codec, nid, 0,
1733                                    AC_VERB_GET_DIGI_CONVERT_1, 0);
1734         codec->spdif_status = convert_to_spdif_status(codec->spdif_ctls);
1735         return 0;
1736 }
1737
1738 /*
1739  * SPDIF sharing with analog output
1740  */
1741 static int spdif_share_sw_get(struct snd_kcontrol *kcontrol,
1742                               struct snd_ctl_elem_value *ucontrol)
1743 {
1744         struct hda_multi_out *mout = snd_kcontrol_chip(kcontrol);
1745         ucontrol->value.integer.value[0] = mout->share_spdif;
1746         return 0;
1747 }
1748
1749 static int spdif_share_sw_put(struct snd_kcontrol *kcontrol,
1750                               struct snd_ctl_elem_value *ucontrol)
1751 {
1752         struct hda_multi_out *mout = snd_kcontrol_chip(kcontrol);
1753         mout->share_spdif = !!ucontrol->value.integer.value[0];
1754         return 0;
1755 }
1756
1757 static struct snd_kcontrol_new spdif_share_sw = {
1758         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1759         .name = "IEC958 Default PCM Playback Switch",
1760         .info = snd_ctl_boolean_mono_info,
1761         .get = spdif_share_sw_get,
1762         .put = spdif_share_sw_put,
1763 };
1764
1765 int snd_hda_create_spdif_share_sw(struct hda_codec *codec,
1766                                   struct hda_multi_out *mout)
1767 {
1768         if (!mout->dig_out_nid)
1769                 return 0;
1770         /* ATTENTION: here mout is passed as private_data, instead of codec */
1771         return snd_hda_ctl_add(codec,
1772                            snd_ctl_new1(&spdif_share_sw, mout));
1773 }
1774
1775 /*
1776  * SPDIF input
1777  */
1778
1779 #define snd_hda_spdif_in_switch_info    snd_hda_spdif_out_switch_info
1780
1781 static int snd_hda_spdif_in_switch_get(struct snd_kcontrol *kcontrol,
1782                                        struct snd_ctl_elem_value *ucontrol)
1783 {
1784         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1785
1786         ucontrol->value.integer.value[0] = codec->spdif_in_enable;
1787         return 0;
1788 }
1789
1790 static int snd_hda_spdif_in_switch_put(struct snd_kcontrol *kcontrol,
1791                                        struct snd_ctl_elem_value *ucontrol)
1792 {
1793         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1794         hda_nid_t nid = kcontrol->private_value;
1795         unsigned int val = !!ucontrol->value.integer.value[0];
1796         int change;
1797
1798         mutex_lock(&codec->spdif_mutex);
1799         change = codec->spdif_in_enable != val;
1800         if (change) {
1801                 codec->spdif_in_enable = val;
1802                 snd_hda_codec_write_cache(codec, nid, 0,
1803                                           AC_VERB_SET_DIGI_CONVERT_1, val);
1804         }
1805         mutex_unlock(&codec->spdif_mutex);
1806         return change;
1807 }
1808
1809 static int snd_hda_spdif_in_status_get(struct snd_kcontrol *kcontrol,
1810                                        struct snd_ctl_elem_value *ucontrol)
1811 {
1812         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1813         hda_nid_t nid = kcontrol->private_value;
1814         unsigned short val;
1815         unsigned int sbits;
1816
1817         val = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_DIGI_CONVERT_1, 0);
1818         sbits = convert_to_spdif_status(val);
1819         ucontrol->value.iec958.status[0] = sbits;
1820         ucontrol->value.iec958.status[1] = sbits >> 8;
1821         ucontrol->value.iec958.status[2] = sbits >> 16;
1822         ucontrol->value.iec958.status[3] = sbits >> 24;
1823         return 0;
1824 }
1825
1826 static struct snd_kcontrol_new dig_in_ctls[] = {
1827         {
1828                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1829                 .name = SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH),
1830                 .info = snd_hda_spdif_in_switch_info,
1831                 .get = snd_hda_spdif_in_switch_get,
1832                 .put = snd_hda_spdif_in_switch_put,
1833         },
1834         {
1835                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
1836                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1837                 .name = SNDRV_CTL_NAME_IEC958("",CAPTURE,DEFAULT),
1838                 .info = snd_hda_spdif_mask_info,
1839                 .get = snd_hda_spdif_in_status_get,
1840         },
1841         { } /* end */
1842 };
1843
1844 /**
1845  * snd_hda_create_spdif_in_ctls - create Input SPDIF-related controls
1846  * @codec: the HDA codec
1847  * @nid: audio in widget NID
1848  *
1849  * Creates controls related with the SPDIF input.
1850  * Called from each patch supporting the SPDIF in.
1851  *
1852  * Returns 0 if successful, or a negative error code.
1853  */
1854 int snd_hda_create_spdif_in_ctls(struct hda_codec *codec, hda_nid_t nid)
1855 {
1856         int err;
1857         struct snd_kcontrol *kctl;
1858         struct snd_kcontrol_new *dig_mix;
1859         int idx;
1860
1861         for (idx = 0; idx < SPDIF_MAX_IDX; idx++) {
1862                 if (!_snd_hda_find_mixer_ctl(codec, "IEC958 Capture Switch",
1863                                              idx))
1864                         break;
1865         }
1866         if (idx >= SPDIF_MAX_IDX) {
1867                 printk(KERN_ERR "hda_codec: too many IEC958 inputs\n");
1868                 return -EBUSY;
1869         }
1870         for (dig_mix = dig_in_ctls; dig_mix->name; dig_mix++) {
1871                 kctl = snd_ctl_new1(dig_mix, codec);
1872                 kctl->private_value = nid;
1873                 err = snd_hda_ctl_add(codec, kctl);
1874                 if (err < 0)
1875                         return err;
1876         }
1877         codec->spdif_in_enable =
1878                 snd_hda_codec_read(codec, nid, 0,
1879                                    AC_VERB_GET_DIGI_CONVERT_1, 0) &
1880                 AC_DIG1_ENABLE;
1881         return 0;
1882 }
1883
1884 #ifdef SND_HDA_NEEDS_RESUME
1885 /*
1886  * command cache
1887  */
1888
1889 /* build a 32bit cache key with the widget id and the command parameter */
1890 #define build_cmd_cache_key(nid, verb)  ((verb << 8) | nid)
1891 #define get_cmd_cache_nid(key)          ((key) & 0xff)
1892 #define get_cmd_cache_cmd(key)          (((key) >> 8) & 0xffff)
1893
1894 /**
1895  * snd_hda_codec_write_cache - send a single command with caching
1896  * @codec: the HDA codec
1897  * @nid: NID to send the command
1898  * @direct: direct flag
1899  * @verb: the verb to send
1900  * @parm: the parameter for the verb
1901  *
1902  * Send a single command without waiting for response.
1903  *
1904  * Returns 0 if successful, or a negative error code.
1905  */
1906 int snd_hda_codec_write_cache(struct hda_codec *codec, hda_nid_t nid,
1907                               int direct, unsigned int verb, unsigned int parm)
1908 {
1909         struct hda_bus *bus = codec->bus;
1910         unsigned int res;
1911         int err;
1912
1913         res = make_codec_cmd(codec, nid, direct, verb, parm);
1914         snd_hda_power_up(codec);
1915         mutex_lock(&bus->cmd_mutex);
1916         err = bus->ops.command(bus, res);
1917         if (!err) {
1918                 struct hda_cache_head *c;
1919                 u32 key = build_cmd_cache_key(nid, verb);
1920                 c = get_alloc_hash(&codec->cmd_cache, key);
1921                 if (c)
1922                         c->val = parm;
1923         }
1924         mutex_unlock(&bus->cmd_mutex);
1925         snd_hda_power_down(codec);
1926         return err;
1927 }
1928
1929 /* resume the all commands from the cache */
1930 void snd_hda_codec_resume_cache(struct hda_codec *codec)
1931 {
1932         struct hda_cache_head *buffer = codec->cmd_cache.buf.list;
1933         int i;
1934
1935         for (i = 0; i < codec->cmd_cache.buf.used; i++, buffer++) {
1936                 u32 key = buffer->key;
1937                 if (!key)
1938                         continue;
1939                 snd_hda_codec_write(codec, get_cmd_cache_nid(key), 0,
1940                                     get_cmd_cache_cmd(key), buffer->val);
1941         }
1942 }
1943
1944 /**
1945  * snd_hda_sequence_write_cache - sequence writes with caching
1946  * @codec: the HDA codec
1947  * @seq: VERB array to send
1948  *
1949  * Send the commands sequentially from the given array.
1950  * Thte commands are recorded on cache for power-save and resume.
1951  * The array must be terminated with NID=0.
1952  */
1953 void snd_hda_sequence_write_cache(struct hda_codec *codec,
1954                                   const struct hda_verb *seq)
1955 {
1956         for (; seq->nid; seq++)
1957                 snd_hda_codec_write_cache(codec, seq->nid, 0, seq->verb,
1958                                           seq->param);
1959 }
1960 #endif /* SND_HDA_NEEDS_RESUME */
1961
1962 /*
1963  * set power state of the codec
1964  */
1965 static void hda_set_power_state(struct hda_codec *codec, hda_nid_t fg,
1966                                 unsigned int power_state)
1967 {
1968         hda_nid_t nid;
1969         int i;
1970
1971         snd_hda_codec_write(codec, fg, 0, AC_VERB_SET_POWER_STATE,
1972                             power_state);
1973         msleep(10); /* partial workaround for "azx_get_response timeout" */
1974
1975         nid = codec->start_nid;
1976         for (i = 0; i < codec->num_nodes; i++, nid++) {
1977                 unsigned int wcaps = get_wcaps(codec, nid);
1978                 if (wcaps & AC_WCAP_POWER) {
1979                         unsigned int wid_type = (wcaps & AC_WCAP_TYPE) >>
1980                                 AC_WCAP_TYPE_SHIFT;
1981                         if (wid_type == AC_WID_PIN) {
1982                                 unsigned int pincap;
1983                                 /*
1984                                  * don't power down the widget if it controls
1985                                  * eapd and EAPD_BTLENABLE is set.
1986                                  */
1987                                 pincap = snd_hda_param_read(codec, nid,
1988                                                             AC_PAR_PIN_CAP);
1989                                 if (pincap & AC_PINCAP_EAPD) {
1990                                         int eapd = snd_hda_codec_read(codec,
1991                                                 nid, 0,
1992                                                 AC_VERB_GET_EAPD_BTLENABLE, 0);
1993                                         eapd &= 0x02;
1994                                         if (power_state == AC_PWRST_D3 && eapd)
1995                                                 continue;
1996                                 }
1997                         }
1998                         snd_hda_codec_write(codec, nid, 0,
1999                                             AC_VERB_SET_POWER_STATE,
2000                                             power_state);
2001                 }
2002         }
2003
2004         if (power_state == AC_PWRST_D0) {
2005                 unsigned long end_time;
2006                 int state;
2007                 msleep(10);
2008                 /* wait until the codec reachs to D0 */
2009                 end_time = jiffies + msecs_to_jiffies(500);
2010                 do {
2011                         state = snd_hda_codec_read(codec, fg, 0,
2012                                                    AC_VERB_GET_POWER_STATE, 0);
2013                         if (state == power_state)
2014                                 break;
2015                         msleep(1);
2016                 } while (time_after_eq(end_time, jiffies));
2017         }
2018 }
2019
2020 #ifdef CONFIG_SND_HDA_HWDEP
2021 /* execute additional init verbs */
2022 static void hda_exec_init_verbs(struct hda_codec *codec)
2023 {
2024         if (codec->init_verbs.list)
2025                 snd_hda_sequence_write(codec, codec->init_verbs.list);
2026 }
2027 #else
2028 static inline void hda_exec_init_verbs(struct hda_codec *codec) {}
2029 #endif
2030
2031 #ifdef SND_HDA_NEEDS_RESUME
2032 /*
2033  * call suspend and power-down; used both from PM and power-save
2034  */
2035 static void hda_call_codec_suspend(struct hda_codec *codec)
2036 {
2037         if (codec->patch_ops.suspend)
2038                 codec->patch_ops.suspend(codec, PMSG_SUSPEND);
2039         hda_set_power_state(codec,
2040                             codec->afg ? codec->afg : codec->mfg,
2041                             AC_PWRST_D3);
2042 #ifdef CONFIG_SND_HDA_POWER_SAVE
2043         cancel_delayed_work(&codec->power_work);
2044         codec->power_on = 0;
2045         codec->power_transition = 0;
2046 #endif
2047 }
2048
2049 /*
2050  * kick up codec; used both from PM and power-save
2051  */
2052 static void hda_call_codec_resume(struct hda_codec *codec)
2053 {
2054         hda_set_power_state(codec,
2055                             codec->afg ? codec->afg : codec->mfg,
2056                             AC_PWRST_D0);
2057         hda_exec_init_verbs(codec);
2058         if (codec->patch_ops.resume)
2059                 codec->patch_ops.resume(codec);
2060         else {
2061                 if (codec->patch_ops.init)
2062                         codec->patch_ops.init(codec);
2063                 snd_hda_codec_resume_amp(codec);
2064                 snd_hda_codec_resume_cache(codec);
2065         }
2066 }
2067 #endif /* SND_HDA_NEEDS_RESUME */
2068
2069
2070 /**
2071  * snd_hda_build_controls - build mixer controls
2072  * @bus: the BUS
2073  *
2074  * Creates mixer controls for each codec included in the bus.
2075  *
2076  * Returns 0 if successful, otherwise a negative error code.
2077  */
2078 int __devinit snd_hda_build_controls(struct hda_bus *bus)
2079 {
2080         struct hda_codec *codec;
2081
2082         list_for_each_entry(codec, &bus->codec_list, list) {
2083                 int err = snd_hda_codec_build_controls(codec);
2084                 if (err < 0)
2085                         return err;
2086         }
2087         return 0;
2088 }
2089
2090 int snd_hda_codec_build_controls(struct hda_codec *codec)
2091 {
2092         int err = 0;
2093         /* fake as if already powered-on */
2094         hda_keep_power_on(codec);
2095         /* then fire up */
2096         hda_set_power_state(codec,
2097                             codec->afg ? codec->afg : codec->mfg,
2098                             AC_PWRST_D0);
2099         hda_exec_init_verbs(codec);
2100         /* continue to initialize... */
2101         if (codec->patch_ops.init)
2102                 err = codec->patch_ops.init(codec);
2103         if (!err && codec->patch_ops.build_controls)
2104                 err = codec->patch_ops.build_controls(codec);
2105         snd_hda_power_down(codec);
2106         if (err < 0)
2107                 return err;
2108         return 0;
2109 }
2110
2111 /*
2112  * stream formats
2113  */
2114 struct hda_rate_tbl {
2115         unsigned int hz;
2116         unsigned int alsa_bits;
2117         unsigned int hda_fmt;
2118 };
2119
2120 static struct hda_rate_tbl rate_bits[] = {
2121         /* rate in Hz, ALSA rate bitmask, HDA format value */
2122
2123         /* autodetected value used in snd_hda_query_supported_pcm */
2124         { 8000, SNDRV_PCM_RATE_8000, 0x0500 }, /* 1/6 x 48 */
2125         { 11025, SNDRV_PCM_RATE_11025, 0x4300 }, /* 1/4 x 44 */
2126         { 16000, SNDRV_PCM_RATE_16000, 0x0200 }, /* 1/3 x 48 */
2127         { 22050, SNDRV_PCM_RATE_22050, 0x4100 }, /* 1/2 x 44 */
2128         { 32000, SNDRV_PCM_RATE_32000, 0x0a00 }, /* 2/3 x 48 */
2129         { 44100, SNDRV_PCM_RATE_44100, 0x4000 }, /* 44 */
2130         { 48000, SNDRV_PCM_RATE_48000, 0x0000 }, /* 48 */
2131         { 88200, SNDRV_PCM_RATE_88200, 0x4800 }, /* 2 x 44 */
2132         { 96000, SNDRV_PCM_RATE_96000, 0x0800 }, /* 2 x 48 */
2133         { 176400, SNDRV_PCM_RATE_176400, 0x5800 },/* 4 x 44 */
2134         { 192000, SNDRV_PCM_RATE_192000, 0x1800 }, /* 4 x 48 */
2135 #define AC_PAR_PCM_RATE_BITS    11
2136         /* up to bits 10, 384kHZ isn't supported properly */
2137
2138         /* not autodetected value */
2139         { 9600, SNDRV_PCM_RATE_KNOT, 0x0400 }, /* 1/5 x 48 */
2140
2141         { 0 } /* terminator */
2142 };
2143
2144 /**
2145  * snd_hda_calc_stream_format - calculate format bitset
2146  * @rate: the sample rate
2147  * @channels: the number of channels
2148  * @format: the PCM format (SNDRV_PCM_FORMAT_XXX)
2149  * @maxbps: the max. bps
2150  *
2151  * Calculate the format bitset from the given rate, channels and th PCM format.
2152  *
2153  * Return zero if invalid.
2154  */
2155 unsigned int snd_hda_calc_stream_format(unsigned int rate,
2156                                         unsigned int channels,
2157                                         unsigned int format,
2158                                         unsigned int maxbps)
2159 {
2160         int i;
2161         unsigned int val = 0;
2162
2163         for (i = 0; rate_bits[i].hz; i++)
2164                 if (rate_bits[i].hz == rate) {
2165                         val = rate_bits[i].hda_fmt;
2166                         break;
2167                 }
2168         if (!rate_bits[i].hz) {
2169                 snd_printdd("invalid rate %d\n", rate);
2170                 return 0;
2171         }
2172
2173         if (channels == 0 || channels > 8) {
2174                 snd_printdd("invalid channels %d\n", channels);
2175                 return 0;
2176         }
2177         val |= channels - 1;
2178
2179         switch (snd_pcm_format_width(format)) {
2180         case 8:  val |= 0x00; break;
2181         case 16: val |= 0x10; break;
2182         case 20:
2183         case 24:
2184         case 32:
2185                 if (maxbps >= 32)
2186                         val |= 0x40;
2187                 else if (maxbps >= 24)
2188                         val |= 0x30;
2189                 else
2190                         val |= 0x20;
2191                 break;
2192         default:
2193                 snd_printdd("invalid format width %d\n",
2194                             snd_pcm_format_width(format));
2195                 return 0;
2196         }
2197
2198         return val;
2199 }
2200
2201 /**
2202  * snd_hda_query_supported_pcm - query the supported PCM rates and formats
2203  * @codec: the HDA codec
2204  * @nid: NID to query
2205  * @ratesp: the pointer to store the detected rate bitflags
2206  * @formatsp: the pointer to store the detected formats
2207  * @bpsp: the pointer to store the detected format widths
2208  *
2209  * Queries the supported PCM rates and formats.  The NULL @ratesp, @formatsp
2210  * or @bsps argument is ignored.
2211  *
2212  * Returns 0 if successful, otherwise a negative error code.
2213  */
2214 static int snd_hda_query_supported_pcm(struct hda_codec *codec, hda_nid_t nid,
2215                                 u32 *ratesp, u64 *formatsp, unsigned int *bpsp)
2216 {
2217         int i;
2218         unsigned int val, streams;
2219
2220         val = 0;
2221         if (nid != codec->afg &&
2222             (get_wcaps(codec, nid) & AC_WCAP_FORMAT_OVRD)) {
2223                 val = snd_hda_param_read(codec, nid, AC_PAR_PCM);
2224                 if (val == -1)
2225                         return -EIO;
2226         }
2227         if (!val)
2228                 val = snd_hda_param_read(codec, codec->afg, AC_PAR_PCM);
2229
2230         if (ratesp) {
2231                 u32 rates = 0;
2232                 for (i = 0; i < AC_PAR_PCM_RATE_BITS; i++) {
2233                         if (val & (1 << i))
2234                                 rates |= rate_bits[i].alsa_bits;
2235                 }
2236                 *ratesp = rates;
2237         }
2238
2239         if (formatsp || bpsp) {
2240                 u64 formats = 0;
2241                 unsigned int bps;
2242                 unsigned int wcaps;
2243
2244                 wcaps = get_wcaps(codec, nid);
2245                 streams = snd_hda_param_read(codec, nid, AC_PAR_STREAM);
2246                 if (streams == -1)
2247                         return -EIO;
2248                 if (!streams) {
2249                         streams = snd_hda_param_read(codec, codec->afg,
2250                                                      AC_PAR_STREAM);
2251                         if (streams == -1)
2252                                 return -EIO;
2253                 }
2254
2255                 bps = 0;
2256                 if (streams & AC_SUPFMT_PCM) {
2257                         if (val & AC_SUPPCM_BITS_8) {
2258                                 formats |= SNDRV_PCM_FMTBIT_U8;
2259                                 bps = 8;
2260                         }
2261                         if (val & AC_SUPPCM_BITS_16) {
2262                                 formats |= SNDRV_PCM_FMTBIT_S16_LE;
2263                                 bps = 16;
2264                         }
2265                         if (wcaps & AC_WCAP_DIGITAL) {
2266                                 if (val & AC_SUPPCM_BITS_32)
2267                                         formats |= SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE;
2268                                 if (val & (AC_SUPPCM_BITS_20|AC_SUPPCM_BITS_24))
2269                                         formats |= SNDRV_PCM_FMTBIT_S32_LE;
2270                                 if (val & AC_SUPPCM_BITS_24)
2271                                         bps = 24;
2272                                 else if (val & AC_SUPPCM_BITS_20)
2273                                         bps = 20;
2274                         } else if (val & (AC_SUPPCM_BITS_20|AC_SUPPCM_BITS_24|
2275                                           AC_SUPPCM_BITS_32)) {
2276                                 formats |= SNDRV_PCM_FMTBIT_S32_LE;
2277                                 if (val & AC_SUPPCM_BITS_32)
2278                                         bps = 32;
2279                                 else if (val & AC_SUPPCM_BITS_24)
2280                                         bps = 24;
2281                                 else if (val & AC_SUPPCM_BITS_20)
2282                                         bps = 20;
2283                         }
2284                 }
2285                 else if (streams == AC_SUPFMT_FLOAT32) {
2286                         /* should be exclusive */
2287                         formats |= SNDRV_PCM_FMTBIT_FLOAT_LE;
2288                         bps = 32;
2289                 } else if (streams == AC_SUPFMT_AC3) {
2290                         /* should be exclusive */
2291                         /* temporary hack: we have still no proper support
2292                          * for the direct AC3 stream...
2293                          */
2294                         formats |= SNDRV_PCM_FMTBIT_U8;
2295                         bps = 8;
2296                 }
2297                 if (formatsp)
2298                         *formatsp = formats;
2299                 if (bpsp)
2300                         *bpsp = bps;
2301         }
2302
2303         return 0;
2304 }
2305
2306 /**
2307  * snd_hda_is_supported_format - check whether the given node supports
2308  * the format val
2309  *
2310  * Returns 1 if supported, 0 if not.
2311  */
2312 int snd_hda_is_supported_format(struct hda_codec *codec, hda_nid_t nid,
2313                                 unsigned int format)
2314 {
2315         int i;
2316         unsigned int val = 0, rate, stream;
2317
2318         if (nid != codec->afg &&
2319             (get_wcaps(codec, nid) & AC_WCAP_FORMAT_OVRD)) {
2320                 val = snd_hda_param_read(codec, nid, AC_PAR_PCM);
2321                 if (val == -1)
2322                         return 0;
2323         }
2324         if (!val) {
2325                 val = snd_hda_param_read(codec, codec->afg, AC_PAR_PCM);
2326                 if (val == -1)
2327                         return 0;
2328         }
2329
2330         rate = format & 0xff00;
2331         for (i = 0; i < AC_PAR_PCM_RATE_BITS; i++)
2332                 if (rate_bits[i].hda_fmt == rate) {
2333                         if (val & (1 << i))
2334                                 break;
2335                         return 0;
2336                 }
2337         if (i >= AC_PAR_PCM_RATE_BITS)
2338                 return 0;
2339
2340         stream = snd_hda_param_read(codec, nid, AC_PAR_STREAM);
2341         if (stream == -1)
2342                 return 0;
2343         if (!stream && nid != codec->afg)
2344                 stream = snd_hda_param_read(codec, codec->afg, AC_PAR_STREAM);
2345         if (!stream || stream == -1)
2346                 return 0;
2347
2348         if (stream & AC_SUPFMT_PCM) {
2349                 switch (format & 0xf0) {
2350                 case 0x00:
2351                         if (!(val & AC_SUPPCM_BITS_8))
2352                                 return 0;
2353                         break;
2354                 case 0x10:
2355                         if (!(val & AC_SUPPCM_BITS_16))
2356                                 return 0;
2357                         break;
2358                 case 0x20:
2359                         if (!(val & AC_SUPPCM_BITS_20))
2360                                 return 0;
2361                         break;
2362                 case 0x30:
2363                         if (!(val & AC_SUPPCM_BITS_24))
2364                                 return 0;
2365                         break;
2366                 case 0x40:
2367                         if (!(val & AC_SUPPCM_BITS_32))
2368                                 return 0;
2369                         break;
2370                 default:
2371                         return 0;
2372                 }
2373         } else {
2374                 /* FIXME: check for float32 and AC3? */
2375         }
2376
2377         return 1;
2378 }
2379
2380 /*
2381  * PCM stuff
2382  */
2383 static int hda_pcm_default_open_close(struct hda_pcm_stream *hinfo,
2384                                       struct hda_codec *codec,
2385                                       struct snd_pcm_substream *substream)
2386 {
2387         return 0;
2388 }
2389
2390 static int hda_pcm_default_prepare(struct hda_pcm_stream *hinfo,
2391                                    struct hda_codec *codec,
2392                                    unsigned int stream_tag,
2393                                    unsigned int format,
2394                                    struct snd_pcm_substream *substream)
2395 {
2396         snd_hda_codec_setup_stream(codec, hinfo->nid, stream_tag, 0, format);
2397         return 0;
2398 }
2399
2400 static int hda_pcm_default_cleanup(struct hda_pcm_stream *hinfo,
2401                                    struct hda_codec *codec,
2402                                    struct snd_pcm_substream *substream)
2403 {
2404         snd_hda_codec_cleanup_stream(codec, hinfo->nid);
2405         return 0;
2406 }
2407
2408 static int set_pcm_default_values(struct hda_codec *codec,
2409                                   struct hda_pcm_stream *info)
2410 {
2411         /* query support PCM information from the given NID */
2412         if (info->nid && (!info->rates || !info->formats)) {
2413                 snd_hda_query_supported_pcm(codec, info->nid,
2414                                 info->rates ? NULL : &info->rates,
2415                                 info->formats ? NULL : &info->formats,
2416                                 info->maxbps ? NULL : &info->maxbps);
2417         }
2418         if (info->ops.open == NULL)
2419                 info->ops.open = hda_pcm_default_open_close;
2420         if (info->ops.close == NULL)
2421                 info->ops.close = hda_pcm_default_open_close;
2422         if (info->ops.prepare == NULL) {
2423                 if (snd_BUG_ON(!info->nid))
2424                         return -EINVAL;
2425                 info->ops.prepare = hda_pcm_default_prepare;
2426         }
2427         if (info->ops.cleanup == NULL) {
2428                 if (snd_BUG_ON(!info->nid))
2429                         return -EINVAL;
2430                 info->ops.cleanup = hda_pcm_default_cleanup;
2431         }
2432         return 0;
2433 }
2434
2435 /*
2436  * attach a new PCM stream
2437  */
2438 static int __devinit
2439 snd_hda_attach_pcm(struct hda_codec *codec, struct hda_pcm *pcm)
2440 {
2441         struct hda_bus *bus = codec->bus;
2442         struct hda_pcm_stream *info;
2443         int stream, err;
2444
2445         if (snd_BUG_ON(!pcm->name))
2446                 return -EINVAL;
2447         for (stream = 0; stream < 2; stream++) {
2448                 info = &pcm->stream[stream];
2449                 if (info->substreams) {
2450                         err = set_pcm_default_values(codec, info);
2451                         if (err < 0)
2452                                 return err;
2453                 }
2454         }
2455         return bus->ops.attach_pcm(bus, codec, pcm);
2456 }
2457
2458 /**
2459  * snd_hda_build_pcms - build PCM information
2460  * @bus: the BUS
2461  *
2462  * Create PCM information for each codec included in the bus.
2463  *
2464  * The build_pcms codec patch is requested to set up codec->num_pcms and
2465  * codec->pcm_info properly.  The array is referred by the top-level driver
2466  * to create its PCM instances.
2467  * The allocated codec->pcm_info should be released in codec->patch_ops.free
2468  * callback.
2469  *
2470  * At least, substreams, channels_min and channels_max must be filled for
2471  * each stream.  substreams = 0 indicates that the stream doesn't exist.
2472  * When rates and/or formats are zero, the supported values are queried
2473  * from the given nid.  The nid is used also by the default ops.prepare
2474  * and ops.cleanup callbacks.
2475  *
2476  * The driver needs to call ops.open in its open callback.  Similarly,
2477  * ops.close is supposed to be called in the close callback.
2478  * ops.prepare should be called in the prepare or hw_params callback
2479  * with the proper parameters for set up.
2480  * ops.cleanup should be called in hw_free for clean up of streams.
2481  *
2482  * This function returns 0 if successfull, or a negative error code.
2483  */
2484 int snd_hda_build_pcms(struct hda_bus *bus)
2485 {
2486         static const char *dev_name[HDA_PCM_NTYPES] = {
2487                 "Audio", "SPDIF", "HDMI", "Modem"
2488         };
2489         /* starting device index for each PCM type */
2490         static int dev_idx[HDA_PCM_NTYPES] = {
2491                 [HDA_PCM_TYPE_AUDIO] = 0,
2492                 [HDA_PCM_TYPE_SPDIF] = 1,
2493                 [HDA_PCM_TYPE_HDMI] = 3,
2494                 [HDA_PCM_TYPE_MODEM] = 6
2495         };
2496         /* normal audio device indices; not linear to keep compatibility */
2497         static int audio_idx[4] = { 0, 2, 4, 5 };
2498         struct hda_codec *codec;
2499         int num_devs[HDA_PCM_NTYPES];
2500
2501         memset(num_devs, 0, sizeof(num_devs));
2502         list_for_each_entry(codec, &bus->codec_list, list) {
2503                 unsigned int pcm;
2504                 int err;
2505                 if (!codec->num_pcms) {
2506                         if (!codec->patch_ops.build_pcms)
2507                                 continue;
2508                         err = codec->patch_ops.build_pcms(codec);
2509                         if (err < 0)
2510                                 return err;
2511                 }
2512                 for (pcm = 0; pcm < codec->num_pcms; pcm++) {
2513                         struct hda_pcm *cpcm = &codec->pcm_info[pcm];
2514                         int type = cpcm->pcm_type;
2515                         int dev;
2516
2517                         if (!cpcm->stream[0].substreams &&
2518                             !cpcm->stream[1].substreams)
2519                                 continue; /* no substreams assigned */
2520
2521                         switch (type) {
2522                         case HDA_PCM_TYPE_AUDIO:
2523                                 if (num_devs[type] >= ARRAY_SIZE(audio_idx)) {
2524                                         snd_printk(KERN_WARNING
2525                                                    "Too many audio devices\n");
2526                                         continue;
2527                                 }
2528                                 dev = audio_idx[num_devs[type]];
2529                                 break;
2530                         case HDA_PCM_TYPE_SPDIF:
2531                         case HDA_PCM_TYPE_HDMI:
2532                         case HDA_PCM_TYPE_MODEM:
2533                                 if (num_devs[type]) {
2534                                         snd_printk(KERN_WARNING
2535                                                    "%s already defined\n",
2536                                                    dev_name[type]);
2537                                         continue;
2538                                 }
2539                                 dev = dev_idx[type];
2540                                 break;
2541                         default:
2542                                 snd_printk(KERN_WARNING
2543                                            "Invalid PCM type %d\n", type);
2544                                 continue;
2545                         }
2546                         num_devs[type]++;
2547                         if (!cpcm->pcm) {
2548                                 cpcm->device = dev;
2549                                 err = snd_hda_attach_pcm(codec, cpcm);
2550                                 if (err < 0)
2551                                         return err;
2552                         }
2553                 }
2554         }
2555         return 0;
2556 }
2557
2558 /**
2559  * snd_hda_check_board_config - compare the current codec with the config table
2560  * @codec: the HDA codec
2561  * @num_configs: number of config enums
2562  * @models: array of model name strings
2563  * @tbl: configuration table, terminated by null entries
2564  *
2565  * Compares the modelname or PCI subsystem id of the current codec with the
2566  * given configuration table.  If a matching entry is found, returns its
2567  * config value (supposed to be 0 or positive).
2568  *
2569  * If no entries are matching, the function returns a negative value.
2570  */
2571 int snd_hda_check_board_config(struct hda_codec *codec,
2572                                int num_configs, const char **models,
2573                                const struct snd_pci_quirk *tbl)
2574 {
2575         if (codec->modelname && models) {
2576                 int i;
2577                 for (i = 0; i < num_configs; i++) {
2578                         if (models[i] &&
2579                             !strcmp(codec->modelname, models[i])) {
2580                                 snd_printd(KERN_INFO "hda_codec: model '%s' is "
2581                                            "selected\n", models[i]);
2582                                 return i;
2583                         }
2584                 }
2585         }
2586
2587         if (!codec->bus->pci || !tbl)
2588                 return -1;
2589
2590         tbl = snd_pci_quirk_lookup(codec->bus->pci, tbl);
2591         if (!tbl)
2592                 return -1;
2593         if (tbl->value >= 0 && tbl->value < num_configs) {
2594 #ifdef CONFIG_SND_DEBUG_VERBOSE
2595                 char tmp[10];
2596                 const char *model = NULL;
2597                 if (models)
2598                         model = models[tbl->value];
2599                 if (!model) {
2600                         sprintf(tmp, "#%d", tbl->value);
2601                         model = tmp;
2602                 }
2603                 snd_printdd(KERN_INFO "hda_codec: model '%s' is selected "
2604                             "for config %x:%x (%s)\n",
2605                             model, tbl->subvendor, tbl->subdevice,
2606                             (tbl->name ? tbl->name : "Unknown device"));
2607 #endif
2608                 return tbl->value;
2609         }
2610         return -1;
2611 }
2612
2613 /**
2614  * snd_hda_add_new_ctls - create controls from the array
2615  * @codec: the HDA codec
2616  * @knew: the array of struct snd_kcontrol_new
2617  *
2618  * This helper function creates and add new controls in the given array.
2619  * The array must be terminated with an empty entry as terminator.
2620  *
2621  * Returns 0 if successful, or a negative error code.
2622  */
2623 int snd_hda_add_new_ctls(struct hda_codec *codec, struct snd_kcontrol_new *knew)
2624 {
2625         int err;
2626
2627         for (; knew->name; knew++) {
2628                 struct snd_kcontrol *kctl;
2629                 kctl = snd_ctl_new1(knew, codec);
2630                 if (!kctl)
2631                         return -ENOMEM;
2632                 err = snd_hda_ctl_add(codec, kctl);
2633                 if (err < 0) {
2634                         if (!codec->addr)
2635                                 return err;
2636                         kctl = snd_ctl_new1(knew, codec);
2637                         if (!kctl)
2638                                 return -ENOMEM;
2639                         kctl->id.device = codec->addr;
2640                         err = snd_hda_ctl_add(codec, kctl);
2641                         if (err < 0)
2642                                 return err;
2643                 }
2644         }
2645         return 0;
2646 }
2647
2648 #ifdef CONFIG_SND_HDA_POWER_SAVE
2649 static void hda_set_power_state(struct hda_codec *codec, hda_nid_t fg,
2650                                 unsigned int power_state);
2651
2652 static void hda_power_work(struct work_struct *work)
2653 {
2654         struct hda_codec *codec =
2655                 container_of(work, struct hda_codec, power_work.work);
2656         struct hda_bus *bus = codec->bus;
2657
2658         if (!codec->power_on || codec->power_count) {
2659                 codec->power_transition = 0;
2660                 return;
2661         }
2662
2663         hda_call_codec_suspend(codec);
2664         if (bus->ops.pm_notify)
2665                 bus->ops.pm_notify(bus);
2666 }
2667
2668 static void hda_keep_power_on(struct hda_codec *codec)
2669 {
2670         codec->power_count++;
2671         codec->power_on = 1;
2672 }
2673
2674 void snd_hda_power_up(struct hda_codec *codec)
2675 {
2676         struct hda_bus *bus = codec->bus;
2677
2678         codec->power_count++;
2679         if (codec->power_on || codec->power_transition)
2680                 return;
2681
2682         codec->power_on = 1;
2683         if (bus->ops.pm_notify)
2684                 bus->ops.pm_notify(bus);
2685         hda_call_codec_resume(codec);
2686         cancel_delayed_work(&codec->power_work);
2687         codec->power_transition = 0;
2688 }
2689
2690 #define power_save(codec)       \
2691         ((codec)->bus->power_save ? *(codec)->bus->power_save : 0)
2692
2693 void snd_hda_power_down(struct hda_codec *codec)
2694 {
2695         --codec->power_count;
2696         if (!codec->power_on || codec->power_count || codec->power_transition)
2697                 return;
2698         if (power_save(codec)) {
2699                 codec->power_transition = 1; /* avoid reentrance */
2700                 schedule_delayed_work(&codec->power_work,
2701                                 msecs_to_jiffies(power_save(codec) * 1000));
2702         }
2703 }
2704
2705 int snd_hda_check_amp_list_power(struct hda_codec *codec,
2706                                  struct hda_loopback_check *check,
2707                                  hda_nid_t nid)
2708 {
2709         struct hda_amp_list *p;
2710         int ch, v;
2711
2712         if (!check->amplist)
2713                 return 0;
2714         for (p = check->amplist; p->nid; p++) {
2715                 if (p->nid == nid)
2716                         break;
2717         }
2718         if (!p->nid)
2719                 return 0; /* nothing changed */
2720
2721         for (p = check->amplist; p->nid; p++) {
2722                 for (ch = 0; ch < 2; ch++) {
2723                         v = snd_hda_codec_amp_read(codec, p->nid, ch, p->dir,
2724                                                    p->idx);
2725                         if (!(v & HDA_AMP_MUTE) && v > 0) {
2726                                 if (!check->power_on) {
2727                                         check->power_on = 1;
2728                                         snd_hda_power_up(codec);
2729                                 }
2730                                 return 1;
2731                         }
2732                 }
2733         }
2734         if (check->power_on) {
2735                 check->power_on = 0;
2736                 snd_hda_power_down(codec);
2737         }
2738         return 0;
2739 }
2740 #endif
2741
2742 /*
2743  * Channel mode helper
2744  */
2745 int snd_hda_ch_mode_info(struct hda_codec *codec,
2746                          struct snd_ctl_elem_info *uinfo,
2747                          const struct hda_channel_mode *chmode,
2748                          int num_chmodes)
2749 {
2750         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
2751         uinfo->count = 1;
2752         uinfo->value.enumerated.items = num_chmodes;
2753         if (uinfo->value.enumerated.item >= num_chmodes)
2754                 uinfo->value.enumerated.item = num_chmodes - 1;
2755         sprintf(uinfo->value.enumerated.name, "%dch",
2756                 chmode[uinfo->value.enumerated.item].channels);
2757         return 0;
2758 }
2759
2760 int snd_hda_ch_mode_get(struct hda_codec *codec,
2761                         struct snd_ctl_elem_value *ucontrol,
2762                         const struct hda_channel_mode *chmode,
2763                         int num_chmodes,
2764                         int max_channels)
2765 {
2766         int i;
2767
2768         for (i = 0; i < num_chmodes; i++) {
2769                 if (max_channels == chmode[i].channels) {
2770                         ucontrol->value.enumerated.item[0] = i;
2771                         break;
2772                 }
2773         }
2774         return 0;
2775 }
2776
2777 int snd_hda_ch_mode_put(struct hda_codec *codec,
2778                         struct snd_ctl_elem_value *ucontrol,
2779                         const struct hda_channel_mode *chmode,
2780                         int num_chmodes,
2781                         int *max_channelsp)
2782 {
2783         unsigned int mode;
2784
2785         mode = ucontrol->value.enumerated.item[0];
2786         if (mode >= num_chmodes)
2787                 return -EINVAL;
2788         if (*max_channelsp == chmode[mode].channels)
2789                 return 0;
2790         /* change the current channel setting */
2791         *max_channelsp = chmode[mode].channels;
2792         if (chmode[mode].sequence)
2793                 snd_hda_sequence_write_cache(codec, chmode[mode].sequence);
2794         return 1;
2795 }
2796
2797 /*
2798  * input MUX helper
2799  */
2800 int snd_hda_input_mux_info(const struct hda_input_mux *imux,
2801                            struct snd_ctl_elem_info *uinfo)
2802 {
2803         unsigned int index;
2804
2805         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
2806         uinfo->count = 1;
2807         uinfo->value.enumerated.items = imux->num_items;
2808         if (!imux->num_items)
2809                 return 0;
2810         index = uinfo->value.enumerated.item;
2811         if (index >= imux->num_items)
2812                 index = imux->num_items - 1;
2813         strcpy(uinfo->value.enumerated.name, imux->items[index].label);
2814         return 0;
2815 }
2816
2817 int snd_hda_input_mux_put(struct hda_codec *codec,
2818                           const struct hda_input_mux *imux,
2819                           struct snd_ctl_elem_value *ucontrol,
2820                           hda_nid_t nid,
2821                           unsigned int *cur_val)
2822 {
2823         unsigned int idx;
2824
2825         if (!imux->num_items)
2826                 return 0;
2827         idx = ucontrol->value.enumerated.item[0];
2828         if (idx >= imux->num_items)
2829                 idx = imux->num_items - 1;
2830         if (*cur_val == idx)
2831                 return 0;
2832         snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_CONNECT_SEL,
2833                                   imux->items[idx].index);
2834         *cur_val = idx;
2835         return 1;
2836 }
2837
2838
2839 /*
2840  * Multi-channel / digital-out PCM helper functions
2841  */
2842
2843 /* setup SPDIF output stream */
2844 static void setup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid,
2845                                  unsigned int stream_tag, unsigned int format)
2846 {
2847         /* turn off SPDIF once; otherwise the IEC958 bits won't be updated */
2848         if (codec->spdif_status_reset && (codec->spdif_ctls & AC_DIG1_ENABLE))
2849                 set_dig_out_convert(codec, nid, 
2850                                     codec->spdif_ctls & ~AC_DIG1_ENABLE & 0xff,
2851                                     -1);
2852         snd_hda_codec_setup_stream(codec, nid, stream_tag, 0, format);
2853         if (codec->slave_dig_outs) {
2854                 hda_nid_t *d;
2855                 for (d = codec->slave_dig_outs; *d; d++)
2856                         snd_hda_codec_setup_stream(codec, *d, stream_tag, 0,
2857                                                    format);
2858         }
2859         /* turn on again (if needed) */
2860         if (codec->spdif_status_reset && (codec->spdif_ctls & AC_DIG1_ENABLE))
2861                 set_dig_out_convert(codec, nid,
2862                                     codec->spdif_ctls & 0xff, -1);
2863 }
2864
2865 static void cleanup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid)
2866 {
2867         snd_hda_codec_cleanup_stream(codec, nid);
2868         if (codec->slave_dig_outs) {
2869                 hda_nid_t *d;
2870                 for (d = codec->slave_dig_outs; *d; d++)
2871                         snd_hda_codec_cleanup_stream(codec, *d);
2872         }
2873 }
2874
2875 /*
2876  * open the digital out in the exclusive mode
2877  */
2878 int snd_hda_multi_out_dig_open(struct hda_codec *codec,
2879                                struct hda_multi_out *mout)
2880 {
2881         mutex_lock(&codec->spdif_mutex);
2882         if (mout->dig_out_used == HDA_DIG_ANALOG_DUP)
2883                 /* already opened as analog dup; reset it once */
2884                 cleanup_dig_out_stream(codec, mout->dig_out_nid);
2885         mout->dig_out_used = HDA_DIG_EXCLUSIVE;
2886         mutex_unlock(&codec->spdif_mutex);
2887         return 0;
2888 }
2889
2890 int snd_hda_multi_out_dig_prepare(struct hda_codec *codec,
2891                                   struct hda_multi_out *mout,
2892                                   unsigned int stream_tag,
2893                                   unsigned int format,
2894                                   struct snd_pcm_substream *substream)
2895 {
2896         mutex_lock(&codec->spdif_mutex);
2897         setup_dig_out_stream(codec, mout->dig_out_nid, stream_tag, format);
2898         mutex_unlock(&codec->spdif_mutex);
2899         return 0;
2900 }
2901
2902 /*
2903  * release the digital out
2904  */
2905 int snd_hda_multi_out_dig_close(struct hda_codec *codec,
2906                                 struct hda_multi_out *mout)
2907 {
2908         mutex_lock(&codec->spdif_mutex);
2909         mout->dig_out_used = 0;
2910         mutex_unlock(&codec->spdif_mutex);
2911         return 0;
2912 }
2913
2914 /*
2915  * set up more restrictions for analog out
2916  */
2917 int snd_hda_multi_out_analog_open(struct hda_codec *codec,
2918                                   struct hda_multi_out *mout,
2919                                   struct snd_pcm_substream *substream,
2920                                   struct hda_pcm_stream *hinfo)
2921 {
2922         struct snd_pcm_runtime *runtime = substream->runtime;
2923         runtime->hw.channels_max = mout->max_channels;
2924         if (mout->dig_out_nid) {
2925                 if (!mout->analog_rates) {
2926                         mout->analog_rates = hinfo->rates;
2927                         mout->analog_formats = hinfo->formats;
2928                         mout->analog_maxbps = hinfo->maxbps;
2929                 } else {
2930                         runtime->hw.rates = mout->analog_rates;
2931                         runtime->hw.formats = mout->analog_formats;
2932                         hinfo->maxbps = mout->analog_maxbps;
2933                 }
2934                 if (!mout->spdif_rates) {
2935                         snd_hda_query_supported_pcm(codec, mout->dig_out_nid,
2936                                                     &mout->spdif_rates,
2937                                                     &mout->spdif_formats,
2938                                                     &mout->spdif_maxbps);
2939                 }
2940                 mutex_lock(&codec->spdif_mutex);
2941                 if (mout->share_spdif) {
2942                         runtime->hw.rates &= mout->spdif_rates;
2943                         runtime->hw.formats &= mout->spdif_formats;
2944                         if (mout->spdif_maxbps < hinfo->maxbps)
2945                                 hinfo->maxbps = mout->spdif_maxbps;
2946                 }
2947                 mutex_unlock(&codec->spdif_mutex);
2948         }
2949         return snd_pcm_hw_constraint_step(substream->runtime, 0,
2950                                           SNDRV_PCM_HW_PARAM_CHANNELS, 2);
2951 }
2952
2953 /*
2954  * set up the i/o for analog out
2955  * when the digital out is available, copy the front out to digital out, too.
2956  */
2957 int snd_hda_multi_out_analog_prepare(struct hda_codec *codec,
2958                                      struct hda_multi_out *mout,
2959                                      unsigned int stream_tag,
2960                                      unsigned int format,
2961                                      struct snd_pcm_substream *substream)
2962 {
2963         hda_nid_t *nids = mout->dac_nids;
2964         int chs = substream->runtime->channels;
2965         int i;
2966
2967         mutex_lock(&codec->spdif_mutex);
2968         if (mout->dig_out_nid && mout->share_spdif &&
2969             mout->dig_out_used != HDA_DIG_EXCLUSIVE) {
2970                 if (chs == 2 &&
2971                     snd_hda_is_supported_format(codec, mout->dig_out_nid,
2972                                                 format) &&
2973                     !(codec->spdif_status & IEC958_AES0_NONAUDIO)) {
2974                         mout->dig_out_used = HDA_DIG_ANALOG_DUP;
2975                         setup_dig_out_stream(codec, mout->dig_out_nid,
2976                                              stream_tag, format);
2977                 } else {
2978                         mout->dig_out_used = 0;
2979                         cleanup_dig_out_stream(codec, mout->dig_out_nid);
2980                 }
2981         }
2982         mutex_unlock(&codec->spdif_mutex);
2983
2984         /* front */
2985         snd_hda_codec_setup_stream(codec, nids[HDA_FRONT], stream_tag,
2986                                    0, format);
2987         if (!mout->no_share_stream &&
2988             mout->hp_nid && mout->hp_nid != nids[HDA_FRONT])
2989                 /* headphone out will just decode front left/right (stereo) */
2990                 snd_hda_codec_setup_stream(codec, mout->hp_nid, stream_tag,
2991                                            0, format);
2992         /* extra outputs copied from front */
2993         for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
2994                 if (!mout->no_share_stream && mout->extra_out_nid[i])
2995                         snd_hda_codec_setup_stream(codec,
2996                                                    mout->extra_out_nid[i],
2997                                                    stream_tag, 0, format);
2998
2999         /* surrounds */
3000         for (i = 1; i < mout->num_dacs; i++) {
3001                 if (chs >= (i + 1) * 2) /* independent out */
3002                         snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
3003                                                    i * 2, format);
3004                 else if (!mout->no_share_stream) /* copy front */
3005                         snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
3006                                                    0, format);
3007         }
3008         return 0;
3009 }
3010
3011 /*
3012  * clean up the setting for analog out
3013  */
3014 int snd_hda_multi_out_analog_cleanup(struct hda_codec *codec,
3015                                      struct hda_multi_out *mout)
3016 {
3017         hda_nid_t *nids = mout->dac_nids;
3018         int i;
3019
3020         for (i = 0; i < mout->num_dacs; i++)
3021                 snd_hda_codec_cleanup_stream(codec, nids[i]);
3022         if (mout->hp_nid)
3023                 snd_hda_codec_cleanup_stream(codec, mout->hp_nid);
3024         for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
3025                 if (mout->extra_out_nid[i])
3026                         snd_hda_codec_cleanup_stream(codec,
3027                                                      mout->extra_out_nid[i]);
3028         mutex_lock(&codec->spdif_mutex);
3029         if (mout->dig_out_nid && mout->dig_out_used == HDA_DIG_ANALOG_DUP) {
3030                 cleanup_dig_out_stream(codec, mout->dig_out_nid);
3031                 mout->dig_out_used = 0;
3032         }
3033         mutex_unlock(&codec->spdif_mutex);
3034         return 0;
3035 }
3036
3037 /*
3038  * Helper for automatic pin configuration
3039  */
3040
3041 static int is_in_nid_list(hda_nid_t nid, hda_nid_t *list)
3042 {
3043         for (; *list; list++)
3044                 if (*list == nid)
3045                         return 1;
3046         return 0;
3047 }
3048
3049
3050 /*
3051  * Sort an associated group of pins according to their sequence numbers.
3052  */
3053 static void sort_pins_by_sequence(hda_nid_t * pins, short * sequences,
3054                                   int num_pins)
3055 {
3056         int i, j;
3057         short seq;
3058         hda_nid_t nid;
3059         
3060         for (i = 0; i < num_pins; i++) {
3061                 for (j = i + 1; j < num_pins; j++) {
3062                         if (sequences[i] > sequences[j]) {
3063                                 seq = sequences[i];
3064                                 sequences[i] = sequences[j];
3065                                 sequences[j] = seq;
3066                                 nid = pins[i];
3067                                 pins[i] = pins[j];
3068                                 pins[j] = nid;
3069                         }
3070                 }
3071         }
3072 }
3073
3074
3075 /*
3076  * Parse all pin widgets and store the useful pin nids to cfg
3077  *
3078  * The number of line-outs or any primary output is stored in line_outs,
3079  * and the corresponding output pins are assigned to line_out_pins[],
3080  * in the order of front, rear, CLFE, side, ...
3081  *
3082  * If more extra outputs (speaker and headphone) are found, the pins are
3083  * assisnged to hp_pins[] and speaker_pins[], respectively.  If no line-out jack
3084  * is detected, one of speaker of HP pins is assigned as the primary
3085  * output, i.e. to line_out_pins[0].  So, line_outs is always positive
3086  * if any analog output exists.
3087  * 
3088  * The analog input pins are assigned to input_pins array.
3089  * The digital input/output pins are assigned to dig_in_pin and dig_out_pin,
3090  * respectively.
3091  */
3092 int snd_hda_parse_pin_def_config(struct hda_codec *codec,
3093                                  struct auto_pin_cfg *cfg,
3094                                  hda_nid_t *ignore_nids)
3095 {
3096         hda_nid_t nid, end_nid;
3097         short seq, assoc_line_out, assoc_speaker;
3098         short sequences_line_out[ARRAY_SIZE(cfg->line_out_pins)];
3099         short sequences_speaker[ARRAY_SIZE(cfg->speaker_pins)];
3100         short sequences_hp[ARRAY_SIZE(cfg->hp_pins)];
3101
3102         memset(cfg, 0, sizeof(*cfg));
3103
3104         memset(sequences_line_out, 0, sizeof(sequences_line_out));
3105         memset(sequences_speaker, 0, sizeof(sequences_speaker));
3106         memset(sequences_hp, 0, sizeof(sequences_hp));
3107         assoc_line_out = assoc_speaker = 0;
3108
3109         end_nid = codec->start_nid + codec->num_nodes;
3110         for (nid = codec->start_nid; nid < end_nid; nid++) {
3111                 unsigned int wid_caps = get_wcaps(codec, nid);
3112                 unsigned int wid_type =
3113                         (wid_caps & AC_WCAP_TYPE) >> AC_WCAP_TYPE_SHIFT;
3114                 unsigned int def_conf;
3115                 short assoc, loc;
3116
3117                 /* read all default configuration for pin complex */
3118                 if (wid_type != AC_WID_PIN)
3119                         continue;
3120                 /* ignore the given nids (e.g. pc-beep returns error) */
3121                 if (ignore_nids && is_in_nid_list(nid, ignore_nids))
3122                         continue;
3123
3124                 def_conf = snd_hda_codec_read(codec, nid, 0,
3125                                               AC_VERB_GET_CONFIG_DEFAULT, 0);
3126                 if (get_defcfg_connect(def_conf) == AC_JACK_PORT_NONE)
3127                         continue;
3128                 loc = get_defcfg_location(def_conf);
3129                 switch (get_defcfg_device(def_conf)) {
3130                 case AC_JACK_LINE_OUT:
3131                         seq = get_defcfg_sequence(def_conf);
3132                         assoc = get_defcfg_association(def_conf);
3133
3134                         if (!(wid_caps & AC_WCAP_STEREO))
3135                                 if (!cfg->mono_out_pin)
3136                                         cfg->mono_out_pin = nid;
3137                         if (!assoc)
3138                                 continue;
3139                         if (!assoc_line_out)
3140                                 assoc_line_out = assoc;
3141                         else if (assoc_line_out != assoc)
3142                                 continue;
3143                         if (cfg->line_outs >= ARRAY_SIZE(cfg->line_out_pins))
3144                                 continue;
3145                         cfg->line_out_pins[cfg->line_outs] = nid;
3146                         sequences_line_out[cfg->line_outs] = seq;
3147                         cfg->line_outs++;
3148                         break;
3149                 case AC_JACK_SPEAKER:
3150                         seq = get_defcfg_sequence(def_conf);
3151                         assoc = get_defcfg_association(def_conf);
3152                         if (! assoc)
3153                                 continue;
3154                         if (! assoc_speaker)
3155                                 assoc_speaker = assoc;
3156                         else if (assoc_speaker != assoc)
3157                                 continue;
3158                         if (cfg->speaker_outs >= ARRAY_SIZE(cfg->speaker_pins))
3159                                 continue;
3160                         cfg->speaker_pins[cfg->speaker_outs] = nid;
3161                         sequences_speaker[cfg->speaker_outs] = seq;
3162                         cfg->speaker_outs++;
3163                         break;
3164                 case AC_JACK_HP_OUT:
3165                         seq = get_defcfg_sequence(def_conf);
3166                         assoc = get_defcfg_association(def_conf);
3167                         if (cfg->hp_outs >= ARRAY_SIZE(cfg->hp_pins))
3168                                 continue;
3169                         cfg->hp_pins[cfg->hp_outs] = nid;
3170                         sequences_hp[cfg->hp_outs] = (assoc << 4) | seq;
3171                         cfg->hp_outs++;
3172                         break;
3173                 case AC_JACK_MIC_IN: {
3174                         int preferred, alt;
3175                         if (loc == AC_JACK_LOC_FRONT) {
3176                                 preferred = AUTO_PIN_FRONT_MIC;
3177                                 alt = AUTO_PIN_MIC;
3178                         } else {
3179                                 preferred = AUTO_PIN_MIC;
3180                                 alt = AUTO_PIN_FRONT_MIC;
3181                         }
3182                         if (!cfg->input_pins[preferred])
3183                                 cfg->input_pins[preferred] = nid;
3184                         else if (!cfg->input_pins[alt])
3185                                 cfg->input_pins[alt] = nid;
3186                         break;
3187                 }
3188                 case AC_JACK_LINE_IN:
3189                         if (loc == AC_JACK_LOC_FRONT)
3190                                 cfg->input_pins[AUTO_PIN_FRONT_LINE] = nid;
3191                         else
3192                                 cfg->input_pins[AUTO_PIN_LINE] = nid;
3193                         break;
3194                 case AC_JACK_CD:
3195                         cfg->input_pins[AUTO_PIN_CD] = nid;
3196                         break;
3197                 case AC_JACK_AUX:
3198                         cfg->input_pins[AUTO_PIN_AUX] = nid;
3199                         break;
3200                 case AC_JACK_SPDIF_OUT:
3201                         cfg->dig_out_pin = nid;
3202                         break;
3203                 case AC_JACK_SPDIF_IN:
3204                         cfg->dig_in_pin = nid;
3205                         break;
3206                 }
3207         }
3208
3209         /* FIX-UP:
3210          * If no line-out is defined but multiple HPs are found,
3211          * some of them might be the real line-outs.
3212          */
3213         if (!cfg->line_outs && cfg->hp_outs > 1) {
3214                 int i = 0;
3215                 while (i < cfg->hp_outs) {
3216                         /* The real HPs should have the sequence 0x0f */
3217                         if ((sequences_hp[i] & 0x0f) == 0x0f) {
3218                                 i++;
3219                                 continue;
3220                         }
3221                         /* Move it to the line-out table */
3222                         cfg->line_out_pins[cfg->line_outs] = cfg->hp_pins[i];
3223                         sequences_line_out[cfg->line_outs] = sequences_hp[i];
3224                         cfg->line_outs++;
3225                         cfg->hp_outs--;
3226                         memmove(cfg->hp_pins + i, cfg->hp_pins + i + 1,
3227                                 sizeof(cfg->hp_pins[0]) * (cfg->hp_outs - i));
3228                         memmove(sequences_hp + i - 1, sequences_hp + i,
3229                                 sizeof(sequences_hp[0]) * (cfg->hp_outs - i));
3230                 }
3231         }
3232
3233         /* sort by sequence */
3234         sort_pins_by_sequence(cfg->line_out_pins, sequences_line_out,
3235                               cfg->line_outs);
3236         sort_pins_by_sequence(cfg->speaker_pins, sequences_speaker,
3237                               cfg->speaker_outs);
3238         sort_pins_by_sequence(cfg->hp_pins, sequences_hp,
3239                               cfg->hp_outs);
3240         
3241         /* if we have only one mic, make it AUTO_PIN_MIC */
3242         if (!cfg->input_pins[AUTO_PIN_MIC] &&
3243             cfg->input_pins[AUTO_PIN_FRONT_MIC]) {
3244                 cfg->input_pins[AUTO_PIN_MIC] =
3245                         cfg->input_pins[AUTO_PIN_FRONT_MIC];
3246                 cfg->input_pins[AUTO_PIN_FRONT_MIC] = 0;
3247         }
3248         /* ditto for line-in */
3249         if (!cfg->input_pins[AUTO_PIN_LINE] &&
3250             cfg->input_pins[AUTO_PIN_FRONT_LINE]) {
3251                 cfg->input_pins[AUTO_PIN_LINE] =
3252                         cfg->input_pins[AUTO_PIN_FRONT_LINE];
3253                 cfg->input_pins[AUTO_PIN_FRONT_LINE] = 0;
3254         }
3255
3256         /*
3257          * FIX-UP: if no line-outs are detected, try to use speaker or HP pin
3258          * as a primary output
3259          */
3260         if (!cfg->line_outs) {
3261                 if (cfg->speaker_outs) {
3262                         cfg->line_outs = cfg->speaker_outs;
3263                         memcpy(cfg->line_out_pins, cfg->speaker_pins,
3264                                sizeof(cfg->speaker_pins));
3265                         cfg->speaker_outs = 0;
3266                         memset(cfg->speaker_pins, 0, sizeof(cfg->speaker_pins));
3267                         cfg->line_out_type = AUTO_PIN_SPEAKER_OUT;
3268                 } else if (cfg->hp_outs) {
3269                         cfg->line_outs = cfg->hp_outs;
3270                         memcpy(cfg->line_out_pins, cfg->hp_pins,
3271                                sizeof(cfg->hp_pins));
3272                         cfg->hp_outs = 0;
3273                         memset(cfg->hp_pins, 0, sizeof(cfg->hp_pins));
3274                         cfg->line_out_type = AUTO_PIN_HP_OUT;
3275                 }
3276         }
3277
3278         /* Reorder the surround channels
3279          * ALSA sequence is front/surr/clfe/side
3280          * HDA sequence is:
3281          *    4-ch: front/surr  =>  OK as it is
3282          *    6-ch: front/clfe/surr
3283          *    8-ch: front/clfe/rear/side|fc
3284          */
3285         switch (cfg->line_outs) {
3286         case 3:
3287         case 4:
3288                 nid = cfg->line_out_pins[1];
3289                 cfg->line_out_pins[1] = cfg->line_out_pins[2];
3290                 cfg->line_out_pins[2] = nid;
3291                 break;
3292         }
3293
3294         /*
3295          * debug prints of the parsed results
3296          */
3297         snd_printd("autoconfig: line_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x)\n",
3298                    cfg->line_outs, cfg->line_out_pins[0], cfg->line_out_pins[1],
3299                    cfg->line_out_pins[2], cfg->line_out_pins[3],
3300                    cfg->line_out_pins[4]);
3301         snd_printd("   speaker_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x)\n",
3302                    cfg->speaker_outs, cfg->speaker_pins[0],
3303                    cfg->speaker_pins[1], cfg->speaker_pins[2],
3304                    cfg->speaker_pins[3], cfg->speaker_pins[4]);
3305         snd_printd("   hp_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x)\n",
3306                    cfg->hp_outs, cfg->hp_pins[0],
3307                    cfg->hp_pins[1], cfg->hp_pins[2],
3308                    cfg->hp_pins[3], cfg->hp_pins[4]);
3309         snd_printd("   mono: mono_out=0x%x\n", cfg->mono_out_pin);
3310         snd_printd("   inputs: mic=0x%x, fmic=0x%x, line=0x%x, fline=0x%x,"
3311                    " cd=0x%x, aux=0x%x\n",
3312                    cfg->input_pins[AUTO_PIN_MIC],
3313                    cfg->input_pins[AUTO_PIN_FRONT_MIC],
3314                    cfg->input_pins[AUTO_PIN_LINE],
3315                    cfg->input_pins[AUTO_PIN_FRONT_LINE],
3316                    cfg->input_pins[AUTO_PIN_CD],
3317                    cfg->input_pins[AUTO_PIN_AUX]);
3318
3319         return 0;
3320 }
3321
3322 /* labels for input pins */
3323 const char *auto_pin_cfg_labels[AUTO_PIN_LAST] = {
3324         "Mic", "Front Mic", "Line", "Front Line", "CD", "Aux"
3325 };
3326
3327
3328 #ifdef CONFIG_PM
3329 /*
3330  * power management
3331  */
3332
3333 /**
3334  * snd_hda_suspend - suspend the codecs
3335  * @bus: the HDA bus
3336  * @state: suspsend state
3337  *
3338  * Returns 0 if successful.
3339  */
3340 int snd_hda_suspend(struct hda_bus *bus, pm_message_t state)
3341 {
3342         struct hda_codec *codec;
3343
3344         list_for_each_entry(codec, &bus->codec_list, list) {
3345 #ifdef CONFIG_SND_HDA_POWER_SAVE
3346                 if (!codec->power_on)
3347                         continue;
3348 #endif
3349                 hda_call_codec_suspend(codec);
3350         }
3351         return 0;
3352 }
3353
3354 /**
3355  * snd_hda_resume - resume the codecs
3356  * @bus: the HDA bus
3357  *
3358  * Returns 0 if successful.
3359  *
3360  * This fucntion is defined only when POWER_SAVE isn't set.
3361  * In the power-save mode, the codec is resumed dynamically.
3362  */
3363 int snd_hda_resume(struct hda_bus *bus)
3364 {
3365         struct hda_codec *codec;
3366
3367         list_for_each_entry(codec, &bus->codec_list, list) {
3368                 if (snd_hda_codec_needs_resume(codec))
3369                         hda_call_codec_resume(codec);
3370         }
3371         return 0;
3372 }
3373 #endif
3374
3375 /*
3376  * generic arrays
3377  */
3378
3379 /* get a new element from the given array
3380  * if it exceeds the pre-allocated array size, re-allocate the array
3381  */
3382 void *snd_array_new(struct snd_array *array)
3383 {
3384         if (array->used >= array->alloced) {
3385                 int num = array->alloced + array->alloc_align;
3386                 void *nlist;
3387                 if (snd_BUG_ON(num >= 4096))
3388                         return NULL;
3389                 nlist = kcalloc(num + 1, array->elem_size, GFP_KERNEL);
3390                 if (!nlist)
3391                         return NULL;
3392                 if (array->list) {
3393                         memcpy(nlist, array->list,
3394                                array->elem_size * array->alloced);
3395                         kfree(array->list);
3396                 }
3397                 array->list = nlist;
3398                 array->alloced = num;
3399         }
3400         return snd_array_elem(array, array->used++);
3401 }
3402
3403 /* free the given array elements */
3404 void snd_array_free(struct snd_array *array)
3405 {
3406         kfree(array->list);
3407         array->used = 0;
3408         array->alloced = 0;
3409         array->list = NULL;
3410 }
3411
3412 /*
3413  * used by hda_proc.c and hda_eld.c
3414  */
3415 void snd_print_pcm_rates(int pcm, char *buf, int buflen)
3416 {
3417         static unsigned int rates[] = {
3418                 8000, 11025, 16000, 22050, 32000, 44100, 48000, 88200,
3419                 96000, 176400, 192000, 384000
3420         };
3421         int i, j;
3422
3423         for (i = 0, j = 0; i < ARRAY_SIZE(rates); i++)
3424                 if (pcm & (1 << i))
3425                         j += snprintf(buf + j, buflen - j,  " %d", rates[i]);
3426
3427         buf[j] = '\0'; /* necessary when j == 0 */
3428 }
3429
3430 void snd_print_pcm_bits(int pcm, char *buf, int buflen)
3431 {
3432         static unsigned int bits[] = { 8, 16, 20, 24, 32 };
3433         int i, j;
3434
3435         for (i = 0, j = 0; i < ARRAY_SIZE(bits); i++)
3436                 if (pcm & (AC_SUPPCM_BITS_8 << i))
3437                         j += snprintf(buf + j, buflen - j,  " %d", bits[i]);
3438
3439         buf[j] = '\0'; /* necessary when j == 0 */
3440 }