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