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