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