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