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