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