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