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