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