]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - sound/pci/hda/hda_codec.c
Merge branches 'pm-cpu', 'pm-cpuidle' and 'pm-domains'
[karo-tx-linux.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)->core.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 #define codec_has_epss(codec) \
52         ((codec)->core.power_caps & AC_PWRST_EPSS)
53 #define codec_has_clkstop(codec) \
54         ((codec)->core.power_caps & AC_PWRST_CLKSTOP)
55
56 /**
57  * snd_hda_get_jack_location - Give a location string of the jack
58  * @cfg: pin default config value
59  *
60  * Parse the pin default config value and returns the string of the
61  * jack location, e.g. "Rear", "Front", etc.
62  */
63 const char *snd_hda_get_jack_location(u32 cfg)
64 {
65         static char *bases[7] = {
66                 "N/A", "Rear", "Front", "Left", "Right", "Top", "Bottom",
67         };
68         static unsigned char specials_idx[] = {
69                 0x07, 0x08,
70                 0x17, 0x18, 0x19,
71                 0x37, 0x38
72         };
73         static char *specials[] = {
74                 "Rear Panel", "Drive Bar",
75                 "Riser", "HDMI", "ATAPI",
76                 "Mobile-In", "Mobile-Out"
77         };
78         int i;
79         cfg = (cfg & AC_DEFCFG_LOCATION) >> AC_DEFCFG_LOCATION_SHIFT;
80         if ((cfg & 0x0f) < 7)
81                 return bases[cfg & 0x0f];
82         for (i = 0; i < ARRAY_SIZE(specials_idx); i++) {
83                 if (cfg == specials_idx[i])
84                         return specials[i];
85         }
86         return "UNKNOWN";
87 }
88 EXPORT_SYMBOL_GPL(snd_hda_get_jack_location);
89
90 /**
91  * snd_hda_get_jack_connectivity - Give a connectivity string of the jack
92  * @cfg: pin default config value
93  *
94  * Parse the pin default config value and returns the string of the
95  * jack connectivity, i.e. external or internal connection.
96  */
97 const char *snd_hda_get_jack_connectivity(u32 cfg)
98 {
99         static char *jack_locations[4] = { "Ext", "Int", "Sep", "Oth" };
100
101         return jack_locations[(cfg >> (AC_DEFCFG_LOCATION_SHIFT + 4)) & 3];
102 }
103 EXPORT_SYMBOL_GPL(snd_hda_get_jack_connectivity);
104
105 /**
106  * snd_hda_get_jack_type - Give a type string of the jack
107  * @cfg: pin default config value
108  *
109  * Parse the pin default config value and returns the string of the
110  * jack type, i.e. the purpose of the jack, such as Line-Out or CD.
111  */
112 const char *snd_hda_get_jack_type(u32 cfg)
113 {
114         static char *jack_types[16] = {
115                 "Line Out", "Speaker", "HP Out", "CD",
116                 "SPDIF Out", "Digital Out", "Modem Line", "Modem Hand",
117                 "Line In", "Aux", "Mic", "Telephony",
118                 "SPDIF In", "Digital In", "Reserved", "Other"
119         };
120
121         return jack_types[(cfg & AC_DEFCFG_DEVICE)
122                                 >> AC_DEFCFG_DEVICE_SHIFT];
123 }
124 EXPORT_SYMBOL_GPL(snd_hda_get_jack_type);
125
126 /*
127  * Send and receive a verb - passed to exec_verb override for hdac_device
128  */
129 static int codec_exec_verb(struct hdac_device *dev, unsigned int cmd,
130                            unsigned int flags, unsigned int *res)
131 {
132         struct hda_codec *codec = container_of(dev, struct hda_codec, core);
133         struct hda_bus *bus = codec->bus;
134         int err;
135
136         if (cmd == ~0)
137                 return -1;
138
139  again:
140         snd_hda_power_up_pm(codec);
141         mutex_lock(&bus->core.cmd_mutex);
142         if (flags & HDA_RW_NO_RESPONSE_FALLBACK)
143                 bus->no_response_fallback = 1;
144         err = snd_hdac_bus_exec_verb_unlocked(&bus->core, codec->core.addr,
145                                               cmd, res);
146         bus->no_response_fallback = 0;
147         mutex_unlock(&bus->core.cmd_mutex);
148         snd_hda_power_down_pm(codec);
149         if (!codec_in_pm(codec) && res && err == -EAGAIN) {
150                 if (bus->response_reset) {
151                         codec_dbg(codec,
152                                   "resetting BUS due to fatal communication error\n");
153                         snd_hda_bus_reset(bus);
154                 }
155                 goto again;
156         }
157         /* clear reset-flag when the communication gets recovered */
158         if (!err || codec_in_pm(codec))
159                 bus->response_reset = 0;
160         return err;
161 }
162
163 /**
164  * snd_hda_codec_read - send a command and get the response
165  * @codec: the HDA codec
166  * @nid: NID to send the command
167  * @flags: optional bit flags
168  * @verb: the verb to send
169  * @parm: the parameter for the verb
170  *
171  * Send a single command and read the corresponding response.
172  *
173  * Returns the obtained response value, or -1 for an error.
174  */
175 unsigned int snd_hda_codec_read(struct hda_codec *codec, hda_nid_t nid,
176                                 int flags,
177                                 unsigned int verb, unsigned int parm)
178 {
179         unsigned int cmd = snd_hdac_make_cmd(&codec->core, nid, verb, parm);
180         unsigned int res;
181         if (snd_hdac_exec_verb(&codec->core, cmd, flags, &res))
182                 return -1;
183         return res;
184 }
185 EXPORT_SYMBOL_GPL(snd_hda_codec_read);
186
187 /**
188  * snd_hda_codec_write - send a single command without waiting for response
189  * @codec: the HDA codec
190  * @nid: NID to send the command
191  * @flags: optional bit flags
192  * @verb: the verb to send
193  * @parm: the parameter for the verb
194  *
195  * Send a single command without waiting for response.
196  *
197  * Returns 0 if successful, or a negative error code.
198  */
199 int snd_hda_codec_write(struct hda_codec *codec, hda_nid_t nid, int flags,
200                         unsigned int verb, unsigned int parm)
201 {
202         unsigned int cmd = snd_hdac_make_cmd(&codec->core, nid, verb, parm);
203         return snd_hdac_exec_verb(&codec->core, cmd, flags, NULL);
204 }
205 EXPORT_SYMBOL_GPL(snd_hda_codec_write);
206
207 /**
208  * snd_hda_sequence_write - sequence writes
209  * @codec: the HDA codec
210  * @seq: VERB array to send
211  *
212  * Send the commands sequentially from the given array.
213  * The array must be terminated with NID=0.
214  */
215 void snd_hda_sequence_write(struct hda_codec *codec, const struct hda_verb *seq)
216 {
217         for (; seq->nid; seq++)
218                 snd_hda_codec_write(codec, seq->nid, 0, seq->verb, seq->param);
219 }
220 EXPORT_SYMBOL_GPL(snd_hda_sequence_write);
221
222 /* connection list element */
223 struct hda_conn_list {
224         struct list_head list;
225         int len;
226         hda_nid_t nid;
227         hda_nid_t conns[0];
228 };
229
230 /* look up the cached results */
231 static struct hda_conn_list *
232 lookup_conn_list(struct hda_codec *codec, hda_nid_t nid)
233 {
234         struct hda_conn_list *p;
235         list_for_each_entry(p, &codec->conn_list, list) {
236                 if (p->nid == nid)
237                         return p;
238         }
239         return NULL;
240 }
241
242 static int add_conn_list(struct hda_codec *codec, hda_nid_t nid, int len,
243                          const hda_nid_t *list)
244 {
245         struct hda_conn_list *p;
246
247         p = kmalloc(sizeof(*p) + len * sizeof(hda_nid_t), GFP_KERNEL);
248         if (!p)
249                 return -ENOMEM;
250         p->len = len;
251         p->nid = nid;
252         memcpy(p->conns, list, len * sizeof(hda_nid_t));
253         list_add(&p->list, &codec->conn_list);
254         return 0;
255 }
256
257 static void remove_conn_list(struct hda_codec *codec)
258 {
259         while (!list_empty(&codec->conn_list)) {
260                 struct hda_conn_list *p;
261                 p = list_first_entry(&codec->conn_list, typeof(*p), list);
262                 list_del(&p->list);
263                 kfree(p);
264         }
265 }
266
267 /* read the connection and add to the cache */
268 static int read_and_add_raw_conns(struct hda_codec *codec, hda_nid_t nid)
269 {
270         hda_nid_t list[32];
271         hda_nid_t *result = list;
272         int len;
273
274         len = snd_hda_get_raw_connections(codec, nid, list, ARRAY_SIZE(list));
275         if (len == -ENOSPC) {
276                 len = snd_hda_get_num_raw_conns(codec, nid);
277                 result = kmalloc(sizeof(hda_nid_t) * len, GFP_KERNEL);
278                 if (!result)
279                         return -ENOMEM;
280                 len = snd_hda_get_raw_connections(codec, nid, result, len);
281         }
282         if (len >= 0)
283                 len = snd_hda_override_conn_list(codec, nid, len, result);
284         if (result != list)
285                 kfree(result);
286         return len;
287 }
288
289 /**
290  * snd_hda_get_conn_list - get connection list
291  * @codec: the HDA codec
292  * @nid: NID to parse
293  * @listp: the pointer to store NID list
294  *
295  * Parses the connection list of the given widget and stores the pointer
296  * to the list of NIDs.
297  *
298  * Returns the number of connections, or a negative error code.
299  *
300  * Note that the returned pointer isn't protected against the list
301  * modification.  If snd_hda_override_conn_list() might be called
302  * concurrently, protect with a mutex appropriately.
303  */
304 int snd_hda_get_conn_list(struct hda_codec *codec, hda_nid_t nid,
305                           const hda_nid_t **listp)
306 {
307         bool added = false;
308
309         for (;;) {
310                 int err;
311                 const struct hda_conn_list *p;
312
313                 /* if the connection-list is already cached, read it */
314                 p = lookup_conn_list(codec, nid);
315                 if (p) {
316                         if (listp)
317                                 *listp = p->conns;
318                         return p->len;
319                 }
320                 if (snd_BUG_ON(added))
321                         return -EINVAL;
322
323                 err = read_and_add_raw_conns(codec, nid);
324                 if (err < 0)
325                         return err;
326                 added = true;
327         }
328 }
329 EXPORT_SYMBOL_GPL(snd_hda_get_conn_list);
330
331 /**
332  * snd_hda_get_connections - copy connection list
333  * @codec: the HDA codec
334  * @nid: NID to parse
335  * @conn_list: connection list array; when NULL, checks only the size
336  * @max_conns: max. number of connections to store
337  *
338  * Parses the connection list of the given widget and stores the list
339  * of NIDs.
340  *
341  * Returns the number of connections, or a negative error code.
342  */
343 int snd_hda_get_connections(struct hda_codec *codec, hda_nid_t nid,
344                             hda_nid_t *conn_list, int max_conns)
345 {
346         const hda_nid_t *list;
347         int len = snd_hda_get_conn_list(codec, nid, &list);
348
349         if (len > 0 && conn_list) {
350                 if (len > max_conns) {
351                         codec_err(codec, "Too many connections %d for NID 0x%x\n",
352                                    len, nid);
353                         return -EINVAL;
354                 }
355                 memcpy(conn_list, list, len * sizeof(hda_nid_t));
356         }
357
358         return len;
359 }
360 EXPORT_SYMBOL_GPL(snd_hda_get_connections);
361
362 /**
363  * snd_hda_override_conn_list - add/modify the connection-list to cache
364  * @codec: the HDA codec
365  * @nid: NID to parse
366  * @len: number of connection list entries
367  * @list: the list of connection entries
368  *
369  * Add or modify the given connection-list to the cache.  If the corresponding
370  * cache already exists, invalidate it and append a new one.
371  *
372  * Returns zero or a negative error code.
373  */
374 int snd_hda_override_conn_list(struct hda_codec *codec, hda_nid_t nid, int len,
375                                const hda_nid_t *list)
376 {
377         struct hda_conn_list *p;
378
379         p = lookup_conn_list(codec, nid);
380         if (p) {
381                 list_del(&p->list);
382                 kfree(p);
383         }
384
385         return add_conn_list(codec, nid, len, list);
386 }
387 EXPORT_SYMBOL_GPL(snd_hda_override_conn_list);
388
389 /**
390  * snd_hda_get_conn_index - get the connection index of the given NID
391  * @codec: the HDA codec
392  * @mux: NID containing the list
393  * @nid: NID to select
394  * @recursive: 1 when searching NID recursively, otherwise 0
395  *
396  * Parses the connection list of the widget @mux and checks whether the
397  * widget @nid is present.  If it is, return the connection index.
398  * Otherwise it returns -1.
399  */
400 int snd_hda_get_conn_index(struct hda_codec *codec, hda_nid_t mux,
401                            hda_nid_t nid, int recursive)
402 {
403         const hda_nid_t *conn;
404         int i, nums;
405
406         nums = snd_hda_get_conn_list(codec, mux, &conn);
407         for (i = 0; i < nums; i++)
408                 if (conn[i] == nid)
409                         return i;
410         if (!recursive)
411                 return -1;
412         if (recursive > 10) {
413                 codec_dbg(codec, "too deep connection for 0x%x\n", nid);
414                 return -1;
415         }
416         recursive++;
417         for (i = 0; i < nums; i++) {
418                 unsigned int type = get_wcaps_type(get_wcaps(codec, conn[i]));
419                 if (type == AC_WID_PIN || type == AC_WID_AUD_OUT)
420                         continue;
421                 if (snd_hda_get_conn_index(codec, conn[i], nid, recursive) >= 0)
422                         return i;
423         }
424         return -1;
425 }
426 EXPORT_SYMBOL_GPL(snd_hda_get_conn_index);
427
428
429 /* return DEVLIST_LEN parameter of the given widget */
430 static unsigned int get_num_devices(struct hda_codec *codec, hda_nid_t nid)
431 {
432         unsigned int wcaps = get_wcaps(codec, nid);
433         unsigned int parm;
434
435         if (!codec->dp_mst || !(wcaps & AC_WCAP_DIGITAL) ||
436             get_wcaps_type(wcaps) != AC_WID_PIN)
437                 return 0;
438
439         parm = snd_hdac_read_parm_uncached(&codec->core, nid, AC_PAR_DEVLIST_LEN);
440         if (parm == -1)
441                 parm = 0;
442         return parm & AC_DEV_LIST_LEN_MASK;
443 }
444
445 /**
446  * snd_hda_get_devices - copy device list without cache
447  * @codec: the HDA codec
448  * @nid: NID of the pin to parse
449  * @dev_list: device list array
450  * @max_devices: max. number of devices to store
451  *
452  * Copy the device list. This info is dynamic and so not cached.
453  * Currently called only from hda_proc.c, so not exported.
454  */
455 int snd_hda_get_devices(struct hda_codec *codec, hda_nid_t nid,
456                         u8 *dev_list, int max_devices)
457 {
458         unsigned int parm;
459         int i, dev_len, devices;
460
461         parm = get_num_devices(codec, nid);
462         if (!parm)      /* not multi-stream capable */
463                 return 0;
464
465         dev_len = parm + 1;
466         dev_len = dev_len < max_devices ? dev_len : max_devices;
467
468         devices = 0;
469         while (devices < dev_len) {
470                 if (snd_hdac_read(&codec->core, nid,
471                                   AC_VERB_GET_DEVICE_LIST, devices, &parm))
472                         break; /* error */
473
474                 for (i = 0; i < 8; i++) {
475                         dev_list[devices] = (u8)parm;
476                         parm >>= 4;
477                         devices++;
478                         if (devices >= dev_len)
479                                 break;
480                 }
481         }
482         return devices;
483 }
484
485 /*
486  * read widget caps for each widget and store in cache
487  */
488 static int read_widget_caps(struct hda_codec *codec, hda_nid_t fg_node)
489 {
490         int i;
491         hda_nid_t nid;
492
493         codec->wcaps = kmalloc(codec->core.num_nodes * 4, GFP_KERNEL);
494         if (!codec->wcaps)
495                 return -ENOMEM;
496         nid = codec->core.start_nid;
497         for (i = 0; i < codec->core.num_nodes; i++, nid++)
498                 codec->wcaps[i] = snd_hdac_read_parm_uncached(&codec->core,
499                                         nid, AC_PAR_AUDIO_WIDGET_CAP);
500         return 0;
501 }
502
503 /* read all pin default configurations and save codec->init_pins */
504 static int read_pin_defaults(struct hda_codec *codec)
505 {
506         hda_nid_t nid;
507
508         for_each_hda_codec_node(nid, codec) {
509                 struct hda_pincfg *pin;
510                 unsigned int wcaps = get_wcaps(codec, nid);
511                 unsigned int wid_type = get_wcaps_type(wcaps);
512                 if (wid_type != AC_WID_PIN)
513                         continue;
514                 pin = snd_array_new(&codec->init_pins);
515                 if (!pin)
516                         return -ENOMEM;
517                 pin->nid = nid;
518                 pin->cfg = snd_hda_codec_read(codec, nid, 0,
519                                               AC_VERB_GET_CONFIG_DEFAULT, 0);
520                 pin->ctrl = snd_hda_codec_read(codec, nid, 0,
521                                                AC_VERB_GET_PIN_WIDGET_CONTROL,
522                                                0);
523         }
524         return 0;
525 }
526
527 /* look up the given pin config list and return the item matching with NID */
528 static struct hda_pincfg *look_up_pincfg(struct hda_codec *codec,
529                                          struct snd_array *array,
530                                          hda_nid_t nid)
531 {
532         int i;
533         for (i = 0; i < array->used; i++) {
534                 struct hda_pincfg *pin = snd_array_elem(array, i);
535                 if (pin->nid == nid)
536                         return pin;
537         }
538         return NULL;
539 }
540
541 /* set the current pin config value for the given NID.
542  * the value is cached, and read via snd_hda_codec_get_pincfg()
543  */
544 int snd_hda_add_pincfg(struct hda_codec *codec, struct snd_array *list,
545                        hda_nid_t nid, unsigned int cfg)
546 {
547         struct hda_pincfg *pin;
548
549         /* the check below may be invalid when pins are added by a fixup
550          * dynamically (e.g. via snd_hda_codec_update_widgets()), so disabled
551          * for now
552          */
553         /*
554         if (get_wcaps_type(get_wcaps(codec, nid)) != AC_WID_PIN)
555                 return -EINVAL;
556         */
557
558         pin = look_up_pincfg(codec, list, nid);
559         if (!pin) {
560                 pin = snd_array_new(list);
561                 if (!pin)
562                         return -ENOMEM;
563                 pin->nid = nid;
564         }
565         pin->cfg = cfg;
566         return 0;
567 }
568
569 /**
570  * snd_hda_codec_set_pincfg - Override a pin default configuration
571  * @codec: the HDA codec
572  * @nid: NID to set the pin config
573  * @cfg: the pin default config value
574  *
575  * Override a pin default configuration value in the cache.
576  * This value can be read by snd_hda_codec_get_pincfg() in a higher
577  * priority than the real hardware value.
578  */
579 int snd_hda_codec_set_pincfg(struct hda_codec *codec,
580                              hda_nid_t nid, unsigned int cfg)
581 {
582         return snd_hda_add_pincfg(codec, &codec->driver_pins, nid, cfg);
583 }
584 EXPORT_SYMBOL_GPL(snd_hda_codec_set_pincfg);
585
586 /**
587  * snd_hda_codec_get_pincfg - Obtain a pin-default configuration
588  * @codec: the HDA codec
589  * @nid: NID to get the pin config
590  *
591  * Get the current pin config value of the given pin NID.
592  * If the pincfg value is cached or overridden via sysfs or driver,
593  * returns the cached value.
594  */
595 unsigned int snd_hda_codec_get_pincfg(struct hda_codec *codec, hda_nid_t nid)
596 {
597         struct hda_pincfg *pin;
598
599 #ifdef CONFIG_SND_HDA_RECONFIG
600         {
601                 unsigned int cfg = 0;
602                 mutex_lock(&codec->user_mutex);
603                 pin = look_up_pincfg(codec, &codec->user_pins, nid);
604                 if (pin)
605                         cfg = pin->cfg;
606                 mutex_unlock(&codec->user_mutex);
607                 if (cfg)
608                         return cfg;
609         }
610 #endif
611         pin = look_up_pincfg(codec, &codec->driver_pins, nid);
612         if (pin)
613                 return pin->cfg;
614         pin = look_up_pincfg(codec, &codec->init_pins, nid);
615         if (pin)
616                 return pin->cfg;
617         return 0;
618 }
619 EXPORT_SYMBOL_GPL(snd_hda_codec_get_pincfg);
620
621 /**
622  * snd_hda_codec_set_pin_target - remember the current pinctl target value
623  * @codec: the HDA codec
624  * @nid: pin NID
625  * @val: assigned pinctl value
626  *
627  * This function stores the given value to a pinctl target value in the
628  * pincfg table.  This isn't always as same as the actually written value
629  * but can be referred at any time via snd_hda_codec_get_pin_target().
630  */
631 int snd_hda_codec_set_pin_target(struct hda_codec *codec, hda_nid_t nid,
632                                  unsigned int val)
633 {
634         struct hda_pincfg *pin;
635
636         pin = look_up_pincfg(codec, &codec->init_pins, nid);
637         if (!pin)
638                 return -EINVAL;
639         pin->target = val;
640         return 0;
641 }
642 EXPORT_SYMBOL_GPL(snd_hda_codec_set_pin_target);
643
644 /**
645  * snd_hda_codec_get_pin_target - return the current pinctl target value
646  * @codec: the HDA codec
647  * @nid: pin NID
648  */
649 int snd_hda_codec_get_pin_target(struct hda_codec *codec, hda_nid_t nid)
650 {
651         struct hda_pincfg *pin;
652
653         pin = look_up_pincfg(codec, &codec->init_pins, nid);
654         if (!pin)
655                 return 0;
656         return pin->target;
657 }
658 EXPORT_SYMBOL_GPL(snd_hda_codec_get_pin_target);
659
660 /**
661  * snd_hda_shutup_pins - Shut up all pins
662  * @codec: the HDA codec
663  *
664  * Clear all pin controls to shup up before suspend for avoiding click noise.
665  * The controls aren't cached so that they can be resumed properly.
666  */
667 void snd_hda_shutup_pins(struct hda_codec *codec)
668 {
669         int i;
670         /* don't shut up pins when unloading the driver; otherwise it breaks
671          * the default pin setup at the next load of the driver
672          */
673         if (codec->bus->shutdown)
674                 return;
675         for (i = 0; i < codec->init_pins.used; i++) {
676                 struct hda_pincfg *pin = snd_array_elem(&codec->init_pins, i);
677                 /* use read here for syncing after issuing each verb */
678                 snd_hda_codec_read(codec, pin->nid, 0,
679                                    AC_VERB_SET_PIN_WIDGET_CONTROL, 0);
680         }
681         codec->pins_shutup = 1;
682 }
683 EXPORT_SYMBOL_GPL(snd_hda_shutup_pins);
684
685 #ifdef CONFIG_PM
686 /* Restore the pin controls cleared previously via snd_hda_shutup_pins() */
687 static void restore_shutup_pins(struct hda_codec *codec)
688 {
689         int i;
690         if (!codec->pins_shutup)
691                 return;
692         if (codec->bus->shutdown)
693                 return;
694         for (i = 0; i < codec->init_pins.used; i++) {
695                 struct hda_pincfg *pin = snd_array_elem(&codec->init_pins, i);
696                 snd_hda_codec_write(codec, pin->nid, 0,
697                                     AC_VERB_SET_PIN_WIDGET_CONTROL,
698                                     pin->ctrl);
699         }
700         codec->pins_shutup = 0;
701 }
702 #endif
703
704 static void hda_jackpoll_work(struct work_struct *work)
705 {
706         struct hda_codec *codec =
707                 container_of(work, struct hda_codec, jackpoll_work.work);
708
709         snd_hda_jack_set_dirty_all(codec);
710         snd_hda_jack_poll_all(codec);
711
712         if (!codec->jackpoll_interval)
713                 return;
714
715         schedule_delayed_work(&codec->jackpoll_work,
716                               codec->jackpoll_interval);
717 }
718
719 /* release all pincfg lists */
720 static void free_init_pincfgs(struct hda_codec *codec)
721 {
722         snd_array_free(&codec->driver_pins);
723 #ifdef CONFIG_SND_HDA_RECONFIG
724         snd_array_free(&codec->user_pins);
725 #endif
726         snd_array_free(&codec->init_pins);
727 }
728
729 /*
730  * audio-converter setup caches
731  */
732 struct hda_cvt_setup {
733         hda_nid_t nid;
734         u8 stream_tag;
735         u8 channel_id;
736         u16 format_id;
737         unsigned char active;   /* cvt is currently used */
738         unsigned char dirty;    /* setups should be cleared */
739 };
740
741 /* get or create a cache entry for the given audio converter NID */
742 static struct hda_cvt_setup *
743 get_hda_cvt_setup(struct hda_codec *codec, hda_nid_t nid)
744 {
745         struct hda_cvt_setup *p;
746         int i;
747
748         for (i = 0; i < codec->cvt_setups.used; i++) {
749                 p = snd_array_elem(&codec->cvt_setups, i);
750                 if (p->nid == nid)
751                         return p;
752         }
753         p = snd_array_new(&codec->cvt_setups);
754         if (p)
755                 p->nid = nid;
756         return p;
757 }
758
759 /*
760  * PCM device
761  */
762 static void release_pcm(struct kref *kref)
763 {
764         struct hda_pcm *pcm = container_of(kref, struct hda_pcm, kref);
765
766         if (pcm->pcm)
767                 snd_device_free(pcm->codec->card, pcm->pcm);
768         clear_bit(pcm->device, pcm->codec->bus->pcm_dev_bits);
769         kfree(pcm->name);
770         kfree(pcm);
771 }
772
773 void snd_hda_codec_pcm_put(struct hda_pcm *pcm)
774 {
775         kref_put(&pcm->kref, release_pcm);
776 }
777 EXPORT_SYMBOL_GPL(snd_hda_codec_pcm_put);
778
779 struct hda_pcm *snd_hda_codec_pcm_new(struct hda_codec *codec,
780                                       const char *fmt, ...)
781 {
782         struct hda_pcm *pcm;
783         va_list args;
784
785         pcm = kzalloc(sizeof(*pcm), GFP_KERNEL);
786         if (!pcm)
787                 return NULL;
788
789         pcm->codec = codec;
790         kref_init(&pcm->kref);
791         va_start(args, fmt);
792         pcm->name = kvasprintf(GFP_KERNEL, fmt, args);
793         va_end(args);
794         if (!pcm->name) {
795                 kfree(pcm);
796                 return NULL;
797         }
798
799         list_add_tail(&pcm->list, &codec->pcm_list_head);
800         return pcm;
801 }
802 EXPORT_SYMBOL_GPL(snd_hda_codec_pcm_new);
803
804 /*
805  * codec destructor
806  */
807 static void codec_release_pcms(struct hda_codec *codec)
808 {
809         struct hda_pcm *pcm, *n;
810
811         list_for_each_entry_safe(pcm, n, &codec->pcm_list_head, list) {
812                 list_del_init(&pcm->list);
813                 if (pcm->pcm)
814                         snd_device_disconnect(codec->card, pcm->pcm);
815                 snd_hda_codec_pcm_put(pcm);
816         }
817 }
818
819 void snd_hda_codec_cleanup_for_unbind(struct hda_codec *codec)
820 {
821         if (codec->registered) {
822                 /* pm_runtime_put() is called in snd_hdac_device_exit() */
823                 pm_runtime_get_noresume(hda_codec_dev(codec));
824                 pm_runtime_disable(hda_codec_dev(codec));
825                 codec->registered = 0;
826         }
827
828         cancel_delayed_work_sync(&codec->jackpoll_work);
829         if (!codec->in_freeing)
830                 snd_hda_ctls_clear(codec);
831         codec_release_pcms(codec);
832         snd_hda_detach_beep_device(codec);
833         memset(&codec->patch_ops, 0, sizeof(codec->patch_ops));
834         snd_hda_jack_tbl_clear(codec);
835         codec->proc_widget_hook = NULL;
836         codec->spec = NULL;
837
838         /* free only driver_pins so that init_pins + user_pins are restored */
839         snd_array_free(&codec->driver_pins);
840         snd_array_free(&codec->cvt_setups);
841         snd_array_free(&codec->spdif_out);
842         snd_array_free(&codec->verbs);
843         codec->preset = NULL;
844         codec->slave_dig_outs = NULL;
845         codec->spdif_status_reset = 0;
846         snd_array_free(&codec->mixers);
847         snd_array_free(&codec->nids);
848         remove_conn_list(codec);
849         snd_hdac_regmap_exit(&codec->core);
850 }
851
852 static unsigned int hda_set_power_state(struct hda_codec *codec,
853                                 unsigned int power_state);
854
855 /* also called from hda_bind.c */
856 void snd_hda_codec_register(struct hda_codec *codec)
857 {
858         if (codec->registered)
859                 return;
860         if (device_is_registered(hda_codec_dev(codec))) {
861                 snd_hda_register_beep_device(codec);
862                 snd_hdac_link_power(&codec->core, true);
863                 pm_runtime_enable(hda_codec_dev(codec));
864                 /* it was powered up in snd_hda_codec_new(), now all done */
865                 snd_hda_power_down(codec);
866                 codec->registered = 1;
867         }
868 }
869
870 static int snd_hda_codec_dev_register(struct snd_device *device)
871 {
872         snd_hda_codec_register(device->device_data);
873         return 0;
874 }
875
876 static int snd_hda_codec_dev_disconnect(struct snd_device *device)
877 {
878         struct hda_codec *codec = device->device_data;
879
880         snd_hda_detach_beep_device(codec);
881         return 0;
882 }
883
884 static int snd_hda_codec_dev_free(struct snd_device *device)
885 {
886         struct hda_codec *codec = device->device_data;
887
888         codec->in_freeing = 1;
889         snd_hdac_device_unregister(&codec->core);
890         snd_hdac_link_power(&codec->core, false);
891         put_device(hda_codec_dev(codec));
892         return 0;
893 }
894
895 static void snd_hda_codec_dev_release(struct device *dev)
896 {
897         struct hda_codec *codec = dev_to_hda_codec(dev);
898
899         free_init_pincfgs(codec);
900         snd_hdac_device_exit(&codec->core);
901         snd_hda_sysfs_clear(codec);
902         kfree(codec->modelname);
903         kfree(codec->wcaps);
904         kfree(codec);
905 }
906
907 /**
908  * snd_hda_codec_new - create a HDA codec
909  * @bus: the bus to assign
910  * @codec_addr: the codec address
911  * @codecp: the pointer to store the generated codec
912  *
913  * Returns 0 if successful, or a negative error code.
914  */
915 int snd_hda_codec_new(struct hda_bus *bus, struct snd_card *card,
916                       unsigned int codec_addr, struct hda_codec **codecp)
917 {
918         struct hda_codec *codec;
919         char component[31];
920         hda_nid_t fg;
921         int err;
922         static struct snd_device_ops dev_ops = {
923                 .dev_register = snd_hda_codec_dev_register,
924                 .dev_disconnect = snd_hda_codec_dev_disconnect,
925                 .dev_free = snd_hda_codec_dev_free,
926         };
927
928         if (snd_BUG_ON(!bus))
929                 return -EINVAL;
930         if (snd_BUG_ON(codec_addr > HDA_MAX_CODEC_ADDRESS))
931                 return -EINVAL;
932
933         codec = kzalloc(sizeof(*codec), GFP_KERNEL);
934         if (!codec)
935                 return -ENOMEM;
936
937         sprintf(component, "hdaudioC%dD%d", card->number, codec_addr);
938         err = snd_hdac_device_init(&codec->core, &bus->core, component,
939                                    codec_addr);
940         if (err < 0) {
941                 kfree(codec);
942                 return err;
943         }
944
945         codec->core.dev.release = snd_hda_codec_dev_release;
946         codec->core.type = HDA_DEV_LEGACY;
947         codec->core.exec_verb = codec_exec_verb;
948
949         codec->bus = bus;
950         codec->card = card;
951         codec->addr = codec_addr;
952         mutex_init(&codec->spdif_mutex);
953         mutex_init(&codec->control_mutex);
954         snd_array_init(&codec->mixers, sizeof(struct hda_nid_item), 32);
955         snd_array_init(&codec->nids, sizeof(struct hda_nid_item), 32);
956         snd_array_init(&codec->init_pins, sizeof(struct hda_pincfg), 16);
957         snd_array_init(&codec->driver_pins, sizeof(struct hda_pincfg), 16);
958         snd_array_init(&codec->cvt_setups, sizeof(struct hda_cvt_setup), 8);
959         snd_array_init(&codec->spdif_out, sizeof(struct hda_spdif_out), 16);
960         snd_array_init(&codec->jacktbl, sizeof(struct hda_jack_tbl), 16);
961         snd_array_init(&codec->verbs, sizeof(struct hda_verb *), 8);
962         INIT_LIST_HEAD(&codec->conn_list);
963         INIT_LIST_HEAD(&codec->pcm_list_head);
964
965         INIT_DELAYED_WORK(&codec->jackpoll_work, hda_jackpoll_work);
966         codec->depop_delay = -1;
967         codec->fixup_id = HDA_FIXUP_ID_NOT_SET;
968
969 #ifdef CONFIG_PM
970         codec->power_jiffies = jiffies;
971 #endif
972
973         snd_hda_sysfs_init(codec);
974
975         if (codec->bus->modelname) {
976                 codec->modelname = kstrdup(codec->bus->modelname, GFP_KERNEL);
977                 if (!codec->modelname) {
978                         err = -ENODEV;
979                         goto error;
980                 }
981         }
982
983         fg = codec->core.afg ? codec->core.afg : codec->core.mfg;
984         err = read_widget_caps(codec, fg);
985         if (err < 0)
986                 goto error;
987         err = read_pin_defaults(codec);
988         if (err < 0)
989                 goto error;
990
991         /* power-up all before initialization */
992         hda_set_power_state(codec, AC_PWRST_D0);
993
994         snd_hda_codec_proc_new(codec);
995
996         snd_hda_create_hwdep(codec);
997
998         sprintf(component, "HDA:%08x,%08x,%08x", codec->core.vendor_id,
999                 codec->core.subsystem_id, codec->core.revision_id);
1000         snd_component_add(card, component);
1001
1002         err = snd_device_new(card, SNDRV_DEV_CODEC, codec, &dev_ops);
1003         if (err < 0)
1004                 goto error;
1005
1006         if (codecp)
1007                 *codecp = codec;
1008         return 0;
1009
1010  error:
1011         put_device(hda_codec_dev(codec));
1012         return err;
1013 }
1014 EXPORT_SYMBOL_GPL(snd_hda_codec_new);
1015
1016 /**
1017  * snd_hda_codec_update_widgets - Refresh widget caps and pin defaults
1018  * @codec: the HDA codec
1019  *
1020  * Forcibly refresh the all widget caps and the init pin configurations of
1021  * the given codec.
1022  */
1023 int snd_hda_codec_update_widgets(struct hda_codec *codec)
1024 {
1025         hda_nid_t fg;
1026         int err;
1027
1028         err = snd_hdac_refresh_widgets(&codec->core);
1029         if (err < 0)
1030                 return err;
1031
1032         /* Assume the function group node does not change,
1033          * only the widget nodes may change.
1034          */
1035         kfree(codec->wcaps);
1036         fg = codec->core.afg ? codec->core.afg : codec->core.mfg;
1037         err = read_widget_caps(codec, fg);
1038         if (err < 0)
1039                 return err;
1040
1041         snd_array_free(&codec->init_pins);
1042         err = read_pin_defaults(codec);
1043
1044         return err;
1045 }
1046 EXPORT_SYMBOL_GPL(snd_hda_codec_update_widgets);
1047
1048 /* update the stream-id if changed */
1049 static void update_pcm_stream_id(struct hda_codec *codec,
1050                                  struct hda_cvt_setup *p, hda_nid_t nid,
1051                                  u32 stream_tag, int channel_id)
1052 {
1053         unsigned int oldval, newval;
1054
1055         if (p->stream_tag != stream_tag || p->channel_id != channel_id) {
1056                 oldval = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_CONV, 0);
1057                 newval = (stream_tag << 4) | channel_id;
1058                 if (oldval != newval)
1059                         snd_hda_codec_write(codec, nid, 0,
1060                                             AC_VERB_SET_CHANNEL_STREAMID,
1061                                             newval);
1062                 p->stream_tag = stream_tag;
1063                 p->channel_id = channel_id;
1064         }
1065 }
1066
1067 /* update the format-id if changed */
1068 static void update_pcm_format(struct hda_codec *codec, struct hda_cvt_setup *p,
1069                               hda_nid_t nid, int format)
1070 {
1071         unsigned int oldval;
1072
1073         if (p->format_id != format) {
1074                 oldval = snd_hda_codec_read(codec, nid, 0,
1075                                             AC_VERB_GET_STREAM_FORMAT, 0);
1076                 if (oldval != format) {
1077                         msleep(1);
1078                         snd_hda_codec_write(codec, nid, 0,
1079                                             AC_VERB_SET_STREAM_FORMAT,
1080                                             format);
1081                 }
1082                 p->format_id = format;
1083         }
1084 }
1085
1086 /**
1087  * snd_hda_codec_setup_stream - set up the codec for streaming
1088  * @codec: the CODEC to set up
1089  * @nid: the NID to set up
1090  * @stream_tag: stream tag to pass, it's between 0x1 and 0xf.
1091  * @channel_id: channel id to pass, zero based.
1092  * @format: stream format.
1093  */
1094 void snd_hda_codec_setup_stream(struct hda_codec *codec, hda_nid_t nid,
1095                                 u32 stream_tag,
1096                                 int channel_id, int format)
1097 {
1098         struct hda_codec *c;
1099         struct hda_cvt_setup *p;
1100         int type;
1101         int i;
1102
1103         if (!nid)
1104                 return;
1105
1106         codec_dbg(codec,
1107                   "hda_codec_setup_stream: NID=0x%x, stream=0x%x, channel=%d, format=0x%x\n",
1108                   nid, stream_tag, channel_id, format);
1109         p = get_hda_cvt_setup(codec, nid);
1110         if (!p)
1111                 return;
1112
1113         if (codec->patch_ops.stream_pm)
1114                 codec->patch_ops.stream_pm(codec, nid, true);
1115         if (codec->pcm_format_first)
1116                 update_pcm_format(codec, p, nid, format);
1117         update_pcm_stream_id(codec, p, nid, stream_tag, channel_id);
1118         if (!codec->pcm_format_first)
1119                 update_pcm_format(codec, p, nid, format);
1120
1121         p->active = 1;
1122         p->dirty = 0;
1123
1124         /* make other inactive cvts with the same stream-tag dirty */
1125         type = get_wcaps_type(get_wcaps(codec, nid));
1126         list_for_each_codec(c, codec->bus) {
1127                 for (i = 0; i < c->cvt_setups.used; i++) {
1128                         p = snd_array_elem(&c->cvt_setups, i);
1129                         if (!p->active && p->stream_tag == stream_tag &&
1130                             get_wcaps_type(get_wcaps(c, p->nid)) == type)
1131                                 p->dirty = 1;
1132                 }
1133         }
1134 }
1135 EXPORT_SYMBOL_GPL(snd_hda_codec_setup_stream);
1136
1137 static void really_cleanup_stream(struct hda_codec *codec,
1138                                   struct hda_cvt_setup *q);
1139
1140 /**
1141  * __snd_hda_codec_cleanup_stream - clean up the codec for closing
1142  * @codec: the CODEC to clean up
1143  * @nid: the NID to clean up
1144  * @do_now: really clean up the stream instead of clearing the active flag
1145  */
1146 void __snd_hda_codec_cleanup_stream(struct hda_codec *codec, hda_nid_t nid,
1147                                     int do_now)
1148 {
1149         struct hda_cvt_setup *p;
1150
1151         if (!nid)
1152                 return;
1153
1154         if (codec->no_sticky_stream)
1155                 do_now = 1;
1156
1157         codec_dbg(codec, "hda_codec_cleanup_stream: NID=0x%x\n", nid);
1158         p = get_hda_cvt_setup(codec, nid);
1159         if (p) {
1160                 /* here we just clear the active flag when do_now isn't set;
1161                  * actual clean-ups will be done later in
1162                  * purify_inactive_streams() called from snd_hda_codec_prpapre()
1163                  */
1164                 if (do_now)
1165                         really_cleanup_stream(codec, p);
1166                 else
1167                         p->active = 0;
1168         }
1169 }
1170 EXPORT_SYMBOL_GPL(__snd_hda_codec_cleanup_stream);
1171
1172 static void really_cleanup_stream(struct hda_codec *codec,
1173                                   struct hda_cvt_setup *q)
1174 {
1175         hda_nid_t nid = q->nid;
1176         if (q->stream_tag || q->channel_id)
1177                 snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_CHANNEL_STREAMID, 0);
1178         if (q->format_id)
1179                 snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_STREAM_FORMAT, 0
1180 );
1181         memset(q, 0, sizeof(*q));
1182         q->nid = nid;
1183         if (codec->patch_ops.stream_pm)
1184                 codec->patch_ops.stream_pm(codec, nid, false);
1185 }
1186
1187 /* clean up the all conflicting obsolete streams */
1188 static void purify_inactive_streams(struct hda_codec *codec)
1189 {
1190         struct hda_codec *c;
1191         int i;
1192
1193         list_for_each_codec(c, codec->bus) {
1194                 for (i = 0; i < c->cvt_setups.used; i++) {
1195                         struct hda_cvt_setup *p;
1196                         p = snd_array_elem(&c->cvt_setups, i);
1197                         if (p->dirty)
1198                                 really_cleanup_stream(c, p);
1199                 }
1200         }
1201 }
1202
1203 #ifdef CONFIG_PM
1204 /* clean up all streams; called from suspend */
1205 static void hda_cleanup_all_streams(struct hda_codec *codec)
1206 {
1207         int i;
1208
1209         for (i = 0; i < codec->cvt_setups.used; i++) {
1210                 struct hda_cvt_setup *p = snd_array_elem(&codec->cvt_setups, i);
1211                 if (p->stream_tag)
1212                         really_cleanup_stream(codec, p);
1213         }
1214 }
1215 #endif
1216
1217 /*
1218  * amp access functions
1219  */
1220
1221 /**
1222  * query_amp_caps - query AMP capabilities
1223  * @codec: the HD-auio codec
1224  * @nid: the NID to query
1225  * @direction: either #HDA_INPUT or #HDA_OUTPUT
1226  *
1227  * Query AMP capabilities for the given widget and direction.
1228  * Returns the obtained capability bits.
1229  *
1230  * When cap bits have been already read, this doesn't read again but
1231  * returns the cached value.
1232  */
1233 u32 query_amp_caps(struct hda_codec *codec, hda_nid_t nid, int direction)
1234 {
1235         if (!(get_wcaps(codec, nid) & AC_WCAP_AMP_OVRD))
1236                 nid = codec->core.afg;
1237         return snd_hda_param_read(codec, nid,
1238                                   direction == HDA_OUTPUT ?
1239                                   AC_PAR_AMP_OUT_CAP : AC_PAR_AMP_IN_CAP);
1240 }
1241 EXPORT_SYMBOL_GPL(query_amp_caps);
1242
1243 /**
1244  * snd_hda_check_amp_caps - query AMP capabilities
1245  * @codec: the HD-audio codec
1246  * @nid: the NID to query
1247  * @dir: either #HDA_INPUT or #HDA_OUTPUT
1248  * @bits: bit mask to check the result
1249  *
1250  * Check whether the widget has the given amp capability for the direction.
1251  */
1252 bool snd_hda_check_amp_caps(struct hda_codec *codec, hda_nid_t nid,
1253                            int dir, unsigned int bits)
1254 {
1255         if (!nid)
1256                 return false;
1257         if (get_wcaps(codec, nid) & (1 << (dir + 1)))
1258                 if (query_amp_caps(codec, nid, dir) & bits)
1259                         return true;
1260         return false;
1261 }
1262 EXPORT_SYMBOL_GPL(snd_hda_check_amp_caps);
1263
1264 /**
1265  * snd_hda_override_amp_caps - Override the AMP capabilities
1266  * @codec: the CODEC to clean up
1267  * @nid: the NID to clean up
1268  * @dir: either #HDA_INPUT or #HDA_OUTPUT
1269  * @caps: the capability bits to set
1270  *
1271  * Override the cached AMP caps bits value by the given one.
1272  * This function is useful if the driver needs to adjust the AMP ranges,
1273  * e.g. limit to 0dB, etc.
1274  *
1275  * Returns zero if successful or a negative error code.
1276  */
1277 int snd_hda_override_amp_caps(struct hda_codec *codec, hda_nid_t nid, int dir,
1278                               unsigned int caps)
1279 {
1280         unsigned int parm;
1281
1282         snd_hda_override_wcaps(codec, nid,
1283                                get_wcaps(codec, nid) | AC_WCAP_AMP_OVRD);
1284         parm = dir == HDA_OUTPUT ? AC_PAR_AMP_OUT_CAP : AC_PAR_AMP_IN_CAP;
1285         return snd_hdac_override_parm(&codec->core, nid, parm, caps);
1286 }
1287 EXPORT_SYMBOL_GPL(snd_hda_override_amp_caps);
1288
1289 /**
1290  * snd_hda_codec_amp_update - update the AMP mono value
1291  * @codec: HD-audio codec
1292  * @nid: NID to read the AMP value
1293  * @ch: channel to update (0 or 1)
1294  * @dir: #HDA_INPUT or #HDA_OUTPUT
1295  * @idx: the index value (only for input direction)
1296  * @mask: bit mask to set
1297  * @val: the bits value to set
1298  *
1299  * Update the AMP values for the given channel, direction and index.
1300  */
1301 int snd_hda_codec_amp_update(struct hda_codec *codec, hda_nid_t nid,
1302                              int ch, int dir, int idx, int mask, int val)
1303 {
1304         unsigned int cmd = snd_hdac_regmap_encode_amp(nid, ch, dir, idx);
1305
1306         /* enable fake mute if no h/w mute but min=mute */
1307         if ((query_amp_caps(codec, nid, dir) &
1308              (AC_AMPCAP_MUTE | AC_AMPCAP_MIN_MUTE)) == AC_AMPCAP_MIN_MUTE)
1309                 cmd |= AC_AMP_FAKE_MUTE;
1310         return snd_hdac_regmap_update_raw(&codec->core, cmd, mask, val);
1311 }
1312 EXPORT_SYMBOL_GPL(snd_hda_codec_amp_update);
1313
1314 /**
1315  * snd_hda_codec_amp_stereo - update the AMP stereo values
1316  * @codec: HD-audio codec
1317  * @nid: NID to read the AMP value
1318  * @direction: #HDA_INPUT or #HDA_OUTPUT
1319  * @idx: the index value (only for input direction)
1320  * @mask: bit mask to set
1321  * @val: the bits value to set
1322  *
1323  * Update the AMP values like snd_hda_codec_amp_update(), but for a
1324  * stereo widget with the same mask and value.
1325  */
1326 int snd_hda_codec_amp_stereo(struct hda_codec *codec, hda_nid_t nid,
1327                              int direction, int idx, int mask, int val)
1328 {
1329         int ch, ret = 0;
1330
1331         if (snd_BUG_ON(mask & ~0xff))
1332                 mask &= 0xff;
1333         for (ch = 0; ch < 2; ch++)
1334                 ret |= snd_hda_codec_amp_update(codec, nid, ch, direction,
1335                                                 idx, mask, val);
1336         return ret;
1337 }
1338 EXPORT_SYMBOL_GPL(snd_hda_codec_amp_stereo);
1339
1340 /**
1341  * snd_hda_codec_amp_init - initialize the AMP value
1342  * @codec: the HDA codec
1343  * @nid: NID to read the AMP value
1344  * @ch: channel (left=0 or right=1)
1345  * @dir: #HDA_INPUT or #HDA_OUTPUT
1346  * @idx: the index value (only for input direction)
1347  * @mask: bit mask to set
1348  * @val: the bits value to set
1349  *
1350  * Works like snd_hda_codec_amp_update() but it writes the value only at
1351  * the first access.  If the amp was already initialized / updated beforehand,
1352  * this does nothing.
1353  */
1354 int snd_hda_codec_amp_init(struct hda_codec *codec, hda_nid_t nid, int ch,
1355                            int dir, int idx, int mask, int val)
1356 {
1357         int orig;
1358
1359         if (!codec->core.regmap)
1360                 return -EINVAL;
1361         regcache_cache_only(codec->core.regmap, true);
1362         orig = snd_hda_codec_amp_read(codec, nid, ch, dir, idx);
1363         regcache_cache_only(codec->core.regmap, false);
1364         if (orig >= 0)
1365                 return 0;
1366         return snd_hda_codec_amp_update(codec, nid, ch, dir, idx, mask, val);
1367 }
1368 EXPORT_SYMBOL_GPL(snd_hda_codec_amp_init);
1369
1370 /**
1371  * snd_hda_codec_amp_init_stereo - initialize the stereo AMP value
1372  * @codec: the HDA codec
1373  * @nid: NID to read the AMP value
1374  * @dir: #HDA_INPUT or #HDA_OUTPUT
1375  * @idx: the index value (only for input direction)
1376  * @mask: bit mask to set
1377  * @val: the bits value to set
1378  *
1379  * Call snd_hda_codec_amp_init() for both stereo channels.
1380  */
1381 int snd_hda_codec_amp_init_stereo(struct hda_codec *codec, hda_nid_t nid,
1382                                   int dir, int idx, int mask, int val)
1383 {
1384         int ch, ret = 0;
1385
1386         if (snd_BUG_ON(mask & ~0xff))
1387                 mask &= 0xff;
1388         for (ch = 0; ch < 2; ch++)
1389                 ret |= snd_hda_codec_amp_init(codec, nid, ch, dir,
1390                                               idx, mask, val);
1391         return ret;
1392 }
1393 EXPORT_SYMBOL_GPL(snd_hda_codec_amp_init_stereo);
1394
1395 static u32 get_amp_max_value(struct hda_codec *codec, hda_nid_t nid, int dir,
1396                              unsigned int ofs)
1397 {
1398         u32 caps = query_amp_caps(codec, nid, dir);
1399         /* get num steps */
1400         caps = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
1401         if (ofs < caps)
1402                 caps -= ofs;
1403         return caps;
1404 }
1405
1406 /**
1407  * snd_hda_mixer_amp_volume_info - Info callback for a standard AMP mixer
1408  * @kcontrol: referred ctl element
1409  * @uinfo: pointer to get/store the data
1410  *
1411  * The control element is supposed to have the private_value field
1412  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1413  */
1414 int snd_hda_mixer_amp_volume_info(struct snd_kcontrol *kcontrol,
1415                                   struct snd_ctl_elem_info *uinfo)
1416 {
1417         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1418         u16 nid = get_amp_nid(kcontrol);
1419         u8 chs = get_amp_channels(kcontrol);
1420         int dir = get_amp_direction(kcontrol);
1421         unsigned int ofs = get_amp_offset(kcontrol);
1422
1423         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1424         uinfo->count = chs == 3 ? 2 : 1;
1425         uinfo->value.integer.min = 0;
1426         uinfo->value.integer.max = get_amp_max_value(codec, nid, dir, ofs);
1427         if (!uinfo->value.integer.max) {
1428                 codec_warn(codec,
1429                            "num_steps = 0 for NID=0x%x (ctl = %s)\n",
1430                            nid, kcontrol->id.name);
1431                 return -EINVAL;
1432         }
1433         return 0;
1434 }
1435 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_volume_info);
1436
1437
1438 static inline unsigned int
1439 read_amp_value(struct hda_codec *codec, hda_nid_t nid,
1440                int ch, int dir, int idx, unsigned int ofs)
1441 {
1442         unsigned int val;
1443         val = snd_hda_codec_amp_read(codec, nid, ch, dir, idx);
1444         val &= HDA_AMP_VOLMASK;
1445         if (val >= ofs)
1446                 val -= ofs;
1447         else
1448                 val = 0;
1449         return val;
1450 }
1451
1452 static inline int
1453 update_amp_value(struct hda_codec *codec, hda_nid_t nid,
1454                  int ch, int dir, int idx, unsigned int ofs,
1455                  unsigned int val)
1456 {
1457         unsigned int maxval;
1458
1459         if (val > 0)
1460                 val += ofs;
1461         /* ofs = 0: raw max value */
1462         maxval = get_amp_max_value(codec, nid, dir, 0);
1463         if (val > maxval)
1464                 val = maxval;
1465         return snd_hda_codec_amp_update(codec, nid, ch, dir, idx,
1466                                         HDA_AMP_VOLMASK, val);
1467 }
1468
1469 /**
1470  * snd_hda_mixer_amp_volume_get - Get callback for a standard AMP mixer volume
1471  * @kcontrol: ctl element
1472  * @ucontrol: pointer to get/store the data
1473  *
1474  * The control element is supposed to have the private_value field
1475  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1476  */
1477 int snd_hda_mixer_amp_volume_get(struct snd_kcontrol *kcontrol,
1478                                  struct snd_ctl_elem_value *ucontrol)
1479 {
1480         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1481         hda_nid_t nid = get_amp_nid(kcontrol);
1482         int chs = get_amp_channels(kcontrol);
1483         int dir = get_amp_direction(kcontrol);
1484         int idx = get_amp_index(kcontrol);
1485         unsigned int ofs = get_amp_offset(kcontrol);
1486         long *valp = ucontrol->value.integer.value;
1487
1488         if (chs & 1)
1489                 *valp++ = read_amp_value(codec, nid, 0, dir, idx, ofs);
1490         if (chs & 2)
1491                 *valp = read_amp_value(codec, nid, 1, dir, idx, ofs);
1492         return 0;
1493 }
1494 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_volume_get);
1495
1496 /**
1497  * snd_hda_mixer_amp_volume_put - Put callback for a standard AMP mixer volume
1498  * @kcontrol: ctl element
1499  * @ucontrol: pointer to get/store the data
1500  *
1501  * The control element is supposed to have the private_value field
1502  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1503  */
1504 int snd_hda_mixer_amp_volume_put(struct snd_kcontrol *kcontrol,
1505                                  struct snd_ctl_elem_value *ucontrol)
1506 {
1507         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1508         hda_nid_t nid = get_amp_nid(kcontrol);
1509         int chs = get_amp_channels(kcontrol);
1510         int dir = get_amp_direction(kcontrol);
1511         int idx = get_amp_index(kcontrol);
1512         unsigned int ofs = get_amp_offset(kcontrol);
1513         long *valp = ucontrol->value.integer.value;
1514         int change = 0;
1515
1516         if (chs & 1) {
1517                 change = update_amp_value(codec, nid, 0, dir, idx, ofs, *valp);
1518                 valp++;
1519         }
1520         if (chs & 2)
1521                 change |= update_amp_value(codec, nid, 1, dir, idx, ofs, *valp);
1522         return change;
1523 }
1524 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_volume_put);
1525
1526 /**
1527  * snd_hda_mixer_amp_volume_put - TLV callback for a standard AMP mixer volume
1528  * @kcontrol: ctl element
1529  * @op_flag: operation flag
1530  * @size: byte size of input TLV
1531  * @_tlv: TLV data
1532  *
1533  * The control element is supposed to have the private_value field
1534  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1535  */
1536 int snd_hda_mixer_amp_tlv(struct snd_kcontrol *kcontrol, int op_flag,
1537                           unsigned int size, unsigned int __user *_tlv)
1538 {
1539         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1540         hda_nid_t nid = get_amp_nid(kcontrol);
1541         int dir = get_amp_direction(kcontrol);
1542         unsigned int ofs = get_amp_offset(kcontrol);
1543         bool min_mute = get_amp_min_mute(kcontrol);
1544         u32 caps, val1, val2;
1545
1546         if (size < 4 * sizeof(unsigned int))
1547                 return -ENOMEM;
1548         caps = query_amp_caps(codec, nid, dir);
1549         val2 = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT;
1550         val2 = (val2 + 1) * 25;
1551         val1 = -((caps & AC_AMPCAP_OFFSET) >> AC_AMPCAP_OFFSET_SHIFT);
1552         val1 += ofs;
1553         val1 = ((int)val1) * ((int)val2);
1554         if (min_mute || (caps & AC_AMPCAP_MIN_MUTE))
1555                 val2 |= TLV_DB_SCALE_MUTE;
1556         if (put_user(SNDRV_CTL_TLVT_DB_SCALE, _tlv))
1557                 return -EFAULT;
1558         if (put_user(2 * sizeof(unsigned int), _tlv + 1))
1559                 return -EFAULT;
1560         if (put_user(val1, _tlv + 2))
1561                 return -EFAULT;
1562         if (put_user(val2, _tlv + 3))
1563                 return -EFAULT;
1564         return 0;
1565 }
1566 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_tlv);
1567
1568 /**
1569  * snd_hda_set_vmaster_tlv - Set TLV for a virtual master control
1570  * @codec: HD-audio codec
1571  * @nid: NID of a reference widget
1572  * @dir: #HDA_INPUT or #HDA_OUTPUT
1573  * @tlv: TLV data to be stored, at least 4 elements
1574  *
1575  * Set (static) TLV data for a virtual master volume using the AMP caps
1576  * obtained from the reference NID.
1577  * The volume range is recalculated as if the max volume is 0dB.
1578  */
1579 void snd_hda_set_vmaster_tlv(struct hda_codec *codec, hda_nid_t nid, int dir,
1580                              unsigned int *tlv)
1581 {
1582         u32 caps;
1583         int nums, step;
1584
1585         caps = query_amp_caps(codec, nid, dir);
1586         nums = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
1587         step = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT;
1588         step = (step + 1) * 25;
1589         tlv[0] = SNDRV_CTL_TLVT_DB_SCALE;
1590         tlv[1] = 2 * sizeof(unsigned int);
1591         tlv[2] = -nums * step;
1592         tlv[3] = step;
1593 }
1594 EXPORT_SYMBOL_GPL(snd_hda_set_vmaster_tlv);
1595
1596 /* find a mixer control element with the given name */
1597 static struct snd_kcontrol *
1598 find_mixer_ctl(struct hda_codec *codec, const char *name, int dev, int idx)
1599 {
1600         struct snd_ctl_elem_id id;
1601         memset(&id, 0, sizeof(id));
1602         id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
1603         id.device = dev;
1604         id.index = idx;
1605         if (snd_BUG_ON(strlen(name) >= sizeof(id.name)))
1606                 return NULL;
1607         strcpy(id.name, name);
1608         return snd_ctl_find_id(codec->card, &id);
1609 }
1610
1611 /**
1612  * snd_hda_find_mixer_ctl - Find a mixer control element with the given name
1613  * @codec: HD-audio codec
1614  * @name: ctl id name string
1615  *
1616  * Get the control element with the given id string and IFACE_MIXER.
1617  */
1618 struct snd_kcontrol *snd_hda_find_mixer_ctl(struct hda_codec *codec,
1619                                             const char *name)
1620 {
1621         return find_mixer_ctl(codec, name, 0, 0);
1622 }
1623 EXPORT_SYMBOL_GPL(snd_hda_find_mixer_ctl);
1624
1625 static int find_empty_mixer_ctl_idx(struct hda_codec *codec, const char *name,
1626                                     int start_idx)
1627 {
1628         int i, idx;
1629         /* 16 ctlrs should be large enough */
1630         for (i = 0, idx = start_idx; i < 16; i++, idx++) {
1631                 if (!find_mixer_ctl(codec, name, 0, idx))
1632                         return idx;
1633         }
1634         return -EBUSY;
1635 }
1636
1637 /**
1638  * snd_hda_ctl_add - Add a control element and assign to the codec
1639  * @codec: HD-audio codec
1640  * @nid: corresponding NID (optional)
1641  * @kctl: the control element to assign
1642  *
1643  * Add the given control element to an array inside the codec instance.
1644  * All control elements belonging to a codec are supposed to be added
1645  * by this function so that a proper clean-up works at the free or
1646  * reconfiguration time.
1647  *
1648  * If non-zero @nid is passed, the NID is assigned to the control element.
1649  * The assignment is shown in the codec proc file.
1650  *
1651  * snd_hda_ctl_add() checks the control subdev id field whether
1652  * #HDA_SUBDEV_NID_FLAG bit is set.  If set (and @nid is zero), the lower
1653  * bits value is taken as the NID to assign. The #HDA_NID_ITEM_AMP bit
1654  * specifies if kctl->private_value is a HDA amplifier value.
1655  */
1656 int snd_hda_ctl_add(struct hda_codec *codec, hda_nid_t nid,
1657                     struct snd_kcontrol *kctl)
1658 {
1659         int err;
1660         unsigned short flags = 0;
1661         struct hda_nid_item *item;
1662
1663         if (kctl->id.subdevice & HDA_SUBDEV_AMP_FLAG) {
1664                 flags |= HDA_NID_ITEM_AMP;
1665                 if (nid == 0)
1666                         nid = get_amp_nid_(kctl->private_value);
1667         }
1668         if ((kctl->id.subdevice & HDA_SUBDEV_NID_FLAG) != 0 && nid == 0)
1669                 nid = kctl->id.subdevice & 0xffff;
1670         if (kctl->id.subdevice & (HDA_SUBDEV_NID_FLAG|HDA_SUBDEV_AMP_FLAG))
1671                 kctl->id.subdevice = 0;
1672         err = snd_ctl_add(codec->card, kctl);
1673         if (err < 0)
1674                 return err;
1675         item = snd_array_new(&codec->mixers);
1676         if (!item)
1677                 return -ENOMEM;
1678         item->kctl = kctl;
1679         item->nid = nid;
1680         item->flags = flags;
1681         return 0;
1682 }
1683 EXPORT_SYMBOL_GPL(snd_hda_ctl_add);
1684
1685 /**
1686  * snd_hda_add_nid - Assign a NID to a control element
1687  * @codec: HD-audio codec
1688  * @nid: corresponding NID (optional)
1689  * @kctl: the control element to assign
1690  * @index: index to kctl
1691  *
1692  * Add the given control element to an array inside the codec instance.
1693  * This function is used when #snd_hda_ctl_add cannot be used for 1:1
1694  * NID:KCTL mapping - for example "Capture Source" selector.
1695  */
1696 int snd_hda_add_nid(struct hda_codec *codec, struct snd_kcontrol *kctl,
1697                     unsigned int index, hda_nid_t nid)
1698 {
1699         struct hda_nid_item *item;
1700
1701         if (nid > 0) {
1702                 item = snd_array_new(&codec->nids);
1703                 if (!item)
1704                         return -ENOMEM;
1705                 item->kctl = kctl;
1706                 item->index = index;
1707                 item->nid = nid;
1708                 return 0;
1709         }
1710         codec_err(codec, "no NID for mapping control %s:%d:%d\n",
1711                   kctl->id.name, kctl->id.index, index);
1712         return -EINVAL;
1713 }
1714 EXPORT_SYMBOL_GPL(snd_hda_add_nid);
1715
1716 /**
1717  * snd_hda_ctls_clear - Clear all controls assigned to the given codec
1718  * @codec: HD-audio codec
1719  */
1720 void snd_hda_ctls_clear(struct hda_codec *codec)
1721 {
1722         int i;
1723         struct hda_nid_item *items = codec->mixers.list;
1724         for (i = 0; i < codec->mixers.used; i++)
1725                 snd_ctl_remove(codec->card, items[i].kctl);
1726         snd_array_free(&codec->mixers);
1727         snd_array_free(&codec->nids);
1728 }
1729
1730 /**
1731  * snd_hda_lock_devices - pseudo device locking
1732  * @bus: the BUS
1733  *
1734  * toggle card->shutdown to allow/disallow the device access (as a hack)
1735  */
1736 int snd_hda_lock_devices(struct hda_bus *bus)
1737 {
1738         struct snd_card *card = bus->card;
1739         struct hda_codec *codec;
1740
1741         spin_lock(&card->files_lock);
1742         if (card->shutdown)
1743                 goto err_unlock;
1744         card->shutdown = 1;
1745         if (!list_empty(&card->ctl_files))
1746                 goto err_clear;
1747
1748         list_for_each_codec(codec, bus) {
1749                 struct hda_pcm *cpcm;
1750                 list_for_each_entry(cpcm, &codec->pcm_list_head, list) {
1751                         if (!cpcm->pcm)
1752                                 continue;
1753                         if (cpcm->pcm->streams[0].substream_opened ||
1754                             cpcm->pcm->streams[1].substream_opened)
1755                                 goto err_clear;
1756                 }
1757         }
1758         spin_unlock(&card->files_lock);
1759         return 0;
1760
1761  err_clear:
1762         card->shutdown = 0;
1763  err_unlock:
1764         spin_unlock(&card->files_lock);
1765         return -EINVAL;
1766 }
1767 EXPORT_SYMBOL_GPL(snd_hda_lock_devices);
1768
1769 /**
1770  * snd_hda_unlock_devices - pseudo device unlocking
1771  * @bus: the BUS
1772  */
1773 void snd_hda_unlock_devices(struct hda_bus *bus)
1774 {
1775         struct snd_card *card = bus->card;
1776
1777         spin_lock(&card->files_lock);
1778         card->shutdown = 0;
1779         spin_unlock(&card->files_lock);
1780 }
1781 EXPORT_SYMBOL_GPL(snd_hda_unlock_devices);
1782
1783 /**
1784  * snd_hda_codec_reset - Clear all objects assigned to the codec
1785  * @codec: HD-audio codec
1786  *
1787  * This frees the all PCM and control elements assigned to the codec, and
1788  * clears the caches and restores the pin default configurations.
1789  *
1790  * When a device is being used, it returns -EBSY.  If successfully freed,
1791  * returns zero.
1792  */
1793 int snd_hda_codec_reset(struct hda_codec *codec)
1794 {
1795         struct hda_bus *bus = codec->bus;
1796
1797         if (snd_hda_lock_devices(bus) < 0)
1798                 return -EBUSY;
1799
1800         /* OK, let it free */
1801         snd_hdac_device_unregister(&codec->core);
1802
1803         /* allow device access again */
1804         snd_hda_unlock_devices(bus);
1805         return 0;
1806 }
1807
1808 typedef int (*map_slave_func_t)(struct hda_codec *, void *, struct snd_kcontrol *);
1809
1810 /* apply the function to all matching slave ctls in the mixer list */
1811 static int map_slaves(struct hda_codec *codec, const char * const *slaves,
1812                       const char *suffix, map_slave_func_t func, void *data) 
1813 {
1814         struct hda_nid_item *items;
1815         const char * const *s;
1816         int i, err;
1817
1818         items = codec->mixers.list;
1819         for (i = 0; i < codec->mixers.used; i++) {
1820                 struct snd_kcontrol *sctl = items[i].kctl;
1821                 if (!sctl || sctl->id.iface != SNDRV_CTL_ELEM_IFACE_MIXER)
1822                         continue;
1823                 for (s = slaves; *s; s++) {
1824                         char tmpname[sizeof(sctl->id.name)];
1825                         const char *name = *s;
1826                         if (suffix) {
1827                                 snprintf(tmpname, sizeof(tmpname), "%s %s",
1828                                          name, suffix);
1829                                 name = tmpname;
1830                         }
1831                         if (!strcmp(sctl->id.name, name)) {
1832                                 err = func(codec, data, sctl);
1833                                 if (err)
1834                                         return err;
1835                                 break;
1836                         }
1837                 }
1838         }
1839         return 0;
1840 }
1841
1842 static int check_slave_present(struct hda_codec *codec,
1843                                void *data, struct snd_kcontrol *sctl)
1844 {
1845         return 1;
1846 }
1847
1848 /* guess the value corresponding to 0dB */
1849 static int get_kctl_0dB_offset(struct hda_codec *codec,
1850                                struct snd_kcontrol *kctl, int *step_to_check)
1851 {
1852         int _tlv[4];
1853         const int *tlv = NULL;
1854         int val = -1;
1855
1856         if (kctl->vd[0].access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) {
1857                 /* FIXME: set_fs() hack for obtaining user-space TLV data */
1858                 mm_segment_t fs = get_fs();
1859                 set_fs(get_ds());
1860                 if (!kctl->tlv.c(kctl, 0, sizeof(_tlv), _tlv))
1861                         tlv = _tlv;
1862                 set_fs(fs);
1863         } else if (kctl->vd[0].access & SNDRV_CTL_ELEM_ACCESS_TLV_READ)
1864                 tlv = kctl->tlv.p;
1865         if (tlv && tlv[0] == SNDRV_CTL_TLVT_DB_SCALE) {
1866                 int step = tlv[3];
1867                 step &= ~TLV_DB_SCALE_MUTE;
1868                 if (!step)
1869                         return -1;
1870                 if (*step_to_check && *step_to_check != step) {
1871                         codec_err(codec, "Mismatching dB step for vmaster slave (%d!=%d)\n",
1872 -                                  *step_to_check, step);
1873                         return -1;
1874                 }
1875                 *step_to_check = step;
1876                 val = -tlv[2] / step;
1877         }
1878         return val;
1879 }
1880
1881 /* call kctl->put with the given value(s) */
1882 static int put_kctl_with_value(struct snd_kcontrol *kctl, int val)
1883 {
1884         struct snd_ctl_elem_value *ucontrol;
1885         ucontrol = kzalloc(sizeof(*ucontrol), GFP_KERNEL);
1886         if (!ucontrol)
1887                 return -ENOMEM;
1888         ucontrol->value.integer.value[0] = val;
1889         ucontrol->value.integer.value[1] = val;
1890         kctl->put(kctl, ucontrol);
1891         kfree(ucontrol);
1892         return 0;
1893 }
1894
1895 /* initialize the slave volume with 0dB */
1896 static int init_slave_0dB(struct hda_codec *codec,
1897                           void *data, struct snd_kcontrol *slave)
1898 {
1899         int offset = get_kctl_0dB_offset(codec, slave, data);
1900         if (offset > 0)
1901                 put_kctl_with_value(slave, offset);
1902         return 0;
1903 }
1904
1905 /* unmute the slave */
1906 static int init_slave_unmute(struct hda_codec *codec,
1907                              void *data, struct snd_kcontrol *slave)
1908 {
1909         return put_kctl_with_value(slave, 1);
1910 }
1911
1912 static int add_slave(struct hda_codec *codec,
1913                      void *data, struct snd_kcontrol *slave)
1914 {
1915         return snd_ctl_add_slave(data, slave);
1916 }
1917
1918 /**
1919  * __snd_hda_add_vmaster - create a virtual master control and add slaves
1920  * @codec: HD-audio codec
1921  * @name: vmaster control name
1922  * @tlv: TLV data (optional)
1923  * @slaves: slave control names (optional)
1924  * @suffix: suffix string to each slave name (optional)
1925  * @init_slave_vol: initialize slaves to unmute/0dB
1926  * @ctl_ret: store the vmaster kcontrol in return
1927  *
1928  * Create a virtual master control with the given name.  The TLV data
1929  * must be either NULL or a valid data.
1930  *
1931  * @slaves is a NULL-terminated array of strings, each of which is a
1932  * slave control name.  All controls with these names are assigned to
1933  * the new virtual master control.
1934  *
1935  * This function returns zero if successful or a negative error code.
1936  */
1937 int __snd_hda_add_vmaster(struct hda_codec *codec, char *name,
1938                         unsigned int *tlv, const char * const *slaves,
1939                           const char *suffix, bool init_slave_vol,
1940                           struct snd_kcontrol **ctl_ret)
1941 {
1942         struct snd_kcontrol *kctl;
1943         int err;
1944
1945         if (ctl_ret)
1946                 *ctl_ret = NULL;
1947
1948         err = map_slaves(codec, slaves, suffix, check_slave_present, NULL);
1949         if (err != 1) {
1950                 codec_dbg(codec, "No slave found for %s\n", name);
1951                 return 0;
1952         }
1953         kctl = snd_ctl_make_virtual_master(name, tlv);
1954         if (!kctl)
1955                 return -ENOMEM;
1956         err = snd_hda_ctl_add(codec, 0, kctl);
1957         if (err < 0)
1958                 return err;
1959
1960         err = map_slaves(codec, slaves, suffix, add_slave, kctl);
1961         if (err < 0)
1962                 return err;
1963
1964         /* init with master mute & zero volume */
1965         put_kctl_with_value(kctl, 0);
1966         if (init_slave_vol) {
1967                 int step = 0;
1968                 map_slaves(codec, slaves, suffix,
1969                            tlv ? init_slave_0dB : init_slave_unmute, &step);
1970         }
1971
1972         if (ctl_ret)
1973                 *ctl_ret = kctl;
1974         return 0;
1975 }
1976 EXPORT_SYMBOL_GPL(__snd_hda_add_vmaster);
1977
1978 /*
1979  * mute-LED control using vmaster
1980  */
1981 static int vmaster_mute_mode_info(struct snd_kcontrol *kcontrol,
1982                                   struct snd_ctl_elem_info *uinfo)
1983 {
1984         static const char * const texts[] = {
1985                 "On", "Off", "Follow Master"
1986         };
1987
1988         return snd_ctl_enum_info(uinfo, 1, 3, texts);
1989 }
1990
1991 static int vmaster_mute_mode_get(struct snd_kcontrol *kcontrol,
1992                                  struct snd_ctl_elem_value *ucontrol)
1993 {
1994         struct hda_vmaster_mute_hook *hook = snd_kcontrol_chip(kcontrol);
1995         ucontrol->value.enumerated.item[0] = hook->mute_mode;
1996         return 0;
1997 }
1998
1999 static int vmaster_mute_mode_put(struct snd_kcontrol *kcontrol,
2000                                  struct snd_ctl_elem_value *ucontrol)
2001 {
2002         struct hda_vmaster_mute_hook *hook = snd_kcontrol_chip(kcontrol);
2003         unsigned int old_mode = hook->mute_mode;
2004
2005         hook->mute_mode = ucontrol->value.enumerated.item[0];
2006         if (hook->mute_mode > HDA_VMUTE_FOLLOW_MASTER)
2007                 hook->mute_mode = HDA_VMUTE_FOLLOW_MASTER;
2008         if (old_mode == hook->mute_mode)
2009                 return 0;
2010         snd_hda_sync_vmaster_hook(hook);
2011         return 1;
2012 }
2013
2014 static struct snd_kcontrol_new vmaster_mute_mode = {
2015         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2016         .name = "Mute-LED Mode",
2017         .info = vmaster_mute_mode_info,
2018         .get = vmaster_mute_mode_get,
2019         .put = vmaster_mute_mode_put,
2020 };
2021
2022 /* meta hook to call each driver's vmaster hook */
2023 static void vmaster_hook(void *private_data, int enabled)
2024 {
2025         struct hda_vmaster_mute_hook *hook = private_data;
2026
2027         if (hook->mute_mode != HDA_VMUTE_FOLLOW_MASTER)
2028                 enabled = hook->mute_mode;
2029         hook->hook(hook->codec, enabled);
2030 }
2031
2032 /**
2033  * snd_hda_add_vmaster_hook - Add a vmaster hook for mute-LED
2034  * @codec: the HDA codec
2035  * @hook: the vmaster hook object
2036  * @expose_enum_ctl: flag to create an enum ctl
2037  *
2038  * Add a mute-LED hook with the given vmaster switch kctl.
2039  * When @expose_enum_ctl is set, "Mute-LED Mode" control is automatically
2040  * created and associated with the given hook.
2041  */
2042 int snd_hda_add_vmaster_hook(struct hda_codec *codec,
2043                              struct hda_vmaster_mute_hook *hook,
2044                              bool expose_enum_ctl)
2045 {
2046         struct snd_kcontrol *kctl;
2047
2048         if (!hook->hook || !hook->sw_kctl)
2049                 return 0;
2050         hook->codec = codec;
2051         hook->mute_mode = HDA_VMUTE_FOLLOW_MASTER;
2052         snd_ctl_add_vmaster_hook(hook->sw_kctl, vmaster_hook, hook);
2053         if (!expose_enum_ctl)
2054                 return 0;
2055         kctl = snd_ctl_new1(&vmaster_mute_mode, hook);
2056         if (!kctl)
2057                 return -ENOMEM;
2058         return snd_hda_ctl_add(codec, 0, kctl);
2059 }
2060 EXPORT_SYMBOL_GPL(snd_hda_add_vmaster_hook);
2061
2062 /**
2063  * snd_hda_sync_vmaster_hook - Sync vmaster hook
2064  * @hook: the vmaster hook
2065  *
2066  * Call the hook with the current value for synchronization.
2067  * Should be called in init callback.
2068  */
2069 void snd_hda_sync_vmaster_hook(struct hda_vmaster_mute_hook *hook)
2070 {
2071         if (!hook->hook || !hook->codec)
2072                 return;
2073         /* don't call vmaster hook in the destructor since it might have
2074          * been already destroyed
2075          */
2076         if (hook->codec->bus->shutdown)
2077                 return;
2078         snd_ctl_sync_vmaster_hook(hook->sw_kctl);
2079 }
2080 EXPORT_SYMBOL_GPL(snd_hda_sync_vmaster_hook);
2081
2082
2083 /**
2084  * snd_hda_mixer_amp_switch_info - Info callback for a standard AMP mixer switch
2085  * @kcontrol: referred ctl element
2086  * @uinfo: pointer to get/store the data
2087  *
2088  * The control element is supposed to have the private_value field
2089  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2090  */
2091 int snd_hda_mixer_amp_switch_info(struct snd_kcontrol *kcontrol,
2092                                   struct snd_ctl_elem_info *uinfo)
2093 {
2094         int chs = get_amp_channels(kcontrol);
2095
2096         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2097         uinfo->count = chs == 3 ? 2 : 1;
2098         uinfo->value.integer.min = 0;
2099         uinfo->value.integer.max = 1;
2100         return 0;
2101 }
2102 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_switch_info);
2103
2104 /**
2105  * snd_hda_mixer_amp_switch_get - Get callback for a standard AMP mixer switch
2106  * @kcontrol: ctl element
2107  * @ucontrol: pointer to get/store the data
2108  *
2109  * The control element is supposed to have the private_value field
2110  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2111  */
2112 int snd_hda_mixer_amp_switch_get(struct snd_kcontrol *kcontrol,
2113                                  struct snd_ctl_elem_value *ucontrol)
2114 {
2115         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2116         hda_nid_t nid = get_amp_nid(kcontrol);
2117         int chs = get_amp_channels(kcontrol);
2118         int dir = get_amp_direction(kcontrol);
2119         int idx = get_amp_index(kcontrol);
2120         long *valp = ucontrol->value.integer.value;
2121
2122         if (chs & 1)
2123                 *valp++ = (snd_hda_codec_amp_read(codec, nid, 0, dir, idx) &
2124                            HDA_AMP_MUTE) ? 0 : 1;
2125         if (chs & 2)
2126                 *valp = (snd_hda_codec_amp_read(codec, nid, 1, dir, idx) &
2127                          HDA_AMP_MUTE) ? 0 : 1;
2128         return 0;
2129 }
2130 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_switch_get);
2131
2132 /**
2133  * snd_hda_mixer_amp_switch_put - Put callback for a standard AMP mixer switch
2134  * @kcontrol: ctl element
2135  * @ucontrol: pointer to get/store the data
2136  *
2137  * The control element is supposed to have the private_value field
2138  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2139  */
2140 int snd_hda_mixer_amp_switch_put(struct snd_kcontrol *kcontrol,
2141                                  struct snd_ctl_elem_value *ucontrol)
2142 {
2143         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2144         hda_nid_t nid = get_amp_nid(kcontrol);
2145         int chs = get_amp_channels(kcontrol);
2146         int dir = get_amp_direction(kcontrol);
2147         int idx = get_amp_index(kcontrol);
2148         long *valp = ucontrol->value.integer.value;
2149         int change = 0;
2150
2151         if (chs & 1) {
2152                 change = snd_hda_codec_amp_update(codec, nid, 0, dir, idx,
2153                                                   HDA_AMP_MUTE,
2154                                                   *valp ? 0 : HDA_AMP_MUTE);
2155                 valp++;
2156         }
2157         if (chs & 2)
2158                 change |= snd_hda_codec_amp_update(codec, nid, 1, dir, idx,
2159                                                    HDA_AMP_MUTE,
2160                                                    *valp ? 0 : HDA_AMP_MUTE);
2161         hda_call_check_power_status(codec, nid);
2162         return change;
2163 }
2164 EXPORT_SYMBOL_GPL(snd_hda_mixer_amp_switch_put);
2165
2166 /*
2167  * bound volume controls
2168  *
2169  * bind multiple volumes (# indices, from 0)
2170  */
2171
2172 #define AMP_VAL_IDX_SHIFT       19
2173 #define AMP_VAL_IDX_MASK        (0x0f<<19)
2174
2175 /**
2176  * snd_hda_mixer_bind_switch_get - Get callback for a bound volume control
2177  * @kcontrol: ctl element
2178  * @ucontrol: pointer to get/store the data
2179  *
2180  * The control element is supposed to have the private_value field
2181  * set up via HDA_BIND_MUTE*() macros.
2182  */
2183 int snd_hda_mixer_bind_switch_get(struct snd_kcontrol *kcontrol,
2184                                   struct snd_ctl_elem_value *ucontrol)
2185 {
2186         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2187         unsigned long pval;
2188         int err;
2189
2190         mutex_lock(&codec->control_mutex);
2191         pval = kcontrol->private_value;
2192         kcontrol->private_value = pval & ~AMP_VAL_IDX_MASK; /* index 0 */
2193         err = snd_hda_mixer_amp_switch_get(kcontrol, ucontrol);
2194         kcontrol->private_value = pval;
2195         mutex_unlock(&codec->control_mutex);
2196         return err;
2197 }
2198 EXPORT_SYMBOL_GPL(snd_hda_mixer_bind_switch_get);
2199
2200 /**
2201  * snd_hda_mixer_bind_switch_put - Put callback for a bound volume control
2202  * @kcontrol: ctl element
2203  * @ucontrol: pointer to get/store the data
2204  *
2205  * The control element is supposed to have the private_value field
2206  * set up via HDA_BIND_MUTE*() macros.
2207  */
2208 int snd_hda_mixer_bind_switch_put(struct snd_kcontrol *kcontrol,
2209                                   struct snd_ctl_elem_value *ucontrol)
2210 {
2211         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2212         unsigned long pval;
2213         int i, indices, err = 0, change = 0;
2214
2215         mutex_lock(&codec->control_mutex);
2216         pval = kcontrol->private_value;
2217         indices = (pval & AMP_VAL_IDX_MASK) >> AMP_VAL_IDX_SHIFT;
2218         for (i = 0; i < indices; i++) {
2219                 kcontrol->private_value = (pval & ~AMP_VAL_IDX_MASK) |
2220                         (i << AMP_VAL_IDX_SHIFT);
2221                 err = snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
2222                 if (err < 0)
2223                         break;
2224                 change |= err;
2225         }
2226         kcontrol->private_value = pval;
2227         mutex_unlock(&codec->control_mutex);
2228         return err < 0 ? err : change;
2229 }
2230 EXPORT_SYMBOL_GPL(snd_hda_mixer_bind_switch_put);
2231
2232 /**
2233  * snd_hda_mixer_bind_ctls_info - Info callback for a generic bound control
2234  * @kcontrol: referred ctl element
2235  * @uinfo: pointer to get/store the data
2236  *
2237  * The control element is supposed to have the private_value field
2238  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
2239  */
2240 int snd_hda_mixer_bind_ctls_info(struct snd_kcontrol *kcontrol,
2241                                  struct snd_ctl_elem_info *uinfo)
2242 {
2243         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2244         struct hda_bind_ctls *c;
2245         int err;
2246
2247         mutex_lock(&codec->control_mutex);
2248         c = (struct hda_bind_ctls *)kcontrol->private_value;
2249         kcontrol->private_value = *c->values;
2250         err = c->ops->info(kcontrol, uinfo);
2251         kcontrol->private_value = (long)c;
2252         mutex_unlock(&codec->control_mutex);
2253         return err;
2254 }
2255 EXPORT_SYMBOL_GPL(snd_hda_mixer_bind_ctls_info);
2256
2257 /**
2258  * snd_hda_mixer_bind_ctls_get - Get callback for a generic bound control
2259  * @kcontrol: ctl element
2260  * @ucontrol: pointer to get/store the data
2261  *
2262  * The control element is supposed to have the private_value field
2263  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
2264  */
2265 int snd_hda_mixer_bind_ctls_get(struct snd_kcontrol *kcontrol,
2266                                 struct snd_ctl_elem_value *ucontrol)
2267 {
2268         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2269         struct hda_bind_ctls *c;
2270         int err;
2271
2272         mutex_lock(&codec->control_mutex);
2273         c = (struct hda_bind_ctls *)kcontrol->private_value;
2274         kcontrol->private_value = *c->values;
2275         err = c->ops->get(kcontrol, ucontrol);
2276         kcontrol->private_value = (long)c;
2277         mutex_unlock(&codec->control_mutex);
2278         return err;
2279 }
2280 EXPORT_SYMBOL_GPL(snd_hda_mixer_bind_ctls_get);
2281
2282 /**
2283  * snd_hda_mixer_bind_ctls_put - Put callback for a generic bound control
2284  * @kcontrol: ctl element
2285  * @ucontrol: pointer to get/store the data
2286  *
2287  * The control element is supposed to have the private_value field
2288  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
2289  */
2290 int snd_hda_mixer_bind_ctls_put(struct snd_kcontrol *kcontrol,
2291                                 struct snd_ctl_elem_value *ucontrol)
2292 {
2293         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2294         struct hda_bind_ctls *c;
2295         unsigned long *vals;
2296         int err = 0, change = 0;
2297
2298         mutex_lock(&codec->control_mutex);
2299         c = (struct hda_bind_ctls *)kcontrol->private_value;
2300         for (vals = c->values; *vals; vals++) {
2301                 kcontrol->private_value = *vals;
2302                 err = c->ops->put(kcontrol, ucontrol);
2303                 if (err < 0)
2304                         break;
2305                 change |= err;
2306         }
2307         kcontrol->private_value = (long)c;
2308         mutex_unlock(&codec->control_mutex);
2309         return err < 0 ? err : change;
2310 }
2311 EXPORT_SYMBOL_GPL(snd_hda_mixer_bind_ctls_put);
2312
2313 /**
2314  * snd_hda_mixer_bind_tlv - TLV callback for a generic bound control
2315  * @kcontrol: ctl element
2316  * @op_flag: operation flag
2317  * @size: byte size of input TLV
2318  * @tlv: TLV data
2319  *
2320  * The control element is supposed to have the private_value field
2321  * set up via HDA_BIND_VOL() macro.
2322  */
2323 int snd_hda_mixer_bind_tlv(struct snd_kcontrol *kcontrol, int op_flag,
2324                            unsigned int size, unsigned int __user *tlv)
2325 {
2326         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2327         struct hda_bind_ctls *c;
2328         int err;
2329
2330         mutex_lock(&codec->control_mutex);
2331         c = (struct hda_bind_ctls *)kcontrol->private_value;
2332         kcontrol->private_value = *c->values;
2333         err = c->ops->tlv(kcontrol, op_flag, size, tlv);
2334         kcontrol->private_value = (long)c;
2335         mutex_unlock(&codec->control_mutex);
2336         return err;
2337 }
2338 EXPORT_SYMBOL_GPL(snd_hda_mixer_bind_tlv);
2339
2340 struct hda_ctl_ops snd_hda_bind_vol = {
2341         .info = snd_hda_mixer_amp_volume_info,
2342         .get = snd_hda_mixer_amp_volume_get,
2343         .put = snd_hda_mixer_amp_volume_put,
2344         .tlv = snd_hda_mixer_amp_tlv
2345 };
2346 EXPORT_SYMBOL_GPL(snd_hda_bind_vol);
2347
2348 struct hda_ctl_ops snd_hda_bind_sw = {
2349         .info = snd_hda_mixer_amp_switch_info,
2350         .get = snd_hda_mixer_amp_switch_get,
2351         .put = snd_hda_mixer_amp_switch_put,
2352         .tlv = snd_hda_mixer_amp_tlv
2353 };
2354 EXPORT_SYMBOL_GPL(snd_hda_bind_sw);
2355
2356 /*
2357  * SPDIF out controls
2358  */
2359
2360 static int snd_hda_spdif_mask_info(struct snd_kcontrol *kcontrol,
2361                                    struct snd_ctl_elem_info *uinfo)
2362 {
2363         uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
2364         uinfo->count = 1;
2365         return 0;
2366 }
2367
2368 static int snd_hda_spdif_cmask_get(struct snd_kcontrol *kcontrol,
2369                                    struct snd_ctl_elem_value *ucontrol)
2370 {
2371         ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
2372                                            IEC958_AES0_NONAUDIO |
2373                                            IEC958_AES0_CON_EMPHASIS_5015 |
2374                                            IEC958_AES0_CON_NOT_COPYRIGHT;
2375         ucontrol->value.iec958.status[1] = IEC958_AES1_CON_CATEGORY |
2376                                            IEC958_AES1_CON_ORIGINAL;
2377         return 0;
2378 }
2379
2380 static int snd_hda_spdif_pmask_get(struct snd_kcontrol *kcontrol,
2381                                    struct snd_ctl_elem_value *ucontrol)
2382 {
2383         ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
2384                                            IEC958_AES0_NONAUDIO |
2385                                            IEC958_AES0_PRO_EMPHASIS_5015;
2386         return 0;
2387 }
2388
2389 static int snd_hda_spdif_default_get(struct snd_kcontrol *kcontrol,
2390                                      struct snd_ctl_elem_value *ucontrol)
2391 {
2392         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2393         int idx = kcontrol->private_value;
2394         struct hda_spdif_out *spdif;
2395
2396         mutex_lock(&codec->spdif_mutex);
2397         spdif = snd_array_elem(&codec->spdif_out, idx);
2398         ucontrol->value.iec958.status[0] = spdif->status & 0xff;
2399         ucontrol->value.iec958.status[1] = (spdif->status >> 8) & 0xff;
2400         ucontrol->value.iec958.status[2] = (spdif->status >> 16) & 0xff;
2401         ucontrol->value.iec958.status[3] = (spdif->status >> 24) & 0xff;
2402         mutex_unlock(&codec->spdif_mutex);
2403
2404         return 0;
2405 }
2406
2407 /* convert from SPDIF status bits to HDA SPDIF bits
2408  * bit 0 (DigEn) is always set zero (to be filled later)
2409  */
2410 static unsigned short convert_from_spdif_status(unsigned int sbits)
2411 {
2412         unsigned short val = 0;
2413
2414         if (sbits & IEC958_AES0_PROFESSIONAL)
2415                 val |= AC_DIG1_PROFESSIONAL;
2416         if (sbits & IEC958_AES0_NONAUDIO)
2417                 val |= AC_DIG1_NONAUDIO;
2418         if (sbits & IEC958_AES0_PROFESSIONAL) {
2419                 if ((sbits & IEC958_AES0_PRO_EMPHASIS) ==
2420                     IEC958_AES0_PRO_EMPHASIS_5015)
2421                         val |= AC_DIG1_EMPHASIS;
2422         } else {
2423                 if ((sbits & IEC958_AES0_CON_EMPHASIS) ==
2424                     IEC958_AES0_CON_EMPHASIS_5015)
2425                         val |= AC_DIG1_EMPHASIS;
2426                 if (!(sbits & IEC958_AES0_CON_NOT_COPYRIGHT))
2427                         val |= AC_DIG1_COPYRIGHT;
2428                 if (sbits & (IEC958_AES1_CON_ORIGINAL << 8))
2429                         val |= AC_DIG1_LEVEL;
2430                 val |= sbits & (IEC958_AES1_CON_CATEGORY << 8);
2431         }
2432         return val;
2433 }
2434
2435 /* convert to SPDIF status bits from HDA SPDIF bits
2436  */
2437 static unsigned int convert_to_spdif_status(unsigned short val)
2438 {
2439         unsigned int sbits = 0;
2440
2441         if (val & AC_DIG1_NONAUDIO)
2442                 sbits |= IEC958_AES0_NONAUDIO;
2443         if (val & AC_DIG1_PROFESSIONAL)
2444                 sbits |= IEC958_AES0_PROFESSIONAL;
2445         if (sbits & IEC958_AES0_PROFESSIONAL) {
2446                 if (val & AC_DIG1_EMPHASIS)
2447                         sbits |= IEC958_AES0_PRO_EMPHASIS_5015;
2448         } else {
2449                 if (val & AC_DIG1_EMPHASIS)
2450                         sbits |= IEC958_AES0_CON_EMPHASIS_5015;
2451                 if (!(val & AC_DIG1_COPYRIGHT))
2452                         sbits |= IEC958_AES0_CON_NOT_COPYRIGHT;
2453                 if (val & AC_DIG1_LEVEL)
2454                         sbits |= (IEC958_AES1_CON_ORIGINAL << 8);
2455                 sbits |= val & (0x7f << 8);
2456         }
2457         return sbits;
2458 }
2459
2460 /* set digital convert verbs both for the given NID and its slaves */
2461 static void set_dig_out(struct hda_codec *codec, hda_nid_t nid,
2462                         int mask, int val)
2463 {
2464         const hda_nid_t *d;
2465
2466         snd_hdac_regmap_update(&codec->core, nid, AC_VERB_SET_DIGI_CONVERT_1,
2467                                mask, val);
2468         d = codec->slave_dig_outs;
2469         if (!d)
2470                 return;
2471         for (; *d; d++)
2472                 snd_hdac_regmap_update(&codec->core, *d,
2473                                        AC_VERB_SET_DIGI_CONVERT_1, mask, val);
2474 }
2475
2476 static inline void set_dig_out_convert(struct hda_codec *codec, hda_nid_t nid,
2477                                        int dig1, int dig2)
2478 {
2479         unsigned int mask = 0;
2480         unsigned int val = 0;
2481
2482         if (dig1 != -1) {
2483                 mask |= 0xff;
2484                 val = dig1;
2485         }
2486         if (dig2 != -1) {
2487                 mask |= 0xff00;
2488                 val |= dig2 << 8;
2489         }
2490         set_dig_out(codec, nid, mask, val);
2491 }
2492
2493 static int snd_hda_spdif_default_put(struct snd_kcontrol *kcontrol,
2494                                      struct snd_ctl_elem_value *ucontrol)
2495 {
2496         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2497         int idx = kcontrol->private_value;
2498         struct hda_spdif_out *spdif;
2499         hda_nid_t nid;
2500         unsigned short val;
2501         int change;
2502
2503         mutex_lock(&codec->spdif_mutex);
2504         spdif = snd_array_elem(&codec->spdif_out, idx);
2505         nid = spdif->nid;
2506         spdif->status = ucontrol->value.iec958.status[0] |
2507                 ((unsigned int)ucontrol->value.iec958.status[1] << 8) |
2508                 ((unsigned int)ucontrol->value.iec958.status[2] << 16) |
2509                 ((unsigned int)ucontrol->value.iec958.status[3] << 24);
2510         val = convert_from_spdif_status(spdif->status);
2511         val |= spdif->ctls & 1;
2512         change = spdif->ctls != val;
2513         spdif->ctls = val;
2514         if (change && nid != (u16)-1)
2515                 set_dig_out_convert(codec, nid, val & 0xff, (val >> 8) & 0xff);
2516         mutex_unlock(&codec->spdif_mutex);
2517         return change;
2518 }
2519
2520 #define snd_hda_spdif_out_switch_info   snd_ctl_boolean_mono_info
2521
2522 static int snd_hda_spdif_out_switch_get(struct snd_kcontrol *kcontrol,
2523                                         struct snd_ctl_elem_value *ucontrol)
2524 {
2525         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2526         int idx = kcontrol->private_value;
2527         struct hda_spdif_out *spdif;
2528
2529         mutex_lock(&codec->spdif_mutex);
2530         spdif = snd_array_elem(&codec->spdif_out, idx);
2531         ucontrol->value.integer.value[0] = spdif->ctls & AC_DIG1_ENABLE;
2532         mutex_unlock(&codec->spdif_mutex);
2533         return 0;
2534 }
2535
2536 static inline void set_spdif_ctls(struct hda_codec *codec, hda_nid_t nid,
2537                                   int dig1, int dig2)
2538 {
2539         set_dig_out_convert(codec, nid, dig1, dig2);
2540         /* unmute amp switch (if any) */
2541         if ((get_wcaps(codec, nid) & AC_WCAP_OUT_AMP) &&
2542             (dig1 & AC_DIG1_ENABLE))
2543                 snd_hda_codec_amp_stereo(codec, nid, HDA_OUTPUT, 0,
2544                                             HDA_AMP_MUTE, 0);
2545 }
2546
2547 static int snd_hda_spdif_out_switch_put(struct snd_kcontrol *kcontrol,
2548                                         struct snd_ctl_elem_value *ucontrol)
2549 {
2550         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2551         int idx = kcontrol->private_value;
2552         struct hda_spdif_out *spdif;
2553         hda_nid_t nid;
2554         unsigned short val;
2555         int change;
2556
2557         mutex_lock(&codec->spdif_mutex);
2558         spdif = snd_array_elem(&codec->spdif_out, idx);
2559         nid = spdif->nid;
2560         val = spdif->ctls & ~AC_DIG1_ENABLE;
2561         if (ucontrol->value.integer.value[0])
2562                 val |= AC_DIG1_ENABLE;
2563         change = spdif->ctls != val;
2564         spdif->ctls = val;
2565         if (change && nid != (u16)-1)
2566                 set_spdif_ctls(codec, nid, val & 0xff, -1);
2567         mutex_unlock(&codec->spdif_mutex);
2568         return change;
2569 }
2570
2571 static struct snd_kcontrol_new dig_mixes[] = {
2572         {
2573                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
2574                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2575                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, CON_MASK),
2576                 .info = snd_hda_spdif_mask_info,
2577                 .get = snd_hda_spdif_cmask_get,
2578         },
2579         {
2580                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
2581                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2582                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, PRO_MASK),
2583                 .info = snd_hda_spdif_mask_info,
2584                 .get = snd_hda_spdif_pmask_get,
2585         },
2586         {
2587                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2588                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, DEFAULT),
2589                 .info = snd_hda_spdif_mask_info,
2590                 .get = snd_hda_spdif_default_get,
2591                 .put = snd_hda_spdif_default_put,
2592         },
2593         {
2594                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2595                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, SWITCH),
2596                 .info = snd_hda_spdif_out_switch_info,
2597                 .get = snd_hda_spdif_out_switch_get,
2598                 .put = snd_hda_spdif_out_switch_put,
2599         },
2600         { } /* end */
2601 };
2602
2603 /**
2604  * snd_hda_create_dig_out_ctls - create Output SPDIF-related controls
2605  * @codec: the HDA codec
2606  * @associated_nid: NID that new ctls associated with
2607  * @cvt_nid: converter NID
2608  * @type: HDA_PCM_TYPE_*
2609  * Creates controls related with the digital output.
2610  * Called from each patch supporting the digital out.
2611  *
2612  * Returns 0 if successful, or a negative error code.
2613  */
2614 int snd_hda_create_dig_out_ctls(struct hda_codec *codec,
2615                                 hda_nid_t associated_nid,
2616                                 hda_nid_t cvt_nid,
2617                                 int type)
2618 {
2619         int err;
2620         struct snd_kcontrol *kctl;
2621         struct snd_kcontrol_new *dig_mix;
2622         int idx = 0;
2623         int val = 0;
2624         const int spdif_index = 16;
2625         struct hda_spdif_out *spdif;
2626         struct hda_bus *bus = codec->bus;
2627
2628         if (bus->primary_dig_out_type == HDA_PCM_TYPE_HDMI &&
2629             type == HDA_PCM_TYPE_SPDIF) {
2630                 idx = spdif_index;
2631         } else if (bus->primary_dig_out_type == HDA_PCM_TYPE_SPDIF &&
2632                    type == HDA_PCM_TYPE_HDMI) {
2633                 /* suppose a single SPDIF device */
2634                 for (dig_mix = dig_mixes; dig_mix->name; dig_mix++) {
2635                         kctl = find_mixer_ctl(codec, dig_mix->name, 0, 0);
2636                         if (!kctl)
2637                                 break;
2638                         kctl->id.index = spdif_index;
2639                 }
2640                 bus->primary_dig_out_type = HDA_PCM_TYPE_HDMI;
2641         }
2642         if (!bus->primary_dig_out_type)
2643                 bus->primary_dig_out_type = type;
2644
2645         idx = find_empty_mixer_ctl_idx(codec, "IEC958 Playback Switch", idx);
2646         if (idx < 0) {
2647                 codec_err(codec, "too many IEC958 outputs\n");
2648                 return -EBUSY;
2649         }
2650         spdif = snd_array_new(&codec->spdif_out);
2651         if (!spdif)
2652                 return -ENOMEM;
2653         for (dig_mix = dig_mixes; dig_mix->name; dig_mix++) {
2654                 kctl = snd_ctl_new1(dig_mix, codec);
2655                 if (!kctl)
2656                         return -ENOMEM;
2657                 kctl->id.index = idx;
2658                 kctl->private_value = codec->spdif_out.used - 1;
2659                 err = snd_hda_ctl_add(codec, associated_nid, kctl);
2660                 if (err < 0)
2661                         return err;
2662         }
2663         spdif->nid = cvt_nid;
2664         snd_hdac_regmap_read(&codec->core, cvt_nid,
2665                              AC_VERB_GET_DIGI_CONVERT_1, &val);
2666         spdif->ctls = val;
2667         spdif->status = convert_to_spdif_status(spdif->ctls);
2668         return 0;
2669 }
2670 EXPORT_SYMBOL_GPL(snd_hda_create_dig_out_ctls);
2671
2672 /**
2673  * snd_hda_spdif_out_of_nid - get the hda_spdif_out entry from the given NID
2674  * @codec: the HDA codec
2675  * @nid: widget NID
2676  *
2677  * call within spdif_mutex lock
2678  */
2679 struct hda_spdif_out *snd_hda_spdif_out_of_nid(struct hda_codec *codec,
2680                                                hda_nid_t nid)
2681 {
2682         int i;
2683         for (i = 0; i < codec->spdif_out.used; i++) {
2684                 struct hda_spdif_out *spdif =
2685                                 snd_array_elem(&codec->spdif_out, i);
2686                 if (spdif->nid == nid)
2687                         return spdif;
2688         }
2689         return NULL;
2690 }
2691 EXPORT_SYMBOL_GPL(snd_hda_spdif_out_of_nid);
2692
2693 /**
2694  * snd_hda_spdif_ctls_unassign - Unassign the given SPDIF ctl
2695  * @codec: the HDA codec
2696  * @idx: the SPDIF ctl index
2697  *
2698  * Unassign the widget from the given SPDIF control.
2699  */
2700 void snd_hda_spdif_ctls_unassign(struct hda_codec *codec, int idx)
2701 {
2702         struct hda_spdif_out *spdif;
2703
2704         mutex_lock(&codec->spdif_mutex);
2705         spdif = snd_array_elem(&codec->spdif_out, idx);
2706         spdif->nid = (u16)-1;
2707         mutex_unlock(&codec->spdif_mutex);
2708 }
2709 EXPORT_SYMBOL_GPL(snd_hda_spdif_ctls_unassign);
2710
2711 /**
2712  * snd_hda_spdif_ctls_assign - Assign the SPDIF controls to the given NID
2713  * @codec: the HDA codec
2714  * @idx: the SPDIF ctl idx
2715  * @nid: widget NID
2716  *
2717  * Assign the widget to the SPDIF control with the given index.
2718  */
2719 void snd_hda_spdif_ctls_assign(struct hda_codec *codec, int idx, hda_nid_t nid)
2720 {
2721         struct hda_spdif_out *spdif;
2722         unsigned short val;
2723
2724         mutex_lock(&codec->spdif_mutex);
2725         spdif = snd_array_elem(&codec->spdif_out, idx);
2726         if (spdif->nid != nid) {
2727                 spdif->nid = nid;
2728                 val = spdif->ctls;
2729                 set_spdif_ctls(codec, nid, val & 0xff, (val >> 8) & 0xff);
2730         }
2731         mutex_unlock(&codec->spdif_mutex);
2732 }
2733 EXPORT_SYMBOL_GPL(snd_hda_spdif_ctls_assign);
2734
2735 /*
2736  * SPDIF sharing with analog output
2737  */
2738 static int spdif_share_sw_get(struct snd_kcontrol *kcontrol,
2739                               struct snd_ctl_elem_value *ucontrol)
2740 {
2741         struct hda_multi_out *mout = snd_kcontrol_chip(kcontrol);
2742         ucontrol->value.integer.value[0] = mout->share_spdif;
2743         return 0;
2744 }
2745
2746 static int spdif_share_sw_put(struct snd_kcontrol *kcontrol,
2747                               struct snd_ctl_elem_value *ucontrol)
2748 {
2749         struct hda_multi_out *mout = snd_kcontrol_chip(kcontrol);
2750         mout->share_spdif = !!ucontrol->value.integer.value[0];
2751         return 0;
2752 }
2753
2754 static struct snd_kcontrol_new spdif_share_sw = {
2755         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2756         .name = "IEC958 Default PCM Playback Switch",
2757         .info = snd_ctl_boolean_mono_info,
2758         .get = spdif_share_sw_get,
2759         .put = spdif_share_sw_put,
2760 };
2761
2762 /**
2763  * snd_hda_create_spdif_share_sw - create Default PCM switch
2764  * @codec: the HDA codec
2765  * @mout: multi-out instance
2766  */
2767 int snd_hda_create_spdif_share_sw(struct hda_codec *codec,
2768                                   struct hda_multi_out *mout)
2769 {
2770         struct snd_kcontrol *kctl;
2771
2772         if (!mout->dig_out_nid)
2773                 return 0;
2774
2775         kctl = snd_ctl_new1(&spdif_share_sw, mout);
2776         if (!kctl)
2777                 return -ENOMEM;
2778         /* ATTENTION: here mout is passed as private_data, instead of codec */
2779         return snd_hda_ctl_add(codec, mout->dig_out_nid, kctl);
2780 }
2781 EXPORT_SYMBOL_GPL(snd_hda_create_spdif_share_sw);
2782
2783 /*
2784  * SPDIF input
2785  */
2786
2787 #define snd_hda_spdif_in_switch_info    snd_hda_spdif_out_switch_info
2788
2789 static int snd_hda_spdif_in_switch_get(struct snd_kcontrol *kcontrol,
2790                                        struct snd_ctl_elem_value *ucontrol)
2791 {
2792         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2793
2794         ucontrol->value.integer.value[0] = codec->spdif_in_enable;
2795         return 0;
2796 }
2797
2798 static int snd_hda_spdif_in_switch_put(struct snd_kcontrol *kcontrol,
2799                                        struct snd_ctl_elem_value *ucontrol)
2800 {
2801         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2802         hda_nid_t nid = kcontrol->private_value;
2803         unsigned int val = !!ucontrol->value.integer.value[0];
2804         int change;
2805
2806         mutex_lock(&codec->spdif_mutex);
2807         change = codec->spdif_in_enable != val;
2808         if (change) {
2809                 codec->spdif_in_enable = val;
2810                 snd_hdac_regmap_write(&codec->core, nid,
2811                                       AC_VERB_SET_DIGI_CONVERT_1, val);
2812         }
2813         mutex_unlock(&codec->spdif_mutex);
2814         return change;
2815 }
2816
2817 static int snd_hda_spdif_in_status_get(struct snd_kcontrol *kcontrol,
2818                                        struct snd_ctl_elem_value *ucontrol)
2819 {
2820         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2821         hda_nid_t nid = kcontrol->private_value;
2822         unsigned int val;
2823         unsigned int sbits;
2824
2825         snd_hdac_regmap_read(&codec->core, nid,
2826                              AC_VERB_GET_DIGI_CONVERT_1, &val);
2827         sbits = convert_to_spdif_status(val);
2828         ucontrol->value.iec958.status[0] = sbits;
2829         ucontrol->value.iec958.status[1] = sbits >> 8;
2830         ucontrol->value.iec958.status[2] = sbits >> 16;
2831         ucontrol->value.iec958.status[3] = sbits >> 24;
2832         return 0;
2833 }
2834
2835 static struct snd_kcontrol_new dig_in_ctls[] = {
2836         {
2837                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2838                 .name = SNDRV_CTL_NAME_IEC958("", CAPTURE, SWITCH),
2839                 .info = snd_hda_spdif_in_switch_info,
2840                 .get = snd_hda_spdif_in_switch_get,
2841                 .put = snd_hda_spdif_in_switch_put,
2842         },
2843         {
2844                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
2845                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2846                 .name = SNDRV_CTL_NAME_IEC958("", CAPTURE, DEFAULT),
2847                 .info = snd_hda_spdif_mask_info,
2848                 .get = snd_hda_spdif_in_status_get,
2849         },
2850         { } /* end */
2851 };
2852
2853 /**
2854  * snd_hda_create_spdif_in_ctls - create Input SPDIF-related controls
2855  * @codec: the HDA codec
2856  * @nid: audio in widget NID
2857  *
2858  * Creates controls related with the SPDIF input.
2859  * Called from each patch supporting the SPDIF in.
2860  *
2861  * Returns 0 if successful, or a negative error code.
2862  */
2863 int snd_hda_create_spdif_in_ctls(struct hda_codec *codec, hda_nid_t nid)
2864 {
2865         int err;
2866         struct snd_kcontrol *kctl;
2867         struct snd_kcontrol_new *dig_mix;
2868         int idx;
2869
2870         idx = find_empty_mixer_ctl_idx(codec, "IEC958 Capture Switch", 0);
2871         if (idx < 0) {
2872                 codec_err(codec, "too many IEC958 inputs\n");
2873                 return -EBUSY;
2874         }
2875         for (dig_mix = dig_in_ctls; dig_mix->name; dig_mix++) {
2876                 kctl = snd_ctl_new1(dig_mix, codec);
2877                 if (!kctl)
2878                         return -ENOMEM;
2879                 kctl->private_value = nid;
2880                 err = snd_hda_ctl_add(codec, nid, kctl);
2881                 if (err < 0)
2882                         return err;
2883         }
2884         codec->spdif_in_enable =
2885                 snd_hda_codec_read(codec, nid, 0,
2886                                    AC_VERB_GET_DIGI_CONVERT_1, 0) &
2887                 AC_DIG1_ENABLE;
2888         return 0;
2889 }
2890 EXPORT_SYMBOL_GPL(snd_hda_create_spdif_in_ctls);
2891
2892 /**
2893  * snd_hda_codec_set_power_to_all - Set the power state to all widgets
2894  * @codec: the HDA codec
2895  * @fg: function group (not used now)
2896  * @power_state: the power state to set (AC_PWRST_*)
2897  *
2898  * Set the given power state to all widgets that have the power control.
2899  * If the codec has power_filter set, it evaluates the power state and
2900  * filter out if it's unchanged as D3.
2901  */
2902 void snd_hda_codec_set_power_to_all(struct hda_codec *codec, hda_nid_t fg,
2903                                     unsigned int power_state)
2904 {
2905         hda_nid_t nid;
2906
2907         for_each_hda_codec_node(nid, codec) {
2908                 unsigned int wcaps = get_wcaps(codec, nid);
2909                 unsigned int state = power_state;
2910                 if (!(wcaps & AC_WCAP_POWER))
2911                         continue;
2912                 if (codec->power_filter) {
2913                         state = codec->power_filter(codec, nid, power_state);
2914                         if (state != power_state && power_state == AC_PWRST_D3)
2915                                 continue;
2916                 }
2917                 snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_POWER_STATE,
2918                                     state);
2919         }
2920 }
2921 EXPORT_SYMBOL_GPL(snd_hda_codec_set_power_to_all);
2922
2923 /*
2924  * wait until the state is reached, returns the current state
2925  */
2926 static unsigned int hda_sync_power_state(struct hda_codec *codec,
2927                                          hda_nid_t fg,
2928                                          unsigned int power_state)
2929 {
2930         unsigned long end_time = jiffies + msecs_to_jiffies(500);
2931         unsigned int state, actual_state;
2932
2933         for (;;) {
2934                 state = snd_hda_codec_read(codec, fg, 0,
2935                                            AC_VERB_GET_POWER_STATE, 0);
2936                 if (state & AC_PWRST_ERROR)
2937                         break;
2938                 actual_state = (state >> 4) & 0x0f;
2939                 if (actual_state == power_state)
2940                         break;
2941                 if (time_after_eq(jiffies, end_time))
2942                         break;
2943                 /* wait until the codec reachs to the target state */
2944                 msleep(1);
2945         }
2946         return state;
2947 }
2948
2949 /**
2950  * snd_hda_codec_eapd_power_filter - A power filter callback for EAPD
2951  * @codec: the HDA codec
2952  * @nid: widget NID
2953  * @power_state: power state to evalue
2954  *
2955  * Don't power down the widget if it controls eapd and EAPD_BTLENABLE is set.
2956  * This can be used a codec power_filter callback.
2957  */
2958 unsigned int snd_hda_codec_eapd_power_filter(struct hda_codec *codec,
2959                                              hda_nid_t nid,
2960                                              unsigned int power_state)
2961 {
2962         if (nid == codec->core.afg || nid == codec->core.mfg)
2963                 return power_state;
2964         if (power_state == AC_PWRST_D3 &&
2965             get_wcaps_type(get_wcaps(codec, nid)) == AC_WID_PIN &&
2966             (snd_hda_query_pin_caps(codec, nid) & AC_PINCAP_EAPD)) {
2967                 int eapd = snd_hda_codec_read(codec, nid, 0,
2968                                               AC_VERB_GET_EAPD_BTLENABLE, 0);
2969                 if (eapd & 0x02)
2970                         return AC_PWRST_D0;
2971         }
2972         return power_state;
2973 }
2974 EXPORT_SYMBOL_GPL(snd_hda_codec_eapd_power_filter);
2975
2976 /*
2977  * set power state of the codec, and return the power state
2978  */
2979 static unsigned int hda_set_power_state(struct hda_codec *codec,
2980                                         unsigned int power_state)
2981 {
2982         hda_nid_t fg = codec->core.afg ? codec->core.afg : codec->core.mfg;
2983         int count;
2984         unsigned int state;
2985         int flags = 0;
2986
2987         /* this delay seems necessary to avoid click noise at power-down */
2988         if (power_state == AC_PWRST_D3) {
2989                 if (codec->depop_delay < 0)
2990                         msleep(codec_has_epss(codec) ? 10 : 100);
2991                 else if (codec->depop_delay > 0)
2992                         msleep(codec->depop_delay);
2993                 flags = HDA_RW_NO_RESPONSE_FALLBACK;
2994         }
2995
2996         /* repeat power states setting at most 10 times*/
2997         for (count = 0; count < 10; count++) {
2998                 if (codec->patch_ops.set_power_state)
2999                         codec->patch_ops.set_power_state(codec, fg,
3000                                                          power_state);
3001                 else {
3002                         state = power_state;
3003                         if (codec->power_filter)
3004                                 state = codec->power_filter(codec, fg, state);
3005                         if (state == power_state || power_state != AC_PWRST_D3)
3006                                 snd_hda_codec_read(codec, fg, flags,
3007                                                    AC_VERB_SET_POWER_STATE,
3008                                                    state);
3009                         snd_hda_codec_set_power_to_all(codec, fg, power_state);
3010                 }
3011                 state = hda_sync_power_state(codec, fg, power_state);
3012                 if (!(state & AC_PWRST_ERROR))
3013                         break;
3014         }
3015
3016         return state;
3017 }
3018
3019 /* sync power states of all widgets;
3020  * this is called at the end of codec parsing
3021  */
3022 static void sync_power_up_states(struct hda_codec *codec)
3023 {
3024         hda_nid_t nid;
3025
3026         /* don't care if no filter is used */
3027         if (!codec->power_filter)
3028                 return;
3029
3030         for_each_hda_codec_node(nid, codec) {
3031                 unsigned int wcaps = get_wcaps(codec, nid);
3032                 unsigned int target;
3033                 if (!(wcaps & AC_WCAP_POWER))
3034                         continue;
3035                 target = codec->power_filter(codec, nid, AC_PWRST_D0);
3036                 if (target == AC_PWRST_D0)
3037                         continue;
3038                 if (!snd_hda_check_power_state(codec, nid, target))
3039                         snd_hda_codec_write(codec, nid, 0,
3040                                             AC_VERB_SET_POWER_STATE, target);
3041         }
3042 }
3043
3044 #ifdef CONFIG_SND_HDA_RECONFIG
3045 /* execute additional init verbs */
3046 static void hda_exec_init_verbs(struct hda_codec *codec)
3047 {
3048         if (codec->init_verbs.list)
3049                 snd_hda_sequence_write(codec, codec->init_verbs.list);
3050 }
3051 #else
3052 static inline void hda_exec_init_verbs(struct hda_codec *codec) {}
3053 #endif
3054
3055 #ifdef CONFIG_PM
3056 /* update the power on/off account with the current jiffies */
3057 static void update_power_acct(struct hda_codec *codec, bool on)
3058 {
3059         unsigned long delta = jiffies - codec->power_jiffies;
3060
3061         if (on)
3062                 codec->power_on_acct += delta;
3063         else
3064                 codec->power_off_acct += delta;
3065         codec->power_jiffies += delta;
3066 }
3067
3068 void snd_hda_update_power_acct(struct hda_codec *codec)
3069 {
3070         update_power_acct(codec, hda_codec_is_power_on(codec));
3071 }
3072
3073 /*
3074  * call suspend and power-down; used both from PM and power-save
3075  * this function returns the power state in the end
3076  */
3077 static unsigned int hda_call_codec_suspend(struct hda_codec *codec)
3078 {
3079         unsigned int state;
3080
3081         atomic_inc(&codec->core.in_pm);
3082
3083         if (codec->patch_ops.suspend)
3084                 codec->patch_ops.suspend(codec);
3085         hda_cleanup_all_streams(codec);
3086         state = hda_set_power_state(codec, AC_PWRST_D3);
3087         update_power_acct(codec, true);
3088         atomic_dec(&codec->core.in_pm);
3089         return state;
3090 }
3091
3092 /*
3093  * kick up codec; used both from PM and power-save
3094  */
3095 static void hda_call_codec_resume(struct hda_codec *codec)
3096 {
3097         atomic_inc(&codec->core.in_pm);
3098
3099         if (codec->core.regmap)
3100                 regcache_mark_dirty(codec->core.regmap);
3101
3102         codec->power_jiffies = jiffies;
3103
3104         hda_set_power_state(codec, AC_PWRST_D0);
3105         restore_shutup_pins(codec);
3106         hda_exec_init_verbs(codec);
3107         snd_hda_jack_set_dirty_all(codec);
3108         if (codec->patch_ops.resume)
3109                 codec->patch_ops.resume(codec);
3110         else {
3111                 if (codec->patch_ops.init)
3112                         codec->patch_ops.init(codec);
3113                 if (codec->core.regmap)
3114                         regcache_sync(codec->core.regmap);
3115         }
3116
3117         if (codec->jackpoll_interval)
3118                 hda_jackpoll_work(&codec->jackpoll_work.work);
3119         else
3120                 snd_hda_jack_report_sync(codec);
3121         atomic_dec(&codec->core.in_pm);
3122 }
3123
3124 static int hda_codec_runtime_suspend(struct device *dev)
3125 {
3126         struct hda_codec *codec = dev_to_hda_codec(dev);
3127         struct hda_pcm *pcm;
3128         unsigned int state;
3129
3130         cancel_delayed_work_sync(&codec->jackpoll_work);
3131         list_for_each_entry(pcm, &codec->pcm_list_head, list)
3132                 snd_pcm_suspend_all(pcm->pcm);
3133         state = hda_call_codec_suspend(codec);
3134         if (codec_has_clkstop(codec) && codec_has_epss(codec) &&
3135             (state & AC_PWRST_CLK_STOP_OK))
3136                 snd_hdac_codec_link_down(&codec->core);
3137         snd_hdac_link_power(&codec->core, false);
3138         return 0;
3139 }
3140
3141 static int hda_codec_runtime_resume(struct device *dev)
3142 {
3143         struct hda_codec *codec = dev_to_hda_codec(dev);
3144
3145         snd_hdac_link_power(&codec->core, true);
3146         snd_hdac_codec_link_up(&codec->core);
3147         hda_call_codec_resume(codec);
3148         pm_runtime_mark_last_busy(dev);
3149         return 0;
3150 }
3151 #endif /* CONFIG_PM */
3152
3153 /* referred in hda_bind.c */
3154 const struct dev_pm_ops hda_codec_driver_pm = {
3155         SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
3156                                 pm_runtime_force_resume)
3157         SET_RUNTIME_PM_OPS(hda_codec_runtime_suspend, hda_codec_runtime_resume,
3158                            NULL)
3159 };
3160
3161 /*
3162  * add standard channel maps if not specified
3163  */
3164 static int add_std_chmaps(struct hda_codec *codec)
3165 {
3166         struct hda_pcm *pcm;
3167         int str, err;
3168
3169         list_for_each_entry(pcm, &codec->pcm_list_head, list) {
3170                 for (str = 0; str < 2; str++) {
3171                         struct hda_pcm_stream *hinfo = &pcm->stream[str];
3172                         struct snd_pcm_chmap *chmap;
3173                         const struct snd_pcm_chmap_elem *elem;
3174
3175                         if (!pcm || !pcm->pcm || pcm->own_chmap ||
3176                             !hinfo->substreams)
3177                                 continue;
3178                         elem = hinfo->chmap ? hinfo->chmap : snd_pcm_std_chmaps;
3179                         err = snd_pcm_add_chmap_ctls(pcm->pcm, str, elem,
3180                                                      hinfo->channels_max,
3181                                                      0, &chmap);
3182                         if (err < 0)
3183                                 return err;
3184                         chmap->channel_mask = SND_PCM_CHMAP_MASK_2468;
3185                 }
3186         }
3187         return 0;
3188 }
3189
3190 /* default channel maps for 2.1 speakers;
3191  * since HD-audio supports only stereo, odd number channels are omitted
3192  */
3193 const struct snd_pcm_chmap_elem snd_pcm_2_1_chmaps[] = {
3194         { .channels = 2,
3195           .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR } },
3196         { .channels = 4,
3197           .map = { SNDRV_CHMAP_FL, SNDRV_CHMAP_FR,
3198                    SNDRV_CHMAP_LFE, SNDRV_CHMAP_LFE } },
3199         { }
3200 };
3201 EXPORT_SYMBOL_GPL(snd_pcm_2_1_chmaps);
3202
3203 int snd_hda_codec_build_controls(struct hda_codec *codec)
3204 {
3205         int err = 0;
3206         hda_exec_init_verbs(codec);
3207         /* continue to initialize... */
3208         if (codec->patch_ops.init)
3209                 err = codec->patch_ops.init(codec);
3210         if (!err && codec->patch_ops.build_controls)
3211                 err = codec->patch_ops.build_controls(codec);
3212         if (err < 0)
3213                 return err;
3214
3215         /* we create chmaps here instead of build_pcms */
3216         err = add_std_chmaps(codec);
3217         if (err < 0)
3218                 return err;
3219
3220         if (codec->jackpoll_interval)
3221                 hda_jackpoll_work(&codec->jackpoll_work.work);
3222         else
3223                 snd_hda_jack_report_sync(codec); /* call at the last init point */
3224         sync_power_up_states(codec);
3225         return 0;
3226 }
3227
3228 /*
3229  * PCM stuff
3230  */
3231 static int hda_pcm_default_open_close(struct hda_pcm_stream *hinfo,
3232                                       struct hda_codec *codec,
3233                                       struct snd_pcm_substream *substream)
3234 {
3235         return 0;
3236 }
3237
3238 static int hda_pcm_default_prepare(struct hda_pcm_stream *hinfo,
3239                                    struct hda_codec *codec,
3240                                    unsigned int stream_tag,
3241                                    unsigned int format,
3242                                    struct snd_pcm_substream *substream)
3243 {
3244         snd_hda_codec_setup_stream(codec, hinfo->nid, stream_tag, 0, format);
3245         return 0;
3246 }
3247
3248 static int hda_pcm_default_cleanup(struct hda_pcm_stream *hinfo,
3249                                    struct hda_codec *codec,
3250                                    struct snd_pcm_substream *substream)
3251 {
3252         snd_hda_codec_cleanup_stream(codec, hinfo->nid);
3253         return 0;
3254 }
3255
3256 static int set_pcm_default_values(struct hda_codec *codec,
3257                                   struct hda_pcm_stream *info)
3258 {
3259         int err;
3260
3261         /* query support PCM information from the given NID */
3262         if (info->nid && (!info->rates || !info->formats)) {
3263                 err = snd_hda_query_supported_pcm(codec, info->nid,
3264                                 info->rates ? NULL : &info->rates,
3265                                 info->formats ? NULL : &info->formats,
3266                                 info->maxbps ? NULL : &info->maxbps);
3267                 if (err < 0)
3268                         return err;
3269         }
3270         if (info->ops.open == NULL)
3271                 info->ops.open = hda_pcm_default_open_close;
3272         if (info->ops.close == NULL)
3273                 info->ops.close = hda_pcm_default_open_close;
3274         if (info->ops.prepare == NULL) {
3275                 if (snd_BUG_ON(!info->nid))
3276                         return -EINVAL;
3277                 info->ops.prepare = hda_pcm_default_prepare;
3278         }
3279         if (info->ops.cleanup == NULL) {
3280                 if (snd_BUG_ON(!info->nid))
3281                         return -EINVAL;
3282                 info->ops.cleanup = hda_pcm_default_cleanup;
3283         }
3284         return 0;
3285 }
3286
3287 /*
3288  * codec prepare/cleanup entries
3289  */
3290 /**
3291  * snd_hda_codec_prepare - Prepare a stream
3292  * @codec: the HDA codec
3293  * @hinfo: PCM information
3294  * @stream: stream tag to assign
3295  * @format: format id to assign
3296  * @substream: PCM substream to assign
3297  *
3298  * Calls the prepare callback set by the codec with the given arguments.
3299  * Clean up the inactive streams when successful.
3300  */
3301 int snd_hda_codec_prepare(struct hda_codec *codec,
3302                           struct hda_pcm_stream *hinfo,
3303                           unsigned int stream,
3304                           unsigned int format,
3305                           struct snd_pcm_substream *substream)
3306 {
3307         int ret;
3308         mutex_lock(&codec->bus->prepare_mutex);
3309         if (hinfo->ops.prepare)
3310                 ret = hinfo->ops.prepare(hinfo, codec, stream, format,
3311                                          substream);
3312         else
3313                 ret = -ENODEV;
3314         if (ret >= 0)
3315                 purify_inactive_streams(codec);
3316         mutex_unlock(&codec->bus->prepare_mutex);
3317         return ret;
3318 }
3319 EXPORT_SYMBOL_GPL(snd_hda_codec_prepare);
3320
3321 /**
3322  * snd_hda_codec_cleanup - Prepare a stream
3323  * @codec: the HDA codec
3324  * @hinfo: PCM information
3325  * @substream: PCM substream
3326  *
3327  * Calls the cleanup callback set by the codec with the given arguments.
3328  */
3329 void snd_hda_codec_cleanup(struct hda_codec *codec,
3330                            struct hda_pcm_stream *hinfo,
3331                            struct snd_pcm_substream *substream)
3332 {
3333         mutex_lock(&codec->bus->prepare_mutex);
3334         if (hinfo->ops.cleanup)
3335                 hinfo->ops.cleanup(hinfo, codec, substream);
3336         mutex_unlock(&codec->bus->prepare_mutex);
3337 }
3338 EXPORT_SYMBOL_GPL(snd_hda_codec_cleanup);
3339
3340 /* global */
3341 const char *snd_hda_pcm_type_name[HDA_PCM_NTYPES] = {
3342         "Audio", "SPDIF", "HDMI", "Modem"
3343 };
3344
3345 /*
3346  * get the empty PCM device number to assign
3347  */
3348 static int get_empty_pcm_device(struct hda_bus *bus, unsigned int type)
3349 {
3350         /* audio device indices; not linear to keep compatibility */
3351         /* assigned to static slots up to dev#10; if more needed, assign
3352          * the later slot dynamically (when CONFIG_SND_DYNAMIC_MINORS=y)
3353          */
3354         static int audio_idx[HDA_PCM_NTYPES][5] = {
3355                 [HDA_PCM_TYPE_AUDIO] = { 0, 2, 4, 5, -1 },
3356                 [HDA_PCM_TYPE_SPDIF] = { 1, -1 },
3357                 [HDA_PCM_TYPE_HDMI]  = { 3, 7, 8, 9, -1 },
3358                 [HDA_PCM_TYPE_MODEM] = { 6, -1 },
3359         };
3360         int i;
3361
3362         if (type >= HDA_PCM_NTYPES) {
3363                 dev_err(bus->card->dev, "Invalid PCM type %d\n", type);
3364                 return -EINVAL;
3365         }
3366
3367         for (i = 0; audio_idx[type][i] >= 0; i++) {
3368 #ifndef CONFIG_SND_DYNAMIC_MINORS
3369                 if (audio_idx[type][i] >= 8)
3370                         break;
3371 #endif
3372                 if (!test_and_set_bit(audio_idx[type][i], bus->pcm_dev_bits))
3373                         return audio_idx[type][i];
3374         }
3375
3376 #ifdef CONFIG_SND_DYNAMIC_MINORS
3377         /* non-fixed slots starting from 10 */
3378         for (i = 10; i < 32; i++) {
3379                 if (!test_and_set_bit(i, bus->pcm_dev_bits))
3380                         return i;
3381         }
3382 #endif
3383
3384         dev_warn(bus->card->dev, "Too many %s devices\n",
3385                 snd_hda_pcm_type_name[type]);
3386 #ifndef CONFIG_SND_DYNAMIC_MINORS
3387         dev_warn(bus->card->dev,
3388                  "Consider building the kernel with CONFIG_SND_DYNAMIC_MINORS=y\n");
3389 #endif
3390         return -EAGAIN;
3391 }
3392
3393 /* call build_pcms ops of the given codec and set up the default parameters */
3394 int snd_hda_codec_parse_pcms(struct hda_codec *codec)
3395 {
3396         struct hda_pcm *cpcm;
3397         int err;
3398
3399         if (!list_empty(&codec->pcm_list_head))
3400                 return 0; /* already parsed */
3401
3402         if (!codec->patch_ops.build_pcms)
3403                 return 0;
3404
3405         err = codec->patch_ops.build_pcms(codec);
3406         if (err < 0) {
3407                 codec_err(codec, "cannot build PCMs for #%d (error %d)\n",
3408                           codec->core.addr, err);
3409                 return err;
3410         }
3411
3412         list_for_each_entry(cpcm, &codec->pcm_list_head, list) {
3413                 int stream;
3414
3415                 for (stream = 0; stream < 2; stream++) {
3416                         struct hda_pcm_stream *info = &cpcm->stream[stream];
3417
3418                         if (!info->substreams)
3419                                 continue;
3420                         err = set_pcm_default_values(codec, info);
3421                         if (err < 0) {
3422                                 codec_warn(codec,
3423                                            "fail to setup default for PCM %s\n",
3424                                            cpcm->name);
3425                                 return err;
3426                         }
3427                 }
3428         }
3429
3430         return 0;
3431 }
3432
3433 /* assign all PCMs of the given codec */
3434 int snd_hda_codec_build_pcms(struct hda_codec *codec)
3435 {
3436         struct hda_bus *bus = codec->bus;
3437         struct hda_pcm *cpcm;
3438         int dev, err;
3439
3440         err = snd_hda_codec_parse_pcms(codec);
3441         if (err < 0) {
3442                 snd_hda_codec_reset(codec);
3443                 return err;
3444         }
3445
3446         /* attach a new PCM streams */
3447         list_for_each_entry(cpcm, &codec->pcm_list_head, list) {
3448                 if (cpcm->pcm)
3449                         continue; /* already attached */
3450                 if (!cpcm->stream[0].substreams && !cpcm->stream[1].substreams)
3451                         continue; /* no substreams assigned */
3452
3453                 dev = get_empty_pcm_device(bus, cpcm->pcm_type);
3454                 if (dev < 0)
3455                         continue; /* no fatal error */
3456                 cpcm->device = dev;
3457                 err =  snd_hda_attach_pcm_stream(bus, codec, cpcm);
3458                 if (err < 0) {
3459                         codec_err(codec,
3460                                   "cannot attach PCM stream %d for codec #%d\n",
3461                                   dev, codec->core.addr);
3462                         continue; /* no fatal error */
3463                 }
3464         }
3465
3466         return 0;
3467 }
3468
3469 /**
3470  * snd_hda_add_new_ctls - create controls from the array
3471  * @codec: the HDA codec
3472  * @knew: the array of struct snd_kcontrol_new
3473  *
3474  * This helper function creates and add new controls in the given array.
3475  * The array must be terminated with an empty entry as terminator.
3476  *
3477  * Returns 0 if successful, or a negative error code.
3478  */
3479 int snd_hda_add_new_ctls(struct hda_codec *codec,
3480                          const struct snd_kcontrol_new *knew)
3481 {
3482         int err;
3483
3484         for (; knew->name; knew++) {
3485                 struct snd_kcontrol *kctl;
3486                 int addr = 0, idx = 0;
3487                 if (knew->iface == -1)  /* skip this codec private value */
3488                         continue;
3489                 for (;;) {
3490                         kctl = snd_ctl_new1(knew, codec);
3491                         if (!kctl)
3492                                 return -ENOMEM;
3493                         if (addr > 0)
3494                                 kctl->id.device = addr;
3495                         if (idx > 0)
3496                                 kctl->id.index = idx;
3497                         err = snd_hda_ctl_add(codec, 0, kctl);
3498                         if (!err)
3499                                 break;
3500                         /* try first with another device index corresponding to
3501                          * the codec addr; if it still fails (or it's the
3502                          * primary codec), then try another control index
3503                          */
3504                         if (!addr && codec->core.addr)
3505                                 addr = codec->core.addr;
3506                         else if (!idx && !knew->index) {
3507                                 idx = find_empty_mixer_ctl_idx(codec,
3508                                                                knew->name, 0);
3509                                 if (idx <= 0)
3510                                         return err;
3511                         } else
3512                                 return err;
3513                 }
3514         }
3515         return 0;
3516 }
3517 EXPORT_SYMBOL_GPL(snd_hda_add_new_ctls);
3518
3519 #ifdef CONFIG_PM
3520 static void codec_set_power_save(struct hda_codec *codec, int delay)
3521 {
3522         struct device *dev = hda_codec_dev(codec);
3523
3524         if (delay == 0 && codec->auto_runtime_pm)
3525                 delay = 3000;
3526
3527         if (delay > 0) {
3528                 pm_runtime_set_autosuspend_delay(dev, delay);
3529                 pm_runtime_use_autosuspend(dev);
3530                 pm_runtime_allow(dev);
3531                 if (!pm_runtime_suspended(dev))
3532                         pm_runtime_mark_last_busy(dev);
3533         } else {
3534                 pm_runtime_dont_use_autosuspend(dev);
3535                 pm_runtime_forbid(dev);
3536         }
3537 }
3538
3539 /**
3540  * snd_hda_set_power_save - reprogram autosuspend for the given delay
3541  * @bus: HD-audio bus
3542  * @delay: autosuspend delay in msec, 0 = off
3543  *
3544  * Synchronize the runtime PM autosuspend state from the power_save option.
3545  */
3546 void snd_hda_set_power_save(struct hda_bus *bus, int delay)
3547 {
3548         struct hda_codec *c;
3549
3550         list_for_each_codec(c, bus)
3551                 codec_set_power_save(c, delay);
3552 }
3553 EXPORT_SYMBOL_GPL(snd_hda_set_power_save);
3554
3555 /**
3556  * snd_hda_check_amp_list_power - Check the amp list and update the power
3557  * @codec: HD-audio codec
3558  * @check: the object containing an AMP list and the status
3559  * @nid: NID to check / update
3560  *
3561  * Check whether the given NID is in the amp list.  If it's in the list,
3562  * check the current AMP status, and update the the power-status according
3563  * to the mute status.
3564  *
3565  * This function is supposed to be set or called from the check_power_status
3566  * patch ops.
3567  */
3568 int snd_hda_check_amp_list_power(struct hda_codec *codec,
3569                                  struct hda_loopback_check *check,
3570                                  hda_nid_t nid)
3571 {
3572         const struct hda_amp_list *p;
3573         int ch, v;
3574
3575         if (!check->amplist)
3576                 return 0;
3577         for (p = check->amplist; p->nid; p++) {
3578                 if (p->nid == nid)
3579                         break;
3580         }
3581         if (!p->nid)
3582                 return 0; /* nothing changed */
3583
3584         for (p = check->amplist; p->nid; p++) {
3585                 for (ch = 0; ch < 2; ch++) {
3586                         v = snd_hda_codec_amp_read(codec, p->nid, ch, p->dir,
3587                                                    p->idx);
3588                         if (!(v & HDA_AMP_MUTE) && v > 0) {
3589                                 if (!check->power_on) {
3590                                         check->power_on = 1;
3591                                         snd_hda_power_up_pm(codec);
3592                                 }
3593                                 return 1;
3594                         }
3595                 }
3596         }
3597         if (check->power_on) {
3598                 check->power_on = 0;
3599                 snd_hda_power_down_pm(codec);
3600         }
3601         return 0;
3602 }
3603 EXPORT_SYMBOL_GPL(snd_hda_check_amp_list_power);
3604 #endif
3605
3606 /*
3607  * input MUX helper
3608  */
3609
3610 /**
3611  * snd_hda_input_mux_info_info - Info callback helper for the input-mux enum
3612  * @imux: imux helper object
3613  * @uinfo: pointer to get/store the data
3614  */
3615 int snd_hda_input_mux_info(const struct hda_input_mux *imux,
3616                            struct snd_ctl_elem_info *uinfo)
3617 {
3618         unsigned int index;
3619
3620         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
3621         uinfo->count = 1;
3622         uinfo->value.enumerated.items = imux->num_items;
3623         if (!imux->num_items)
3624                 return 0;
3625         index = uinfo->value.enumerated.item;
3626         if (index >= imux->num_items)
3627                 index = imux->num_items - 1;
3628         strcpy(uinfo->value.enumerated.name, imux->items[index].label);
3629         return 0;
3630 }
3631 EXPORT_SYMBOL_GPL(snd_hda_input_mux_info);
3632
3633 /**
3634  * snd_hda_input_mux_info_put - Put callback helper for the input-mux enum
3635  * @codec: the HDA codec
3636  * @imux: imux helper object
3637  * @ucontrol: pointer to get/store the data
3638  * @nid: input mux NID
3639  * @cur_val: pointer to get/store the current imux value
3640  */
3641 int snd_hda_input_mux_put(struct hda_codec *codec,
3642                           const struct hda_input_mux *imux,
3643                           struct snd_ctl_elem_value *ucontrol,
3644                           hda_nid_t nid,
3645                           unsigned int *cur_val)
3646 {
3647         unsigned int idx;
3648
3649         if (!imux->num_items)
3650                 return 0;
3651         idx = ucontrol->value.enumerated.item[0];
3652         if (idx >= imux->num_items)
3653                 idx = imux->num_items - 1;
3654         if (*cur_val == idx)
3655                 return 0;
3656         snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_CONNECT_SEL,
3657                                   imux->items[idx].index);
3658         *cur_val = idx;
3659         return 1;
3660 }
3661 EXPORT_SYMBOL_GPL(snd_hda_input_mux_put);
3662
3663
3664 /**
3665  * snd_hda_enum_helper_info - Helper for simple enum ctls
3666  * @kcontrol: ctl element
3667  * @uinfo: pointer to get/store the data
3668  * @num_items: number of enum items
3669  * @texts: enum item string array
3670  *
3671  * process kcontrol info callback of a simple string enum array
3672  * when @num_items is 0 or @texts is NULL, assume a boolean enum array
3673  */
3674 int snd_hda_enum_helper_info(struct snd_kcontrol *kcontrol,
3675                              struct snd_ctl_elem_info *uinfo,
3676                              int num_items, const char * const *texts)
3677 {
3678         static const char * const texts_default[] = {
3679                 "Disabled", "Enabled"
3680         };
3681
3682         if (!texts || !num_items) {
3683                 num_items = 2;
3684                 texts = texts_default;
3685         }
3686
3687         return snd_ctl_enum_info(uinfo, 1, num_items, texts);
3688 }
3689 EXPORT_SYMBOL_GPL(snd_hda_enum_helper_info);
3690
3691 /*
3692  * Multi-channel / digital-out PCM helper functions
3693  */
3694
3695 /* setup SPDIF output stream */
3696 static void setup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid,
3697                                  unsigned int stream_tag, unsigned int format)
3698 {
3699         struct hda_spdif_out *spdif;
3700         unsigned int curr_fmt;
3701         bool reset;
3702
3703         spdif = snd_hda_spdif_out_of_nid(codec, nid);
3704         curr_fmt = snd_hda_codec_read(codec, nid, 0,
3705                                       AC_VERB_GET_STREAM_FORMAT, 0);
3706         reset = codec->spdif_status_reset &&
3707                 (spdif->ctls & AC_DIG1_ENABLE) &&
3708                 curr_fmt != format;
3709
3710         /* turn off SPDIF if needed; otherwise the IEC958 bits won't be
3711            updated */
3712         if (reset)
3713                 set_dig_out_convert(codec, nid,
3714                                     spdif->ctls & ~AC_DIG1_ENABLE & 0xff,
3715                                     -1);
3716         snd_hda_codec_setup_stream(codec, nid, stream_tag, 0, format);
3717         if (codec->slave_dig_outs) {
3718                 const hda_nid_t *d;
3719                 for (d = codec->slave_dig_outs; *d; d++)
3720                         snd_hda_codec_setup_stream(codec, *d, stream_tag, 0,
3721                                                    format);
3722         }
3723         /* turn on again (if needed) */
3724         if (reset)
3725                 set_dig_out_convert(codec, nid,
3726                                     spdif->ctls & 0xff, -1);
3727 }
3728
3729 static void cleanup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid)
3730 {
3731         snd_hda_codec_cleanup_stream(codec, nid);
3732         if (codec->slave_dig_outs) {
3733                 const hda_nid_t *d;
3734                 for (d = codec->slave_dig_outs; *d; d++)
3735                         snd_hda_codec_cleanup_stream(codec, *d);
3736         }
3737 }
3738
3739 /**
3740  * snd_hda_multi_out_dig_open - open the digital out in the exclusive mode
3741  * @codec: the HDA codec
3742  * @mout: hda_multi_out object
3743  */
3744 int snd_hda_multi_out_dig_open(struct hda_codec *codec,
3745                                struct hda_multi_out *mout)
3746 {
3747         mutex_lock(&codec->spdif_mutex);
3748         if (mout->dig_out_used == HDA_DIG_ANALOG_DUP)
3749                 /* already opened as analog dup; reset it once */
3750                 cleanup_dig_out_stream(codec, mout->dig_out_nid);
3751         mout->dig_out_used = HDA_DIG_EXCLUSIVE;
3752         mutex_unlock(&codec->spdif_mutex);
3753         return 0;
3754 }
3755 EXPORT_SYMBOL_GPL(snd_hda_multi_out_dig_open);
3756
3757 /**
3758  * snd_hda_multi_out_dig_prepare - prepare the digital out stream
3759  * @codec: the HDA codec
3760  * @mout: hda_multi_out object
3761  * @stream_tag: stream tag to assign
3762  * @format: format id to assign
3763  * @substream: PCM substream to assign
3764  */
3765 int snd_hda_multi_out_dig_prepare(struct hda_codec *codec,
3766                                   struct hda_multi_out *mout,
3767                                   unsigned int stream_tag,
3768                                   unsigned int format,
3769                                   struct snd_pcm_substream *substream)
3770 {
3771         mutex_lock(&codec->spdif_mutex);
3772         setup_dig_out_stream(codec, mout->dig_out_nid, stream_tag, format);
3773         mutex_unlock(&codec->spdif_mutex);
3774         return 0;
3775 }
3776 EXPORT_SYMBOL_GPL(snd_hda_multi_out_dig_prepare);
3777
3778 /**
3779  * snd_hda_multi_out_dig_cleanup - clean-up the digital out stream
3780  * @codec: the HDA codec
3781  * @mout: hda_multi_out object
3782  */
3783 int snd_hda_multi_out_dig_cleanup(struct hda_codec *codec,
3784                                   struct hda_multi_out *mout)
3785 {
3786         mutex_lock(&codec->spdif_mutex);
3787         cleanup_dig_out_stream(codec, mout->dig_out_nid);
3788         mutex_unlock(&codec->spdif_mutex);
3789         return 0;
3790 }
3791 EXPORT_SYMBOL_GPL(snd_hda_multi_out_dig_cleanup);
3792
3793 /**
3794  * snd_hda_multi_out_dig_close - release the digital out stream
3795  * @codec: the HDA codec
3796  * @mout: hda_multi_out object
3797  */
3798 int snd_hda_multi_out_dig_close(struct hda_codec *codec,
3799                                 struct hda_multi_out *mout)
3800 {
3801         mutex_lock(&codec->spdif_mutex);
3802         mout->dig_out_used = 0;
3803         mutex_unlock(&codec->spdif_mutex);
3804         return 0;
3805 }
3806 EXPORT_SYMBOL_GPL(snd_hda_multi_out_dig_close);
3807
3808 /**
3809  * snd_hda_multi_out_analog_open - open analog outputs
3810  * @codec: the HDA codec
3811  * @mout: hda_multi_out object
3812  * @substream: PCM substream to assign
3813  * @hinfo: PCM information to assign
3814  *
3815  * Open analog outputs and set up the hw-constraints.
3816  * If the digital outputs can be opened as slave, open the digital
3817  * outputs, too.
3818  */
3819 int snd_hda_multi_out_analog_open(struct hda_codec *codec,
3820                                   struct hda_multi_out *mout,
3821                                   struct snd_pcm_substream *substream,
3822                                   struct hda_pcm_stream *hinfo)
3823 {
3824         struct snd_pcm_runtime *runtime = substream->runtime;
3825         runtime->hw.channels_max = mout->max_channels;
3826         if (mout->dig_out_nid) {
3827                 if (!mout->analog_rates) {
3828                         mout->analog_rates = hinfo->rates;
3829                         mout->analog_formats = hinfo->formats;
3830                         mout->analog_maxbps = hinfo->maxbps;
3831                 } else {
3832                         runtime->hw.rates = mout->analog_rates;
3833                         runtime->hw.formats = mout->analog_formats;
3834                         hinfo->maxbps = mout->analog_maxbps;
3835                 }
3836                 if (!mout->spdif_rates) {
3837                         snd_hda_query_supported_pcm(codec, mout->dig_out_nid,
3838                                                     &mout->spdif_rates,
3839                                                     &mout->spdif_formats,
3840                                                     &mout->spdif_maxbps);
3841                 }
3842                 mutex_lock(&codec->spdif_mutex);
3843                 if (mout->share_spdif) {
3844                         if ((runtime->hw.rates & mout->spdif_rates) &&
3845                             (runtime->hw.formats & mout->spdif_formats)) {
3846                                 runtime->hw.rates &= mout->spdif_rates;
3847                                 runtime->hw.formats &= mout->spdif_formats;
3848                                 if (mout->spdif_maxbps < hinfo->maxbps)
3849                                         hinfo->maxbps = mout->spdif_maxbps;
3850                         } else {
3851                                 mout->share_spdif = 0;
3852                                 /* FIXME: need notify? */
3853                         }
3854                 }
3855                 mutex_unlock(&codec->spdif_mutex);
3856         }
3857         return snd_pcm_hw_constraint_step(substream->runtime, 0,
3858                                           SNDRV_PCM_HW_PARAM_CHANNELS, 2);
3859 }
3860 EXPORT_SYMBOL_GPL(snd_hda_multi_out_analog_open);
3861
3862 /**
3863  * snd_hda_multi_out_analog_prepare - Preapre the analog outputs.
3864  * @codec: the HDA codec
3865  * @mout: hda_multi_out object
3866  * @stream_tag: stream tag to assign
3867  * @format: format id to assign
3868  * @substream: PCM substream to assign
3869  *
3870  * Set up the i/o for analog out.
3871  * When the digital out is available, copy the front out to digital out, too.
3872  */
3873 int snd_hda_multi_out_analog_prepare(struct hda_codec *codec,
3874                                      struct hda_multi_out *mout,
3875                                      unsigned int stream_tag,
3876                                      unsigned int format,
3877                                      struct snd_pcm_substream *substream)
3878 {
3879         const hda_nid_t *nids = mout->dac_nids;
3880         int chs = substream->runtime->channels;
3881         struct hda_spdif_out *spdif;
3882         int i;
3883
3884         mutex_lock(&codec->spdif_mutex);
3885         spdif = snd_hda_spdif_out_of_nid(codec, mout->dig_out_nid);
3886         if (mout->dig_out_nid && mout->share_spdif &&
3887             mout->dig_out_used != HDA_DIG_EXCLUSIVE) {
3888                 if (chs == 2 &&
3889                     snd_hda_is_supported_format(codec, mout->dig_out_nid,
3890                                                 format) &&
3891                     !(spdif->status & IEC958_AES0_NONAUDIO)) {
3892                         mout->dig_out_used = HDA_DIG_ANALOG_DUP;
3893                         setup_dig_out_stream(codec, mout->dig_out_nid,
3894                                              stream_tag, format);
3895                 } else {
3896                         mout->dig_out_used = 0;
3897                         cleanup_dig_out_stream(codec, mout->dig_out_nid);
3898                 }
3899         }
3900         mutex_unlock(&codec->spdif_mutex);
3901
3902         /* front */
3903         snd_hda_codec_setup_stream(codec, nids[HDA_FRONT], stream_tag,
3904                                    0, format);
3905         if (!mout->no_share_stream &&
3906             mout->hp_nid && mout->hp_nid != nids[HDA_FRONT])
3907                 /* headphone out will just decode front left/right (stereo) */
3908                 snd_hda_codec_setup_stream(codec, mout->hp_nid, stream_tag,
3909                                            0, format);
3910         /* extra outputs copied from front */
3911         for (i = 0; i < ARRAY_SIZE(mout->hp_out_nid); i++)
3912                 if (!mout->no_share_stream && mout->hp_out_nid[i])
3913                         snd_hda_codec_setup_stream(codec,
3914                                                    mout->hp_out_nid[i],
3915                                                    stream_tag, 0, format);
3916
3917         /* surrounds */
3918         for (i = 1; i < mout->num_dacs; i++) {
3919                 if (chs >= (i + 1) * 2) /* independent out */
3920                         snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
3921                                                    i * 2, format);
3922                 else if (!mout->no_share_stream) /* copy front */
3923                         snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
3924                                                    0, format);
3925         }
3926
3927         /* extra surrounds */
3928         for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++) {
3929                 int ch = 0;
3930                 if (!mout->extra_out_nid[i])
3931                         break;
3932                 if (chs >= (i + 1) * 2)
3933                         ch = i * 2;
3934                 else if (!mout->no_share_stream)
3935                         break;
3936                 snd_hda_codec_setup_stream(codec, mout->extra_out_nid[i],
3937                                            stream_tag, ch, format);
3938         }
3939
3940         return 0;
3941 }
3942 EXPORT_SYMBOL_GPL(snd_hda_multi_out_analog_prepare);
3943
3944 /**
3945  * snd_hda_multi_out_analog_cleanup - clean up the setting for analog out
3946  * @codec: the HDA codec
3947  * @mout: hda_multi_out object
3948  */
3949 int snd_hda_multi_out_analog_cleanup(struct hda_codec *codec,
3950                                      struct hda_multi_out *mout)
3951 {
3952         const hda_nid_t *nids = mout->dac_nids;
3953         int i;
3954
3955         for (i = 0; i < mout->num_dacs; i++)
3956                 snd_hda_codec_cleanup_stream(codec, nids[i]);
3957         if (mout->hp_nid)
3958                 snd_hda_codec_cleanup_stream(codec, mout->hp_nid);
3959         for (i = 0; i < ARRAY_SIZE(mout->hp_out_nid); i++)
3960                 if (mout->hp_out_nid[i])
3961                         snd_hda_codec_cleanup_stream(codec,
3962                                                      mout->hp_out_nid[i]);
3963         for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
3964                 if (mout->extra_out_nid[i])
3965                         snd_hda_codec_cleanup_stream(codec,
3966                                                      mout->extra_out_nid[i]);
3967         mutex_lock(&codec->spdif_mutex);
3968         if (mout->dig_out_nid && mout->dig_out_used == HDA_DIG_ANALOG_DUP) {
3969                 cleanup_dig_out_stream(codec, mout->dig_out_nid);
3970                 mout->dig_out_used = 0;
3971         }
3972         mutex_unlock(&codec->spdif_mutex);
3973         return 0;
3974 }
3975 EXPORT_SYMBOL_GPL(snd_hda_multi_out_analog_cleanup);
3976
3977 /**
3978  * snd_hda_get_default_vref - Get the default (mic) VREF pin bits
3979  * @codec: the HDA codec
3980  * @pin: referred pin NID
3981  *
3982  * Guess the suitable VREF pin bits to be set as the pin-control value.
3983  * Note: the function doesn't set the AC_PINCTL_IN_EN bit.
3984  */
3985 unsigned int snd_hda_get_default_vref(struct hda_codec *codec, hda_nid_t pin)
3986 {
3987         unsigned int pincap;
3988         unsigned int oldval;
3989         oldval = snd_hda_codec_read(codec, pin, 0,
3990                                     AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
3991         pincap = snd_hda_query_pin_caps(codec, pin);
3992         pincap = (pincap & AC_PINCAP_VREF) >> AC_PINCAP_VREF_SHIFT;
3993         /* Exception: if the default pin setup is vref50, we give it priority */
3994         if ((pincap & AC_PINCAP_VREF_80) && oldval != PIN_VREF50)
3995                 return AC_PINCTL_VREF_80;
3996         else if (pincap & AC_PINCAP_VREF_50)
3997                 return AC_PINCTL_VREF_50;
3998         else if (pincap & AC_PINCAP_VREF_100)
3999                 return AC_PINCTL_VREF_100;
4000         else if (pincap & AC_PINCAP_VREF_GRD)
4001                 return AC_PINCTL_VREF_GRD;
4002         return AC_PINCTL_VREF_HIZ;
4003 }
4004 EXPORT_SYMBOL_GPL(snd_hda_get_default_vref);
4005
4006 /**
4007  * snd_hda_correct_pin_ctl - correct the pin ctl value for matching with the pin cap
4008  * @codec: the HDA codec
4009  * @pin: referred pin NID
4010  * @val: pin ctl value to audit
4011  */
4012 unsigned int snd_hda_correct_pin_ctl(struct hda_codec *codec,
4013                                      hda_nid_t pin, unsigned int val)
4014 {
4015         static unsigned int cap_lists[][2] = {
4016                 { AC_PINCTL_VREF_100, AC_PINCAP_VREF_100 },
4017                 { AC_PINCTL_VREF_80, AC_PINCAP_VREF_80 },
4018                 { AC_PINCTL_VREF_50, AC_PINCAP_VREF_50 },
4019                 { AC_PINCTL_VREF_GRD, AC_PINCAP_VREF_GRD },
4020         };
4021         unsigned int cap;
4022
4023         if (!val)
4024                 return 0;
4025         cap = snd_hda_query_pin_caps(codec, pin);
4026         if (!cap)
4027                 return val; /* don't know what to do... */
4028
4029         if (val & AC_PINCTL_OUT_EN) {
4030                 if (!(cap & AC_PINCAP_OUT))
4031                         val &= ~(AC_PINCTL_OUT_EN | AC_PINCTL_HP_EN);
4032                 else if ((val & AC_PINCTL_HP_EN) && !(cap & AC_PINCAP_HP_DRV))
4033                         val &= ~AC_PINCTL_HP_EN;
4034         }
4035
4036         if (val & AC_PINCTL_IN_EN) {
4037                 if (!(cap & AC_PINCAP_IN))
4038                         val &= ~(AC_PINCTL_IN_EN | AC_PINCTL_VREFEN);
4039                 else {
4040                         unsigned int vcap, vref;
4041                         int i;
4042                         vcap = (cap & AC_PINCAP_VREF) >> AC_PINCAP_VREF_SHIFT;
4043                         vref = val & AC_PINCTL_VREFEN;
4044                         for (i = 0; i < ARRAY_SIZE(cap_lists); i++) {
4045                                 if (vref == cap_lists[i][0] &&
4046                                     !(vcap & cap_lists[i][1])) {
4047                                         if (i == ARRAY_SIZE(cap_lists) - 1)
4048                                                 vref = AC_PINCTL_VREF_HIZ;
4049                                         else
4050                                                 vref = cap_lists[i + 1][0];
4051                                 }
4052                         }
4053                         val &= ~AC_PINCTL_VREFEN;
4054                         val |= vref;
4055                 }
4056         }
4057
4058         return val;
4059 }
4060 EXPORT_SYMBOL_GPL(snd_hda_correct_pin_ctl);
4061
4062 /**
4063  * _snd_hda_pin_ctl - Helper to set pin ctl value
4064  * @codec: the HDA codec
4065  * @pin: referred pin NID
4066  * @val: pin control value to set
4067  * @cached: access over codec pinctl cache or direct write
4068  *
4069  * This function is a helper to set a pin ctl value more safely.
4070  * It corrects the pin ctl value via snd_hda_correct_pin_ctl(), stores the
4071  * value in pin target array via snd_hda_codec_set_pin_target(), then
4072  * actually writes the value via either snd_hda_codec_update_cache() or
4073  * snd_hda_codec_write() depending on @cached flag.
4074  */
4075 int _snd_hda_set_pin_ctl(struct hda_codec *codec, hda_nid_t pin,
4076                          unsigned int val, bool cached)
4077 {
4078         val = snd_hda_correct_pin_ctl(codec, pin, val);
4079         snd_hda_codec_set_pin_target(codec, pin, val);
4080         if (cached)
4081                 return snd_hda_codec_update_cache(codec, pin, 0,
4082                                 AC_VERB_SET_PIN_WIDGET_CONTROL, val);
4083         else
4084                 return snd_hda_codec_write(codec, pin, 0,
4085                                            AC_VERB_SET_PIN_WIDGET_CONTROL, val);
4086 }
4087 EXPORT_SYMBOL_GPL(_snd_hda_set_pin_ctl);
4088
4089 /**
4090  * snd_hda_add_imux_item - Add an item to input_mux
4091  * @codec: the HDA codec
4092  * @imux: imux helper object
4093  * @label: the name of imux item to assign
4094  * @index: index number of imux item to assign
4095  * @type_idx: pointer to store the resultant label index
4096  *
4097  * When the same label is used already in the existing items, the number
4098  * suffix is appended to the label.  This label index number is stored
4099  * to type_idx when non-NULL pointer is given.
4100  */
4101 int snd_hda_add_imux_item(struct hda_codec *codec,
4102                           struct hda_input_mux *imux, const char *label,
4103                           int index, int *type_idx)
4104 {
4105         int i, label_idx = 0;
4106         if (imux->num_items >= HDA_MAX_NUM_INPUTS) {
4107                 codec_err(codec, "hda_codec: Too many imux items!\n");
4108                 return -EINVAL;
4109         }
4110         for (i = 0; i < imux->num_items; i++) {
4111                 if (!strncmp(label, imux->items[i].label, strlen(label)))
4112                         label_idx++;
4113         }
4114         if (type_idx)
4115                 *type_idx = label_idx;
4116         if (label_idx > 0)
4117                 snprintf(imux->items[imux->num_items].label,
4118                          sizeof(imux->items[imux->num_items].label),
4119                          "%s %d", label, label_idx);
4120         else
4121                 strlcpy(imux->items[imux->num_items].label, label,
4122                         sizeof(imux->items[imux->num_items].label));
4123         imux->items[imux->num_items].index = index;
4124         imux->num_items++;
4125         return 0;
4126 }
4127 EXPORT_SYMBOL_GPL(snd_hda_add_imux_item);
4128
4129 /**
4130  * snd_hda_bus_reset_codecs - Reset the bus
4131  * @bus: HD-audio bus
4132  */
4133 void snd_hda_bus_reset_codecs(struct hda_bus *bus)
4134 {
4135         struct hda_codec *codec;
4136
4137         list_for_each_codec(codec, bus) {
4138                 /* FIXME: maybe a better way needed for forced reset */
4139                 cancel_delayed_work_sync(&codec->jackpoll_work);
4140 #ifdef CONFIG_PM
4141                 if (hda_codec_is_power_on(codec)) {
4142                         hda_call_codec_suspend(codec);
4143                         hda_call_codec_resume(codec);
4144                 }
4145 #endif
4146         }
4147 }
4148
4149 /**
4150  * snd_print_pcm_bits - Print the supported PCM fmt bits to the string buffer
4151  * @pcm: PCM caps bits
4152  * @buf: the string buffer to write
4153  * @buflen: the max buffer length
4154  *
4155  * used by hda_proc.c and hda_eld.c
4156  */
4157 void snd_print_pcm_bits(int pcm, char *buf, int buflen)
4158 {
4159         static unsigned int bits[] = { 8, 16, 20, 24, 32 };
4160         int i, j;
4161
4162         for (i = 0, j = 0; i < ARRAY_SIZE(bits); i++)
4163                 if (pcm & (AC_SUPPCM_BITS_8 << i))
4164                         j += snprintf(buf + j, buflen - j,  " %d", bits[i]);
4165
4166         buf[j] = '\0'; /* necessary when j == 0 */
4167 }
4168 EXPORT_SYMBOL_GPL(snd_print_pcm_bits);
4169
4170 MODULE_DESCRIPTION("HDA codec core");
4171 MODULE_LICENSE("GPL");