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