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