ALSA: hda - Add snd_hda_get_conn_list() helper function
[linux-2.6.git] / sound / pci / hda / hda_codec.c
1 /*
2  * Universal Interface for Intel High Definition Audio Codec
3  *
4  * Copyright (c) 2004 Takashi Iwai <tiwai@suse.de>
5  *
6  *
7  *  This driver is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This driver is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20  */
21
22 #include <linux/init.h>
23 #include <linux/delay.h>
24 #include <linux/slab.h>
25 #include <linux/pci.h>
26 #include <linux/mutex.h>
27 #include <sound/core.h>
28 #include "hda_codec.h"
29 #include <sound/asoundef.h>
30 #include <sound/tlv.h>
31 #include <sound/initval.h>
32 #include <sound/jack.h>
33 #include "hda_local.h"
34 #include "hda_beep.h"
35 #include <sound/hda_hwdep.h>
36
37 /*
38  * vendor / preset table
39  */
40
41 struct hda_vendor_id {
42         unsigned int id;
43         const char *name;
44 };
45
46 /* codec vendor labels */
47 static struct hda_vendor_id hda_vendor_ids[] = {
48         { 0x1002, "ATI" },
49         { 0x1013, "Cirrus Logic" },
50         { 0x1057, "Motorola" },
51         { 0x1095, "Silicon Image" },
52         { 0x10de, "Nvidia" },
53         { 0x10ec, "Realtek" },
54         { 0x1102, "Creative" },
55         { 0x1106, "VIA" },
56         { 0x111d, "IDT" },
57         { 0x11c1, "LSI" },
58         { 0x11d4, "Analog Devices" },
59         { 0x13f6, "C-Media" },
60         { 0x14f1, "Conexant" },
61         { 0x17e8, "Chrontel" },
62         { 0x1854, "LG" },
63         { 0x1aec, "Wolfson Microelectronics" },
64         { 0x434d, "C-Media" },
65         { 0x8086, "Intel" },
66         { 0x8384, "SigmaTel" },
67         {} /* terminator */
68 };
69
70 static DEFINE_MUTEX(preset_mutex);
71 static LIST_HEAD(hda_preset_tables);
72
73 int snd_hda_add_codec_preset(struct hda_codec_preset_list *preset)
74 {
75         mutex_lock(&preset_mutex);
76         list_add_tail(&preset->list, &hda_preset_tables);
77         mutex_unlock(&preset_mutex);
78         return 0;
79 }
80 EXPORT_SYMBOL_HDA(snd_hda_add_codec_preset);
81
82 int snd_hda_delete_codec_preset(struct hda_codec_preset_list *preset)
83 {
84         mutex_lock(&preset_mutex);
85         list_del(&preset->list);
86         mutex_unlock(&preset_mutex);
87         return 0;
88 }
89 EXPORT_SYMBOL_HDA(snd_hda_delete_codec_preset);
90
91 #ifdef CONFIG_SND_HDA_POWER_SAVE
92 static void hda_power_work(struct work_struct *work);
93 static void hda_keep_power_on(struct hda_codec *codec);
94 #else
95 static inline void hda_keep_power_on(struct hda_codec *codec) {}
96 #endif
97
98 /**
99  * snd_hda_get_jack_location - Give a location string of the jack
100  * @cfg: pin default config value
101  *
102  * Parse the pin default config value and returns the string of the
103  * jack location, e.g. "Rear", "Front", etc.
104  */
105 const char *snd_hda_get_jack_location(u32 cfg)
106 {
107         static char *bases[7] = {
108                 "N/A", "Rear", "Front", "Left", "Right", "Top", "Bottom",
109         };
110         static unsigned char specials_idx[] = {
111                 0x07, 0x08,
112                 0x17, 0x18, 0x19,
113                 0x37, 0x38
114         };
115         static char *specials[] = {
116                 "Rear Panel", "Drive Bar",
117                 "Riser", "HDMI", "ATAPI",
118                 "Mobile-In", "Mobile-Out"
119         };
120         int i;
121         cfg = (cfg & AC_DEFCFG_LOCATION) >> AC_DEFCFG_LOCATION_SHIFT;
122         if ((cfg & 0x0f) < 7)
123                 return bases[cfg & 0x0f];
124         for (i = 0; i < ARRAY_SIZE(specials_idx); i++) {
125                 if (cfg == specials_idx[i])
126                         return specials[i];
127         }
128         return "UNKNOWN";
129 }
130 EXPORT_SYMBOL_HDA(snd_hda_get_jack_location);
131
132 /**
133  * snd_hda_get_jack_connectivity - Give a connectivity string of the jack
134  * @cfg: pin default config value
135  *
136  * Parse the pin default config value and returns the string of the
137  * jack connectivity, i.e. external or internal connection.
138  */
139 const char *snd_hda_get_jack_connectivity(u32 cfg)
140 {
141         static char *jack_locations[4] = { "Ext", "Int", "Sep", "Oth" };
142
143         return jack_locations[(cfg >> (AC_DEFCFG_LOCATION_SHIFT + 4)) & 3];
144 }
145 EXPORT_SYMBOL_HDA(snd_hda_get_jack_connectivity);
146
147 /**
148  * snd_hda_get_jack_type - Give a type string of the jack
149  * @cfg: pin default config value
150  *
151  * Parse the pin default config value and returns the string of the
152  * jack type, i.e. the purpose of the jack, such as Line-Out or CD.
153  */
154 const char *snd_hda_get_jack_type(u32 cfg)
155 {
156         static char *jack_types[16] = {
157                 "Line Out", "Speaker", "HP Out", "CD",
158                 "SPDIF Out", "Digital Out", "Modem Line", "Modem Hand",
159                 "Line In", "Aux", "Mic", "Telephony",
160                 "SPDIF In", "Digitial In", "Reserved", "Other"
161         };
162
163         return jack_types[(cfg & AC_DEFCFG_DEVICE)
164                                 >> AC_DEFCFG_DEVICE_SHIFT];
165 }
166 EXPORT_SYMBOL_HDA(snd_hda_get_jack_type);
167
168 /*
169  * Compose a 32bit command word to be sent to the HD-audio controller
170  */
171 static inline unsigned int
172 make_codec_cmd(struct hda_codec *codec, hda_nid_t nid, int direct,
173                unsigned int verb, unsigned int parm)
174 {
175         u32 val;
176
177         if ((codec->addr & ~0xf) || (direct & ~1) || (nid & ~0x7f) ||
178             (verb & ~0xfff) || (parm & ~0xffff)) {
179                 printk(KERN_ERR "hda-codec: out of range cmd %x:%x:%x:%x:%x\n",
180                        codec->addr, direct, nid, verb, parm);
181                 return ~0;
182         }
183
184         val = (u32)codec->addr << 28;
185         val |= (u32)direct << 27;
186         val |= (u32)nid << 20;
187         val |= verb << 8;
188         val |= parm;
189         return val;
190 }
191
192 /*
193  * Send and receive a verb
194  */
195 static int codec_exec_verb(struct hda_codec *codec, unsigned int cmd,
196                            unsigned int *res)
197 {
198         struct hda_bus *bus = codec->bus;
199         int err;
200
201         if (cmd == ~0)
202                 return -1;
203
204         if (res)
205                 *res = -1;
206  again:
207         snd_hda_power_up(codec);
208         mutex_lock(&bus->cmd_mutex);
209         err = bus->ops.command(bus, cmd);
210         if (!err && res)
211                 *res = bus->ops.get_response(bus, codec->addr);
212         mutex_unlock(&bus->cmd_mutex);
213         snd_hda_power_down(codec);
214         if (res && *res == -1 && bus->rirb_error) {
215                 if (bus->response_reset) {
216                         snd_printd("hda_codec: resetting BUS due to "
217                                    "fatal communication error\n");
218                         bus->ops.bus_reset(bus);
219                 }
220                 goto again;
221         }
222         /* clear reset-flag when the communication gets recovered */
223         if (!err)
224                 bus->response_reset = 0;
225         return err;
226 }
227
228 /**
229  * snd_hda_codec_read - send a command and get the response
230  * @codec: the HDA codec
231  * @nid: NID to send the command
232  * @direct: direct flag
233  * @verb: the verb to send
234  * @parm: the parameter for the verb
235  *
236  * Send a single command and read the corresponding response.
237  *
238  * Returns the obtained response value, or -1 for an error.
239  */
240 unsigned int snd_hda_codec_read(struct hda_codec *codec, hda_nid_t nid,
241                                 int direct,
242                                 unsigned int verb, unsigned int parm)
243 {
244         unsigned cmd = make_codec_cmd(codec, nid, direct, verb, parm);
245         unsigned int res;
246         if (codec_exec_verb(codec, cmd, &res))
247                 return -1;
248         return res;
249 }
250 EXPORT_SYMBOL_HDA(snd_hda_codec_read);
251
252 /**
253  * snd_hda_codec_write - send a single command without waiting for response
254  * @codec: the HDA codec
255  * @nid: NID to send the command
256  * @direct: direct flag
257  * @verb: the verb to send
258  * @parm: the parameter for the verb
259  *
260  * Send a single command without waiting for response.
261  *
262  * Returns 0 if successful, or a negative error code.
263  */
264 int snd_hda_codec_write(struct hda_codec *codec, hda_nid_t nid, int direct,
265                          unsigned int verb, unsigned int parm)
266 {
267         unsigned int cmd = make_codec_cmd(codec, nid, direct, verb, parm);
268         unsigned int res;
269         return codec_exec_verb(codec, cmd,
270                                codec->bus->sync_write ? &res : NULL);
271 }
272 EXPORT_SYMBOL_HDA(snd_hda_codec_write);
273
274 /**
275  * snd_hda_sequence_write - sequence writes
276  * @codec: the HDA codec
277  * @seq: VERB array to send
278  *
279  * Send the commands sequentially from the given array.
280  * The array must be terminated with NID=0.
281  */
282 void snd_hda_sequence_write(struct hda_codec *codec, const struct hda_verb *seq)
283 {
284         for (; seq->nid; seq++)
285                 snd_hda_codec_write(codec, seq->nid, 0, seq->verb, seq->param);
286 }
287 EXPORT_SYMBOL_HDA(snd_hda_sequence_write);
288
289 /**
290  * snd_hda_get_sub_nodes - get the range of sub nodes
291  * @codec: the HDA codec
292  * @nid: NID to parse
293  * @start_id: the pointer to store the start NID
294  *
295  * Parse the NID and store the start NID of its sub-nodes.
296  * Returns the number of sub-nodes.
297  */
298 int snd_hda_get_sub_nodes(struct hda_codec *codec, hda_nid_t nid,
299                           hda_nid_t *start_id)
300 {
301         unsigned int parm;
302
303         parm = snd_hda_param_read(codec, nid, AC_PAR_NODE_COUNT);
304         if (parm == -1)
305                 return 0;
306         *start_id = (parm >> 16) & 0x7fff;
307         return (int)(parm & 0x7fff);
308 }
309 EXPORT_SYMBOL_HDA(snd_hda_get_sub_nodes);
310
311 static int _hda_get_connections(struct hda_codec *codec, hda_nid_t nid,
312                                 hda_nid_t *conn_list, int max_conns);
313 static bool add_conn_list(struct snd_array *array, hda_nid_t nid);
314
315 /**
316  * snd_hda_get_connections - get connection list
317  * @codec: the HDA codec
318  * @nid: NID to parse
319  * @listp: the pointer to store NID list
320  *
321  * Parses the connection list of the given widget and stores the list
322  * of NIDs.
323  *
324  * Returns the number of connections, or a negative error code.
325  */
326 int snd_hda_get_conn_list(struct hda_codec *codec, hda_nid_t nid,
327                           const hda_nid_t **listp)
328 {
329         struct snd_array *array = &codec->conn_lists;
330         int i, len, old_used;
331         hda_nid_t list[HDA_MAX_CONNECTIONS];
332         hda_nid_t *p;
333
334         /* look up the cached results */
335         for (i = 0; i < array->used; ) {
336                 p = snd_array_elem(array, i);
337                 len = p[1];
338                 if (nid == *p) {
339                         if (listp)
340                                 *listp = p + 2;
341                         return len;
342                 }
343                 i += len + 2;
344         }
345
346         len = _hda_get_connections(codec, nid, list, HDA_MAX_CONNECTIONS);
347         if (len < 0)
348                 return len;
349
350         /* add to the cache */
351         old_used = array->used;
352         if (!add_conn_list(array, nid) || !add_conn_list(array, len))
353                 goto error_add;
354         for (i = 0; i < len; i++)
355                 if (!add_conn_list(array, list[i]))
356                         goto error_add;
357
358         p = snd_array_elem(array, old_used);
359         if (listp)
360                 *listp = p + 2;
361         return len;
362                 
363  error_add:
364         array->used = old_used;
365         return -ENOMEM;
366 }
367 EXPORT_SYMBOL_HDA(snd_hda_get_conn_list);
368
369 /**
370  * snd_hda_get_connections - copy connection list
371  * @codec: the HDA codec
372  * @nid: NID to parse
373  * @conn_list: connection list array
374  * @max_conns: max. number of connections to store
375  *
376  * Parses the connection list of the given widget and stores the list
377  * of NIDs.
378  *
379  * Returns the number of connections, or a negative error code.
380  */
381 int snd_hda_get_connections(struct hda_codec *codec, hda_nid_t nid,
382                              hda_nid_t *conn_list, int max_conns)
383 {
384         const hda_nid_t *list;
385         int len = snd_hda_get_conn_list(codec, nid, &list);
386
387         if (len <= 0)
388                 return len;
389         if (len > max_conns) {
390                 snd_printk(KERN_ERR "hda_codec: "
391                            "Too many connections %d for NID 0x%x\n",
392                            len, nid);
393                 return -EINVAL;
394         }
395         memcpy(conn_list, list, len * sizeof(hda_nid_t));
396         return len;
397 }
398 EXPORT_SYMBOL_HDA(snd_hda_get_connections);
399
400 static int _hda_get_connections(struct hda_codec *codec, hda_nid_t nid,
401                              hda_nid_t *conn_list, int max_conns)
402 {
403         unsigned int parm;
404         int i, conn_len, conns;
405         unsigned int shift, num_elems, mask;
406         unsigned int wcaps;
407         hda_nid_t prev_nid;
408
409         if (snd_BUG_ON(!conn_list || max_conns <= 0))
410                 return -EINVAL;
411
412         wcaps = get_wcaps(codec, nid);
413         if (!(wcaps & AC_WCAP_CONN_LIST) &&
414             get_wcaps_type(wcaps) != AC_WID_VOL_KNB) {
415                 snd_printk(KERN_WARNING "hda_codec: "
416                            "connection list not available for 0x%x\n", nid);
417                 return -EINVAL;
418         }
419
420         parm = snd_hda_param_read(codec, nid, AC_PAR_CONNLIST_LEN);
421         if (parm & AC_CLIST_LONG) {
422                 /* long form */
423                 shift = 16;
424                 num_elems = 2;
425         } else {
426                 /* short form */
427                 shift = 8;
428                 num_elems = 4;
429         }
430         conn_len = parm & AC_CLIST_LENGTH;
431         mask = (1 << (shift-1)) - 1;
432
433         if (!conn_len)
434                 return 0; /* no connection */
435
436         if (conn_len == 1) {
437                 /* single connection */
438                 parm = snd_hda_codec_read(codec, nid, 0,
439                                           AC_VERB_GET_CONNECT_LIST, 0);
440                 if (parm == -1 && codec->bus->rirb_error)
441                         return -EIO;
442                 conn_list[0] = parm & mask;
443                 return 1;
444         }
445
446         /* multi connection */
447         conns = 0;
448         prev_nid = 0;
449         for (i = 0; i < conn_len; i++) {
450                 int range_val;
451                 hda_nid_t val, n;
452
453                 if (i % num_elems == 0) {
454                         parm = snd_hda_codec_read(codec, nid, 0,
455                                                   AC_VERB_GET_CONNECT_LIST, i);
456                         if (parm == -1 && codec->bus->rirb_error)
457                                 return -EIO;
458                 }
459                 range_val = !!(parm & (1 << (shift-1))); /* ranges */
460                 val = parm & mask;
461                 if (val == 0) {
462                         snd_printk(KERN_WARNING "hda_codec: "
463                                    "invalid CONNECT_LIST verb %x[%i]:%x\n",
464                                     nid, i, parm);
465                         return 0;
466                 }
467                 parm >>= shift;
468                 if (range_val) {
469                         /* ranges between the previous and this one */
470                         if (!prev_nid || prev_nid >= val) {
471                                 snd_printk(KERN_WARNING "hda_codec: "
472                                            "invalid dep_range_val %x:%x\n",
473                                            prev_nid, val);
474                                 continue;
475                         }
476                         for (n = prev_nid + 1; n <= val; n++) {
477                                 if (conns >= max_conns) {
478                                         snd_printk(KERN_ERR "hda_codec: "
479                                                    "Too many connections %d for NID 0x%x\n",
480                                                    conns, nid);
481                                         return -EINVAL;
482                                 }
483                                 conn_list[conns++] = n;
484                         }
485                 } else {
486                         if (conns >= max_conns) {
487                                 snd_printk(KERN_ERR "hda_codec: "
488                                            "Too many connections %d for NID 0x%x\n",
489                                            conns, nid);
490                                 return -EINVAL;
491                         }
492                         conn_list[conns++] = val;
493                 }
494                 prev_nid = val;
495         }
496         return conns;
497 }
498
499 static bool add_conn_list(struct snd_array *array, hda_nid_t nid)
500 {
501         hda_nid_t *p = snd_array_new(array);
502         if (!p)
503                 return false;
504         *p = nid;
505         return true;
506 }
507
508 /**
509  * snd_hda_queue_unsol_event - add an unsolicited event to queue
510  * @bus: the BUS
511  * @res: unsolicited event (lower 32bit of RIRB entry)
512  * @res_ex: codec addr and flags (upper 32bit or RIRB entry)
513  *
514  * Adds the given event to the queue.  The events are processed in
515  * the workqueue asynchronously.  Call this function in the interrupt
516  * hanlder when RIRB receives an unsolicited event.
517  *
518  * Returns 0 if successful, or a negative error code.
519  */
520 int snd_hda_queue_unsol_event(struct hda_bus *bus, u32 res, u32 res_ex)
521 {
522         struct hda_bus_unsolicited *unsol;
523         unsigned int wp;
524
525         unsol = bus->unsol;
526         if (!unsol)
527                 return 0;
528
529         wp = (unsol->wp + 1) % HDA_UNSOL_QUEUE_SIZE;
530         unsol->wp = wp;
531
532         wp <<= 1;
533         unsol->queue[wp] = res;
534         unsol->queue[wp + 1] = res_ex;
535
536         queue_work(bus->workq, &unsol->work);
537
538         return 0;
539 }
540 EXPORT_SYMBOL_HDA(snd_hda_queue_unsol_event);
541
542 /*
543  * process queued unsolicited events
544  */
545 static void process_unsol_events(struct work_struct *work)
546 {
547         struct hda_bus_unsolicited *unsol =
548                 container_of(work, struct hda_bus_unsolicited, work);
549         struct hda_bus *bus = unsol->bus;
550         struct hda_codec *codec;
551         unsigned int rp, caddr, res;
552
553         while (unsol->rp != unsol->wp) {
554                 rp = (unsol->rp + 1) % HDA_UNSOL_QUEUE_SIZE;
555                 unsol->rp = rp;
556                 rp <<= 1;
557                 res = unsol->queue[rp];
558                 caddr = unsol->queue[rp + 1];
559                 if (!(caddr & (1 << 4))) /* no unsolicited event? */
560                         continue;
561                 codec = bus->caddr_tbl[caddr & 0x0f];
562                 if (codec && codec->patch_ops.unsol_event)
563                         codec->patch_ops.unsol_event(codec, res);
564         }
565 }
566
567 /*
568  * initialize unsolicited queue
569  */
570 static int init_unsol_queue(struct hda_bus *bus)
571 {
572         struct hda_bus_unsolicited *unsol;
573
574         if (bus->unsol) /* already initialized */
575                 return 0;
576
577         unsol = kzalloc(sizeof(*unsol), GFP_KERNEL);
578         if (!unsol) {
579                 snd_printk(KERN_ERR "hda_codec: "
580                            "can't allocate unsolicited queue\n");
581                 return -ENOMEM;
582         }
583         INIT_WORK(&unsol->work, process_unsol_events);
584         unsol->bus = bus;
585         bus->unsol = unsol;
586         return 0;
587 }
588
589 /*
590  * destructor
591  */
592 static void snd_hda_codec_free(struct hda_codec *codec);
593
594 static int snd_hda_bus_free(struct hda_bus *bus)
595 {
596         struct hda_codec *codec, *n;
597
598         if (!bus)
599                 return 0;
600         if (bus->workq)
601                 flush_workqueue(bus->workq);
602         if (bus->unsol)
603                 kfree(bus->unsol);
604         list_for_each_entry_safe(codec, n, &bus->codec_list, list) {
605                 snd_hda_codec_free(codec);
606         }
607         if (bus->ops.private_free)
608                 bus->ops.private_free(bus);
609         if (bus->workq)
610                 destroy_workqueue(bus->workq);
611         kfree(bus);
612         return 0;
613 }
614
615 static int snd_hda_bus_dev_free(struct snd_device *device)
616 {
617         struct hda_bus *bus = device->device_data;
618         bus->shutdown = 1;
619         return snd_hda_bus_free(bus);
620 }
621
622 #ifdef CONFIG_SND_HDA_HWDEP
623 static int snd_hda_bus_dev_register(struct snd_device *device)
624 {
625         struct hda_bus *bus = device->device_data;
626         struct hda_codec *codec;
627         list_for_each_entry(codec, &bus->codec_list, list) {
628                 snd_hda_hwdep_add_sysfs(codec);
629                 snd_hda_hwdep_add_power_sysfs(codec);
630         }
631         return 0;
632 }
633 #else
634 #define snd_hda_bus_dev_register        NULL
635 #endif
636
637 /**
638  * snd_hda_bus_new - create a HDA bus
639  * @card: the card entry
640  * @temp: the template for hda_bus information
641  * @busp: the pointer to store the created bus instance
642  *
643  * Returns 0 if successful, or a negative error code.
644  */
645 int /*__devinit*/ snd_hda_bus_new(struct snd_card *card,
646                               const struct hda_bus_template *temp,
647                               struct hda_bus **busp)
648 {
649         struct hda_bus *bus;
650         int err;
651         static struct snd_device_ops dev_ops = {
652                 .dev_register = snd_hda_bus_dev_register,
653                 .dev_free = snd_hda_bus_dev_free,
654         };
655
656         if (snd_BUG_ON(!temp))
657                 return -EINVAL;
658         if (snd_BUG_ON(!temp->ops.command || !temp->ops.get_response))
659                 return -EINVAL;
660
661         if (busp)
662                 *busp = NULL;
663
664         bus = kzalloc(sizeof(*bus), GFP_KERNEL);
665         if (bus == NULL) {
666                 snd_printk(KERN_ERR "can't allocate struct hda_bus\n");
667                 return -ENOMEM;
668         }
669
670         bus->card = card;
671         bus->private_data = temp->private_data;
672         bus->pci = temp->pci;
673         bus->modelname = temp->modelname;
674         bus->power_save = temp->power_save;
675         bus->ops = temp->ops;
676
677         mutex_init(&bus->cmd_mutex);
678         mutex_init(&bus->prepare_mutex);
679         INIT_LIST_HEAD(&bus->codec_list);
680
681         snprintf(bus->workq_name, sizeof(bus->workq_name),
682                  "hd-audio%d", card->number);
683         bus->workq = create_singlethread_workqueue(bus->workq_name);
684         if (!bus->workq) {
685                 snd_printk(KERN_ERR "cannot create workqueue %s\n",
686                            bus->workq_name);
687                 kfree(bus);
688                 return -ENOMEM;
689         }
690
691         err = snd_device_new(card, SNDRV_DEV_BUS, bus, &dev_ops);
692         if (err < 0) {
693                 snd_hda_bus_free(bus);
694                 return err;
695         }
696         if (busp)
697                 *busp = bus;
698         return 0;
699 }
700 EXPORT_SYMBOL_HDA(snd_hda_bus_new);
701
702 #ifdef CONFIG_SND_HDA_GENERIC
703 #define is_generic_config(codec) \
704         (codec->modelname && !strcmp(codec->modelname, "generic"))
705 #else
706 #define is_generic_config(codec)        0
707 #endif
708
709 #ifdef MODULE
710 #define HDA_MODREQ_MAX_COUNT    2       /* two request_modules()'s */
711 #else
712 #define HDA_MODREQ_MAX_COUNT    0       /* all presets are statically linked */
713 #endif
714
715 /*
716  * find a matching codec preset
717  */
718 static const struct hda_codec_preset *
719 find_codec_preset(struct hda_codec *codec)
720 {
721         struct hda_codec_preset_list *tbl;
722         const struct hda_codec_preset *preset;
723         int mod_requested = 0;
724
725         if (is_generic_config(codec))
726                 return NULL; /* use the generic parser */
727
728  again:
729         mutex_lock(&preset_mutex);
730         list_for_each_entry(tbl, &hda_preset_tables, list) {
731                 if (!try_module_get(tbl->owner)) {
732                         snd_printk(KERN_ERR "hda_codec: cannot module_get\n");
733                         continue;
734                 }
735                 for (preset = tbl->preset; preset->id; preset++) {
736                         u32 mask = preset->mask;
737                         if (preset->afg && preset->afg != codec->afg)
738                                 continue;
739                         if (preset->mfg && preset->mfg != codec->mfg)
740                                 continue;
741                         if (!mask)
742                                 mask = ~0;
743                         if (preset->id == (codec->vendor_id & mask) &&
744                             (!preset->rev ||
745                              preset->rev == codec->revision_id)) {
746                                 mutex_unlock(&preset_mutex);
747                                 codec->owner = tbl->owner;
748                                 return preset;
749                         }
750                 }
751                 module_put(tbl->owner);
752         }
753         mutex_unlock(&preset_mutex);
754
755         if (mod_requested < HDA_MODREQ_MAX_COUNT) {
756                 char name[32];
757                 if (!mod_requested)
758                         snprintf(name, sizeof(name), "snd-hda-codec-id:%08x",
759                                  codec->vendor_id);
760                 else
761                         snprintf(name, sizeof(name), "snd-hda-codec-id:%04x*",
762                                  (codec->vendor_id >> 16) & 0xffff);
763                 request_module(name);
764                 mod_requested++;
765                 goto again;
766         }
767         return NULL;
768 }
769
770 /*
771  * get_codec_name - store the codec name
772  */
773 static int get_codec_name(struct hda_codec *codec)
774 {
775         const struct hda_vendor_id *c;
776         const char *vendor = NULL;
777         u16 vendor_id = codec->vendor_id >> 16;
778         char tmp[16];
779
780         if (codec->vendor_name)
781                 goto get_chip_name;
782
783         for (c = hda_vendor_ids; c->id; c++) {
784                 if (c->id == vendor_id) {
785                         vendor = c->name;
786                         break;
787                 }
788         }
789         if (!vendor) {
790                 sprintf(tmp, "Generic %04x", vendor_id);
791                 vendor = tmp;
792         }
793         codec->vendor_name = kstrdup(vendor, GFP_KERNEL);
794         if (!codec->vendor_name)
795                 return -ENOMEM;
796
797  get_chip_name:
798         if (codec->chip_name)
799                 return 0;
800
801         if (codec->preset && codec->preset->name)
802                 codec->chip_name = kstrdup(codec->preset->name, GFP_KERNEL);
803         else {
804                 sprintf(tmp, "ID %x", codec->vendor_id & 0xffff);
805                 codec->chip_name = kstrdup(tmp, GFP_KERNEL);
806         }
807         if (!codec->chip_name)
808                 return -ENOMEM;
809         return 0;
810 }
811
812 /*
813  * look for an AFG and MFG nodes
814  */
815 static void /*__devinit*/ setup_fg_nodes(struct hda_codec *codec)
816 {
817         int i, total_nodes, function_id;
818         hda_nid_t nid;
819
820         total_nodes = snd_hda_get_sub_nodes(codec, AC_NODE_ROOT, &nid);
821         for (i = 0; i < total_nodes; i++, nid++) {
822                 function_id = snd_hda_param_read(codec, nid,
823                                                 AC_PAR_FUNCTION_TYPE);
824                 switch (function_id & 0xff) {
825                 case AC_GRP_AUDIO_FUNCTION:
826                         codec->afg = nid;
827                         codec->afg_function_id = function_id & 0xff;
828                         codec->afg_unsol = (function_id >> 8) & 1;
829                         break;
830                 case AC_GRP_MODEM_FUNCTION:
831                         codec->mfg = nid;
832                         codec->mfg_function_id = function_id & 0xff;
833                         codec->mfg_unsol = (function_id >> 8) & 1;
834                         break;
835                 default:
836                         break;
837                 }
838         }
839 }
840
841 /*
842  * read widget caps for each widget and store in cache
843  */
844 static int read_widget_caps(struct hda_codec *codec, hda_nid_t fg_node)
845 {
846         int i;
847         hda_nid_t nid;
848
849         codec->num_nodes = snd_hda_get_sub_nodes(codec, fg_node,
850                                                  &codec->start_nid);
851         codec->wcaps = kmalloc(codec->num_nodes * 4, GFP_KERNEL);
852         if (!codec->wcaps)
853                 return -ENOMEM;
854         nid = codec->start_nid;
855         for (i = 0; i < codec->num_nodes; i++, nid++)
856                 codec->wcaps[i] = snd_hda_param_read(codec, nid,
857                                                      AC_PAR_AUDIO_WIDGET_CAP);
858         return 0;
859 }
860
861 /* read all pin default configurations and save codec->init_pins */
862 static int read_pin_defaults(struct hda_codec *codec)
863 {
864         int i;
865         hda_nid_t nid = codec->start_nid;
866
867         for (i = 0; i < codec->num_nodes; i++, nid++) {
868                 struct hda_pincfg *pin;
869                 unsigned int wcaps = get_wcaps(codec, nid);
870                 unsigned int wid_type = get_wcaps_type(wcaps);
871                 if (wid_type != AC_WID_PIN)
872                         continue;
873                 pin = snd_array_new(&codec->init_pins);
874                 if (!pin)
875                         return -ENOMEM;
876                 pin->nid = nid;
877                 pin->cfg = snd_hda_codec_read(codec, nid, 0,
878                                               AC_VERB_GET_CONFIG_DEFAULT, 0);
879                 pin->ctrl = snd_hda_codec_read(codec, nid, 0,
880                                                AC_VERB_GET_PIN_WIDGET_CONTROL,
881                                                0);
882         }
883         return 0;
884 }
885
886 /* look up the given pin config list and return the item matching with NID */
887 static struct hda_pincfg *look_up_pincfg(struct hda_codec *codec,
888                                          struct snd_array *array,
889                                          hda_nid_t nid)
890 {
891         int i;
892         for (i = 0; i < array->used; i++) {
893                 struct hda_pincfg *pin = snd_array_elem(array, i);
894                 if (pin->nid == nid)
895                         return pin;
896         }
897         return NULL;
898 }
899
900 /* write a config value for the given NID */
901 static void set_pincfg(struct hda_codec *codec, hda_nid_t nid,
902                        unsigned int cfg)
903 {
904         int i;
905         for (i = 0; i < 4; i++) {
906                 snd_hda_codec_write(codec, nid, 0,
907                                     AC_VERB_SET_CONFIG_DEFAULT_BYTES_0 + i,
908                                     cfg & 0xff);
909                 cfg >>= 8;
910         }
911 }
912
913 /* set the current pin config value for the given NID.
914  * the value is cached, and read via snd_hda_codec_get_pincfg()
915  */
916 int snd_hda_add_pincfg(struct hda_codec *codec, struct snd_array *list,
917                        hda_nid_t nid, unsigned int cfg)
918 {
919         struct hda_pincfg *pin;
920         unsigned int oldcfg;
921
922         if (get_wcaps_type(get_wcaps(codec, nid)) != AC_WID_PIN)
923                 return -EINVAL;
924
925         oldcfg = snd_hda_codec_get_pincfg(codec, nid);
926         pin = look_up_pincfg(codec, list, nid);
927         if (!pin) {
928                 pin = snd_array_new(list);
929                 if (!pin)
930                         return -ENOMEM;
931                 pin->nid = nid;
932         }
933         pin->cfg = cfg;
934
935         /* change only when needed; e.g. if the pincfg is already present
936          * in user_pins[], don't write it
937          */
938         cfg = snd_hda_codec_get_pincfg(codec, nid);
939         if (oldcfg != cfg)
940                 set_pincfg(codec, nid, cfg);
941         return 0;
942 }
943
944 /**
945  * snd_hda_codec_set_pincfg - Override a pin default configuration
946  * @codec: the HDA codec
947  * @nid: NID to set the pin config
948  * @cfg: the pin default config value
949  *
950  * Override a pin default configuration value in the cache.
951  * This value can be read by snd_hda_codec_get_pincfg() in a higher
952  * priority than the real hardware value.
953  */
954 int snd_hda_codec_set_pincfg(struct hda_codec *codec,
955                              hda_nid_t nid, unsigned int cfg)
956 {
957         return snd_hda_add_pincfg(codec, &codec->driver_pins, nid, cfg);
958 }
959 EXPORT_SYMBOL_HDA(snd_hda_codec_set_pincfg);
960
961 /**
962  * snd_hda_codec_get_pincfg - Obtain a pin-default configuration
963  * @codec: the HDA codec
964  * @nid: NID to get the pin config
965  *
966  * Get the current pin config value of the given pin NID.
967  * If the pincfg value is cached or overridden via sysfs or driver,
968  * returns the cached value.
969  */
970 unsigned int snd_hda_codec_get_pincfg(struct hda_codec *codec, hda_nid_t nid)
971 {
972         struct hda_pincfg *pin;
973
974 #ifdef CONFIG_SND_HDA_HWDEP
975         pin = look_up_pincfg(codec, &codec->user_pins, nid);
976         if (pin)
977                 return pin->cfg;
978 #endif
979         pin = look_up_pincfg(codec, &codec->driver_pins, nid);
980         if (pin)
981                 return pin->cfg;
982         pin = look_up_pincfg(codec, &codec->init_pins, nid);
983         if (pin)
984                 return pin->cfg;
985         return 0;
986 }
987 EXPORT_SYMBOL_HDA(snd_hda_codec_get_pincfg);
988
989 /* restore all current pin configs */
990 static void restore_pincfgs(struct hda_codec *codec)
991 {
992         int i;
993         for (i = 0; i < codec->init_pins.used; i++) {
994                 struct hda_pincfg *pin = snd_array_elem(&codec->init_pins, i);
995                 set_pincfg(codec, pin->nid,
996                            snd_hda_codec_get_pincfg(codec, pin->nid));
997         }
998 }
999
1000 /**
1001  * snd_hda_shutup_pins - Shut up all pins
1002  * @codec: the HDA codec
1003  *
1004  * Clear all pin controls to shup up before suspend for avoiding click noise.
1005  * The controls aren't cached so that they can be resumed properly.
1006  */
1007 void snd_hda_shutup_pins(struct hda_codec *codec)
1008 {
1009         int i;
1010         /* don't shut up pins when unloading the driver; otherwise it breaks
1011          * the default pin setup at the next load of the driver
1012          */
1013         if (codec->bus->shutdown)
1014                 return;
1015         for (i = 0; i < codec->init_pins.used; i++) {
1016                 struct hda_pincfg *pin = snd_array_elem(&codec->init_pins, i);
1017                 /* use read here for syncing after issuing each verb */
1018                 snd_hda_codec_read(codec, pin->nid, 0,
1019                                    AC_VERB_SET_PIN_WIDGET_CONTROL, 0);
1020         }
1021         codec->pins_shutup = 1;
1022 }
1023 EXPORT_SYMBOL_HDA(snd_hda_shutup_pins);
1024
1025 #ifdef SND_HDA_NEEDS_RESUME
1026 /* Restore the pin controls cleared previously via snd_hda_shutup_pins() */
1027 static void restore_shutup_pins(struct hda_codec *codec)
1028 {
1029         int i;
1030         if (!codec->pins_shutup)
1031                 return;
1032         if (codec->bus->shutdown)
1033                 return;
1034         for (i = 0; i < codec->init_pins.used; i++) {
1035                 struct hda_pincfg *pin = snd_array_elem(&codec->init_pins, i);
1036                 snd_hda_codec_write(codec, pin->nid, 0,
1037                                     AC_VERB_SET_PIN_WIDGET_CONTROL,
1038                                     pin->ctrl);
1039         }
1040         codec->pins_shutup = 0;
1041 }
1042 #endif
1043
1044 static void init_hda_cache(struct hda_cache_rec *cache,
1045                            unsigned int record_size);
1046 static void free_hda_cache(struct hda_cache_rec *cache);
1047
1048 /* restore the initial pin cfgs and release all pincfg lists */
1049 static void restore_init_pincfgs(struct hda_codec *codec)
1050 {
1051         /* first free driver_pins and user_pins, then call restore_pincfg
1052          * so that only the values in init_pins are restored
1053          */
1054         snd_array_free(&codec->driver_pins);
1055 #ifdef CONFIG_SND_HDA_HWDEP
1056         snd_array_free(&codec->user_pins);
1057 #endif
1058         restore_pincfgs(codec);
1059         snd_array_free(&codec->init_pins);
1060 }
1061
1062 /*
1063  * audio-converter setup caches
1064  */
1065 struct hda_cvt_setup {
1066         hda_nid_t nid;
1067         u8 stream_tag;
1068         u8 channel_id;
1069         u16 format_id;
1070         unsigned char active;   /* cvt is currently used */
1071         unsigned char dirty;    /* setups should be cleared */
1072 };
1073
1074 /* get or create a cache entry for the given audio converter NID */
1075 static struct hda_cvt_setup *
1076 get_hda_cvt_setup(struct hda_codec *codec, hda_nid_t nid)
1077 {
1078         struct hda_cvt_setup *p;
1079         int i;
1080
1081         for (i = 0; i < codec->cvt_setups.used; i++) {
1082                 p = snd_array_elem(&codec->cvt_setups, i);
1083                 if (p->nid == nid)
1084                         return p;
1085         }
1086         p = snd_array_new(&codec->cvt_setups);
1087         if (p)
1088                 p->nid = nid;
1089         return p;
1090 }
1091
1092 /*
1093  * codec destructor
1094  */
1095 static void snd_hda_codec_free(struct hda_codec *codec)
1096 {
1097         if (!codec)
1098                 return;
1099         restore_init_pincfgs(codec);
1100 #ifdef CONFIG_SND_HDA_POWER_SAVE
1101         cancel_delayed_work(&codec->power_work);
1102         flush_workqueue(codec->bus->workq);
1103 #endif
1104         list_del(&codec->list);
1105         snd_array_free(&codec->mixers);
1106         snd_array_free(&codec->nids);
1107         snd_array_free(&codec->conn_lists);
1108         snd_array_free(&codec->spdif_out);
1109         codec->bus->caddr_tbl[codec->addr] = NULL;
1110         if (codec->patch_ops.free)
1111                 codec->patch_ops.free(codec);
1112         module_put(codec->owner);
1113         free_hda_cache(&codec->amp_cache);
1114         free_hda_cache(&codec->cmd_cache);
1115         kfree(codec->vendor_name);
1116         kfree(codec->chip_name);
1117         kfree(codec->modelname);
1118         kfree(codec->wcaps);
1119         kfree(codec);
1120 }
1121
1122 static void hda_set_power_state(struct hda_codec *codec, hda_nid_t fg,
1123                                 unsigned int power_state);
1124
1125 /**
1126  * snd_hda_codec_new - create a HDA codec
1127  * @bus: the bus to assign
1128  * @codec_addr: the codec address
1129  * @codecp: the pointer to store the generated codec
1130  *
1131  * Returns 0 if successful, or a negative error code.
1132  */
1133 int /*__devinit*/ snd_hda_codec_new(struct hda_bus *bus,
1134                                 unsigned int codec_addr,
1135                                 struct hda_codec **codecp)
1136 {
1137         struct hda_codec *codec;
1138         char component[31];
1139         int err;
1140
1141         if (snd_BUG_ON(!bus))
1142                 return -EINVAL;
1143         if (snd_BUG_ON(codec_addr > HDA_MAX_CODEC_ADDRESS))
1144                 return -EINVAL;
1145
1146         if (bus->caddr_tbl[codec_addr]) {
1147                 snd_printk(KERN_ERR "hda_codec: "
1148                            "address 0x%x is already occupied\n", codec_addr);
1149                 return -EBUSY;
1150         }
1151
1152         codec = kzalloc(sizeof(*codec), GFP_KERNEL);
1153         if (codec == NULL) {
1154                 snd_printk(KERN_ERR "can't allocate struct hda_codec\n");
1155                 return -ENOMEM;
1156         }
1157
1158         codec->bus = bus;
1159         codec->addr = codec_addr;
1160         mutex_init(&codec->spdif_mutex);
1161         mutex_init(&codec->control_mutex);
1162         init_hda_cache(&codec->amp_cache, sizeof(struct hda_amp_info));
1163         init_hda_cache(&codec->cmd_cache, sizeof(struct hda_cache_head));
1164         snd_array_init(&codec->mixers, sizeof(struct hda_nid_item), 32);
1165         snd_array_init(&codec->nids, sizeof(struct hda_nid_item), 32);
1166         snd_array_init(&codec->init_pins, sizeof(struct hda_pincfg), 16);
1167         snd_array_init(&codec->driver_pins, sizeof(struct hda_pincfg), 16);
1168         snd_array_init(&codec->cvt_setups, sizeof(struct hda_cvt_setup), 8);
1169         snd_array_init(&codec->conn_lists, sizeof(hda_nid_t), 64);
1170         snd_array_init(&codec->spdif_out, sizeof(struct hda_spdif_out), 16);
1171         if (codec->bus->modelname) {
1172                 codec->modelname = kstrdup(codec->bus->modelname, GFP_KERNEL);
1173                 if (!codec->modelname) {
1174                         snd_hda_codec_free(codec);
1175                         return -ENODEV;
1176                 }
1177         }
1178
1179 #ifdef CONFIG_SND_HDA_POWER_SAVE
1180         INIT_DELAYED_WORK(&codec->power_work, hda_power_work);
1181         /* snd_hda_codec_new() marks the codec as power-up, and leave it as is.
1182          * the caller has to power down appropriatley after initialization
1183          * phase.
1184          */
1185         hda_keep_power_on(codec);
1186 #endif
1187
1188         list_add_tail(&codec->list, &bus->codec_list);
1189         bus->caddr_tbl[codec_addr] = codec;
1190
1191         codec->vendor_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1192                                               AC_PAR_VENDOR_ID);
1193         if (codec->vendor_id == -1)
1194                 /* read again, hopefully the access method was corrected
1195                  * in the last read...
1196                  */
1197                 codec->vendor_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1198                                                       AC_PAR_VENDOR_ID);
1199         codec->subsystem_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1200                                                  AC_PAR_SUBSYSTEM_ID);
1201         codec->revision_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1202                                                 AC_PAR_REV_ID);
1203
1204         setup_fg_nodes(codec);
1205         if (!codec->afg && !codec->mfg) {
1206                 snd_printdd("hda_codec: no AFG or MFG node found\n");
1207                 err = -ENODEV;
1208                 goto error;
1209         }
1210
1211         err = read_widget_caps(codec, codec->afg ? codec->afg : codec->mfg);
1212         if (err < 0) {
1213                 snd_printk(KERN_ERR "hda_codec: cannot malloc\n");
1214                 goto error;
1215         }
1216         err = read_pin_defaults(codec);
1217         if (err < 0)
1218                 goto error;
1219
1220         if (!codec->subsystem_id) {
1221                 hda_nid_t nid = codec->afg ? codec->afg : codec->mfg;
1222                 codec->subsystem_id =
1223                         snd_hda_codec_read(codec, nid, 0,
1224                                            AC_VERB_GET_SUBSYSTEM_ID, 0);
1225         }
1226
1227         /* power-up all before initialization */
1228         hda_set_power_state(codec,
1229                             codec->afg ? codec->afg : codec->mfg,
1230                             AC_PWRST_D0);
1231
1232         snd_hda_codec_proc_new(codec);
1233
1234         snd_hda_create_hwdep(codec);
1235
1236         sprintf(component, "HDA:%08x,%08x,%08x", codec->vendor_id,
1237                 codec->subsystem_id, codec->revision_id);
1238         snd_component_add(codec->bus->card, component);
1239
1240         if (codecp)
1241                 *codecp = codec;
1242         return 0;
1243
1244  error:
1245         snd_hda_codec_free(codec);
1246         return err;
1247 }
1248 EXPORT_SYMBOL_HDA(snd_hda_codec_new);
1249
1250 /**
1251  * snd_hda_codec_configure - (Re-)configure the HD-audio codec
1252  * @codec: the HDA codec
1253  *
1254  * Start parsing of the given codec tree and (re-)initialize the whole
1255  * patch instance.
1256  *
1257  * Returns 0 if successful or a negative error code.
1258  */
1259 int snd_hda_codec_configure(struct hda_codec *codec)
1260 {
1261         int err;
1262
1263         codec->preset = find_codec_preset(codec);
1264         if (!codec->vendor_name || !codec->chip_name) {
1265                 err = get_codec_name(codec);
1266                 if (err < 0)
1267                         return err;
1268         }
1269
1270         if (is_generic_config(codec)) {
1271                 err = snd_hda_parse_generic_codec(codec);
1272                 goto patched;
1273         }
1274         if (codec->preset && codec->preset->patch) {
1275                 err = codec->preset->patch(codec);
1276                 goto patched;
1277         }
1278
1279         /* call the default parser */
1280         err = snd_hda_parse_generic_codec(codec);
1281         if (err < 0)
1282                 printk(KERN_ERR "hda-codec: No codec parser is available\n");
1283
1284  patched:
1285         if (!err && codec->patch_ops.unsol_event)
1286                 err = init_unsol_queue(codec->bus);
1287         /* audio codec should override the mixer name */
1288         if (!err && (codec->afg || !*codec->bus->card->mixername))
1289                 snprintf(codec->bus->card->mixername,
1290                          sizeof(codec->bus->card->mixername),
1291                          "%s %s", codec->vendor_name, codec->chip_name);
1292         return err;
1293 }
1294 EXPORT_SYMBOL_HDA(snd_hda_codec_configure);
1295
1296 /**
1297  * snd_hda_codec_setup_stream - set up the codec for streaming
1298  * @codec: the CODEC to set up
1299  * @nid: the NID to set up
1300  * @stream_tag: stream tag to pass, it's between 0x1 and 0xf.
1301  * @channel_id: channel id to pass, zero based.
1302  * @format: stream format.
1303  */
1304 void snd_hda_codec_setup_stream(struct hda_codec *codec, hda_nid_t nid,
1305                                 u32 stream_tag,
1306                                 int channel_id, int format)
1307 {
1308         struct hda_codec *c;
1309         struct hda_cvt_setup *p;
1310         unsigned int oldval, newval;
1311         int type;
1312         int i;
1313
1314         if (!nid)
1315                 return;
1316
1317         snd_printdd("hda_codec_setup_stream: "
1318                     "NID=0x%x, stream=0x%x, channel=%d, format=0x%x\n",
1319                     nid, stream_tag, channel_id, format);
1320         p = get_hda_cvt_setup(codec, nid);
1321         if (!p)
1322                 return;
1323         /* update the stream-id if changed */
1324         if (p->stream_tag != stream_tag || p->channel_id != channel_id) {
1325                 oldval = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_CONV, 0);
1326                 newval = (stream_tag << 4) | channel_id;
1327                 if (oldval != newval)
1328                         snd_hda_codec_write(codec, nid, 0,
1329                                             AC_VERB_SET_CHANNEL_STREAMID,
1330                                             newval);
1331                 p->stream_tag = stream_tag;
1332                 p->channel_id = channel_id;
1333         }
1334         /* update the format-id if changed */
1335         if (p->format_id != format) {
1336                 oldval = snd_hda_codec_read(codec, nid, 0,
1337                                             AC_VERB_GET_STREAM_FORMAT, 0);
1338                 if (oldval != format) {
1339                         msleep(1);
1340                         snd_hda_codec_write(codec, nid, 0,
1341                                             AC_VERB_SET_STREAM_FORMAT,
1342                                             format);
1343                 }
1344                 p->format_id = format;
1345         }
1346         p->active = 1;
1347         p->dirty = 0;
1348
1349         /* make other inactive cvts with the same stream-tag dirty */
1350         type = get_wcaps_type(get_wcaps(codec, nid));
1351         list_for_each_entry(c, &codec->bus->codec_list, list) {
1352                 for (i = 0; i < c->cvt_setups.used; i++) {
1353                         p = snd_array_elem(&c->cvt_setups, i);
1354                         if (!p->active && p->stream_tag == stream_tag &&
1355                             get_wcaps_type(get_wcaps(codec, p->nid)) == type)
1356                                 p->dirty = 1;
1357                 }
1358         }
1359 }
1360 EXPORT_SYMBOL_HDA(snd_hda_codec_setup_stream);
1361
1362 static void really_cleanup_stream(struct hda_codec *codec,
1363                                   struct hda_cvt_setup *q);
1364
1365 /**
1366  * __snd_hda_codec_cleanup_stream - clean up the codec for closing
1367  * @codec: the CODEC to clean up
1368  * @nid: the NID to clean up
1369  * @do_now: really clean up the stream instead of clearing the active flag
1370  */
1371 void __snd_hda_codec_cleanup_stream(struct hda_codec *codec, hda_nid_t nid,
1372                                     int do_now)
1373 {
1374         struct hda_cvt_setup *p;
1375
1376         if (!nid)
1377                 return;
1378
1379         if (codec->no_sticky_stream)
1380                 do_now = 1;
1381
1382         snd_printdd("hda_codec_cleanup_stream: NID=0x%x\n", nid);
1383         p = get_hda_cvt_setup(codec, nid);
1384         if (p) {
1385                 /* here we just clear the active flag when do_now isn't set;
1386                  * actual clean-ups will be done later in
1387                  * purify_inactive_streams() called from snd_hda_codec_prpapre()
1388                  */
1389                 if (do_now)
1390                         really_cleanup_stream(codec, p);
1391                 else
1392                         p->active = 0;
1393         }
1394 }
1395 EXPORT_SYMBOL_HDA(__snd_hda_codec_cleanup_stream);
1396
1397 static void really_cleanup_stream(struct hda_codec *codec,
1398                                   struct hda_cvt_setup *q)
1399 {
1400         hda_nid_t nid = q->nid;
1401         snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_CHANNEL_STREAMID, 0);
1402         snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_STREAM_FORMAT, 0);
1403         memset(q, 0, sizeof(*q));
1404         q->nid = nid;
1405 }
1406
1407 /* clean up the all conflicting obsolete streams */
1408 static void purify_inactive_streams(struct hda_codec *codec)
1409 {
1410         struct hda_codec *c;
1411         int i;
1412
1413         list_for_each_entry(c, &codec->bus->codec_list, list) {
1414                 for (i = 0; i < c->cvt_setups.used; i++) {
1415                         struct hda_cvt_setup *p;
1416                         p = snd_array_elem(&c->cvt_setups, i);
1417                         if (p->dirty)
1418                                 really_cleanup_stream(c, p);
1419                 }
1420         }
1421 }
1422
1423 #ifdef SND_HDA_NEEDS_RESUME
1424 /* clean up all streams; called from suspend */
1425 static void hda_cleanup_all_streams(struct hda_codec *codec)
1426 {
1427         int i;
1428
1429         for (i = 0; i < codec->cvt_setups.used; i++) {
1430                 struct hda_cvt_setup *p = snd_array_elem(&codec->cvt_setups, i);
1431                 if (p->stream_tag)
1432                         really_cleanup_stream(codec, p);
1433         }
1434 }
1435 #endif
1436
1437 /*
1438  * amp access functions
1439  */
1440
1441 /* FIXME: more better hash key? */
1442 #define HDA_HASH_KEY(nid, dir, idx) (u32)((nid) + ((idx) << 16) + ((dir) << 24))
1443 #define HDA_HASH_PINCAP_KEY(nid) (u32)((nid) + (0x02 << 24))
1444 #define HDA_HASH_PARPCM_KEY(nid) (u32)((nid) + (0x03 << 24))
1445 #define HDA_HASH_PARSTR_KEY(nid) (u32)((nid) + (0x04 << 24))
1446 #define INFO_AMP_CAPS   (1<<0)
1447 #define INFO_AMP_VOL(ch)        (1 << (1 + (ch)))
1448
1449 /* initialize the hash table */
1450 static void /*__devinit*/ init_hda_cache(struct hda_cache_rec *cache,
1451                                      unsigned int record_size)
1452 {
1453         memset(cache, 0, sizeof(*cache));
1454         memset(cache->hash, 0xff, sizeof(cache->hash));
1455         snd_array_init(&cache->buf, record_size, 64);
1456 }
1457
1458 static void free_hda_cache(struct hda_cache_rec *cache)
1459 {
1460         snd_array_free(&cache->buf);
1461 }
1462
1463 /* query the hash.  allocate an entry if not found. */
1464 static struct hda_cache_head  *get_hash(struct hda_cache_rec *cache, u32 key)
1465 {
1466         u16 idx = key % (u16)ARRAY_SIZE(cache->hash);
1467         u16 cur = cache->hash[idx];
1468         struct hda_cache_head *info;
1469
1470         while (cur != 0xffff) {
1471                 info = snd_array_elem(&cache->buf, cur);
1472                 if (info->key == key)
1473                         return info;
1474                 cur = info->next;
1475         }
1476         return NULL;
1477 }
1478
1479 /* query the hash.  allocate an entry if not found. */
1480 static struct hda_cache_head  *get_alloc_hash(struct hda_cache_rec *cache,
1481                                               u32 key)
1482 {
1483         struct hda_cache_head *info = get_hash(cache, key);
1484         if (!info) {
1485                 u16 idx, cur;
1486                 /* add a new hash entry */
1487                 info = snd_array_new(&cache->buf);
1488                 if (!info)
1489                         return NULL;
1490                 cur = snd_array_index(&cache->buf, info);
1491                 info->key = key;
1492                 info->val = 0;
1493                 idx = key % (u16)ARRAY_SIZE(cache->hash);
1494                 info->next = cache->hash[idx];
1495                 cache->hash[idx] = cur;
1496         }
1497         return info;
1498 }
1499
1500 /* query and allocate an amp hash entry */
1501 static inline struct hda_amp_info *
1502 get_alloc_amp_hash(struct hda_codec *codec, u32 key)
1503 {
1504         return (struct hda_amp_info *)get_alloc_hash(&codec->amp_cache, key);
1505 }
1506
1507 /**
1508  * query_amp_caps - query AMP capabilities
1509  * @codec: the HD-auio codec
1510  * @nid: the NID to query
1511  * @direction: either #HDA_INPUT or #HDA_OUTPUT
1512  *
1513  * Query AMP capabilities for the given widget and direction.
1514  * Returns the obtained capability bits.
1515  *
1516  * When cap bits have been already read, this doesn't read again but
1517  * returns the cached value.
1518  */
1519 u32 query_amp_caps(struct hda_codec *codec, hda_nid_t nid, int direction)
1520 {
1521         struct hda_amp_info *info;
1522
1523         info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, direction, 0));
1524         if (!info)
1525                 return 0;
1526         if (!(info->head.val & INFO_AMP_CAPS)) {
1527                 if (!(get_wcaps(codec, nid) & AC_WCAP_AMP_OVRD))
1528                         nid = codec->afg;
1529                 info->amp_caps = snd_hda_param_read(codec, nid,
1530                                                     direction == HDA_OUTPUT ?
1531                                                     AC_PAR_AMP_OUT_CAP :
1532                                                     AC_PAR_AMP_IN_CAP);
1533                 if (info->amp_caps)
1534                         info->head.val |= INFO_AMP_CAPS;
1535         }
1536         return info->amp_caps;
1537 }
1538 EXPORT_SYMBOL_HDA(query_amp_caps);
1539
1540 /**
1541  * snd_hda_override_amp_caps - Override the AMP capabilities
1542  * @codec: the CODEC to clean up
1543  * @nid: the NID to clean up
1544  * @direction: either #HDA_INPUT or #HDA_OUTPUT
1545  * @caps: the capability bits to set
1546  *
1547  * Override the cached AMP caps bits value by the given one.
1548  * This function is useful if the driver needs to adjust the AMP ranges,
1549  * e.g. limit to 0dB, etc.
1550  *
1551  * Returns zero if successful or a negative error code.
1552  */
1553 int snd_hda_override_amp_caps(struct hda_codec *codec, hda_nid_t nid, int dir,
1554                               unsigned int caps)
1555 {
1556         struct hda_amp_info *info;
1557
1558         info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, dir, 0));
1559         if (!info)
1560                 return -EINVAL;
1561         info->amp_caps = caps;
1562         info->head.val |= INFO_AMP_CAPS;
1563         return 0;
1564 }
1565 EXPORT_SYMBOL_HDA(snd_hda_override_amp_caps);
1566
1567 static unsigned int
1568 query_caps_hash(struct hda_codec *codec, hda_nid_t nid, u32 key,
1569                 unsigned int (*func)(struct hda_codec *, hda_nid_t))
1570 {
1571         struct hda_amp_info *info;
1572
1573         info = get_alloc_amp_hash(codec, key);
1574         if (!info)
1575                 return 0;
1576         if (!info->head.val) {
1577                 info->head.val |= INFO_AMP_CAPS;
1578                 info->amp_caps = func(codec, nid);
1579         }
1580         return info->amp_caps;
1581 }
1582
1583 static unsigned int read_pin_cap(struct hda_codec *codec, hda_nid_t nid)
1584 {
1585         return snd_hda_param_read(codec, nid, AC_PAR_PIN_CAP);
1586 }
1587
1588 /**
1589  * snd_hda_query_pin_caps - Query PIN capabilities
1590  * @codec: the HD-auio codec
1591  * @nid: the NID to query
1592  *
1593  * Query PIN capabilities for the given widget.
1594  * Returns the obtained capability bits.
1595  *
1596  * When cap bits have been already read, this doesn't read again but
1597  * returns the cached value.
1598  */
1599 u32 snd_hda_query_pin_caps(struct hda_codec *codec, hda_nid_t nid)
1600 {
1601         return query_caps_hash(codec, nid, HDA_HASH_PINCAP_KEY(nid),
1602                                read_pin_cap);
1603 }
1604 EXPORT_SYMBOL_HDA(snd_hda_query_pin_caps);
1605
1606 /**
1607  * snd_hda_pin_sense - execute pin sense measurement
1608  * @codec: the CODEC to sense
1609  * @nid: the pin NID to sense
1610  *
1611  * Execute necessary pin sense measurement and return its Presence Detect,
1612  * Impedance, ELD Valid etc. status bits.
1613  */
1614 u32 snd_hda_pin_sense(struct hda_codec *codec, hda_nid_t nid)
1615 {
1616         u32 pincap;
1617
1618         if (!codec->no_trigger_sense) {
1619                 pincap = snd_hda_query_pin_caps(codec, nid);
1620                 if (pincap & AC_PINCAP_TRIG_REQ) /* need trigger? */
1621                         snd_hda_codec_read(codec, nid, 0,
1622                                         AC_VERB_SET_PIN_SENSE, 0);
1623         }
1624         return snd_hda_codec_read(codec, nid, 0,
1625                                   AC_VERB_GET_PIN_SENSE, 0);
1626 }
1627 EXPORT_SYMBOL_HDA(snd_hda_pin_sense);
1628
1629 /**
1630  * snd_hda_jack_detect - query pin Presence Detect status
1631  * @codec: the CODEC to sense
1632  * @nid: the pin NID to sense
1633  *
1634  * Query and return the pin's Presence Detect status.
1635  */
1636 int snd_hda_jack_detect(struct hda_codec *codec, hda_nid_t nid)
1637 {
1638         u32 sense = snd_hda_pin_sense(codec, nid);
1639         return !!(sense & AC_PINSENSE_PRESENCE);
1640 }
1641 EXPORT_SYMBOL_HDA(snd_hda_jack_detect);
1642
1643 /*
1644  * read the current volume to info
1645  * if the cache exists, read the cache value.
1646  */
1647 static unsigned int get_vol_mute(struct hda_codec *codec,
1648                                  struct hda_amp_info *info, hda_nid_t nid,
1649                                  int ch, int direction, int index)
1650 {
1651         u32 val, parm;
1652
1653         if (info->head.val & INFO_AMP_VOL(ch))
1654                 return info->vol[ch];
1655
1656         parm = ch ? AC_AMP_GET_RIGHT : AC_AMP_GET_LEFT;
1657         parm |= direction == HDA_OUTPUT ? AC_AMP_GET_OUTPUT : AC_AMP_GET_INPUT;
1658         parm |= index;
1659         val = snd_hda_codec_read(codec, nid, 0,
1660                                  AC_VERB_GET_AMP_GAIN_MUTE, parm);
1661         info->vol[ch] = val & 0xff;
1662         info->head.val |= INFO_AMP_VOL(ch);
1663         return info->vol[ch];
1664 }
1665
1666 /*
1667  * write the current volume in info to the h/w and update the cache
1668  */
1669 static void put_vol_mute(struct hda_codec *codec, struct hda_amp_info *info,
1670                          hda_nid_t nid, int ch, int direction, int index,
1671                          int val)
1672 {
1673         u32 parm;
1674
1675         parm = ch ? AC_AMP_SET_RIGHT : AC_AMP_SET_LEFT;
1676         parm |= direction == HDA_OUTPUT ? AC_AMP_SET_OUTPUT : AC_AMP_SET_INPUT;
1677         parm |= index << AC_AMP_SET_INDEX_SHIFT;
1678         parm |= val;
1679         snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_AMP_GAIN_MUTE, parm);
1680         info->vol[ch] = val;
1681 }
1682
1683 /**
1684  * snd_hda_codec_amp_read - Read AMP value
1685  * @codec: HD-audio codec
1686  * @nid: NID to read the AMP value
1687  * @ch: channel (left=0 or right=1)
1688  * @direction: #HDA_INPUT or #HDA_OUTPUT
1689  * @index: the index value (only for input direction)
1690  *
1691  * Read AMP value.  The volume is between 0 to 0x7f, 0x80 = mute bit.
1692  */
1693 int snd_hda_codec_amp_read(struct hda_codec *codec, hda_nid_t nid, int ch,
1694                            int direction, int index)
1695 {
1696         struct hda_amp_info *info;
1697         info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, direction, index));
1698         if (!info)
1699                 return 0;
1700         return get_vol_mute(codec, info, nid, ch, direction, index);
1701 }
1702 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_read);
1703
1704 /**
1705  * snd_hda_codec_amp_update - update the AMP value
1706  * @codec: HD-audio codec
1707  * @nid: NID to read the AMP value
1708  * @ch: channel (left=0 or right=1)
1709  * @direction: #HDA_INPUT or #HDA_OUTPUT
1710  * @idx: the index value (only for input direction)
1711  * @mask: bit mask to set
1712  * @val: the bits value to set
1713  *
1714  * Update the AMP value with a bit mask.
1715  * Returns 0 if the value is unchanged, 1 if changed.
1716  */
1717 int snd_hda_codec_amp_update(struct hda_codec *codec, hda_nid_t nid, int ch,
1718                              int direction, int idx, int mask, int val)
1719 {
1720         struct hda_amp_info *info;
1721
1722         info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, direction, idx));
1723         if (!info)
1724                 return 0;
1725         if (snd_BUG_ON(mask & ~0xff))
1726                 mask &= 0xff;
1727         val &= mask;
1728         val |= get_vol_mute(codec, info, nid, ch, direction, idx) & ~mask;
1729         if (info->vol[ch] == val)
1730                 return 0;
1731         put_vol_mute(codec, info, nid, ch, direction, idx, val);
1732         return 1;
1733 }
1734 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_update);
1735
1736 /**
1737  * snd_hda_codec_amp_stereo - update the AMP stereo values
1738  * @codec: HD-audio codec
1739  * @nid: NID to read the AMP value
1740  * @direction: #HDA_INPUT or #HDA_OUTPUT
1741  * @idx: the index value (only for input direction)
1742  * @mask: bit mask to set
1743  * @val: the bits value to set
1744  *
1745  * Update the AMP values like snd_hda_codec_amp_update(), but for a
1746  * stereo widget with the same mask and value.
1747  */
1748 int snd_hda_codec_amp_stereo(struct hda_codec *codec, hda_nid_t nid,
1749                              int direction, int idx, int mask, int val)
1750 {
1751         int ch, ret = 0;
1752
1753         if (snd_BUG_ON(mask & ~0xff))
1754                 mask &= 0xff;
1755         for (ch = 0; ch < 2; ch++)
1756                 ret |= snd_hda_codec_amp_update(codec, nid, ch, direction,
1757                                                 idx, mask, val);
1758         return ret;
1759 }
1760 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_stereo);
1761
1762 #ifdef SND_HDA_NEEDS_RESUME
1763 /**
1764  * snd_hda_codec_resume_amp - Resume all AMP commands from the cache
1765  * @codec: HD-audio codec
1766  *
1767  * Resume the all amp commands from the cache.
1768  */
1769 void snd_hda_codec_resume_amp(struct hda_codec *codec)
1770 {
1771         struct hda_amp_info *buffer = codec->amp_cache.buf.list;
1772         int i;
1773
1774         for (i = 0; i < codec->amp_cache.buf.used; i++, buffer++) {
1775                 u32 key = buffer->head.key;
1776                 hda_nid_t nid;
1777                 unsigned int idx, dir, ch;
1778                 if (!key)
1779                         continue;
1780                 nid = key & 0xff;
1781                 idx = (key >> 16) & 0xff;
1782                 dir = (key >> 24) & 0xff;
1783                 for (ch = 0; ch < 2; ch++) {
1784                         if (!(buffer->head.val & INFO_AMP_VOL(ch)))
1785                                 continue;
1786                         put_vol_mute(codec, buffer, nid, ch, dir, idx,
1787                                      buffer->vol[ch]);
1788                 }
1789         }
1790 }
1791 EXPORT_SYMBOL_HDA(snd_hda_codec_resume_amp);
1792 #endif /* SND_HDA_NEEDS_RESUME */
1793
1794 static u32 get_amp_max_value(struct hda_codec *codec, hda_nid_t nid, int dir,
1795                              unsigned int ofs)
1796 {
1797         u32 caps = query_amp_caps(codec, nid, dir);
1798         /* get num steps */
1799         caps = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
1800         if (ofs < caps)
1801                 caps -= ofs;
1802         return caps;
1803 }
1804
1805 /**
1806  * snd_hda_mixer_amp_volume_info - Info callback for a standard AMP mixer
1807  *
1808  * The control element is supposed to have the private_value field
1809  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1810  */
1811 int snd_hda_mixer_amp_volume_info(struct snd_kcontrol *kcontrol,
1812                                   struct snd_ctl_elem_info *uinfo)
1813 {
1814         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1815         u16 nid = get_amp_nid(kcontrol);
1816         u8 chs = get_amp_channels(kcontrol);
1817         int dir = get_amp_direction(kcontrol);
1818         unsigned int ofs = get_amp_offset(kcontrol);
1819
1820         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1821         uinfo->count = chs == 3 ? 2 : 1;
1822         uinfo->value.integer.min = 0;
1823         uinfo->value.integer.max = get_amp_max_value(codec, nid, dir, ofs);
1824         if (!uinfo->value.integer.max) {
1825                 printk(KERN_WARNING "hda_codec: "
1826                        "num_steps = 0 for NID=0x%x (ctl = %s)\n", nid,
1827                        kcontrol->id.name);
1828                 return -EINVAL;
1829         }
1830         return 0;
1831 }
1832 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_volume_info);
1833
1834
1835 static inline unsigned int
1836 read_amp_value(struct hda_codec *codec, hda_nid_t nid,
1837                int ch, int dir, int idx, unsigned int ofs)
1838 {
1839         unsigned int val;
1840         val = snd_hda_codec_amp_read(codec, nid, ch, dir, idx);
1841         val &= HDA_AMP_VOLMASK;
1842         if (val >= ofs)
1843                 val -= ofs;
1844         else
1845                 val = 0;
1846         return val;
1847 }
1848
1849 static inline int
1850 update_amp_value(struct hda_codec *codec, hda_nid_t nid,
1851                  int ch, int dir, int idx, unsigned int ofs,
1852                  unsigned int val)
1853 {
1854         unsigned int maxval;
1855
1856         if (val > 0)
1857                 val += ofs;
1858         /* ofs = 0: raw max value */
1859         maxval = get_amp_max_value(codec, nid, dir, 0);
1860         if (val > maxval)
1861                 val = maxval;
1862         return snd_hda_codec_amp_update(codec, nid, ch, dir, idx,
1863                                         HDA_AMP_VOLMASK, val);
1864 }
1865
1866 /**
1867  * snd_hda_mixer_amp_volume_get - Get callback for a standard AMP mixer volume
1868  *
1869  * The control element is supposed to have the private_value field
1870  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1871  */
1872 int snd_hda_mixer_amp_volume_get(struct snd_kcontrol *kcontrol,
1873                                  struct snd_ctl_elem_value *ucontrol)
1874 {
1875         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1876         hda_nid_t nid = get_amp_nid(kcontrol);
1877         int chs = get_amp_channels(kcontrol);
1878         int dir = get_amp_direction(kcontrol);
1879         int idx = get_amp_index(kcontrol);
1880         unsigned int ofs = get_amp_offset(kcontrol);
1881         long *valp = ucontrol->value.integer.value;
1882
1883         if (chs & 1)
1884                 *valp++ = read_amp_value(codec, nid, 0, dir, idx, ofs);
1885         if (chs & 2)
1886                 *valp = read_amp_value(codec, nid, 1, dir, idx, ofs);
1887         return 0;
1888 }
1889 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_volume_get);
1890
1891 /**
1892  * snd_hda_mixer_amp_volume_put - Put callback for a standard AMP mixer volume
1893  *
1894  * The control element is supposed to have the private_value field
1895  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1896  */
1897 int snd_hda_mixer_amp_volume_put(struct snd_kcontrol *kcontrol,
1898                                  struct snd_ctl_elem_value *ucontrol)
1899 {
1900         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1901         hda_nid_t nid = get_amp_nid(kcontrol);
1902         int chs = get_amp_channels(kcontrol);
1903         int dir = get_amp_direction(kcontrol);
1904         int idx = get_amp_index(kcontrol);
1905         unsigned int ofs = get_amp_offset(kcontrol);
1906         long *valp = ucontrol->value.integer.value;
1907         int change = 0;
1908
1909         snd_hda_power_up(codec);
1910         if (chs & 1) {
1911                 change = update_amp_value(codec, nid, 0, dir, idx, ofs, *valp);
1912                 valp++;
1913         }
1914         if (chs & 2)
1915                 change |= update_amp_value(codec, nid, 1, dir, idx, ofs, *valp);
1916         snd_hda_power_down(codec);
1917         return change;
1918 }
1919 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_volume_put);
1920
1921 /**
1922  * snd_hda_mixer_amp_volume_put - TLV callback for a standard AMP mixer volume
1923  *
1924  * The control element is supposed to have the private_value field
1925  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1926  */
1927 int snd_hda_mixer_amp_tlv(struct snd_kcontrol *kcontrol, int op_flag,
1928                           unsigned int size, unsigned int __user *_tlv)
1929 {
1930         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1931         hda_nid_t nid = get_amp_nid(kcontrol);
1932         int dir = get_amp_direction(kcontrol);
1933         unsigned int ofs = get_amp_offset(kcontrol);
1934         bool min_mute = get_amp_min_mute(kcontrol);
1935         u32 caps, val1, val2;
1936
1937         if (size < 4 * sizeof(unsigned int))
1938                 return -ENOMEM;
1939         caps = query_amp_caps(codec, nid, dir);
1940         val2 = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT;
1941         val2 = (val2 + 1) * 25;
1942         val1 = -((caps & AC_AMPCAP_OFFSET) >> AC_AMPCAP_OFFSET_SHIFT);
1943         val1 += ofs;
1944         val1 = ((int)val1) * ((int)val2);
1945         if (min_mute)
1946                 val2 |= TLV_DB_SCALE_MUTE;
1947         if (put_user(SNDRV_CTL_TLVT_DB_SCALE, _tlv))
1948                 return -EFAULT;
1949         if (put_user(2 * sizeof(unsigned int), _tlv + 1))
1950                 return -EFAULT;
1951         if (put_user(val1, _tlv + 2))
1952                 return -EFAULT;
1953         if (put_user(val2, _tlv + 3))
1954                 return -EFAULT;
1955         return 0;
1956 }
1957 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_tlv);
1958
1959 /**
1960  * snd_hda_set_vmaster_tlv - Set TLV for a virtual master control
1961  * @codec: HD-audio codec
1962  * @nid: NID of a reference widget
1963  * @dir: #HDA_INPUT or #HDA_OUTPUT
1964  * @tlv: TLV data to be stored, at least 4 elements
1965  *
1966  * Set (static) TLV data for a virtual master volume using the AMP caps
1967  * obtained from the reference NID.
1968  * The volume range is recalculated as if the max volume is 0dB.
1969  */
1970 void snd_hda_set_vmaster_tlv(struct hda_codec *codec, hda_nid_t nid, int dir,
1971                              unsigned int *tlv)
1972 {
1973         u32 caps;
1974         int nums, step;
1975
1976         caps = query_amp_caps(codec, nid, dir);
1977         nums = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
1978         step = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT;
1979         step = (step + 1) * 25;
1980         tlv[0] = SNDRV_CTL_TLVT_DB_SCALE;
1981         tlv[1] = 2 * sizeof(unsigned int);
1982         tlv[2] = -nums * step;
1983         tlv[3] = step;
1984 }
1985 EXPORT_SYMBOL_HDA(snd_hda_set_vmaster_tlv);
1986
1987 /* find a mixer control element with the given name */
1988 static struct snd_kcontrol *
1989 _snd_hda_find_mixer_ctl(struct hda_codec *codec,
1990                         const char *name, int idx)
1991 {
1992         struct snd_ctl_elem_id id;
1993         memset(&id, 0, sizeof(id));
1994         id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
1995         id.index = idx;
1996         if (snd_BUG_ON(strlen(name) >= sizeof(id.name)))
1997                 return NULL;
1998         strcpy(id.name, name);
1999         return snd_ctl_find_id(codec->bus->card, &id);
2000 }
2001
2002 /**
2003  * snd_hda_find_mixer_ctl - Find a mixer control element with the given name
2004  * @codec: HD-audio codec
2005  * @name: ctl id name string
2006  *
2007  * Get the control element with the given id string and IFACE_MIXER.
2008  */
2009 struct snd_kcontrol *snd_hda_find_mixer_ctl(struct hda_codec *codec,
2010                                             const char *name)
2011 {
2012         return _snd_hda_find_mixer_ctl(codec, name, 0);
2013 }
2014 EXPORT_SYMBOL_HDA(snd_hda_find_mixer_ctl);
2015
2016 static int find_empty_mixer_ctl_idx(struct hda_codec *codec, const char *name)
2017 {
2018         int idx;
2019         for (idx = 0; idx < 16; idx++) { /* 16 ctlrs should be large enough */
2020                 if (!_snd_hda_find_mixer_ctl(codec, name, idx))
2021                         return idx;
2022         }
2023         return -EBUSY;
2024 }
2025
2026 /**
2027  * snd_hda_ctl_add - Add a control element and assign to the codec
2028  * @codec: HD-audio codec
2029  * @nid: corresponding NID (optional)
2030  * @kctl: the control element to assign
2031  *
2032  * Add the given control element to an array inside the codec instance.
2033  * All control elements belonging to a codec are supposed to be added
2034  * by this function so that a proper clean-up works at the free or
2035  * reconfiguration time.
2036  *
2037  * If non-zero @nid is passed, the NID is assigned to the control element.
2038  * The assignment is shown in the codec proc file.
2039  *
2040  * snd_hda_ctl_add() checks the control subdev id field whether
2041  * #HDA_SUBDEV_NID_FLAG bit is set.  If set (and @nid is zero), the lower
2042  * bits value is taken as the NID to assign. The #HDA_NID_ITEM_AMP bit
2043  * specifies if kctl->private_value is a HDA amplifier value.
2044  */
2045 int snd_hda_ctl_add(struct hda_codec *codec, hda_nid_t nid,
2046                     struct snd_kcontrol *kctl)
2047 {
2048         int err;
2049         unsigned short flags = 0;
2050         struct hda_nid_item *item;
2051
2052         if (kctl->id.subdevice & HDA_SUBDEV_AMP_FLAG) {
2053                 flags |= HDA_NID_ITEM_AMP;
2054                 if (nid == 0)
2055                         nid = get_amp_nid_(kctl->private_value);
2056         }
2057         if ((kctl->id.subdevice & HDA_SUBDEV_NID_FLAG) != 0 && nid == 0)
2058                 nid = kctl->id.subdevice & 0xffff;
2059         if (kctl->id.subdevice & (HDA_SUBDEV_NID_FLAG|HDA_SUBDEV_AMP_FLAG))
2060                 kctl->id.subdevice = 0;
2061         err = snd_ctl_add(codec->bus->card, kctl);
2062         if (err < 0)
2063                 return err;
2064         item = snd_array_new(&codec->mixers);
2065         if (!item)
2066                 return -ENOMEM;
2067         item->kctl = kctl;
2068         item->nid = nid;
2069         item->flags = flags;
2070         return 0;
2071 }
2072 EXPORT_SYMBOL_HDA(snd_hda_ctl_add);
2073
2074 /**
2075  * snd_hda_add_nid - Assign a NID to a control element
2076  * @codec: HD-audio codec
2077  * @nid: corresponding NID (optional)
2078  * @kctl: the control element to assign
2079  * @index: index to kctl
2080  *
2081  * Add the given control element to an array inside the codec instance.
2082  * This function is used when #snd_hda_ctl_add cannot be used for 1:1
2083  * NID:KCTL mapping - for example "Capture Source" selector.
2084  */
2085 int snd_hda_add_nid(struct hda_codec *codec, struct snd_kcontrol *kctl,
2086                     unsigned int index, hda_nid_t nid)
2087 {
2088         struct hda_nid_item *item;
2089
2090         if (nid > 0) {
2091                 item = snd_array_new(&codec->nids);
2092                 if (!item)
2093                         return -ENOMEM;
2094                 item->kctl = kctl;
2095                 item->index = index;
2096                 item->nid = nid;
2097                 return 0;
2098         }
2099         printk(KERN_ERR "hda-codec: no NID for mapping control %s:%d:%d\n",
2100                kctl->id.name, kctl->id.index, index);
2101         return -EINVAL;
2102 }
2103 EXPORT_SYMBOL_HDA(snd_hda_add_nid);
2104
2105 /**
2106  * snd_hda_ctls_clear - Clear all controls assigned to the given codec
2107  * @codec: HD-audio codec
2108  */
2109 void snd_hda_ctls_clear(struct hda_codec *codec)
2110 {
2111         int i;
2112         struct hda_nid_item *items = codec->mixers.list;
2113         for (i = 0; i < codec->mixers.used; i++)
2114                 snd_ctl_remove(codec->bus->card, items[i].kctl);
2115         snd_array_free(&codec->mixers);
2116         snd_array_free(&codec->nids);
2117 }
2118
2119 /* pseudo device locking
2120  * toggle card->shutdown to allow/disallow the device access (as a hack)
2121  */
2122 static int hda_lock_devices(struct snd_card *card)
2123 {
2124         spin_lock(&card->files_lock);
2125         if (card->shutdown) {
2126                 spin_unlock(&card->files_lock);
2127                 return -EINVAL;
2128         }
2129         card->shutdown = 1;
2130         spin_unlock(&card->files_lock);
2131         return 0;
2132 }
2133
2134 static void hda_unlock_devices(struct snd_card *card)
2135 {
2136         spin_lock(&card->files_lock);
2137         card->shutdown = 0;
2138         spin_unlock(&card->files_lock);
2139 }
2140
2141 /**
2142  * snd_hda_codec_reset - Clear all objects assigned to the codec
2143  * @codec: HD-audio codec
2144  *
2145  * This frees the all PCM and control elements assigned to the codec, and
2146  * clears the caches and restores the pin default configurations.
2147  *
2148  * When a device is being used, it returns -EBSY.  If successfully freed,
2149  * returns zero.
2150  */
2151 int snd_hda_codec_reset(struct hda_codec *codec)
2152 {
2153         struct snd_card *card = codec->bus->card;
2154         int i, pcm;
2155
2156         if (hda_lock_devices(card) < 0)
2157                 return -EBUSY;
2158         /* check whether the codec isn't used by any mixer or PCM streams */
2159         if (!list_empty(&card->ctl_files)) {
2160                 hda_unlock_devices(card);
2161                 return -EBUSY;
2162         }
2163         for (pcm = 0; pcm < codec->num_pcms; pcm++) {
2164                 struct hda_pcm *cpcm = &codec->pcm_info[pcm];
2165                 if (!cpcm->pcm)
2166                         continue;
2167                 if (cpcm->pcm->streams[0].substream_opened ||
2168                     cpcm->pcm->streams[1].substream_opened) {
2169                         hda_unlock_devices(card);
2170                         return -EBUSY;
2171                 }
2172         }
2173
2174         /* OK, let it free */
2175
2176 #ifdef CONFIG_SND_HDA_POWER_SAVE
2177         cancel_delayed_work(&codec->power_work);
2178         flush_workqueue(codec->bus->workq);
2179 #endif
2180         snd_hda_ctls_clear(codec);
2181         /* relase PCMs */
2182         for (i = 0; i < codec->num_pcms; i++) {
2183                 if (codec->pcm_info[i].pcm) {
2184                         snd_device_free(card, codec->pcm_info[i].pcm);
2185                         clear_bit(codec->pcm_info[i].device,
2186                                   codec->bus->pcm_dev_bits);
2187                 }
2188         }
2189         if (codec->patch_ops.free)
2190                 codec->patch_ops.free(codec);
2191         codec->proc_widget_hook = NULL;
2192         codec->spec = NULL;
2193         free_hda_cache(&codec->amp_cache);
2194         free_hda_cache(&codec->cmd_cache);
2195         init_hda_cache(&codec->amp_cache, sizeof(struct hda_amp_info));
2196         init_hda_cache(&codec->cmd_cache, sizeof(struct hda_cache_head));
2197         /* free only driver_pins so that init_pins + user_pins are restored */
2198         snd_array_free(&codec->driver_pins);
2199         restore_pincfgs(codec);
2200         codec->num_pcms = 0;
2201         codec->pcm_info = NULL;
2202         codec->preset = NULL;
2203         memset(&codec->patch_ops, 0, sizeof(codec->patch_ops));
2204         codec->slave_dig_outs = NULL;
2205         codec->spdif_status_reset = 0;
2206         module_put(codec->owner);
2207         codec->owner = NULL;
2208
2209         /* allow device access again */
2210         hda_unlock_devices(card);
2211         return 0;
2212 }
2213
2214 /**
2215  * snd_hda_add_vmaster - create a virtual master control and add slaves
2216  * @codec: HD-audio codec
2217  * @name: vmaster control name
2218  * @tlv: TLV data (optional)
2219  * @slaves: slave control names (optional)
2220  *
2221  * Create a virtual master control with the given name.  The TLV data
2222  * must be either NULL or a valid data.
2223  *
2224  * @slaves is a NULL-terminated array of strings, each of which is a
2225  * slave control name.  All controls with these names are assigned to
2226  * the new virtual master control.
2227  *
2228  * This function returns zero if successful or a negative error code.
2229  */
2230 int snd_hda_add_vmaster(struct hda_codec *codec, char *name,
2231                         unsigned int *tlv, const char * const *slaves)
2232 {
2233         struct snd_kcontrol *kctl;
2234         const char * const *s;
2235         int err;
2236
2237         for (s = slaves; *s && !snd_hda_find_mixer_ctl(codec, *s); s++)
2238                 ;
2239         if (!*s) {
2240                 snd_printdd("No slave found for %s\n", name);
2241                 return 0;
2242         }
2243         kctl = snd_ctl_make_virtual_master(name, tlv);
2244         if (!kctl)
2245                 return -ENOMEM;
2246         err = snd_hda_ctl_add(codec, 0, kctl);
2247         if (err < 0)
2248                 return err;
2249
2250         for (s = slaves; *s; s++) {
2251                 struct snd_kcontrol *sctl;
2252                 int i = 0;
2253                 for (;;) {
2254                         sctl = _snd_hda_find_mixer_ctl(codec, *s, i);
2255                         if (!sctl) {
2256                                 if (!i)
2257                                         snd_printdd("Cannot find slave %s, "
2258                                                     "skipped\n", *s);
2259                                 break;
2260                         }
2261                         err = snd_ctl_add_slave(kctl, sctl);
2262                         if (err < 0)
2263                                 return err;
2264                         i++;
2265                 }
2266         }
2267         return 0;
2268 }
2269 EXPORT_SYMBOL_HDA(snd_hda_add_vmaster);
2270
2271 /**
2272  * snd_hda_mixer_amp_switch_info - Info callback for a standard AMP mixer switch
2273  *
2274  * The control element is supposed to have the private_value field
2275  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2276  */
2277 int snd_hda_mixer_amp_switch_info(struct snd_kcontrol *kcontrol,
2278                                   struct snd_ctl_elem_info *uinfo)
2279 {
2280         int chs = get_amp_channels(kcontrol);
2281
2282         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2283         uinfo->count = chs == 3 ? 2 : 1;
2284         uinfo->value.integer.min = 0;
2285         uinfo->value.integer.max = 1;
2286         return 0;
2287 }
2288 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_info);
2289
2290 /**
2291  * snd_hda_mixer_amp_switch_get - Get callback for a standard AMP mixer switch
2292  *
2293  * The control element is supposed to have the private_value field
2294  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2295  */
2296 int snd_hda_mixer_amp_switch_get(struct snd_kcontrol *kcontrol,
2297                                  struct snd_ctl_elem_value *ucontrol)
2298 {
2299         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2300         hda_nid_t nid = get_amp_nid(kcontrol);
2301         int chs = get_amp_channels(kcontrol);
2302         int dir = get_amp_direction(kcontrol);
2303         int idx = get_amp_index(kcontrol);
2304         long *valp = ucontrol->value.integer.value;
2305
2306         if (chs & 1)
2307                 *valp++ = (snd_hda_codec_amp_read(codec, nid, 0, dir, idx) &
2308                            HDA_AMP_MUTE) ? 0 : 1;
2309         if (chs & 2)
2310                 *valp = (snd_hda_codec_amp_read(codec, nid, 1, dir, idx) &
2311                          HDA_AMP_MUTE) ? 0 : 1;
2312         return 0;
2313 }
2314 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_get);
2315
2316 /**
2317  * snd_hda_mixer_amp_switch_put - Put callback for a standard AMP mixer switch
2318  *
2319  * The control element is supposed to have the private_value field
2320  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2321  */
2322 int snd_hda_mixer_amp_switch_put(struct snd_kcontrol *kcontrol,
2323                                  struct snd_ctl_elem_value *ucontrol)
2324 {
2325         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2326         hda_nid_t nid = get_amp_nid(kcontrol);
2327         int chs = get_amp_channels(kcontrol);
2328         int dir = get_amp_direction(kcontrol);
2329         int idx = get_amp_index(kcontrol);
2330         long *valp = ucontrol->value.integer.value;
2331         int change = 0;
2332
2333         snd_hda_power_up(codec);
2334         if (chs & 1) {
2335                 change = snd_hda_codec_amp_update(codec, nid, 0, dir, idx,
2336                                                   HDA_AMP_MUTE,
2337                                                   *valp ? 0 : HDA_AMP_MUTE);
2338                 valp++;
2339         }
2340         if (chs & 2)
2341                 change |= snd_hda_codec_amp_update(codec, nid, 1, dir, idx,
2342                                                    HDA_AMP_MUTE,
2343                                                    *valp ? 0 : HDA_AMP_MUTE);
2344         hda_call_check_power_status(codec, nid);
2345         snd_hda_power_down(codec);
2346         return change;
2347 }
2348 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_put);
2349
2350 #ifdef CONFIG_SND_HDA_INPUT_BEEP
2351 /**
2352  * snd_hda_mixer_amp_switch_put_beep - Put callback for a beep AMP switch
2353  *
2354  * This function calls snd_hda_enable_beep_device(), which behaves differently
2355  * depending on beep_mode option.
2356  */
2357 int snd_hda_mixer_amp_switch_put_beep(struct snd_kcontrol *kcontrol,
2358                                       struct snd_ctl_elem_value *ucontrol)
2359 {
2360         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2361         long *valp = ucontrol->value.integer.value;
2362
2363         snd_hda_enable_beep_device(codec, *valp);
2364         return snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
2365 }
2366 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_put_beep);
2367 #endif /* CONFIG_SND_HDA_INPUT_BEEP */
2368
2369 /*
2370  * bound volume controls
2371  *
2372  * bind multiple volumes (# indices, from 0)
2373  */
2374
2375 #define AMP_VAL_IDX_SHIFT       19
2376 #define AMP_VAL_IDX_MASK        (0x0f<<19)
2377
2378 /**
2379  * snd_hda_mixer_bind_switch_get - Get callback for a bound volume control
2380  *
2381  * The control element is supposed to have the private_value field
2382  * set up via HDA_BIND_MUTE*() macros.
2383  */
2384 int snd_hda_mixer_bind_switch_get(struct snd_kcontrol *kcontrol,
2385                                   struct snd_ctl_elem_value *ucontrol)
2386 {
2387         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2388         unsigned long pval;
2389         int err;
2390
2391         mutex_lock(&codec->control_mutex);
2392         pval = kcontrol->private_value;
2393         kcontrol->private_value = pval & ~AMP_VAL_IDX_MASK; /* index 0 */
2394         err = snd_hda_mixer_amp_switch_get(kcontrol, ucontrol);
2395         kcontrol->private_value = pval;
2396         mutex_unlock(&codec->control_mutex);
2397         return err;
2398 }
2399 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_switch_get);
2400
2401 /**
2402  * snd_hda_mixer_bind_switch_put - Put callback for a bound volume control
2403  *
2404  * The control element is supposed to have the private_value field
2405  * set up via HDA_BIND_MUTE*() macros.
2406  */
2407 int snd_hda_mixer_bind_switch_put(struct snd_kcontrol *kcontrol,
2408                                   struct snd_ctl_elem_value *ucontrol)
2409 {
2410         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2411         unsigned long pval;
2412         int i, indices, err = 0, change = 0;
2413
2414         mutex_lock(&codec->control_mutex);
2415         pval = kcontrol->private_value;
2416         indices = (pval & AMP_VAL_IDX_MASK) >> AMP_VAL_IDX_SHIFT;
2417         for (i = 0; i < indices; i++) {
2418                 kcontrol->private_value = (pval & ~AMP_VAL_IDX_MASK) |
2419                         (i << AMP_VAL_IDX_SHIFT);
2420                 err = snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
2421                 if (err < 0)
2422                         break;
2423                 change |= err;
2424         }
2425         kcontrol->private_value = pval;
2426         mutex_unlock(&codec->control_mutex);
2427         return err < 0 ? err : change;
2428 }
2429 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_switch_put);
2430
2431 /**
2432  * snd_hda_mixer_bind_ctls_info - Info callback for a generic bound control
2433  *
2434  * The control element is supposed to have the private_value field
2435  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
2436  */
2437 int snd_hda_mixer_bind_ctls_info(struct snd_kcontrol *kcontrol,
2438                                  struct snd_ctl_elem_info *uinfo)
2439 {
2440         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2441         struct hda_bind_ctls *c;
2442         int err;
2443
2444         mutex_lock(&codec->control_mutex);
2445         c = (struct hda_bind_ctls *)kcontrol->private_value;
2446         kcontrol->private_value = *c->values;
2447         err = c->ops->info(kcontrol, uinfo);
2448         kcontrol->private_value = (long)c;
2449         mutex_unlock(&codec->control_mutex);
2450         return err;
2451 }
2452 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_ctls_info);
2453
2454 /**
2455  * snd_hda_mixer_bind_ctls_get - Get callback for a generic bound control
2456  *
2457  * The control element is supposed to have the private_value field
2458  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
2459  */
2460 int snd_hda_mixer_bind_ctls_get(struct snd_kcontrol *kcontrol,
2461                                 struct snd_ctl_elem_value *ucontrol)
2462 {
2463         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2464         struct hda_bind_ctls *c;
2465         int err;
2466
2467         mutex_lock(&codec->control_mutex);
2468         c = (struct hda_bind_ctls *)kcontrol->private_value;
2469         kcontrol->private_value = *c->values;
2470         err = c->ops->get(kcontrol, ucontrol);
2471         kcontrol->private_value = (long)c;
2472         mutex_unlock(&codec->control_mutex);
2473         return err;
2474 }
2475 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_ctls_get);
2476
2477 /**
2478  * snd_hda_mixer_bind_ctls_put - Put callback for a generic bound control
2479  *
2480  * The control element is supposed to have the private_value field
2481  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
2482  */
2483 int snd_hda_mixer_bind_ctls_put(struct snd_kcontrol *kcontrol,
2484                                 struct snd_ctl_elem_value *ucontrol)
2485 {
2486         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2487         struct hda_bind_ctls *c;
2488         unsigned long *vals;
2489         int err = 0, change = 0;
2490
2491         mutex_lock(&codec->control_mutex);
2492         c = (struct hda_bind_ctls *)kcontrol->private_value;
2493         for (vals = c->values; *vals; vals++) {
2494                 kcontrol->private_value = *vals;
2495                 err = c->ops->put(kcontrol, ucontrol);
2496                 if (err < 0)
2497                         break;
2498                 change |= err;
2499         }
2500         kcontrol->private_value = (long)c;
2501         mutex_unlock(&codec->control_mutex);
2502         return err < 0 ? err : change;
2503 }
2504 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_ctls_put);
2505
2506 /**
2507  * snd_hda_mixer_bind_tlv - TLV callback for a generic bound control
2508  *
2509  * The control element is supposed to have the private_value field
2510  * set up via HDA_BIND_VOL() macro.
2511  */
2512 int snd_hda_mixer_bind_tlv(struct snd_kcontrol *kcontrol, int op_flag,
2513                            unsigned int size, unsigned int __user *tlv)
2514 {
2515         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2516         struct hda_bind_ctls *c;
2517         int err;
2518
2519         mutex_lock(&codec->control_mutex);
2520         c = (struct hda_bind_ctls *)kcontrol->private_value;
2521         kcontrol->private_value = *c->values;
2522         err = c->ops->tlv(kcontrol, op_flag, size, tlv);
2523         kcontrol->private_value = (long)c;
2524         mutex_unlock(&codec->control_mutex);
2525         return err;
2526 }
2527 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_tlv);
2528
2529 struct hda_ctl_ops snd_hda_bind_vol = {
2530         .info = snd_hda_mixer_amp_volume_info,
2531         .get = snd_hda_mixer_amp_volume_get,
2532         .put = snd_hda_mixer_amp_volume_put,
2533         .tlv = snd_hda_mixer_amp_tlv
2534 };
2535 EXPORT_SYMBOL_HDA(snd_hda_bind_vol);
2536
2537 struct hda_ctl_ops snd_hda_bind_sw = {
2538         .info = snd_hda_mixer_amp_switch_info,
2539         .get = snd_hda_mixer_amp_switch_get,
2540         .put = snd_hda_mixer_amp_switch_put,
2541         .tlv = snd_hda_mixer_amp_tlv
2542 };
2543 EXPORT_SYMBOL_HDA(snd_hda_bind_sw);
2544
2545 /*
2546  * SPDIF out controls
2547  */
2548
2549 static int snd_hda_spdif_mask_info(struct snd_kcontrol *kcontrol,
2550                                    struct snd_ctl_elem_info *uinfo)
2551 {
2552         uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
2553         uinfo->count = 1;
2554         return 0;
2555 }
2556
2557 static int snd_hda_spdif_cmask_get(struct snd_kcontrol *kcontrol,
2558                                    struct snd_ctl_elem_value *ucontrol)
2559 {
2560         ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
2561                                            IEC958_AES0_NONAUDIO |
2562                                            IEC958_AES0_CON_EMPHASIS_5015 |
2563                                            IEC958_AES0_CON_NOT_COPYRIGHT;
2564         ucontrol->value.iec958.status[1] = IEC958_AES1_CON_CATEGORY |
2565                                            IEC958_AES1_CON_ORIGINAL;
2566         return 0;
2567 }
2568
2569 static int snd_hda_spdif_pmask_get(struct snd_kcontrol *kcontrol,
2570                                    struct snd_ctl_elem_value *ucontrol)
2571 {
2572         ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
2573                                            IEC958_AES0_NONAUDIO |
2574                                            IEC958_AES0_PRO_EMPHASIS_5015;
2575         return 0;
2576 }
2577
2578 static int snd_hda_spdif_default_get(struct snd_kcontrol *kcontrol,
2579                                      struct snd_ctl_elem_value *ucontrol)
2580 {
2581         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2582         int idx = kcontrol->private_value;
2583         struct hda_spdif_out *spdif = snd_array_elem(&codec->spdif_out, idx);
2584
2585         ucontrol->value.iec958.status[0] = spdif->status & 0xff;
2586         ucontrol->value.iec958.status[1] = (spdif->status >> 8) & 0xff;
2587         ucontrol->value.iec958.status[2] = (spdif->status >> 16) & 0xff;
2588         ucontrol->value.iec958.status[3] = (spdif->status >> 24) & 0xff;
2589
2590         return 0;
2591 }
2592
2593 /* convert from SPDIF status bits to HDA SPDIF bits
2594  * bit 0 (DigEn) is always set zero (to be filled later)
2595  */
2596 static unsigned short convert_from_spdif_status(unsigned int sbits)
2597 {
2598         unsigned short val = 0;
2599
2600         if (sbits & IEC958_AES0_PROFESSIONAL)
2601                 val |= AC_DIG1_PROFESSIONAL;
2602         if (sbits & IEC958_AES0_NONAUDIO)
2603                 val |= AC_DIG1_NONAUDIO;
2604         if (sbits & IEC958_AES0_PROFESSIONAL) {
2605                 if ((sbits & IEC958_AES0_PRO_EMPHASIS) ==
2606                     IEC958_AES0_PRO_EMPHASIS_5015)
2607                         val |= AC_DIG1_EMPHASIS;
2608         } else {
2609                 if ((sbits & IEC958_AES0_CON_EMPHASIS) ==
2610                     IEC958_AES0_CON_EMPHASIS_5015)
2611                         val |= AC_DIG1_EMPHASIS;
2612                 if (!(sbits & IEC958_AES0_CON_NOT_COPYRIGHT))
2613                         val |= AC_DIG1_COPYRIGHT;
2614                 if (sbits & (IEC958_AES1_CON_ORIGINAL << 8))
2615                         val |= AC_DIG1_LEVEL;
2616                 val |= sbits & (IEC958_AES1_CON_CATEGORY << 8);
2617         }
2618         return val;
2619 }
2620
2621 /* convert to SPDIF status bits from HDA SPDIF bits
2622  */
2623 static unsigned int convert_to_spdif_status(unsigned short val)
2624 {
2625         unsigned int sbits = 0;
2626
2627         if (val & AC_DIG1_NONAUDIO)
2628                 sbits |= IEC958_AES0_NONAUDIO;
2629         if (val & AC_DIG1_PROFESSIONAL)
2630                 sbits |= IEC958_AES0_PROFESSIONAL;
2631         if (sbits & IEC958_AES0_PROFESSIONAL) {
2632                 if (sbits & AC_DIG1_EMPHASIS)
2633                         sbits |= IEC958_AES0_PRO_EMPHASIS_5015;
2634         } else {
2635                 if (val & AC_DIG1_EMPHASIS)
2636                         sbits |= IEC958_AES0_CON_EMPHASIS_5015;
2637                 if (!(val & AC_DIG1_COPYRIGHT))
2638                         sbits |= IEC958_AES0_CON_NOT_COPYRIGHT;
2639                 if (val & AC_DIG1_LEVEL)
2640                         sbits |= (IEC958_AES1_CON_ORIGINAL << 8);
2641                 sbits |= val & (0x7f << 8);
2642         }
2643         return sbits;
2644 }
2645
2646 /* set digital convert verbs both for the given NID and its slaves */
2647 static void set_dig_out(struct hda_codec *codec, hda_nid_t nid,
2648                         int verb, int val)
2649 {
2650         const hda_nid_t *d;
2651
2652         snd_hda_codec_write_cache(codec, nid, 0, verb, val);
2653         d = codec->slave_dig_outs;
2654         if (!d)
2655                 return;
2656         for (; *d; d++)
2657                 snd_hda_codec_write_cache(codec, *d, 0, verb, val);
2658 }
2659
2660 static inline void set_dig_out_convert(struct hda_codec *codec, hda_nid_t nid,
2661                                        int dig1, int dig2)
2662 {
2663         if (dig1 != -1)
2664                 set_dig_out(codec, nid, AC_VERB_SET_DIGI_CONVERT_1, dig1);
2665         if (dig2 != -1)
2666                 set_dig_out(codec, nid, AC_VERB_SET_DIGI_CONVERT_2, dig2);
2667 }
2668
2669 static int snd_hda_spdif_default_put(struct snd_kcontrol *kcontrol,
2670                                      struct snd_ctl_elem_value *ucontrol)
2671 {
2672         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2673         int idx = kcontrol->private_value;
2674         struct hda_spdif_out *spdif = snd_array_elem(&codec->spdif_out, idx);
2675         hda_nid_t nid = spdif->nid;
2676         unsigned short val;
2677         int change;
2678
2679         mutex_lock(&codec->spdif_mutex);
2680         spdif->status = ucontrol->value.iec958.status[0] |
2681                 ((unsigned int)ucontrol->value.iec958.status[1] << 8) |
2682                 ((unsigned int)ucontrol->value.iec958.status[2] << 16) |
2683                 ((unsigned int)ucontrol->value.iec958.status[3] << 24);
2684         val = convert_from_spdif_status(spdif->status);
2685         val |= spdif->ctls & 1;
2686         change = spdif->ctls != val;
2687         spdif->ctls = val;
2688         if (change && nid != (u16)-1)
2689                 set_dig_out_convert(codec, nid, val & 0xff, (val >> 8) & 0xff);
2690         mutex_unlock(&codec->spdif_mutex);
2691         return change;
2692 }
2693
2694 #define snd_hda_spdif_out_switch_info   snd_ctl_boolean_mono_info
2695
2696 static int snd_hda_spdif_out_switch_get(struct snd_kcontrol *kcontrol,
2697                                         struct snd_ctl_elem_value *ucontrol)
2698 {
2699         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2700         int idx = kcontrol->private_value;
2701         struct hda_spdif_out *spdif = snd_array_elem(&codec->spdif_out, idx);
2702
2703         ucontrol->value.integer.value[0] = spdif->ctls & AC_DIG1_ENABLE;
2704         return 0;
2705 }
2706
2707 static inline void set_spdif_ctls(struct hda_codec *codec, hda_nid_t nid,
2708                                   int dig1, int dig2)
2709 {
2710         set_dig_out_convert(codec, nid, dig1, dig2);
2711         /* unmute amp switch (if any) */
2712         if ((get_wcaps(codec, nid) & AC_WCAP_OUT_AMP) &&
2713             (dig1 & AC_DIG1_ENABLE))
2714                 snd_hda_codec_amp_stereo(codec, nid, HDA_OUTPUT, 0,
2715                                             HDA_AMP_MUTE, 0);
2716 }
2717
2718 static int snd_hda_spdif_out_switch_put(struct snd_kcontrol *kcontrol,
2719                                         struct snd_ctl_elem_value *ucontrol)
2720 {
2721         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2722         int idx = kcontrol->private_value;
2723         struct hda_spdif_out *spdif = snd_array_elem(&codec->spdif_out, idx);
2724         hda_nid_t nid = spdif->nid;
2725         unsigned short val;
2726         int change;
2727
2728         mutex_lock(&codec->spdif_mutex);
2729         val = spdif->ctls & ~AC_DIG1_ENABLE;
2730         if (ucontrol->value.integer.value[0])
2731                 val |= AC_DIG1_ENABLE;
2732         change = spdif->ctls != val;
2733         spdif->ctls = val;
2734         if (change && nid != (u16)-1)
2735                 set_spdif_ctls(codec, nid, val & 0xff, -1);
2736         mutex_unlock(&codec->spdif_mutex);
2737         return change;
2738 }
2739
2740 static struct snd_kcontrol_new dig_mixes[] = {
2741         {
2742                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
2743                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2744                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, CON_MASK),
2745                 .info = snd_hda_spdif_mask_info,
2746                 .get = snd_hda_spdif_cmask_get,
2747         },
2748         {
2749                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
2750                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2751                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, PRO_MASK),
2752                 .info = snd_hda_spdif_mask_info,
2753                 .get = snd_hda_spdif_pmask_get,
2754         },
2755         {
2756                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2757                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, DEFAULT),
2758                 .info = snd_hda_spdif_mask_info,
2759                 .get = snd_hda_spdif_default_get,
2760                 .put = snd_hda_spdif_default_put,
2761         },
2762         {
2763                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2764                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, SWITCH),
2765                 .info = snd_hda_spdif_out_switch_info,
2766                 .get = snd_hda_spdif_out_switch_get,
2767                 .put = snd_hda_spdif_out_switch_put,
2768         },
2769         { } /* end */
2770 };
2771
2772 /**
2773  * snd_hda_create_spdif_out_ctls - create Output SPDIF-related controls
2774  * @codec: the HDA codec
2775  * @nid: audio out widget NID
2776  *
2777  * Creates controls related with the SPDIF output.
2778  * Called from each patch supporting the SPDIF out.
2779  *
2780  * Returns 0 if successful, or a negative error code.
2781  */
2782 int snd_hda_create_spdif_out_ctls(struct hda_codec *codec,
2783                                   hda_nid_t associated_nid,
2784                                   hda_nid_t cvt_nid)
2785 {
2786         int err;
2787         struct snd_kcontrol *kctl;
2788         struct snd_kcontrol_new *dig_mix;
2789         int idx;
2790         struct hda_spdif_out *spdif;
2791
2792         idx = find_empty_mixer_ctl_idx(codec, "IEC958 Playback Switch");
2793         if (idx < 0) {
2794                 printk(KERN_ERR "hda_codec: too many IEC958 outputs\n");
2795                 return -EBUSY;
2796         }
2797         spdif = snd_array_new(&codec->spdif_out);
2798         for (dig_mix = dig_mixes; dig_mix->name; dig_mix++) {
2799                 kctl = snd_ctl_new1(dig_mix, codec);
2800                 if (!kctl)
2801                         return -ENOMEM;
2802                 kctl->id.index = idx;
2803                 kctl->private_value = codec->spdif_out.used - 1;
2804                 err = snd_hda_ctl_add(codec, associated_nid, kctl);
2805                 if (err < 0)
2806                         return err;
2807         }
2808         spdif->nid = cvt_nid;
2809         spdif->ctls = snd_hda_codec_read(codec, cvt_nid, 0,
2810                                          AC_VERB_GET_DIGI_CONVERT_1, 0);
2811         spdif->status = convert_to_spdif_status(spdif->ctls);
2812         return 0;
2813 }
2814 EXPORT_SYMBOL_HDA(snd_hda_create_spdif_out_ctls);
2815
2816 struct hda_spdif_out *snd_hda_spdif_out_of_nid(struct hda_codec *codec,
2817                                                hda_nid_t nid)
2818 {
2819         int i;
2820         for (i = 0; i < codec->spdif_out.used; i++) {
2821                 struct hda_spdif_out *spdif =
2822                                 snd_array_elem(&codec->spdif_out, i);
2823                 if (spdif->nid == nid)
2824                         return spdif;
2825         }
2826         return NULL;
2827 }
2828 EXPORT_SYMBOL_HDA(snd_hda_spdif_out_of_nid);
2829
2830 void snd_hda_spdif_ctls_unassign(struct hda_codec *codec, int idx)
2831 {
2832         struct hda_spdif_out *spdif = snd_array_elem(&codec->spdif_out, idx);
2833
2834         mutex_lock(&codec->spdif_mutex);
2835         spdif->nid = (u16)-1;
2836         mutex_unlock(&codec->spdif_mutex);
2837 }
2838 EXPORT_SYMBOL_HDA(snd_hda_spdif_ctls_unassign);
2839
2840 void snd_hda_spdif_ctls_assign(struct hda_codec *codec, int idx, hda_nid_t nid)
2841 {
2842         struct hda_spdif_out *spdif = snd_array_elem(&codec->spdif_out, idx);
2843         unsigned short val;
2844
2845         mutex_lock(&codec->spdif_mutex);
2846         if (spdif->nid != nid) {
2847                 spdif->nid = nid;
2848                 val = spdif->ctls;
2849                 set_spdif_ctls(codec, nid, val & 0xff, (val >> 8) & 0xff);
2850         }
2851         mutex_unlock(&codec->spdif_mutex);
2852 }
2853 EXPORT_SYMBOL_HDA(snd_hda_spdif_ctls_assign);
2854
2855 /*
2856  * SPDIF sharing with analog output
2857  */
2858 static int spdif_share_sw_get(struct snd_kcontrol *kcontrol,
2859                               struct snd_ctl_elem_value *ucontrol)
2860 {
2861         struct hda_multi_out *mout = snd_kcontrol_chip(kcontrol);
2862         ucontrol->value.integer.value[0] = mout->share_spdif;
2863         return 0;
2864 }
2865
2866 static int spdif_share_sw_put(struct snd_kcontrol *kcontrol,
2867                               struct snd_ctl_elem_value *ucontrol)
2868 {
2869         struct hda_multi_out *mout = snd_kcontrol_chip(kcontrol);
2870         mout->share_spdif = !!ucontrol->value.integer.value[0];
2871         return 0;
2872 }
2873
2874 static struct snd_kcontrol_new spdif_share_sw = {
2875         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2876         .name = "IEC958 Default PCM Playback Switch",
2877         .info = snd_ctl_boolean_mono_info,
2878         .get = spdif_share_sw_get,
2879         .put = spdif_share_sw_put,
2880 };
2881
2882 /**
2883  * snd_hda_create_spdif_share_sw - create Default PCM switch
2884  * @codec: the HDA codec
2885  * @mout: multi-out instance
2886  */
2887 int snd_hda_create_spdif_share_sw(struct hda_codec *codec,
2888                                   struct hda_multi_out *mout)
2889 {
2890         if (!mout->dig_out_nid)
2891                 return 0;
2892         /* ATTENTION: here mout is passed as private_data, instead of codec */
2893         return snd_hda_ctl_add(codec, mout->dig_out_nid,
2894                               snd_ctl_new1(&spdif_share_sw, mout));
2895 }
2896 EXPORT_SYMBOL_HDA(snd_hda_create_spdif_share_sw);
2897
2898 /*
2899  * SPDIF input
2900  */
2901
2902 #define snd_hda_spdif_in_switch_info    snd_hda_spdif_out_switch_info
2903
2904 static int snd_hda_spdif_in_switch_get(struct snd_kcontrol *kcontrol,
2905                                        struct snd_ctl_elem_value *ucontrol)
2906 {
2907         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2908
2909         ucontrol->value.integer.value[0] = codec->spdif_in_enable;
2910         return 0;
2911 }
2912
2913 static int snd_hda_spdif_in_switch_put(struct snd_kcontrol *kcontrol,
2914                                        struct snd_ctl_elem_value *ucontrol)
2915 {
2916         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2917         hda_nid_t nid = kcontrol->private_value;
2918         unsigned int val = !!ucontrol->value.integer.value[0];
2919         int change;
2920
2921         mutex_lock(&codec->spdif_mutex);
2922         change = codec->spdif_in_enable != val;
2923         if (change) {
2924                 codec->spdif_in_enable = val;
2925                 snd_hda_codec_write_cache(codec, nid, 0,
2926                                           AC_VERB_SET_DIGI_CONVERT_1, val);
2927         }
2928         mutex_unlock(&codec->spdif_mutex);
2929         return change;
2930 }
2931
2932 static int snd_hda_spdif_in_status_get(struct snd_kcontrol *kcontrol,
2933                                        struct snd_ctl_elem_value *ucontrol)
2934 {
2935         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2936         hda_nid_t nid = kcontrol->private_value;
2937         unsigned short val;
2938         unsigned int sbits;
2939
2940         val = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_DIGI_CONVERT_1, 0);
2941         sbits = convert_to_spdif_status(val);
2942         ucontrol->value.iec958.status[0] = sbits;
2943         ucontrol->value.iec958.status[1] = sbits >> 8;
2944         ucontrol->value.iec958.status[2] = sbits >> 16;
2945         ucontrol->value.iec958.status[3] = sbits >> 24;
2946         return 0;
2947 }
2948
2949 static struct snd_kcontrol_new dig_in_ctls[] = {
2950         {
2951                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2952                 .name = SNDRV_CTL_NAME_IEC958("", CAPTURE, SWITCH),
2953                 .info = snd_hda_spdif_in_switch_info,
2954                 .get = snd_hda_spdif_in_switch_get,
2955                 .put = snd_hda_spdif_in_switch_put,
2956         },
2957         {
2958                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
2959                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2960                 .name = SNDRV_CTL_NAME_IEC958("", CAPTURE, DEFAULT),
2961                 .info = snd_hda_spdif_mask_info,
2962                 .get = snd_hda_spdif_in_status_get,
2963         },
2964         { } /* end */
2965 };
2966
2967 /**
2968  * snd_hda_create_spdif_in_ctls - create Input SPDIF-related controls
2969  * @codec: the HDA codec
2970  * @nid: audio in widget NID
2971  *
2972  * Creates controls related with the SPDIF input.
2973  * Called from each patch supporting the SPDIF in.
2974  *
2975  * Returns 0 if successful, or a negative error code.
2976  */
2977 int snd_hda_create_spdif_in_ctls(struct hda_codec *codec, hda_nid_t nid)
2978 {
2979         int err;
2980         struct snd_kcontrol *kctl;
2981         struct snd_kcontrol_new *dig_mix;
2982         int idx;
2983
2984         idx = find_empty_mixer_ctl_idx(codec, "IEC958 Capture Switch");
2985         if (idx < 0) {
2986                 printk(KERN_ERR "hda_codec: too many IEC958 inputs\n");
2987                 return -EBUSY;
2988         }
2989         for (dig_mix = dig_in_ctls; dig_mix->name; dig_mix++) {
2990                 kctl = snd_ctl_new1(dig_mix, codec);
2991                 if (!kctl)
2992                         return -ENOMEM;
2993                 kctl->private_value = nid;
2994                 err = snd_hda_ctl_add(codec, nid, kctl);
2995                 if (err < 0)
2996                         return err;
2997         }
2998         codec->spdif_in_enable =
2999                 snd_hda_codec_read(codec, nid, 0,
3000                                    AC_VERB_GET_DIGI_CONVERT_1, 0) &
3001                 AC_DIG1_ENABLE;
3002         return 0;
3003 }
3004 EXPORT_SYMBOL_HDA(snd_hda_create_spdif_in_ctls);
3005
3006 #ifdef SND_HDA_NEEDS_RESUME
3007 /*
3008  * command cache
3009  */
3010
3011 /* build a 32bit cache key with the widget id and the command parameter */
3012 #define build_cmd_cache_key(nid, verb)  ((verb << 8) | nid)
3013 #define get_cmd_cache_nid(key)          ((key) & 0xff)
3014 #define get_cmd_cache_cmd(key)          (((key) >> 8) & 0xffff)
3015
3016 /**
3017  * snd_hda_codec_write_cache - send a single command with caching
3018  * @codec: the HDA codec
3019  * @nid: NID to send the command
3020  * @direct: direct flag
3021  * @verb: the verb to send
3022  * @parm: the parameter for the verb
3023  *
3024  * Send a single command without waiting for response.
3025  *
3026  * Returns 0 if successful, or a negative error code.
3027  */
3028 int snd_hda_codec_write_cache(struct hda_codec *codec, hda_nid_t nid,
3029                               int direct, unsigned int verb, unsigned int parm)
3030 {
3031         int err = snd_hda_codec_write(codec, nid, direct, verb, parm);
3032         struct hda_cache_head *c;
3033         u32 key;
3034
3035         if (err < 0)
3036                 return err;
3037         /* parm may contain the verb stuff for get/set amp */
3038         verb = verb | (parm >> 8);
3039         parm &= 0xff;
3040         key = build_cmd_cache_key(nid, verb);
3041         mutex_lock(&codec->bus->cmd_mutex);
3042         c = get_alloc_hash(&codec->cmd_cache, key);
3043         if (c)
3044                 c->val = parm;
3045         mutex_unlock(&codec->bus->cmd_mutex);
3046         return 0;
3047 }
3048 EXPORT_SYMBOL_HDA(snd_hda_codec_write_cache);
3049
3050 /**
3051  * snd_hda_codec_update_cache - check cache and write the cmd only when needed
3052  * @codec: the HDA codec
3053  * @nid: NID to send the command
3054  * @direct: direct flag
3055  * @verb: the verb to send
3056  * @parm: the parameter for the verb
3057  *
3058  * This function works like snd_hda_codec_write_cache(), but it doesn't send
3059  * command if the parameter is already identical with the cached value.
3060  * If not, it sends the command and refreshes the cache.
3061  *
3062  * Returns 0 if successful, or a negative error code.
3063  */
3064 int snd_hda_codec_update_cache(struct hda_codec *codec, hda_nid_t nid,
3065                                int direct, unsigned int verb, unsigned int parm)
3066 {
3067         struct hda_cache_head *c;
3068         u32 key;
3069
3070         /* parm may contain the verb stuff for get/set amp */
3071         verb = verb | (parm >> 8);
3072         parm &= 0xff;
3073         key = build_cmd_cache_key(nid, verb);
3074         mutex_lock(&codec->bus->cmd_mutex);
3075         c = get_hash(&codec->cmd_cache, key);
3076         if (c && c->val == parm) {
3077                 mutex_unlock(&codec->bus->cmd_mutex);
3078                 return 0;
3079         }
3080         mutex_unlock(&codec->bus->cmd_mutex);
3081         return snd_hda_codec_write_cache(codec, nid, direct, verb, parm);
3082 }
3083 EXPORT_SYMBOL_HDA(snd_hda_codec_update_cache);
3084
3085 /**
3086  * snd_hda_codec_resume_cache - Resume the all commands from the cache
3087  * @codec: HD-audio codec
3088  *
3089  * Execute all verbs recorded in the command caches to resume.
3090  */
3091 void snd_hda_codec_resume_cache(struct hda_codec *codec)
3092 {
3093         struct hda_cache_head *buffer = codec->cmd_cache.buf.list;
3094         int i;
3095
3096         for (i = 0; i < codec->cmd_cache.buf.used; i++, buffer++) {
3097                 u32 key = buffer->key;
3098                 if (!key)
3099                         continue;
3100                 snd_hda_codec_write(codec, get_cmd_cache_nid(key), 0,
3101                                     get_cmd_cache_cmd(key), buffer->val);
3102         }
3103 }
3104 EXPORT_SYMBOL_HDA(snd_hda_codec_resume_cache);
3105
3106 /**
3107  * snd_hda_sequence_write_cache - sequence writes with caching
3108  * @codec: the HDA codec
3109  * @seq: VERB array to send
3110  *
3111  * Send the commands sequentially from the given array.
3112  * Thte commands are recorded on cache for power-save and resume.
3113  * The array must be terminated with NID=0.
3114  */
3115 void snd_hda_sequence_write_cache(struct hda_codec *codec,
3116                                   const struct hda_verb *seq)
3117 {
3118         for (; seq->nid; seq++)
3119                 snd_hda_codec_write_cache(codec, seq->nid, 0, seq->verb,
3120                                           seq->param);
3121 }
3122 EXPORT_SYMBOL_HDA(snd_hda_sequence_write_cache);
3123 #endif /* SND_HDA_NEEDS_RESUME */
3124
3125 /*
3126  * set power state of the codec
3127  */
3128 static void hda_set_power_state(struct hda_codec *codec, hda_nid_t fg,
3129                                 unsigned int power_state)
3130 {
3131         hda_nid_t nid;
3132         int i;
3133
3134         /* this delay seems necessary to avoid click noise at power-down */
3135         if (power_state == AC_PWRST_D3)
3136                 msleep(100);
3137         snd_hda_codec_read(codec, fg, 0, AC_VERB_SET_POWER_STATE,
3138                             power_state);
3139         /* partial workaround for "azx_get_response timeout" */
3140         if (power_state == AC_PWRST_D0 &&
3141             (codec->vendor_id & 0xffff0000) == 0x14f10000)
3142                 msleep(10);
3143
3144         nid = codec->start_nid;
3145         for (i = 0; i < codec->num_nodes; i++, nid++) {
3146                 unsigned int wcaps = get_wcaps(codec, nid);
3147                 if (wcaps & AC_WCAP_POWER) {
3148                         unsigned int wid_type = get_wcaps_type(wcaps);
3149                         if (power_state == AC_PWRST_D3 &&
3150                             wid_type == AC_WID_PIN) {
3151                                 unsigned int pincap;
3152                                 /*
3153                                  * don't power down the widget if it controls
3154                                  * eapd and EAPD_BTLENABLE is set.
3155                                  */
3156                                 pincap = snd_hda_query_pin_caps(codec, nid);
3157                                 if (pincap & AC_PINCAP_EAPD) {
3158                                         int eapd = snd_hda_codec_read(codec,
3159                                                 nid, 0,
3160                                                 AC_VERB_GET_EAPD_BTLENABLE, 0);
3161                                         eapd &= 0x02;
3162                                         if (eapd)
3163                                                 continue;
3164                                 }
3165                         }
3166                         snd_hda_codec_write(codec, nid, 0,
3167                                             AC_VERB_SET_POWER_STATE,
3168                                             power_state);
3169                 }
3170         }
3171
3172         if (power_state == AC_PWRST_D0) {
3173                 unsigned long end_time;
3174                 int state;
3175                 /* wait until the codec reachs to D0 */
3176                 end_time = jiffies + msecs_to_jiffies(500);
3177                 do {
3178                         state = snd_hda_codec_read(codec, fg, 0,
3179                                                    AC_VERB_GET_POWER_STATE, 0);
3180                         if (state == power_state)
3181                                 break;
3182                         msleep(1);
3183                 } while (time_after_eq(end_time, jiffies));
3184         }
3185 }
3186
3187 #ifdef CONFIG_SND_HDA_HWDEP
3188 /* execute additional init verbs */
3189 static void hda_exec_init_verbs(struct hda_codec *codec)
3190 {
3191         if (codec->init_verbs.list)
3192                 snd_hda_sequence_write(codec, codec->init_verbs.list);
3193 }
3194 #else
3195 static inline void hda_exec_init_verbs(struct hda_codec *codec) {}
3196 #endif
3197
3198 #ifdef SND_HDA_NEEDS_RESUME
3199 /*
3200  * call suspend and power-down; used both from PM and power-save
3201  */
3202 static void hda_call_codec_suspend(struct hda_codec *codec)
3203 {
3204         if (codec->patch_ops.suspend)
3205                 codec->patch_ops.suspend(codec, PMSG_SUSPEND);
3206         hda_cleanup_all_streams(codec);
3207         hda_set_power_state(codec,
3208                             codec->afg ? codec->afg : codec->mfg,
3209                             AC_PWRST_D3);
3210 #ifdef CONFIG_SND_HDA_POWER_SAVE
3211         snd_hda_update_power_acct(codec);
3212         cancel_delayed_work(&codec->power_work);
3213         codec->power_on = 0;
3214         codec->power_transition = 0;
3215         codec->power_jiffies = jiffies;
3216 #endif
3217 }
3218
3219 /*
3220  * kick up codec; used both from PM and power-save
3221  */
3222 static void hda_call_codec_resume(struct hda_codec *codec)
3223 {
3224         hda_set_power_state(codec,
3225                             codec->afg ? codec->afg : codec->mfg,
3226                             AC_PWRST_D0);
3227         restore_pincfgs(codec); /* restore all current pin configs */
3228         restore_shutup_pins(codec);
3229         hda_exec_init_verbs(codec);
3230         if (codec->patch_ops.resume)
3231                 codec->patch_ops.resume(codec);
3232         else {
3233                 if (codec->patch_ops.init)
3234                         codec->patch_ops.init(codec);
3235                 snd_hda_codec_resume_amp(codec);
3236                 snd_hda_codec_resume_cache(codec);
3237         }
3238 }
3239 #endif /* SND_HDA_NEEDS_RESUME */
3240
3241
3242 /**
3243  * snd_hda_build_controls - build mixer controls
3244  * @bus: the BUS
3245  *
3246  * Creates mixer controls for each codec included in the bus.
3247  *
3248  * Returns 0 if successful, otherwise a negative error code.
3249  */
3250 int /*__devinit*/ snd_hda_build_controls(struct hda_bus *bus)
3251 {
3252         struct hda_codec *codec;
3253
3254         list_for_each_entry(codec, &bus->codec_list, list) {
3255                 int err = snd_hda_codec_build_controls(codec);
3256                 if (err < 0) {
3257                         printk(KERN_ERR "hda_codec: cannot build controls "
3258                                "for #%d (error %d)\n", codec->addr, err);
3259                         err = snd_hda_codec_reset(codec);
3260                         if (err < 0) {
3261                                 printk(KERN_ERR
3262                                        "hda_codec: cannot revert codec\n");
3263                                 return err;
3264                         }
3265                 }
3266         }
3267         return 0;
3268 }
3269 EXPORT_SYMBOL_HDA(snd_hda_build_controls);
3270
3271 int snd_hda_codec_build_controls(struct hda_codec *codec)
3272 {
3273         int err = 0;
3274         hda_exec_init_verbs(codec);
3275         /* continue to initialize... */
3276         if (codec->patch_ops.init)
3277                 err = codec->patch_ops.init(codec);
3278         if (!err && codec->patch_ops.build_controls)
3279                 err = codec->patch_ops.build_controls(codec);
3280         if (err < 0)
3281                 return err;
3282         return 0;
3283 }
3284
3285 /*
3286  * stream formats
3287  */
3288 struct hda_rate_tbl {
3289         unsigned int hz;
3290         unsigned int alsa_bits;
3291         unsigned int hda_fmt;
3292 };
3293
3294 /* rate = base * mult / div */
3295 #define HDA_RATE(base, mult, div) \
3296         (AC_FMT_BASE_##base##K | (((mult) - 1) << AC_FMT_MULT_SHIFT) | \
3297          (((div) - 1) << AC_FMT_DIV_SHIFT))
3298
3299 static struct hda_rate_tbl rate_bits[] = {
3300         /* rate in Hz, ALSA rate bitmask, HDA format value */
3301
3302         /* autodetected value used in snd_hda_query_supported_pcm */
3303         { 8000, SNDRV_PCM_RATE_8000, HDA_RATE(48, 1, 6) },
3304         { 11025, SNDRV_PCM_RATE_11025, HDA_RATE(44, 1, 4) },
3305         { 16000, SNDRV_PCM_RATE_16000, HDA_RATE(48, 1, 3) },
3306         { 22050, SNDRV_PCM_RATE_22050, HDA_RATE(44, 1, 2) },
3307         { 32000, SNDRV_PCM_RATE_32000, HDA_RATE(48, 2, 3) },
3308         { 44100, SNDRV_PCM_RATE_44100, HDA_RATE(44, 1, 1) },
3309         { 48000, SNDRV_PCM_RATE_48000, HDA_RATE(48, 1, 1) },
3310         { 88200, SNDRV_PCM_RATE_88200, HDA_RATE(44, 2, 1) },
3311         { 96000, SNDRV_PCM_RATE_96000, HDA_RATE(48, 2, 1) },
3312         { 176400, SNDRV_PCM_RATE_176400, HDA_RATE(44, 4, 1) },
3313         { 192000, SNDRV_PCM_RATE_192000, HDA_RATE(48, 4, 1) },
3314 #define AC_PAR_PCM_RATE_BITS    11
3315         /* up to bits 10, 384kHZ isn't supported properly */
3316
3317         /* not autodetected value */
3318         { 9600, SNDRV_PCM_RATE_KNOT, HDA_RATE(48, 1, 5) },
3319
3320         { 0 } /* terminator */
3321 };
3322
3323 /**
3324  * snd_hda_calc_stream_format - calculate format bitset
3325  * @rate: the sample rate
3326  * @channels: the number of channels
3327  * @format: the PCM format (SNDRV_PCM_FORMAT_XXX)
3328  * @maxbps: the max. bps
3329  *
3330  * Calculate the format bitset from the given rate, channels and th PCM format.
3331  *
3332  * Return zero if invalid.
3333  */
3334 unsigned int snd_hda_calc_stream_format(unsigned int rate,
3335                                         unsigned int channels,
3336                                         unsigned int format,
3337                                         unsigned int maxbps,
3338                                         unsigned short spdif_ctls)
3339 {
3340         int i;
3341         unsigned int val = 0;
3342
3343         for (i = 0; rate_bits[i].hz; i++)
3344                 if (rate_bits[i].hz == rate) {
3345                         val = rate_bits[i].hda_fmt;
3346                         break;
3347                 }
3348         if (!rate_bits[i].hz) {
3349                 snd_printdd("invalid rate %d\n", rate);
3350                 return 0;
3351         }
3352
3353         if (channels == 0 || channels > 8) {
3354                 snd_printdd("invalid channels %d\n", channels);
3355                 return 0;
3356         }
3357         val |= channels - 1;
3358
3359         switch (snd_pcm_format_width(format)) {
3360         case 8:
3361                 val |= AC_FMT_BITS_8;
3362                 break;
3363         case 16:
3364                 val |= AC_FMT_BITS_16;
3365                 break;
3366         case 20:
3367         case 24:
3368         case 32:
3369                 if (maxbps >= 32 || format == SNDRV_PCM_FORMAT_FLOAT_LE)
3370                         val |= AC_FMT_BITS_32;
3371                 else if (maxbps >= 24)
3372                         val |= AC_FMT_BITS_24;
3373                 else
3374                         val |= AC_FMT_BITS_20;
3375                 break;
3376         default:
3377                 snd_printdd("invalid format width %d\n",
3378                             snd_pcm_format_width(format));
3379                 return 0;
3380         }
3381
3382         if (spdif_ctls & AC_DIG1_NONAUDIO)
3383                 val |= AC_FMT_TYPE_NON_PCM;
3384
3385         return val;
3386 }
3387 EXPORT_SYMBOL_HDA(snd_hda_calc_stream_format);
3388
3389 static unsigned int get_pcm_param(struct hda_codec *codec, hda_nid_t nid)
3390 {
3391         unsigned int val = 0;
3392         if (nid != codec->afg &&
3393             (get_wcaps(codec, nid) & AC_WCAP_FORMAT_OVRD))
3394                 val = snd_hda_param_read(codec, nid, AC_PAR_PCM);
3395         if (!val || val == -1)
3396                 val = snd_hda_param_read(codec, codec->afg, AC_PAR_PCM);
3397         if (!val || val == -1)
3398                 return 0;
3399         return val;
3400 }
3401
3402 static unsigned int query_pcm_param(struct hda_codec *codec, hda_nid_t nid)
3403 {
3404         return query_caps_hash(codec, nid, HDA_HASH_PARPCM_KEY(nid),
3405                                get_pcm_param);
3406 }
3407
3408 static unsigned int get_stream_param(struct hda_codec *codec, hda_nid_t nid)
3409 {
3410         unsigned int streams = snd_hda_param_read(codec, nid, AC_PAR_STREAM);
3411         if (!streams || streams == -1)
3412                 streams = snd_hda_param_read(codec, codec->afg, AC_PAR_STREAM);
3413         if (!streams || streams == -1)
3414                 return 0;
3415         return streams;
3416 }
3417
3418 static unsigned int query_stream_param(struct hda_codec *codec, hda_nid_t nid)
3419 {
3420         return query_caps_hash(codec, nid, HDA_HASH_PARSTR_KEY(nid),
3421                                get_stream_param);
3422 }
3423
3424 /**
3425  * snd_hda_query_supported_pcm - query the supported PCM rates and formats
3426  * @codec: the HDA codec
3427  * @nid: NID to query
3428  * @ratesp: the pointer to store the detected rate bitflags
3429  * @formatsp: the pointer to store the detected formats
3430  * @bpsp: the pointer to store the detected format widths
3431  *
3432  * Queries the supported PCM rates and formats.  The NULL @ratesp, @formatsp
3433  * or @bsps argument is ignored.
3434  *
3435  * Returns 0 if successful, otherwise a negative error code.
3436  */
3437 int snd_hda_query_supported_pcm(struct hda_codec *codec, hda_nid_t nid,
3438                                 u32 *ratesp, u64 *formatsp, unsigned int *bpsp)
3439 {
3440         unsigned int i, val, wcaps;
3441
3442         wcaps = get_wcaps(codec, nid);
3443         val = query_pcm_param(codec, nid);
3444
3445         if (ratesp) {
3446                 u32 rates = 0;
3447                 for (i = 0; i < AC_PAR_PCM_RATE_BITS; i++) {
3448                         if (val & (1 << i))
3449                                 rates |= rate_bits[i].alsa_bits;
3450                 }
3451                 if (rates == 0) {
3452                         snd_printk(KERN_ERR "hda_codec: rates == 0 "
3453                                    "(nid=0x%x, val=0x%x, ovrd=%i)\n",
3454                                         nid, val,
3455                                         (wcaps & AC_WCAP_FORMAT_OVRD) ? 1 : 0);
3456                         return -EIO;
3457                 }
3458                 *ratesp = rates;
3459         }
3460
3461         if (formatsp || bpsp) {
3462                 u64 formats = 0;
3463                 unsigned int streams, bps;
3464
3465                 streams = query_stream_param(codec, nid);
3466                 if (!streams)
3467                         return -EIO;
3468
3469                 bps = 0;
3470                 if (streams & AC_SUPFMT_PCM) {
3471                         if (val & AC_SUPPCM_BITS_8) {
3472                                 formats |= SNDRV_PCM_FMTBIT_U8;
3473                                 bps = 8;
3474                         }
3475                         if (val & AC_SUPPCM_BITS_16) {
3476                                 formats |= SNDRV_PCM_FMTBIT_S16_LE;
3477                                 bps = 16;
3478                         }
3479                         if (wcaps & AC_WCAP_DIGITAL) {
3480                                 if (val & AC_SUPPCM_BITS_32)
3481                                         formats |= SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE;
3482                                 if (val & (AC_SUPPCM_BITS_20|AC_SUPPCM_BITS_24))
3483                                         formats |= SNDRV_PCM_FMTBIT_S32_LE;
3484                                 if (val & AC_SUPPCM_BITS_24)
3485                                         bps = 24;
3486                                 else if (val & AC_SUPPCM_BITS_20)
3487                                         bps = 20;
3488                         } else if (val & (AC_SUPPCM_BITS_20|AC_SUPPCM_BITS_24|
3489                                           AC_SUPPCM_BITS_32)) {
3490                                 formats |= SNDRV_PCM_FMTBIT_S32_LE;
3491                                 if (val & AC_SUPPCM_BITS_32)
3492                                         bps = 32;
3493                                 else if (val & AC_SUPPCM_BITS_24)
3494                                         bps = 24;
3495                                 else if (val & AC_SUPPCM_BITS_20)
3496                                         bps = 20;
3497                         }
3498                 }
3499                 if (streams & AC_SUPFMT_FLOAT32) {
3500                         formats |= SNDRV_PCM_FMTBIT_FLOAT_LE;
3501                         if (!bps)
3502                                 bps = 32;
3503                 }
3504                 if (streams == AC_SUPFMT_AC3) {
3505                         /* should be exclusive */
3506                         /* temporary hack: we have still no proper support
3507                          * for the direct AC3 stream...
3508                          */
3509                         formats |= SNDRV_PCM_FMTBIT_U8;
3510                         bps = 8;
3511                 }
3512                 if (formats == 0) {
3513                         snd_printk(KERN_ERR "hda_codec: formats == 0 "
3514                                    "(nid=0x%x, val=0x%x, ovrd=%i, "
3515                                    "streams=0x%x)\n",
3516                                         nid, val,
3517                                         (wcaps & AC_WCAP_FORMAT_OVRD) ? 1 : 0,
3518                                         streams);
3519                         return -EIO;
3520                 }
3521                 if (formatsp)
3522                         *formatsp = formats;
3523                 if (bpsp)
3524                         *bpsp = bps;
3525         }
3526
3527         return 0;
3528 }
3529 EXPORT_SYMBOL_HDA(snd_hda_query_supported_pcm);
3530
3531 /**
3532  * snd_hda_is_supported_format - Check the validity of the format
3533  * @codec: HD-audio codec
3534  * @nid: NID to check
3535  * @format: the HD-audio format value to check
3536  *
3537  * Check whether the given node supports the format value.
3538  *
3539  * Returns 1 if supported, 0 if not.
3540  */
3541 int snd_hda_is_supported_format(struct hda_codec *codec, hda_nid_t nid,
3542                                 unsigned int format)
3543 {
3544         int i;
3545         unsigned int val = 0, rate, stream;
3546
3547         val = query_pcm_param(codec, nid);
3548         if (!val)
3549                 return 0;
3550
3551         rate = format & 0xff00;
3552         for (i = 0; i < AC_PAR_PCM_RATE_BITS; i++)
3553                 if (rate_bits[i].hda_fmt == rate) {
3554                         if (val & (1 << i))
3555                                 break;
3556                         return 0;
3557                 }
3558         if (i >= AC_PAR_PCM_RATE_BITS)
3559                 return 0;
3560
3561         stream = query_stream_param(codec, nid);
3562         if (!stream)
3563                 return 0;
3564
3565         if (stream & AC_SUPFMT_PCM) {
3566                 switch (format & 0xf0) {
3567                 case 0x00:
3568                         if (!(val & AC_SUPPCM_BITS_8))
3569                                 return 0;
3570                         break;
3571                 case 0x10:
3572                         if (!(val & AC_SUPPCM_BITS_16))
3573                                 return 0;
3574                         break;
3575                 case 0x20:
3576                         if (!(val & AC_SUPPCM_BITS_20))
3577                                 return 0;
3578                         break;
3579                 case 0x30:
3580                         if (!(val & AC_SUPPCM_BITS_24))
3581                                 return 0;
3582                         break;
3583                 case 0x40:
3584                         if (!(val & AC_SUPPCM_BITS_32))
3585                                 return 0;
3586                         break;
3587                 default:
3588                         return 0;
3589                 }
3590         } else {
3591                 /* FIXME: check for float32 and AC3? */
3592         }
3593
3594         return 1;
3595 }
3596 EXPORT_SYMBOL_HDA(snd_hda_is_supported_format);
3597
3598 /*
3599  * PCM stuff
3600  */
3601 static int hda_pcm_default_open_close(struct hda_pcm_stream *hinfo,
3602                                       struct hda_codec *codec,
3603                                       struct snd_pcm_substream *substream)
3604 {
3605         return 0;
3606 }
3607
3608 static int hda_pcm_default_prepare(struct hda_pcm_stream *hinfo,
3609                                    struct hda_codec *codec,
3610                                    unsigned int stream_tag,
3611                                    unsigned int format,
3612                                    struct snd_pcm_substream *substream)
3613 {
3614         snd_hda_codec_setup_stream(codec, hinfo->nid, stream_tag, 0, format);
3615         return 0;
3616 }
3617
3618 static int hda_pcm_default_cleanup(struct hda_pcm_stream *hinfo,
3619                                    struct hda_codec *codec,
3620                                    struct snd_pcm_substream *substream)
3621 {
3622         snd_hda_codec_cleanup_stream(codec, hinfo->nid);
3623         return 0;
3624 }
3625
3626 static int set_pcm_default_values(struct hda_codec *codec,
3627                                   struct hda_pcm_stream *info)
3628 {
3629         int err;
3630
3631         /* query support PCM information from the given NID */
3632         if (info->nid && (!info->rates || !info->formats)) {
3633                 err = snd_hda_query_supported_pcm(codec, info->nid,
3634                                 info->rates ? NULL : &info->rates,
3635                                 info->formats ? NULL : &info->formats,
3636                                 info->maxbps ? NULL : &info->maxbps);
3637                 if (err < 0)
3638                         return err;
3639         }
3640         if (info->ops.open == NULL)
3641                 info->ops.open = hda_pcm_default_open_close;
3642         if (info->ops.close == NULL)
3643                 info->ops.close = hda_pcm_default_open_close;
3644         if (info->ops.prepare == NULL) {
3645                 if (snd_BUG_ON(!info->nid))
3646                         return -EINVAL;
3647                 info->ops.prepare = hda_pcm_default_prepare;
3648         }
3649         if (info->ops.cleanup == NULL) {
3650                 if (snd_BUG_ON(!info->nid))
3651                         return -EINVAL;
3652                 info->ops.cleanup = hda_pcm_default_cleanup;
3653         }
3654         return 0;
3655 }
3656
3657 /*
3658  * codec prepare/cleanup entries
3659  */
3660 int snd_hda_codec_prepare(struct hda_codec *codec,
3661                           struct hda_pcm_stream *hinfo,
3662                           unsigned int stream,
3663                           unsigned int format,
3664                           struct snd_pcm_substream *substream)
3665 {
3666         int ret;
3667         mutex_lock(&codec->bus->prepare_mutex);
3668         ret = hinfo->ops.prepare(hinfo, codec, stream, format, substream);
3669         if (ret >= 0)
3670                 purify_inactive_streams(codec);
3671         mutex_unlock(&codec->bus->prepare_mutex);
3672         return ret;
3673 }
3674 EXPORT_SYMBOL_HDA(snd_hda_codec_prepare);
3675
3676 void snd_hda_codec_cleanup(struct hda_codec *codec,
3677                            struct hda_pcm_stream *hinfo,
3678                            struct snd_pcm_substream *substream)
3679 {
3680         mutex_lock(&codec->bus->prepare_mutex);
3681         hinfo->ops.cleanup(hinfo, codec, substream);
3682         mutex_unlock(&codec->bus->prepare_mutex);
3683 }
3684 EXPORT_SYMBOL_HDA(snd_hda_codec_cleanup);
3685
3686 /* global */
3687 const char *snd_hda_pcm_type_name[HDA_PCM_NTYPES] = {
3688         "Audio", "SPDIF", "HDMI", "Modem"
3689 };
3690
3691 /*
3692  * get the empty PCM device number to assign
3693  *
3694  * note the max device number is limited by HDA_MAX_PCMS, currently 10
3695  */
3696 static int get_empty_pcm_device(struct hda_bus *bus, int type)
3697 {
3698         /* audio device indices; not linear to keep compatibility */
3699         static int audio_idx[HDA_PCM_NTYPES][5] = {
3700                 [HDA_PCM_TYPE_AUDIO] = { 0, 2, 4, 5, -1 },
3701                 [HDA_PCM_TYPE_SPDIF] = { 1, -1 },
3702                 [HDA_PCM_TYPE_HDMI]  = { 3, 7, 8, 9, -1 },
3703                 [HDA_PCM_TYPE_MODEM] = { 6, -1 },
3704         };
3705         int i;
3706
3707         if (type >= HDA_PCM_NTYPES) {
3708                 snd_printk(KERN_WARNING "Invalid PCM type %d\n", type);
3709                 return -EINVAL;
3710         }
3711
3712         for (i = 0; audio_idx[type][i] >= 0 ; i++)
3713                 if (!test_and_set_bit(audio_idx[type][i], bus->pcm_dev_bits))
3714                         return audio_idx[type][i];
3715
3716         snd_printk(KERN_WARNING "Too many %s devices\n",
3717                 snd_hda_pcm_type_name[type]);
3718         return -EAGAIN;
3719 }
3720
3721 /*
3722  * attach a new PCM stream
3723  */
3724 static int snd_hda_attach_pcm(struct hda_codec *codec, struct hda_pcm *pcm)
3725 {
3726         struct hda_bus *bus = codec->bus;
3727         struct hda_pcm_stream *info;
3728         int stream, err;
3729
3730         if (snd_BUG_ON(!pcm->name))
3731                 return -EINVAL;
3732         for (stream = 0; stream < 2; stream++) {
3733                 info = &pcm->stream[stream];
3734                 if (info->substreams) {
3735                         err = set_pcm_default_values(codec, info);
3736                         if (err < 0)
3737                                 return err;
3738                 }
3739         }
3740         return bus->ops.attach_pcm(bus, codec, pcm);
3741 }
3742
3743 /* assign all PCMs of the given codec */
3744 int snd_hda_codec_build_pcms(struct hda_codec *codec)
3745 {
3746         unsigned int pcm;
3747         int err;
3748
3749         if (!codec->num_pcms) {
3750                 if (!codec->patch_ops.build_pcms)
3751                         return 0;
3752                 err = codec->patch_ops.build_pcms(codec);
3753                 if (err < 0) {
3754                         printk(KERN_ERR "hda_codec: cannot build PCMs"
3755                                "for #%d (error %d)\n", codec->addr, err);
3756                         err = snd_hda_codec_reset(codec);
3757                         if (err < 0) {
3758                                 printk(KERN_ERR
3759                                        "hda_codec: cannot revert codec\n");
3760                                 return err;
3761                         }
3762                 }
3763         }
3764         for (pcm = 0; pcm < codec->num_pcms; pcm++) {
3765                 struct hda_pcm *cpcm = &codec->pcm_info[pcm];
3766                 int dev;
3767
3768                 if (!cpcm->stream[0].substreams && !cpcm->stream[1].substreams)
3769                         continue; /* no substreams assigned */
3770
3771                 if (!cpcm->pcm) {
3772                         dev = get_empty_pcm_device(codec->bus, cpcm->pcm_type);
3773                         if (dev < 0)
3774                                 continue; /* no fatal error */
3775                         cpcm->device = dev;
3776                         err = snd_hda_attach_pcm(codec, cpcm);
3777                         if (err < 0) {
3778                                 printk(KERN_ERR "hda_codec: cannot attach "
3779                                        "PCM stream %d for codec #%d\n",
3780                                        dev, codec->addr);
3781                                 continue; /* no fatal error */
3782                         }
3783                 }
3784         }
3785         return 0;
3786 }
3787
3788 /**
3789  * snd_hda_build_pcms - build PCM information
3790  * @bus: the BUS
3791  *
3792  * Create PCM information for each codec included in the bus.
3793  *
3794  * The build_pcms codec patch is requested to set up codec->num_pcms and
3795  * codec->pcm_info properly.  The array is referred by the top-level driver
3796  * to create its PCM instances.
3797  * The allocated codec->pcm_info should be released in codec->patch_ops.free
3798  * callback.
3799  *
3800  * At least, substreams, channels_min and channels_max must be filled for
3801  * each stream.  substreams = 0 indicates that the stream doesn't exist.
3802  * When rates and/or formats are zero, the supported values are queried
3803  * from the given nid.  The nid is used also by the default ops.prepare
3804  * and ops.cleanup callbacks.
3805  *
3806  * The driver needs to call ops.open in its open callback.  Similarly,
3807  * ops.close is supposed to be called in the close callback.
3808  * ops.prepare should be called in the prepare or hw_params callback
3809  * with the proper parameters for set up.
3810  * ops.cleanup should be called in hw_free for clean up of streams.
3811  *
3812  * This function returns 0 if successful, or a negative error code.
3813  */
3814 int __devinit snd_hda_build_pcms(struct hda_bus *bus)
3815 {
3816         struct hda_codec *codec;
3817
3818         list_for_each_entry(codec, &bus->codec_list, list) {
3819                 int err = snd_hda_codec_build_pcms(codec);
3820                 if (err < 0)
3821                         return err;
3822         }
3823         return 0;
3824 }
3825 EXPORT_SYMBOL_HDA(snd_hda_build_pcms);
3826
3827 /**
3828  * snd_hda_check_board_config - compare the current codec with the config table
3829  * @codec: the HDA codec
3830  * @num_configs: number of config enums
3831  * @models: array of model name strings
3832  * @tbl: configuration table, terminated by null entries
3833  *
3834  * Compares the modelname or PCI subsystem id of the current codec with the
3835  * given configuration table.  If a matching entry is found, returns its
3836  * config value (supposed to be 0 or positive).
3837  *
3838  * If no entries are matching, the function returns a negative value.
3839  */
3840 int snd_hda_check_board_config(struct hda_codec *codec,
3841                                int num_configs, const char * const *models,
3842                                const struct snd_pci_quirk *tbl)
3843 {
3844         if (codec->modelname && models) {
3845                 int i;
3846                 for (i = 0; i < num_configs; i++) {
3847                         if (models[i] &&
3848                             !strcmp(codec->modelname, models[i])) {
3849                                 snd_printd(KERN_INFO "hda_codec: model '%s' is "
3850                                            "selected\n", models[i]);
3851                                 return i;
3852                         }
3853                 }
3854         }
3855
3856         if (!codec->bus->pci || !tbl)
3857                 return -1;
3858
3859         tbl = snd_pci_quirk_lookup(codec->bus->pci, tbl);
3860         if (!tbl)
3861                 return -1;
3862         if (tbl->value >= 0 && tbl->value < num_configs) {
3863 #ifdef CONFIG_SND_DEBUG_VERBOSE
3864                 char tmp[10];
3865                 const char *model = NULL;
3866                 if (models)
3867                         model = models[tbl->value];
3868                 if (!model) {
3869                         sprintf(tmp, "#%d", tbl->value);
3870                         model = tmp;
3871                 }
3872                 snd_printdd(KERN_INFO "hda_codec: model '%s' is selected "
3873                             "for config %x:%x (%s)\n",
3874                             model, tbl->subvendor, tbl->subdevice,
3875                             (tbl->name ? tbl->name : "Unknown device"));
3876 #endif
3877                 return tbl->value;
3878         }
3879         return -1;
3880 }
3881 EXPORT_SYMBOL_HDA(snd_hda_check_board_config);
3882
3883 /**
3884  * snd_hda_check_board_codec_sid_config - compare the current codec
3885                                         subsystem ID with the
3886                                         config table
3887
3888            This is important for Gateway notebooks with SB450 HDA Audio
3889            where the vendor ID of the PCI device is:
3890                 ATI Technologies Inc SB450 HDA Audio [1002:437b]
3891            and the vendor/subvendor are found only at the codec.
3892
3893  * @codec: the HDA codec
3894  * @num_configs: number of config enums
3895  * @models: array of model name strings
3896  * @tbl: configuration table, terminated by null entries
3897  *
3898  * Compares the modelname or PCI subsystem id of the current codec with the
3899  * given configuration table.  If a matching entry is found, returns its
3900  * config value (supposed to be 0 or positive).
3901  *
3902  * If no entries are matching, the function returns a negative value.
3903  */
3904 int snd_hda_check_board_codec_sid_config(struct hda_codec *codec,
3905                                int num_configs, const char * const *models,
3906                                const struct snd_pci_quirk *tbl)
3907 {
3908         const struct snd_pci_quirk *q;
3909
3910         /* Search for codec ID */
3911         for (q = tbl; q->subvendor; q++) {
3912                 unsigned long vendorid = (q->subdevice) | (q->subvendor << 16);
3913
3914                 if (vendorid == codec->subsystem_id)
3915                         break;
3916         }
3917
3918         if (!q->subvendor)
3919                 return -1;
3920
3921         tbl = q;
3922
3923         if (tbl->value >= 0 && tbl->value < num_configs) {
3924 #ifdef CONFIG_SND_DEBUG_VERBOSE
3925                 char tmp[10];
3926                 const char *model = NULL;
3927                 if (models)
3928                         model = models[tbl->value];
3929                 if (!model) {
3930                         sprintf(tmp, "#%d", tbl->value);
3931                         model = tmp;
3932                 }
3933                 snd_printdd(KERN_INFO "hda_codec: model '%s' is selected "
3934                             "for config %x:%x (%s)\n",
3935                             model, tbl->subvendor, tbl->subdevice,
3936                             (tbl->name ? tbl->name : "Unknown device"));
3937 #endif
3938                 return tbl->value;
3939         }
3940         return -1;
3941 }
3942 EXPORT_SYMBOL_HDA(snd_hda_check_board_codec_sid_config);
3943
3944 /**
3945  * snd_hda_add_new_ctls - create controls from the array
3946  * @codec: the HDA codec
3947  * @knew: the array of struct snd_kcontrol_new
3948  *
3949  * This helper function creates and add new controls in the given array.
3950  * The array must be terminated with an empty entry as terminator.
3951  *
3952  * Returns 0 if successful, or a negative error code.
3953  */
3954 int snd_hda_add_new_ctls(struct hda_codec *codec,
3955                          const struct snd_kcontrol_new *knew)
3956 {
3957         int err;
3958
3959         for (; knew->name; knew++) {
3960                 struct snd_kcontrol *kctl;
3961                 int addr = 0, idx = 0;
3962                 if (knew->iface == -1)  /* skip this codec private value */
3963                         continue;
3964                 for (;;) {
3965                         kctl = snd_ctl_new1(knew, codec);
3966                         if (!kctl)
3967                                 return -ENOMEM;
3968                         if (addr > 0)
3969                                 kctl->id.device = addr;
3970                         if (idx > 0)
3971                                 kctl->id.index = idx;
3972                         err = snd_hda_ctl_add(codec, 0, kctl);
3973                         if (!err)
3974                                 break;
3975                         /* try first with another device index corresponding to
3976                          * the codec addr; if it still fails (or it's the
3977                          * primary codec), then try another control index
3978                          */
3979                         if (!addr && codec->addr)
3980                                 addr = codec->addr;
3981                         else if (!idx && !knew->index) {
3982                                 idx = find_empty_mixer_ctl_idx(codec,
3983                                                                knew->name);
3984                                 if (idx <= 0)
3985                                         return err;
3986                         } else
3987                                 return err;
3988                 }
3989         }
3990         return 0;
3991 }
3992 EXPORT_SYMBOL_HDA(snd_hda_add_new_ctls);
3993
3994 #ifdef CONFIG_SND_HDA_POWER_SAVE
3995 static void hda_set_power_state(struct hda_codec *codec, hda_nid_t fg,
3996                                 unsigned int power_state);
3997
3998 static void hda_power_work(struct work_struct *work)
3999 {
4000         struct hda_codec *codec =
4001                 container_of(work, struct hda_codec, power_work.work);
4002         struct hda_bus *bus = codec->bus;
4003
4004         if (!codec->power_on || codec->power_count) {
4005                 codec->power_transition = 0;
4006                 return;
4007         }
4008
4009         hda_call_codec_suspend(codec);
4010         if (bus->ops.pm_notify)
4011                 bus->ops.pm_notify(bus);
4012 }
4013
4014 static void hda_keep_power_on(struct hda_codec *codec)
4015 {
4016         codec->power_count++;
4017         codec->power_on = 1;
4018         codec->power_jiffies = jiffies;
4019 }
4020
4021 /* update the power on/off account with the current jiffies */
4022 void snd_hda_update_power_acct(struct hda_codec *codec)
4023 {
4024         unsigned long delta = jiffies - codec->power_jiffies;
4025         if (codec->power_on)
4026                 codec->power_on_acct += delta;
4027         else
4028                 codec->power_off_acct += delta;
4029         codec->power_jiffies += delta;
4030 }
4031
4032 /**
4033  * snd_hda_power_up - Power-up the codec
4034  * @codec: HD-audio codec
4035  *
4036  * Increment the power-up counter and power up the hardware really when
4037  * not turned on yet.
4038  */
4039 void snd_hda_power_up(struct hda_codec *codec)
4040 {
4041         struct hda_bus *bus = codec->bus;
4042
4043         codec->power_count++;
4044         if (codec->power_on || codec->power_transition)
4045                 return;
4046
4047         snd_hda_update_power_acct(codec);
4048         codec->power_on = 1;
4049         codec->power_jiffies = jiffies;
4050         if (bus->ops.pm_notify)
4051                 bus->ops.pm_notify(bus);
4052         hda_call_codec_resume(codec);
4053         cancel_delayed_work(&codec->power_work);
4054         codec->power_transition = 0;
4055 }
4056 EXPORT_SYMBOL_HDA(snd_hda_power_up);
4057
4058 #define power_save(codec)       \
4059         ((codec)->bus->power_save ? *(codec)->bus->power_save : 0)
4060
4061 /**
4062  * snd_hda_power_down - Power-down the codec
4063  * @codec: HD-audio codec
4064  *
4065  * Decrement the power-up counter and schedules the power-off work if
4066  * the counter rearches to zero.
4067  */
4068 void snd_hda_power_down(struct hda_codec *codec)
4069 {
4070         --codec->power_count;
4071         if (!codec->power_on || codec->power_count || codec->power_transition)
4072                 return;
4073         if (power_save(codec)) {
4074                 codec->power_transition = 1; /* avoid reentrance */
4075                 queue_delayed_work(codec->bus->workq, &codec->power_work,
4076                                 msecs_to_jiffies(power_save(codec) * 1000));
4077         }
4078 }
4079 EXPORT_SYMBOL_HDA(snd_hda_power_down);
4080
4081 /**
4082  * snd_hda_check_amp_list_power - Check the amp list and update the power
4083  * @codec: HD-audio codec
4084  * @check: the object containing an AMP list and the status
4085  * @nid: NID to check / update
4086  *
4087  * Check whether the given NID is in the amp list.  If it's in the list,
4088  * check the current AMP status, and update the the power-status according
4089  * to the mute status.
4090  *
4091  * This function is supposed to be set or called from the check_power_status
4092  * patch ops.
4093  */
4094 int snd_hda_check_amp_list_power(struct hda_codec *codec,
4095                                  struct hda_loopback_check *check,
4096                                  hda_nid_t nid)
4097 {
4098         const struct hda_amp_list *p;
4099         int ch, v;
4100
4101         if (!check->amplist)
4102                 return 0;
4103         for (p = check->amplist; p->nid; p++) {
4104                 if (p->nid == nid)
4105                         break;
4106         }
4107         if (!p->nid)
4108                 return 0; /* nothing changed */
4109
4110         for (p = check->amplist; p->nid; p++) {
4111                 for (ch = 0; ch < 2; ch++) {
4112                         v = snd_hda_codec_amp_read(codec, p->nid, ch, p->dir,
4113                                                    p->idx);
4114                         if (!(v & HDA_AMP_MUTE) && v > 0) {
4115                                 if (!check->power_on) {
4116                                         check->power_on = 1;
4117                                         snd_hda_power_up(codec);
4118                                 }
4119                                 return 1;
4120                         }
4121                 }
4122         }
4123         if (check->power_on) {
4124                 check->power_on = 0;
4125                 snd_hda_power_down(codec);
4126         }
4127         return 0;
4128 }
4129 EXPORT_SYMBOL_HDA(snd_hda_check_amp_list_power);
4130 #endif
4131
4132 /*
4133  * Channel mode helper
4134  */
4135
4136 /**
4137  * snd_hda_ch_mode_info - Info callback helper for the channel mode enum
4138  */
4139 int snd_hda_ch_mode_info(struct hda_codec *codec,
4140                          struct snd_ctl_elem_info *uinfo,
4141                          const struct hda_channel_mode *chmode,
4142                          int num_chmodes)
4143 {
4144         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
4145         uinfo->count = 1;
4146         uinfo->value.enumerated.items = num_chmodes;
4147         if (uinfo->value.enumerated.item >= num_chmodes)
4148                 uinfo->value.enumerated.item = num_chmodes - 1;
4149         sprintf(uinfo->value.enumerated.name, "%dch",
4150                 chmode[uinfo->value.enumerated.item].channels);
4151         return 0;
4152 }
4153 EXPORT_SYMBOL_HDA(snd_hda_ch_mode_info);
4154
4155 /**
4156  * snd_hda_ch_mode_get - Get callback helper for the channel mode enum
4157  */
4158 int snd_hda_ch_mode_get(struct hda_codec *codec,
4159                         struct snd_ctl_elem_value *ucontrol,
4160                         const struct hda_channel_mode *chmode,
4161                         int num_chmodes,
4162                         int max_channels)
4163 {
4164         int i;
4165
4166         for (i = 0; i < num_chmodes; i++) {
4167                 if (max_channels == chmode[i].channels) {
4168                         ucontrol->value.enumerated.item[0] = i;
4169                         break;
4170                 }
4171         }
4172         return 0;
4173 }
4174 EXPORT_SYMBOL_HDA(snd_hda_ch_mode_get);
4175
4176 /**
4177  * snd_hda_ch_mode_put - Put callback helper for the channel mode enum
4178  */
4179 int snd_hda_ch_mode_put(struct hda_codec *codec,
4180                         struct snd_ctl_elem_value *ucontrol,
4181                         const struct hda_channel_mode *chmode,
4182                         int num_chmodes,
4183                         int *max_channelsp)
4184 {
4185         unsigned int mode;
4186
4187         mode = ucontrol->value.enumerated.item[0];
4188         if (mode >= num_chmodes)
4189                 return -EINVAL;
4190         if (*max_channelsp == chmode[mode].channels)
4191                 return 0;
4192         /* change the current channel setting */
4193         *max_channelsp = chmode[mode].channels;
4194         if (chmode[mode].sequence)
4195                 snd_hda_sequence_write_cache(codec, chmode[mode].sequence);
4196         return 1;
4197 }
4198 EXPORT_SYMBOL_HDA(snd_hda_ch_mode_put);
4199
4200 /*
4201  * input MUX helper
4202  */
4203
4204 /**
4205  * snd_hda_input_mux_info_info - Info callback helper for the input-mux enum
4206  */
4207 int snd_hda_input_mux_info(const struct hda_input_mux *imux,
4208                            struct snd_ctl_elem_info *uinfo)
4209 {
4210         unsigned int index;
4211
4212         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
4213         uinfo->count = 1;
4214         uinfo->value.enumerated.items = imux->num_items;
4215         if (!imux->num_items)
4216                 return 0;
4217         index = uinfo->value.enumerated.item;
4218         if (index >= imux->num_items)
4219                 index = imux->num_items - 1;
4220         strcpy(uinfo->value.enumerated.name, imux->items[index].label);
4221         return 0;
4222 }
4223 EXPORT_SYMBOL_HDA(snd_hda_input_mux_info);
4224
4225 /**
4226  * snd_hda_input_mux_info_put - Put callback helper for the input-mux enum
4227  */
4228 int snd_hda_input_mux_put(struct hda_codec *codec,
4229                           const struct hda_input_mux *imux,
4230                           struct snd_ctl_elem_value *ucontrol,
4231                           hda_nid_t nid,
4232                           unsigned int *cur_val)
4233 {
4234         unsigned int idx;
4235
4236         if (!imux->num_items)
4237                 return 0;
4238         idx = ucontrol->value.enumerated.item[0];
4239         if (idx >= imux->num_items)
4240                 idx = imux->num_items - 1;
4241         if (*cur_val == idx)
4242                 return 0;
4243         snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_CONNECT_SEL,
4244                                   imux->items[idx].index);
4245         *cur_val = idx;
4246         return 1;
4247 }
4248 EXPORT_SYMBOL_HDA(snd_hda_input_mux_put);
4249
4250
4251 /*
4252  * Multi-channel / digital-out PCM helper functions
4253  */
4254
4255 /* setup SPDIF output stream */
4256 static void setup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid,
4257                                  unsigned int stream_tag, unsigned int format)
4258 {
4259         struct hda_spdif_out *spdif = snd_hda_spdif_out_of_nid(codec, nid);
4260
4261         /* turn off SPDIF once; otherwise the IEC958 bits won't be updated */
4262         if (codec->spdif_status_reset && (spdif->ctls & AC_DIG1_ENABLE))
4263                 set_dig_out_convert(codec, nid,
4264                                     spdif->ctls & ~AC_DIG1_ENABLE & 0xff,
4265                                     -1);
4266         snd_hda_codec_setup_stream(codec, nid, stream_tag, 0, format);
4267         if (codec->slave_dig_outs) {
4268                 const hda_nid_t *d;
4269                 for (d = codec->slave_dig_outs; *d; d++)
4270                         snd_hda_codec_setup_stream(codec, *d, stream_tag, 0,
4271                                                    format);
4272         }
4273         /* turn on again (if needed) */
4274         if (codec->spdif_status_reset && (spdif->ctls & AC_DIG1_ENABLE))
4275                 set_dig_out_convert(codec, nid,
4276                                     spdif->ctls & 0xff, -1);
4277 }
4278
4279 static void cleanup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid)
4280 {
4281         snd_hda_codec_cleanup_stream(codec, nid);
4282         if (codec->slave_dig_outs) {
4283                 const hda_nid_t *d;
4284                 for (d = codec->slave_dig_outs; *d; d++)
4285                         snd_hda_codec_cleanup_stream(codec, *d);
4286         }
4287 }
4288
4289 /**
4290  * snd_hda_bus_reboot_notify - call the reboot notifier of each codec
4291  * @bus: HD-audio bus
4292  */
4293 void snd_hda_bus_reboot_notify(struct hda_bus *bus)
4294 {
4295         struct hda_codec *codec;
4296
4297         if (!bus)
4298                 return;
4299         list_for_each_entry(codec, &bus->codec_list, list) {
4300 #ifdef CONFIG_SND_HDA_POWER_SAVE
4301                 if (!codec->power_on)
4302                         continue;
4303 #endif
4304                 if (codec->patch_ops.reboot_notify)
4305                         codec->patch_ops.reboot_notify(codec);
4306         }
4307 }
4308 EXPORT_SYMBOL_HDA(snd_hda_bus_reboot_notify);
4309
4310 /**
4311  * snd_hda_multi_out_dig_open - open the digital out in the exclusive mode
4312  */
4313 int snd_hda_multi_out_dig_open(struct hda_codec *codec,
4314                                struct hda_multi_out *mout)
4315 {
4316         mutex_lock(&codec->spdif_mutex);
4317         if (mout->dig_out_used == HDA_DIG_ANALOG_DUP)
4318                 /* already opened as analog dup; reset it once */
4319                 cleanup_dig_out_stream(codec, mout->dig_out_nid);
4320         mout->dig_out_used = HDA_DIG_EXCLUSIVE;
4321         mutex_unlock(&codec->spdif_mutex);
4322         return 0;
4323 }
4324 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_open);
4325
4326 /**
4327  * snd_hda_multi_out_dig_prepare - prepare the digital out stream
4328  */
4329 int snd_hda_multi_out_dig_prepare(struct hda_codec *codec,
4330                                   struct hda_multi_out *mout,
4331                                   unsigned int stream_tag,
4332                                   unsigned int format,
4333                                   struct snd_pcm_substream *substream)
4334 {
4335         mutex_lock(&codec->spdif_mutex);
4336         setup_dig_out_stream(codec, mout->dig_out_nid, stream_tag, format);
4337         mutex_unlock(&codec->spdif_mutex);
4338         return 0;
4339 }
4340 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_prepare);
4341
4342 /**
4343  * snd_hda_multi_out_dig_cleanup - clean-up the digital out stream
4344  */
4345 int snd_hda_multi_out_dig_cleanup(struct hda_codec *codec,
4346                                   struct hda_multi_out *mout)
4347 {
4348         mutex_lock(&codec->spdif_mutex);
4349         cleanup_dig_out_stream(codec, mout->dig_out_nid);
4350         mutex_unlock(&codec->spdif_mutex);
4351         return 0;
4352 }
4353 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_cleanup);
4354
4355 /**
4356  * snd_hda_multi_out_dig_close - release the digital out stream
4357  */
4358 int snd_hda_multi_out_dig_close(struct hda_codec *codec,
4359                                 struct hda_multi_out *mout)
4360 {
4361         mutex_lock(&codec->spdif_mutex);
4362         mout->dig_out_used = 0;
4363         mutex_unlock(&codec->spdif_mutex);
4364         return 0;
4365 }
4366 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_close);
4367
4368 /**
4369  * snd_hda_multi_out_analog_open - open analog outputs
4370  *
4371  * Open analog outputs and set up the hw-constraints.
4372  * If the digital outputs can be opened as slave, open the digital
4373  * outputs, too.
4374  */
4375 int snd_hda_multi_out_analog_open(struct hda_codec *codec,
4376                                   struct hda_multi_out *mout,
4377                                   struct snd_pcm_substream *substream,
4378                                   struct hda_pcm_stream *hinfo)
4379 {
4380         struct snd_pcm_runtime *runtime = substream->runtime;
4381         runtime->hw.channels_max = mout->max_channels;
4382         if (mout->dig_out_nid) {
4383                 if (!mout->analog_rates) {
4384                         mout->analog_rates = hinfo->rates;
4385                         mout->analog_formats = hinfo->formats;
4386                         mout->analog_maxbps = hinfo->maxbps;
4387                 } else {
4388                         runtime->hw.rates = mout->analog_rates;
4389                         runtime->hw.formats = mout->analog_formats;
4390                         hinfo->maxbps = mout->analog_maxbps;
4391                 }
4392                 if (!mout->spdif_rates) {
4393                         snd_hda_query_supported_pcm(codec, mout->dig_out_nid,
4394                                                     &mout->spdif_rates,
4395                                                     &mout->spdif_formats,
4396                                                     &mout->spdif_maxbps);
4397                 }
4398                 mutex_lock(&codec->spdif_mutex);
4399                 if (mout->share_spdif) {
4400                         if ((runtime->hw.rates & mout->spdif_rates) &&
4401                             (runtime->hw.formats & mout->spdif_formats)) {
4402                                 runtime->hw.rates &= mout->spdif_rates;
4403                                 runtime->hw.formats &= mout->spdif_formats;
4404                                 if (mout->spdif_maxbps < hinfo->maxbps)
4405                                         hinfo->maxbps = mout->spdif_maxbps;
4406                         } else {
4407                                 mout->share_spdif = 0;
4408                                 /* FIXME: need notify? */
4409                         }
4410                 }
4411                 mutex_unlock(&codec->spdif_mutex);
4412         }
4413         return snd_pcm_hw_constraint_step(substream->runtime, 0,
4414                                           SNDRV_PCM_HW_PARAM_CHANNELS, 2);
4415 }
4416 EXPORT_SYMBOL_HDA(snd_hda_multi_out_analog_open);
4417
4418 /**
4419  * snd_hda_multi_out_analog_prepare - Preapre the analog outputs.
4420  *
4421  * Set up the i/o for analog out.
4422  * When the digital out is available, copy the front out to digital out, too.
4423  */
4424 int snd_hda_multi_out_analog_prepare(struct hda_codec *codec,
4425                                      struct hda_multi_out *mout,
4426                                      unsigned int stream_tag,
4427                                      unsigned int format,
4428                                      struct snd_pcm_substream *substream)
4429 {
4430         const hda_nid_t *nids = mout->dac_nids;
4431         int chs = substream->runtime->channels;
4432         struct hda_spdif_out *spdif =
4433                         snd_hda_spdif_out_of_nid(codec, mout->dig_out_nid);
4434         int i;
4435
4436         mutex_lock(&codec->spdif_mutex);
4437         if (mout->dig_out_nid && mout->share_spdif &&
4438             mout->dig_out_used != HDA_DIG_EXCLUSIVE) {
4439                 if (chs == 2 &&
4440                     snd_hda_is_supported_format(codec, mout->dig_out_nid,
4441                                                 format) &&
4442                     !(spdif->status & IEC958_AES0_NONAUDIO)) {
4443                         mout->dig_out_used = HDA_DIG_ANALOG_DUP;
4444                         setup_dig_out_stream(codec, mout->dig_out_nid,
4445                                              stream_tag, format);
4446                 } else {
4447                         mout->dig_out_used = 0;
4448                         cleanup_dig_out_stream(codec, mout->dig_out_nid);
4449                 }
4450         }
4451         mutex_unlock(&codec->spdif_mutex);
4452
4453         /* front */
4454         snd_hda_codec_setup_stream(codec, nids[HDA_FRONT], stream_tag,
4455                                    0, format);
4456         if (!mout->no_share_stream &&
4457             mout->hp_nid && mout->hp_nid != nids[HDA_FRONT])
4458                 /* headphone out will just decode front left/right (stereo) */
4459                 snd_hda_codec_setup_stream(codec, mout->hp_nid, stream_tag,
4460                                            0, format);
4461         /* extra outputs copied from front */
4462         for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
4463                 if (!mout->no_share_stream && mout->extra_out_nid[i])
4464                         snd_hda_codec_setup_stream(codec,
4465                                                    mout->extra_out_nid[i],
4466                                                    stream_tag, 0, format);
4467
4468         /* surrounds */
4469         for (i = 1; i < mout->num_dacs; i++) {
4470                 if (chs >= (i + 1) * 2) /* independent out */
4471                         snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
4472                                                    i * 2, format);
4473                 else if (!mout->no_share_stream) /* copy front */
4474                         snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
4475                                                    0, format);
4476         }
4477         return 0;
4478 }
4479 EXPORT_SYMBOL_HDA(snd_hda_multi_out_analog_prepare);
4480
4481 /**
4482  * snd_hda_multi_out_analog_cleanup - clean up the setting for analog out
4483  */
4484 int snd_hda_multi_out_analog_cleanup(struct hda_codec *codec,
4485                                      struct hda_multi_out *mout)
4486 {
4487         const hda_nid_t *nids = mout->dac_nids;
4488         int i;
4489
4490         for (i = 0; i < mout->num_dacs; i++)
4491                 snd_hda_codec_cleanup_stream(codec, nids[i]);
4492         if (mout->hp_nid)
4493                 snd_hda_codec_cleanup_stream(codec, mout->hp_nid);
4494         for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
4495                 if (mout->extra_out_nid[i])
4496                         snd_hda_codec_cleanup_stream(codec,
4497                                                      mout->extra_out_nid[i]);
4498         mutex_lock(&codec->spdif_mutex);
4499         if (mout->dig_out_nid && mout->dig_out_used == HDA_DIG_ANALOG_DUP) {
4500                 cleanup_dig_out_stream(codec, mout->dig_out_nid);
4501                 mout->dig_out_used = 0;
4502         }
4503         mutex_unlock(&codec->spdif_mutex);
4504         return 0;
4505 }
4506 EXPORT_SYMBOL_HDA(snd_hda_multi_out_analog_cleanup);
4507
4508 /*
4509  * Helper for automatic pin configuration
4510  */
4511
4512 static int is_in_nid_list(hda_nid_t nid, const hda_nid_t *list)
4513 {
4514         for (; *list; list++)
4515                 if (*list == nid)
4516                         return 1;
4517         return 0;
4518 }
4519
4520
4521 /*
4522  * Sort an associated group of pins according to their sequence numbers.
4523  */
4524 static void sort_pins_by_sequence(hda_nid_t *pins, short *sequences,
4525                                   int num_pins)
4526 {
4527         int i, j;
4528         short seq;
4529         hda_nid_t nid;
4530
4531         for (i = 0; i < num_pins; i++) {
4532                 for (j = i + 1; j < num_pins; j++) {
4533                         if (sequences[i] > sequences[j]) {
4534                                 seq = sequences[i];
4535                                 sequences[i] = sequences[j];
4536                                 sequences[j] = seq;
4537                                 nid = pins[i];
4538                                 pins[i] = pins[j];
4539                                 pins[j] = nid;
4540                         }
4541                 }
4542         }
4543 }
4544
4545
4546 /* add the found input-pin to the cfg->inputs[] table */
4547 static void add_auto_cfg_input_pin(struct auto_pin_cfg *cfg, hda_nid_t nid,
4548                                    int type)
4549 {
4550         if (cfg->num_inputs < AUTO_CFG_MAX_INS) {
4551                 cfg->inputs[cfg->num_inputs].pin = nid;
4552                 cfg->inputs[cfg->num_inputs].type = type;
4553                 cfg->num_inputs++;
4554         }
4555 }
4556
4557 /* sort inputs in the order of AUTO_PIN_* type */
4558 static void sort_autocfg_input_pins(struct auto_pin_cfg *cfg)
4559 {
4560         int i, j;
4561
4562         for (i = 0; i < cfg->num_inputs; i++) {
4563                 for (j = i + 1; j < cfg->num_inputs; j++) {
4564                         if (cfg->inputs[i].type > cfg->inputs[j].type) {
4565                                 struct auto_pin_cfg_item tmp;
4566                                 tmp = cfg->inputs[i];
4567                                 cfg->inputs[i] = cfg->inputs[j];
4568                                 cfg->inputs[j] = tmp;
4569                         }
4570                 }
4571         }
4572 }
4573
4574 /*
4575  * Parse all pin widgets and store the useful pin nids to cfg
4576  *
4577  * The number of line-outs or any primary output is stored in line_outs,
4578  * and the corresponding output pins are assigned to line_out_pins[],
4579  * in the order of front, rear, CLFE, side, ...
4580  *
4581  * If more extra outputs (speaker and headphone) are found, the pins are
4582  * assisnged to hp_pins[] and speaker_pins[], respectively.  If no line-out jack
4583  * is detected, one of speaker of HP pins is assigned as the primary
4584  * output, i.e. to line_out_pins[0].  So, line_outs is always positive
4585  * if any analog output exists.
4586  *
4587  * The analog input pins are assigned to inputs array.
4588  * The digital input/output pins are assigned to dig_in_pin and dig_out_pin,
4589  * respectively.
4590  */
4591 int snd_hda_parse_pin_def_config(struct hda_codec *codec,
4592                                  struct auto_pin_cfg *cfg,
4593                                  const hda_nid_t *ignore_nids)
4594 {
4595         hda_nid_t nid, end_nid;
4596         short seq, assoc_line_out, assoc_speaker;
4597         short sequences_line_out[ARRAY_SIZE(cfg->line_out_pins)];
4598         short sequences_speaker[ARRAY_SIZE(cfg->speaker_pins)];
4599         short sequences_hp[ARRAY_SIZE(cfg->hp_pins)];
4600         int i;
4601
4602         memset(cfg, 0, sizeof(*cfg));
4603
4604         memset(sequences_line_out, 0, sizeof(sequences_line_out));
4605         memset(sequences_speaker, 0, sizeof(sequences_speaker));
4606         memset(sequences_hp, 0, sizeof(sequences_hp));
4607         assoc_line_out = assoc_speaker = 0;
4608
4609         end_nid = codec->start_nid + codec->num_nodes;
4610         for (nid = codec->start_nid; nid < end_nid; nid++) {
4611                 unsigned int wid_caps = get_wcaps(codec, nid);
4612                 unsigned int wid_type = get_wcaps_type(wid_caps);
4613                 unsigned int def_conf;
4614                 short assoc, loc, conn, dev;
4615
4616                 /* read all default configuration for pin complex */
4617                 if (wid_type != AC_WID_PIN)
4618                         continue;
4619                 /* ignore the given nids (e.g. pc-beep returns error) */
4620                 if (ignore_nids && is_in_nid_list(nid, ignore_nids))
4621                         continue;
4622
4623                 def_conf = snd_hda_codec_get_pincfg(codec, nid);
4624                 conn = get_defcfg_connect(def_conf);
4625                 if (conn == AC_JACK_PORT_NONE)
4626                         continue;
4627                 loc = get_defcfg_location(def_conf);
4628                 dev = get_defcfg_device(def_conf);
4629
4630                 /* workaround for buggy BIOS setups */
4631                 if (dev == AC_JACK_LINE_OUT) {
4632                         if (conn == AC_JACK_PORT_FIXED)
4633                                 dev = AC_JACK_SPEAKER;
4634                 }
4635
4636                 switch (dev) {
4637                 case AC_JACK_LINE_OUT:
4638                         seq = get_defcfg_sequence(def_conf);
4639                         assoc = get_defcfg_association(def_conf);
4640
4641                         if (!(wid_caps & AC_WCAP_STEREO))
4642                                 if (!cfg->mono_out_pin)
4643                                         cfg->mono_out_pin = nid;
4644                         if (!assoc)
4645                                 continue;
4646                         if (!assoc_line_out)
4647                                 assoc_line_out = assoc;
4648                         else if (assoc_line_out != assoc)
4649                                 continue;
4650                         if (cfg->line_outs >= ARRAY_SIZE(cfg->line_out_pins))
4651                                 continue;
4652                         cfg->line_out_pins[cfg->line_outs] = nid;
4653                         sequences_line_out[cfg->line_outs] = seq;
4654                         cfg->line_outs++;
4655                         break;
4656                 case AC_JACK_SPEAKER:
4657                         seq = get_defcfg_sequence(def_conf);
4658                         assoc = get_defcfg_association(def_conf);
4659                         if (!assoc)
4660                                 continue;
4661                         if (!assoc_speaker)
4662                                 assoc_speaker = assoc;
4663                         else if (assoc_speaker != assoc)
4664                                 continue;
4665                         if (cfg->speaker_outs >= ARRAY_SIZE(cfg->speaker_pins))
4666                                 continue;
4667                         cfg->speaker_pins[cfg->speaker_outs] = nid;
4668                         sequences_speaker[cfg->speaker_outs] = seq;
4669                         cfg->speaker_outs++;
4670                         break;
4671                 case AC_JACK_HP_OUT:
4672                         seq = get_defcfg_sequence(def_conf);
4673                         assoc = get_defcfg_association(def_conf);
4674                         if (cfg->hp_outs >= ARRAY_SIZE(cfg->hp_pins))
4675                                 continue;
4676                         cfg->hp_pins[cfg->hp_outs] = nid;
4677                         sequences_hp[cfg->hp_outs] = (assoc << 4) | seq;
4678                         cfg->hp_outs++;
4679                         break;
4680                 case AC_JACK_MIC_IN:
4681                         add_auto_cfg_input_pin(cfg, nid, AUTO_PIN_MIC);
4682                         break;
4683                 case AC_JACK_LINE_IN:
4684                         add_auto_cfg_input_pin(cfg, nid, AUTO_PIN_LINE_IN);
4685                         break;
4686                 case AC_JACK_CD:
4687                         add_auto_cfg_input_pin(cfg, nid, AUTO_PIN_CD);
4688                         break;
4689                 case AC_JACK_AUX:
4690                         add_auto_cfg_input_pin(cfg, nid, AUTO_PIN_AUX);
4691                         break;
4692                 case AC_JACK_SPDIF_OUT:
4693                 case AC_JACK_DIG_OTHER_OUT:
4694                         if (cfg->dig_outs >= ARRAY_SIZE(cfg->dig_out_pins))
4695                                 continue;
4696                         cfg->dig_out_pins[cfg->dig_outs] = nid;
4697                         cfg->dig_out_type[cfg->dig_outs] =
4698                                 (loc == AC_JACK_LOC_HDMI) ?
4699                                 HDA_PCM_TYPE_HDMI : HDA_PCM_TYPE_SPDIF;
4700                         cfg->dig_outs++;
4701                         break;
4702                 case AC_JACK_SPDIF_IN:
4703                 case AC_JACK_DIG_OTHER_IN:
4704                         cfg->dig_in_pin = nid;
4705                         if (loc == AC_JACK_LOC_HDMI)
4706                                 cfg->dig_in_type = HDA_PCM_TYPE_HDMI;
4707                         else
4708                                 cfg->dig_in_type = HDA_PCM_TYPE_SPDIF;
4709                         break;
4710                 }
4711         }
4712
4713         /* FIX-UP:
4714          * If no line-out is defined but multiple HPs are found,
4715          * some of them might be the real line-outs.
4716          */
4717         if (!cfg->line_outs && cfg->hp_outs > 1) {
4718                 int i = 0;
4719                 while (i < cfg->hp_outs) {
4720                         /* The real HPs should have the sequence 0x0f */
4721                         if ((sequences_hp[i] & 0x0f) == 0x0f) {
4722                                 i++;
4723                                 continue;
4724                         }
4725                         /* Move it to the line-out table */
4726                         cfg->line_out_pins[cfg->line_outs] = cfg->hp_pins[i];
4727                         sequences_line_out[cfg->line_outs] = sequences_hp[i];
4728                         cfg->line_outs++;
4729                         cfg->hp_outs--;
4730                         memmove(cfg->hp_pins + i, cfg->hp_pins + i + 1,
4731                                 sizeof(cfg->hp_pins[0]) * (cfg->hp_outs - i));
4732                         memmove(sequences_hp + i, sequences_hp + i + 1,
4733                                 sizeof(sequences_hp[0]) * (cfg->hp_outs - i));
4734                 }
4735                 memset(cfg->hp_pins + cfg->hp_outs, 0,
4736                        sizeof(hda_nid_t) * (AUTO_CFG_MAX_OUTS - cfg->hp_outs));
4737                 if (!cfg->hp_outs)
4738                         cfg->line_out_type = AUTO_PIN_HP_OUT;
4739
4740         }
4741
4742         /* sort by sequence */
4743         sort_pins_by_sequence(cfg->line_out_pins, sequences_line_out,
4744                               cfg->line_outs);
4745         sort_pins_by_sequence(cfg->speaker_pins, sequences_speaker,
4746                               cfg->speaker_outs);
4747         sort_pins_by_sequence(cfg->hp_pins, sequences_hp,
4748                               cfg->hp_outs);
4749
4750         /*
4751          * FIX-UP: if no line-outs are detected, try to use speaker or HP pin
4752          * as a primary output
4753          */
4754         if (!cfg->line_outs) {
4755                 if (cfg->speaker_outs) {
4756                         cfg->line_outs = cfg->speaker_outs;
4757                         memcpy(cfg->line_out_pins, cfg->speaker_pins,
4758                                sizeof(cfg->speaker_pins));
4759                         cfg->speaker_outs = 0;
4760                         memset(cfg->speaker_pins, 0, sizeof(cfg->speaker_pins));
4761                         cfg->line_out_type = AUTO_PIN_SPEAKER_OUT;
4762                 } else if (cfg->hp_outs) {
4763                         cfg->line_outs = cfg->hp_outs;
4764                         memcpy(cfg->line_out_pins, cfg->hp_pins,
4765                                sizeof(cfg->hp_pins));
4766                         cfg->hp_outs = 0;
4767                         memset(cfg->hp_pins, 0, sizeof(cfg->hp_pins));
4768                         cfg->line_out_type = AUTO_PIN_HP_OUT;
4769                 }
4770         }
4771
4772         /* Reorder the surround channels
4773          * ALSA sequence is front/surr/clfe/side
4774          * HDA sequence is:
4775          *    4-ch: front/surr  =>  OK as it is
4776          *    6-ch: front/clfe/surr
4777          *    8-ch: front/clfe/rear/side|fc
4778          */
4779         switch (cfg->line_outs) {
4780         case 3:
4781         case 4:
4782                 nid = cfg->line_out_pins[1];
4783                 cfg->line_out_pins[1] = cfg->line_out_pins[2];
4784                 cfg->line_out_pins[2] = nid;
4785                 break;
4786         }
4787
4788         sort_autocfg_input_pins(cfg);
4789
4790         /*
4791          * debug prints of the parsed results
4792          */
4793         snd_printd("autoconfig: line_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x) type:%s\n",
4794                    cfg->line_outs, cfg->line_out_pins[0], cfg->line_out_pins[1],
4795                    cfg->line_out_pins[2], cfg->line_out_pins[3],
4796                    cfg->line_out_pins[4],
4797                    cfg->line_out_type == AUTO_PIN_HP_OUT ? "hp" :
4798                    (cfg->line_out_type == AUTO_PIN_SPEAKER_OUT ?
4799                     "speaker" : "line"));
4800         snd_printd("   speaker_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x)\n",
4801                    cfg->speaker_outs, cfg->speaker_pins[0],
4802                    cfg->speaker_pins[1], cfg->speaker_pins[2],
4803                    cfg->speaker_pins[3], cfg->speaker_pins[4]);
4804         snd_printd("   hp_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x)\n",
4805                    cfg->hp_outs, cfg->hp_pins[0],
4806                    cfg->hp_pins[1], cfg->hp_pins[2],
4807                    cfg->hp_pins[3], cfg->hp_pins[4]);
4808         snd_printd("   mono: mono_out=0x%x\n", cfg->mono_out_pin);
4809         if (cfg->dig_outs)
4810                 snd_printd("   dig-out=0x%x/0x%x\n",
4811                            cfg->dig_out_pins[0], cfg->dig_out_pins[1]);
4812         snd_printd("   inputs:");
4813         for (i = 0; i < cfg->num_inputs; i++) {
4814                 snd_printd(" %s=0x%x",
4815                             hda_get_autocfg_input_label(codec, cfg, i),
4816                             cfg->inputs[i].pin);
4817         }
4818         snd_printd("\n");
4819         if (cfg->dig_in_pin)
4820                 snd_printd("   dig-in=0x%x\n", cfg->dig_in_pin);
4821
4822         return 0;
4823 }
4824 EXPORT_SYMBOL_HDA(snd_hda_parse_pin_def_config);
4825
4826 int snd_hda_get_input_pin_attr(unsigned int def_conf)
4827 {
4828         unsigned int loc = get_defcfg_location(def_conf);
4829         unsigned int conn = get_defcfg_connect(def_conf);
4830         if (conn == AC_JACK_PORT_NONE)
4831                 return INPUT_PIN_ATTR_UNUSED;
4832         /* Windows may claim the internal mic to be BOTH, too */
4833         if (conn == AC_JACK_PORT_FIXED || conn == AC_JACK_PORT_BOTH)
4834                 return INPUT_PIN_ATTR_INT;
4835         if ((loc & 0x30) == AC_JACK_LOC_INTERNAL)
4836                 return INPUT_PIN_ATTR_INT;
4837         if ((loc & 0x30) == AC_JACK_LOC_SEPARATE)
4838                 return INPUT_PIN_ATTR_DOCK;
4839         if (loc == AC_JACK_LOC_REAR)
4840                 return INPUT_PIN_ATTR_REAR;
4841         if (loc == AC_JACK_LOC_FRONT)
4842                 return INPUT_PIN_ATTR_FRONT;
4843         return INPUT_PIN_ATTR_NORMAL;
4844 }
4845 EXPORT_SYMBOL_HDA(snd_hda_get_input_pin_attr);
4846
4847 /**
4848  * hda_get_input_pin_label - Give a label for the given input pin
4849  *
4850  * When check_location is true, the function checks the pin location
4851  * for mic and line-in pins, and set an appropriate prefix like "Front",
4852  * "Rear", "Internal".
4853  */
4854
4855 const char *hda_get_input_pin_label(struct hda_codec *codec, hda_nid_t pin,
4856                                         int check_location)
4857 {
4858         unsigned int def_conf;
4859         static const char * const mic_names[] = {
4860                 "Internal Mic", "Dock Mic", "Mic", "Front Mic", "Rear Mic",
4861         };
4862         int attr;
4863
4864         def_conf = snd_hda_codec_get_pincfg(codec, pin);
4865
4866         switch (get_defcfg_device(def_conf)) {
4867         case AC_JACK_MIC_IN:
4868                 if (!check_location)
4869                         return "Mic";
4870                 attr = snd_hda_get_input_pin_attr(def_conf);
4871                 if (!attr)
4872                         return "None";
4873                 return mic_names[attr - 1];
4874         case AC_JACK_LINE_IN:
4875                 if (!check_location)
4876                         return "Line";
4877                 attr = snd_hda_get_input_pin_attr(def_conf);
4878                 if (!attr)
4879                         return "None";
4880                 if (attr == INPUT_PIN_ATTR_DOCK)
4881                         return "Dock Line";
4882                 return "Line";
4883         case AC_JACK_AUX:
4884                 return "Aux";
4885         case AC_JACK_CD:
4886                 return "CD";
4887         case AC_JACK_SPDIF_IN:
4888                 return "SPDIF In";
4889         case AC_JACK_DIG_OTHER_IN:
4890                 return "Digital In";
4891         default:
4892                 return "Misc";
4893         }
4894 }
4895 EXPORT_SYMBOL_HDA(hda_get_input_pin_label);
4896
4897 /* Check whether the location prefix needs to be added to the label.
4898  * If all mic-jacks are in the same location (e.g. rear panel), we don't
4899  * have to put "Front" prefix to each label.  In such a case, returns false.
4900  */
4901 static int check_mic_location_need(struct hda_codec *codec,
4902                                    const struct auto_pin_cfg *cfg,
4903                                    int input)
4904 {
4905         unsigned int defc;
4906         int i, attr, attr2;
4907
4908         defc = snd_hda_codec_get_pincfg(codec, cfg->inputs[input].pin);
4909         attr = snd_hda_get_input_pin_attr(defc);
4910         /* for internal or docking mics, we need locations */
4911         if (attr <= INPUT_PIN_ATTR_NORMAL)
4912                 return 1;
4913
4914         attr = 0;
4915         for (i = 0; i < cfg->num_inputs; i++) {
4916                 defc = snd_hda_codec_get_pincfg(codec, cfg->inputs[i].pin);
4917                 attr2 = snd_hda_get_input_pin_attr(defc);
4918                 if (attr2 >= INPUT_PIN_ATTR_NORMAL) {
4919                         if (attr && attr != attr2)
4920                                 return 1; /* different locations found */
4921                         attr = attr2;
4922                 }
4923         }
4924         return 0;
4925 }
4926
4927 /**
4928  * hda_get_autocfg_input_label - Get a label for the given input
4929  *
4930  * Get a label for the given input pin defined by the autocfg item.
4931  * Unlike hda_get_input_pin_label(), this function checks all inputs
4932  * defined in autocfg and avoids the redundant mic/line prefix as much as
4933  * possible.
4934  */
4935 const char *hda_get_autocfg_input_label(struct hda_codec *codec,
4936                                         const struct auto_pin_cfg *cfg,
4937                                         int input)
4938 {
4939         int type = cfg->inputs[input].type;
4940         int has_multiple_pins = 0;
4941
4942         if ((input > 0 && cfg->inputs[input - 1].type == type) ||
4943             (input < cfg->num_inputs - 1 && cfg->inputs[input + 1].type == type))
4944                 has_multiple_pins = 1;
4945         if (has_multiple_pins && type == AUTO_PIN_MIC)
4946                 has_multiple_pins &= check_mic_location_need(codec, cfg, input);
4947         return hda_get_input_pin_label(codec, cfg->inputs[input].pin,
4948                                        has_multiple_pins);
4949 }
4950 EXPORT_SYMBOL_HDA(hda_get_autocfg_input_label);
4951
4952 /**
4953  * snd_hda_add_imux_item - Add an item to input_mux
4954  *
4955  * When the same label is used already in the existing items, the number
4956  * suffix is appended to the label.  This label index number is stored
4957  * to type_idx when non-NULL pointer is given.
4958  */
4959 int snd_hda_add_imux_item(struct hda_input_mux *imux, const char *label,
4960                           int index, int *type_idx)
4961 {
4962         int i, label_idx = 0;
4963         if (imux->num_items >= HDA_MAX_NUM_INPUTS) {
4964                 snd_printd(KERN_ERR "hda_codec: Too many imux items!\n");
4965                 return -EINVAL;
4966         }
4967         for (i = 0; i < imux->num_items; i++) {
4968                 if (!strncmp(label, imux->items[i].label, strlen(label)))
4969                         label_idx++;
4970         }
4971         if (type_idx)
4972                 *type_idx = label_idx;
4973         if (label_idx > 0)
4974                 snprintf(imux->items[imux->num_items].label,
4975                          sizeof(imux->items[imux->num_items].label),
4976                          "%s %d", label, label_idx);
4977         else
4978                 strlcpy(imux->items[imux->num_items].label, label,
4979                         sizeof(imux->items[imux->num_items].label));
4980         imux->items[imux->num_items].index = index;
4981         imux->num_items++;
4982         return 0;
4983 }
4984 EXPORT_SYMBOL_HDA(snd_hda_add_imux_item);
4985
4986
4987 #ifdef CONFIG_PM
4988 /*
4989  * power management
4990  */
4991
4992 /**
4993  * snd_hda_suspend - suspend the codecs
4994  * @bus: the HDA bus
4995  *
4996  * Returns 0 if successful.
4997  */
4998 int snd_hda_suspend(struct hda_bus *bus)
4999 {
5000         struct hda_codec *codec;
5001
5002         list_for_each_entry(codec, &bus->codec_list, list) {
5003 #ifdef CONFIG_SND_HDA_POWER_SAVE
5004                 if (!codec->power_on)
5005                         continue;
5006 #endif
5007                 hda_call_codec_suspend(codec);
5008         }
5009         return 0;
5010 }
5011 EXPORT_SYMBOL_HDA(snd_hda_suspend);
5012
5013 /**
5014  * snd_hda_resume - resume the codecs
5015  * @bus: the HDA bus
5016  *
5017  * Returns 0 if successful.
5018  *
5019  * This function is defined only when POWER_SAVE isn't set.
5020  * In the power-save mode, the codec is resumed dynamically.
5021  */
5022 int snd_hda_resume(struct hda_bus *bus)
5023 {
5024         struct hda_codec *codec;
5025
5026         list_for_each_entry(codec, &bus->codec_list, list) {
5027                 if (snd_hda_codec_needs_resume(codec))
5028                         hda_call_codec_resume(codec);
5029         }
5030         return 0;
5031 }
5032 EXPORT_SYMBOL_HDA(snd_hda_resume);
5033 #endif /* CONFIG_PM */
5034
5035 /*
5036  * generic arrays
5037  */
5038
5039 /**
5040  * snd_array_new - get a new element from the given array
5041  * @array: the array object
5042  *
5043  * Get a new element from the given array.  If it exceeds the
5044  * pre-allocated array size, re-allocate the array.
5045  *
5046  * Returns NULL if allocation failed.
5047  */
5048 void *snd_array_new(struct snd_array *array)
5049 {
5050         if (array->used >= array->alloced) {
5051                 int num = array->alloced + array->alloc_align;
5052                 void *nlist;
5053                 if (snd_BUG_ON(num >= 4096))
5054                         return NULL;
5055                 nlist = kcalloc(num + 1, array->elem_size, GFP_KERNEL);
5056                 if (!nlist)
5057                         return NULL;
5058                 if (array->list) {
5059                         memcpy(nlist, array->list,
5060                                array->elem_size * array->alloced);
5061                         kfree(array->list);
5062                 }
5063                 array->list = nlist;
5064                 array->alloced = num;
5065         }
5066         return snd_array_elem(array, array->used++);
5067 }
5068 EXPORT_SYMBOL_HDA(snd_array_new);
5069
5070 /**
5071  * snd_array_free - free the given array elements
5072  * @array: the array object
5073  */
5074 void snd_array_free(struct snd_array *array)
5075 {
5076         kfree(array->list);
5077         array->used = 0;
5078         array->alloced = 0;
5079         array->list = NULL;
5080 }
5081 EXPORT_SYMBOL_HDA(snd_array_free);
5082
5083 /**
5084  * snd_print_pcm_rates - Print the supported PCM rates to the string buffer
5085  * @pcm: PCM caps bits
5086  * @buf: the string buffer to write
5087  * @buflen: the max buffer length
5088  *
5089  * used by hda_proc.c and hda_eld.c
5090  */
5091 void snd_print_pcm_rates(int pcm, char *buf, int buflen)
5092 {
5093         static unsigned int rates[] = {
5094                 8000, 11025, 16000, 22050, 32000, 44100, 48000, 88200,
5095                 96000, 176400, 192000, 384000
5096         };
5097         int i, j;
5098
5099         for (i = 0, j = 0; i < ARRAY_SIZE(rates); i++)
5100                 if (pcm & (1 << i))
5101                         j += snprintf(buf + j, buflen - j,  " %d", rates[i]);
5102
5103         buf[j] = '\0'; /* necessary when j == 0 */
5104 }
5105 EXPORT_SYMBOL_HDA(snd_print_pcm_rates);
5106
5107 /**
5108  * snd_print_pcm_bits - Print the supported PCM fmt bits to the string buffer
5109  * @pcm: PCM caps bits
5110  * @buf: the string buffer to write
5111  * @buflen: the max buffer length
5112  *
5113  * used by hda_proc.c and hda_eld.c
5114  */
5115 void snd_print_pcm_bits(int pcm, char *buf, int buflen)
5116 {
5117         static unsigned int bits[] = { 8, 16, 20, 24, 32 };
5118         int i, j;
5119
5120         for (i = 0, j = 0; i < ARRAY_SIZE(bits); i++)
5121                 if (pcm & (AC_SUPPCM_BITS_8 << i))
5122                         j += snprintf(buf + j, buflen - j,  " %d", bits[i]);
5123
5124         buf[j] = '\0'; /* necessary when j == 0 */
5125 }
5126 EXPORT_SYMBOL_HDA(snd_print_pcm_bits);
5127
5128 #ifdef CONFIG_SND_HDA_INPUT_JACK
5129 /*
5130  * Input-jack notification support
5131  */
5132 struct hda_jack_item {
5133         hda_nid_t nid;
5134         int type;
5135         struct snd_jack *jack;
5136 };
5137
5138 static const char *get_jack_default_name(struct hda_codec *codec, hda_nid_t nid,
5139                                          int type)
5140 {
5141         switch (type) {
5142         case SND_JACK_HEADPHONE:
5143                 return "Headphone";
5144         case SND_JACK_MICROPHONE:
5145                 return "Mic";
5146         case SND_JACK_LINEOUT:
5147                 return "Line-out";
5148         case SND_JACK_HEADSET:
5149                 return "Headset";
5150         case SND_JACK_VIDEOOUT:
5151                 return "HDMI/DP";
5152         default:
5153                 return "Misc";
5154         }
5155 }
5156
5157 static void hda_free_jack_priv(struct snd_jack *jack)
5158 {
5159         struct hda_jack_item *jacks = jack->private_data;
5160         jacks->nid = 0;
5161         jacks->jack = NULL;
5162 }
5163
5164 int snd_hda_input_jack_add(struct hda_codec *codec, hda_nid_t nid, int type,
5165                            const char *name)
5166 {
5167         struct hda_jack_item *jack;
5168         int err;
5169
5170         snd_array_init(&codec->jacks, sizeof(*jack), 32);
5171         jack = snd_array_new(&codec->jacks);
5172         if (!jack)
5173                 return -ENOMEM;
5174
5175         jack->nid = nid;
5176         jack->type = type;
5177         if (!name)
5178                 name = get_jack_default_name(codec, nid, type);
5179         err = snd_jack_new(codec->bus->card, name, type, &jack->jack);
5180         if (err < 0) {
5181                 jack->nid = 0;
5182                 return err;
5183         }
5184         jack->jack->private_data = jack;
5185         jack->jack->private_free = hda_free_jack_priv;
5186         return 0;
5187 }
5188 EXPORT_SYMBOL_HDA(snd_hda_input_jack_add);
5189
5190 void snd_hda_input_jack_report(struct hda_codec *codec, hda_nid_t nid)
5191 {
5192         struct hda_jack_item *jacks = codec->jacks.list;
5193         int i;
5194
5195         if (!jacks)
5196                 return;
5197
5198         for (i = 0; i < codec->jacks.used; i++, jacks++) {
5199                 unsigned int pin_ctl;
5200                 unsigned int present;
5201                 int type;
5202
5203                 if (jacks->nid != nid)
5204                         continue;
5205                 present = snd_hda_jack_detect(codec, nid);
5206                 type = jacks->type;
5207                 if (type == (SND_JACK_HEADPHONE | SND_JACK_LINEOUT)) {
5208                         pin_ctl = snd_hda_codec_read(codec, nid, 0,
5209                                              AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
5210                         type = (pin_ctl & AC_PINCTL_HP_EN) ?
5211                                 SND_JACK_HEADPHONE : SND_JACK_LINEOUT;
5212                 }
5213                 snd_jack_report(jacks->jack, present ? type : 0);
5214         }
5215 }
5216 EXPORT_SYMBOL_HDA(snd_hda_input_jack_report);
5217
5218 /* free jack instances manually when clearing/reconfiguring */
5219 void snd_hda_input_jack_free(struct hda_codec *codec)
5220 {
5221         if (!codec->bus->shutdown && codec->jacks.list) {
5222                 struct hda_jack_item *jacks = codec->jacks.list;
5223                 int i;
5224                 for (i = 0; i < codec->jacks.used; i++, jacks++) {
5225                         if (jacks->jack)
5226                                 snd_device_free(codec->bus->card, jacks->jack);
5227                 }
5228         }
5229         snd_array_free(&codec->jacks);
5230 }
5231 EXPORT_SYMBOL_HDA(snd_hda_input_jack_free);
5232 #endif /* CONFIG_SND_HDA_INPUT_JACK */
5233
5234 MODULE_DESCRIPTION("HDA codec core");
5235 MODULE_LICENSE("GPL");