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