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