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