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