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