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