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