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