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