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