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