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