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