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