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