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