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