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