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