OSDN Git Service

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