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