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