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