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