~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/sound/pci/hda/hda_codec.c

Version: ~ [ linux-5.1-rc1 ] ~ [ linux-5.0.3 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.30 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.107 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.164 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.176 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.136 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.63 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.39.4 ] ~ [ linux-2.6.38.8 ] ~ [ linux-2.6.37.6 ] ~ [ linux-2.6.36.4 ] ~ [ linux-2.6.35.14 ] ~ [ linux-2.6.34.15 ] ~ [ linux-2.6.33.20 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  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/pci.h>
 26 #include <linux/mutex.h>
 27 #include <sound/core.h>
 28 #include "hda_codec.h"
 29 #include <sound/asoundef.h>
 30 #include <sound/tlv.h>
 31 #include <sound/initval.h>
 32 #include <sound/jack.h>
 33 #include "hda_local.h"
 34 #include "hda_beep.h"
 35 #include <sound/hda_hwdep.h>
 36 
 37 /*
 38  * vendor / preset table
 39  */
 40 
 41 struct hda_vendor_id {
 42         unsigned int id;
 43         const char *name;
 44 };
 45 
 46 /* codec vendor labels */
 47 static struct hda_vendor_id hda_vendor_ids[] = {
 48         { 0x1002, "ATI" },
 49         { 0x1013, "Cirrus Logic" },
 50         { 0x1057, "Motorola" },
 51         { 0x1095, "Silicon Image" },
 52         { 0x10de, "Nvidia" },
 53         { 0x10ec, "Realtek" },
 54         { 0x1102, "Creative" },
 55         { 0x1106, "VIA" },
 56         { 0x111d, "IDT" },
 57         { 0x11c1, "LSI" },
 58         { 0x11d4, "Analog Devices" },
 59         { 0x13f6, "C-Media" },
 60         { 0x14f1, "Conexant" },
 61         { 0x17e8, "Chrontel" },
 62         { 0x1854, "LG" },
 63         { 0x1aec, "Wolfson Microelectronics" },
 64         { 0x434d, "C-Media" },
 65         { 0x8086, "Intel" },
 66         { 0x8384, "SigmaTel" },
 67         {} /* terminator */
 68 };
 69 
 70 static DEFINE_MUTEX(preset_mutex);
 71 static LIST_HEAD(hda_preset_tables);
 72 
 73 int snd_hda_add_codec_preset(struct hda_codec_preset_list *preset)
 74 {
 75         mutex_lock(&preset_mutex);
 76         list_add_tail(&preset->list, &hda_preset_tables);
 77         mutex_unlock(&preset_mutex);
 78         return 0;
 79 }
 80 EXPORT_SYMBOL_HDA(snd_hda_add_codec_preset);
 81 
 82 int snd_hda_delete_codec_preset(struct hda_codec_preset_list *preset)
 83 {
 84         mutex_lock(&preset_mutex);
 85         list_del(&preset->list);
 86         mutex_unlock(&preset_mutex);
 87         return 0;
 88 }
 89 EXPORT_SYMBOL_HDA(snd_hda_delete_codec_preset);
 90 
 91 #ifdef CONFIG_SND_HDA_POWER_SAVE
 92 static void hda_power_work(struct work_struct *work);
 93 static void hda_keep_power_on(struct hda_codec *codec);
 94 #else
 95 static inline void hda_keep_power_on(struct hda_codec *codec) {}
 96 #endif
 97 
 98 /**
 99  * snd_hda_get_jack_location - Give a location string of the jack
100  * @cfg: pin default config value
101  *
102  * Parse the pin default config value and returns the string of the
103  * jack location, e.g. "Rear", "Front", etc.
104  */
105 const char *snd_hda_get_jack_location(u32 cfg)
106 {
107         static char *bases[7] = {
108                 "N/A", "Rear", "Front", "Left", "Right", "Top", "Bottom",
109         };
110         static unsigned char specials_idx[] = {
111                 0x07, 0x08,
112                 0x17, 0x18, 0x19,
113                 0x37, 0x38
114         };
115         static char *specials[] = {
116                 "Rear Panel", "Drive Bar",
117                 "Riser", "HDMI", "ATAPI",
118                 "Mobile-In", "Mobile-Out"
119         };
120         int i;
121         cfg = (cfg & AC_DEFCFG_LOCATION) >> AC_DEFCFG_LOCATION_SHIFT;
122         if ((cfg & 0x0f) < 7)
123                 return bases[cfg & 0x0f];
124         for (i = 0; i < ARRAY_SIZE(specials_idx); i++) {
125                 if (cfg == specials_idx[i])
126                         return specials[i];
127         }
128         return "UNKNOWN";
129 }
130 EXPORT_SYMBOL_HDA(snd_hda_get_jack_location);
131 
132 /**
133  * snd_hda_get_jack_connectivity - Give a connectivity string of the jack
134  * @cfg: pin default config value
135  *
136  * Parse the pin default config value and returns the string of the
137  * jack connectivity, i.e. external or internal connection.
138  */
139 const char *snd_hda_get_jack_connectivity(u32 cfg)
140 {
141         static char *jack_locations[4] = { "Ext", "Int", "Sep", "Oth" };
142 
143         return jack_locations[(cfg >> (AC_DEFCFG_LOCATION_SHIFT + 4)) & 3];
144 }
145 EXPORT_SYMBOL_HDA(snd_hda_get_jack_connectivity);
146 
147 /**
148  * snd_hda_get_jack_type - Give a type string of the jack
149  * @cfg: pin default config value
150  *
151  * Parse the pin default config value and returns the string of the
152  * jack type, i.e. the purpose of the jack, such as Line-Out or CD.
153  */
154 const char *snd_hda_get_jack_type(u32 cfg)
155 {
156         static char *jack_types[16] = {
157                 "Line Out", "Speaker", "HP Out", "CD",
158                 "SPDIF Out", "Digital Out", "Modem Line", "Modem Hand",
159                 "Line In", "Aux", "Mic", "Telephony",
160                 "SPDIF In", "Digital In", "Reserved", "Other"
161         };
162 
163         return jack_types[(cfg & AC_DEFCFG_DEVICE)
164                                 >> AC_DEFCFG_DEVICE_SHIFT];
165 }
166 EXPORT_SYMBOL_HDA(snd_hda_get_jack_type);
167 
168 /*
169  * Compose a 32bit command word to be sent to the HD-audio controller
170  */
171 static inline unsigned int
172 make_codec_cmd(struct hda_codec *codec, hda_nid_t nid, int direct,
173                unsigned int verb, unsigned int parm)
174 {
175         u32 val;
176 
177         if ((codec->addr & ~0xf) || (direct & ~1) || (nid & ~0x7f) ||
178             (verb & ~0xfff) || (parm & ~0xffff)) {
179                 printk(KERN_ERR "hda-codec: out of range cmd %x:%x:%x:%x:%x\n",
180                        codec->addr, direct, nid, verb, parm);
181                 return ~0;
182         }
183 
184         val = (u32)codec->addr << 28;
185         val |= (u32)direct << 27;
186         val |= (u32)nid << 20;
187         val |= verb << 8;
188         val |= parm;
189         return val;
190 }
191 
192 /*
193  * Send and receive a verb
194  */
195 static int codec_exec_verb(struct hda_codec *codec, unsigned int cmd,
196                            unsigned int *res)
197 {
198         struct hda_bus *bus = codec->bus;
199         int err;
200 
201         if (cmd == ~0)
202                 return -1;
203 
204         if (res)
205                 *res = -1;
206  again:
207         snd_hda_power_up(codec);
208         mutex_lock(&bus->cmd_mutex);
209         err = bus->ops.command(bus, cmd);
210         if (!err && res)
211                 *res = bus->ops.get_response(bus, codec->addr);
212         mutex_unlock(&bus->cmd_mutex);
213         snd_hda_power_down(codec);
214         if (res && *res == -1 && bus->rirb_error) {
215                 if (bus->response_reset) {
216                         snd_printd("hda_codec: resetting BUS due to "
217                                    "fatal communication error\n");
218                         bus->ops.bus_reset(bus);
219                 }
220                 goto again;
221         }
222         /* clear reset-flag when the communication gets recovered */
223         if (!err)
224                 bus->response_reset = 0;
225         return err;
226 }
227 
228 /**
229  * snd_hda_codec_read - send a command and get the response
230  * @codec: the HDA codec
231  * @nid: NID to send the command
232  * @direct: direct flag
233  * @verb: the verb to send
234  * @parm: the parameter for the verb
235  *
236  * Send a single command and read the corresponding response.
237  *
238  * Returns the obtained response value, or -1 for an error.
239  */
240 unsigned int snd_hda_codec_read(struct hda_codec *codec, hda_nid_t nid,
241                                 int direct,
242                                 unsigned int verb, unsigned int parm)
243 {
244         unsigned cmd = make_codec_cmd(codec, nid, direct, verb, parm);
245         unsigned int res;
246         codec_exec_verb(codec, cmd, &res);
247         return res;
248 }
249 EXPORT_SYMBOL_HDA(snd_hda_codec_read);
250 
251 /**
252  * snd_hda_codec_write - send a single command without waiting for response
253  * @codec: the HDA codec
254  * @nid: NID to send the command
255  * @direct: direct flag
256  * @verb: the verb to send
257  * @parm: the parameter for the verb
258  *
259  * Send a single command without waiting for response.
260  *
261  * Returns 0 if successful, or a negative error code.
262  */
263 int snd_hda_codec_write(struct hda_codec *codec, hda_nid_t nid, int direct,
264                          unsigned int verb, unsigned int parm)
265 {
266         unsigned int cmd = make_codec_cmd(codec, nid, direct, verb, parm);
267         unsigned int res;
268         return codec_exec_verb(codec, cmd,
269                                codec->bus->sync_write ? &res : NULL);
270 }
271 EXPORT_SYMBOL_HDA(snd_hda_codec_write);
272 
273 /**
274  * snd_hda_sequence_write - sequence writes
275  * @codec: the HDA codec
276  * @seq: VERB array to send
277  *
278  * Send the commands sequentially from the given array.
279  * The array must be terminated with NID=0.
280  */
281 void snd_hda_sequence_write(struct hda_codec *codec, const struct hda_verb *seq)
282 {
283         for (; seq->nid; seq++)
284                 snd_hda_codec_write(codec, seq->nid, 0, seq->verb, seq->param);
285 }
286 EXPORT_SYMBOL_HDA(snd_hda_sequence_write);
287 
288 /**
289  * snd_hda_get_sub_nodes - get the range of sub nodes
290  * @codec: the HDA codec
291  * @nid: NID to parse
292  * @start_id: the pointer to store the start NID
293  *
294  * Parse the NID and store the start NID of its sub-nodes.
295  * Returns the number of sub-nodes.
296  */
297 int snd_hda_get_sub_nodes(struct hda_codec *codec, hda_nid_t nid,
298                           hda_nid_t *start_id)
299 {
300         unsigned int parm;
301 
302         parm = snd_hda_param_read(codec, nid, AC_PAR_NODE_COUNT);
303         if (parm == -1)
304                 return 0;
305         *start_id = (parm >> 16) & 0x7fff;
306         return (int)(parm & 0x7fff);
307 }
308 EXPORT_SYMBOL_HDA(snd_hda_get_sub_nodes);
309 
310 static int _hda_get_connections(struct hda_codec *codec, hda_nid_t nid,
311                                 hda_nid_t *conn_list, int max_conns);
312 static bool add_conn_list(struct snd_array *array, hda_nid_t nid);
313 static int copy_conn_list(hda_nid_t nid, hda_nid_t *dst, int max_dst,
314                           hda_nid_t *src, int len);
315 
316 /**
317  * snd_hda_get_connections - get connection list
318  * @codec: the HDA codec
319  * @nid: NID to parse
320  * @conn_list: connection list array
321  * @max_conns: max. number of connections to store
322  *
323  * Parses the connection list of the given widget and stores the list
324  * of NIDs.
325  *
326  * Returns the number of connections, or a negative error code.
327  */
328 int snd_hda_get_connections(struct hda_codec *codec, hda_nid_t nid,
329                              hda_nid_t *conn_list, int max_conns)
330 {
331         struct snd_array *array = &codec->conn_lists;
332         int i, len, old_used;
333         hda_nid_t list[HDA_MAX_CONNECTIONS];
334 
335         /* look up the cached results */
336         for (i = 0; i < array->used; ) {
337                 hda_nid_t *p = snd_array_elem(array, i);
338                 len = p[1];
339                 if (nid == *p)
340                         return copy_conn_list(nid, conn_list, max_conns,
341                                               p + 2, len);
342                 i += len + 2;
343         }
344 
345         len = _hda_get_connections(codec, nid, list, HDA_MAX_CONNECTIONS);
346         if (len < 0)
347                 return len;
348 
349         /* add to the cache */
350         old_used = array->used;
351         if (!add_conn_list(array, nid) || !add_conn_list(array, len))
352                 goto error_add;
353         for (i = 0; i < len; i++)
354                 if (!add_conn_list(array, list[i]))
355                         goto error_add;
356 
357         return copy_conn_list(nid, conn_list, max_conns, list, len);
358                 
359  error_add:
360         array->used = old_used;
361         return -ENOMEM;
362 }
363 EXPORT_SYMBOL_HDA(snd_hda_get_connections);
364 
365 static int _hda_get_connections(struct hda_codec *codec, hda_nid_t nid,
366                              hda_nid_t *conn_list, int max_conns)
367 {
368         unsigned int parm;
369         int i, conn_len, conns;
370         unsigned int shift, num_elems, mask;
371         unsigned int wcaps;
372         hda_nid_t prev_nid;
373 
374         if (snd_BUG_ON(!conn_list || max_conns <= 0))
375                 return -EINVAL;
376 
377         wcaps = get_wcaps(codec, nid);
378         if (!(wcaps & AC_WCAP_CONN_LIST) &&
379             get_wcaps_type(wcaps) != AC_WID_VOL_KNB) {
380                 snd_printk(KERN_WARNING "hda_codec: "
381                            "connection list not available for 0x%x\n", nid);
382                 return -EINVAL;
383         }
384 
385         parm = snd_hda_param_read(codec, nid, AC_PAR_CONNLIST_LEN);
386         if (parm & AC_CLIST_LONG) {
387                 /* long form */
388                 shift = 16;
389                 num_elems = 2;
390         } else {
391                 /* short form */
392                 shift = 8;
393                 num_elems = 4;
394         }
395         conn_len = parm & AC_CLIST_LENGTH;
396         mask = (1 << (shift-1)) - 1;
397 
398         if (!conn_len)
399                 return 0; /* no connection */
400 
401         if (conn_len == 1) {
402                 /* single connection */
403                 parm = snd_hda_codec_read(codec, nid, 0,
404                                           AC_VERB_GET_CONNECT_LIST, 0);
405                 if (parm == -1 && codec->bus->rirb_error)
406                         return -EIO;
407                 conn_list[0] = parm & mask;
408                 return 1;
409         }
410 
411         /* multi connection */
412         conns = 0;
413         prev_nid = 0;
414         for (i = 0; i < conn_len; i++) {
415                 int range_val;
416                 hda_nid_t val, n;
417 
418                 if (i % num_elems == 0) {
419                         parm = snd_hda_codec_read(codec, nid, 0,
420                                                   AC_VERB_GET_CONNECT_LIST, i);
421                         if (parm == -1 && codec->bus->rirb_error)
422                                 return -EIO;
423                 }
424                 range_val = !!(parm & (1 << (shift-1))); /* ranges */
425                 val = parm & mask;
426                 if (val == 0) {
427                         snd_printk(KERN_WARNING "hda_codec: "
428                                    "invalid CONNECT_LIST verb %x[%i]:%x\n",
429                                     nid, i, parm);
430                         return 0;
431                 }
432                 parm >>= shift;
433                 if (range_val) {
434                         /* ranges between the previous and this one */
435                         if (!prev_nid || prev_nid >= val) {
436                                 snd_printk(KERN_WARNING "hda_codec: "
437                                            "invalid dep_range_val %x:%x\n",
438                                            prev_nid, val);
439                                 continue;
440                         }
441                         for (n = prev_nid + 1; n <= val; n++) {
442                                 if (conns >= max_conns) {
443                                         snd_printk(KERN_ERR "hda_codec: "
444                                                    "Too many connections %d for NID 0x%x\n",
445                                                    conns, nid);
446                                         return -EINVAL;
447                                 }
448                                 conn_list[conns++] = n;
449                         }
450                 } else {
451                         if (conns >= max_conns) {
452                                 snd_printk(KERN_ERR "hda_codec: "
453                                            "Too many connections %d for NID 0x%x\n",
454                                            conns, nid);
455                                 return -EINVAL;
456                         }
457                         conn_list[conns++] = val;
458                 }
459                 prev_nid = val;
460         }
461         return conns;
462 }
463 
464 static bool add_conn_list(struct snd_array *array, hda_nid_t nid)
465 {
466         hda_nid_t *p = snd_array_new(array);
467         if (!p)
468                 return false;
469         *p = nid;
470         return true;
471 }
472 
473 static int copy_conn_list(hda_nid_t nid, hda_nid_t *dst, int max_dst,
474                           hda_nid_t *src, int len)
475 {
476         if (len > max_dst) {
477                 snd_printk(KERN_ERR "hda_codec: "
478                            "Too many connections %d for NID 0x%x\n",
479                            len, nid);
480                 return -EINVAL;
481         }
482         memcpy(dst, src, len * sizeof(hda_nid_t));
483         return len;
484 }
485 
486 /**
487  * snd_hda_queue_unsol_event - add an unsolicited event to queue
488  * @bus: the BUS
489  * @res: unsolicited event (lower 32bit of RIRB entry)
490  * @res_ex: codec addr and flags (upper 32bit or RIRB entry)
491  *
492  * Adds the given event to the queue.  The events are processed in
493  * the workqueue asynchronously.  Call this function in the interrupt
494  * hanlder when RIRB receives an unsolicited event.
495  *
496  * Returns 0 if successful, or a negative error code.
497  */
498 int snd_hda_queue_unsol_event(struct hda_bus *bus, u32 res, u32 res_ex)
499 {
500         struct hda_bus_unsolicited *unsol;
501         unsigned int wp;
502 
503         unsol = bus->unsol;
504         if (!unsol)
505                 return 0;
506 
507         wp = (unsol->wp + 1) % HDA_UNSOL_QUEUE_SIZE;
508         unsol->wp = wp;
509 
510         wp <<= 1;
511         unsol->queue[wp] = res;
512         unsol->queue[wp + 1] = res_ex;
513 
514         queue_work(bus->workq, &unsol->work);
515 
516         return 0;
517 }
518 EXPORT_SYMBOL_HDA(snd_hda_queue_unsol_event);
519 
520 /*
521  * process queued unsolicited events
522  */
523 static void process_unsol_events(struct work_struct *work)
524 {
525         struct hda_bus_unsolicited *unsol =
526                 container_of(work, struct hda_bus_unsolicited, work);
527         struct hda_bus *bus = unsol->bus;
528         struct hda_codec *codec;
529         unsigned int rp, caddr, res;
530 
531         while (unsol->rp != unsol->wp) {
532                 rp = (unsol->rp + 1) % HDA_UNSOL_QUEUE_SIZE;
533                 unsol->rp = rp;
534                 rp <<= 1;
535                 res = unsol->queue[rp];
536                 caddr = unsol->queue[rp + 1];
537                 if (!(caddr & (1 << 4))) /* no unsolicited event? */
538                         continue;
539                 codec = bus->caddr_tbl[caddr & 0x0f];
540                 if (codec && codec->patch_ops.unsol_event)
541                         codec->patch_ops.unsol_event(codec, res);
542         }
543 }
544 
545 /*
546  * initialize unsolicited queue
547  */
548 static int init_unsol_queue(struct hda_bus *bus)
549 {
550         struct hda_bus_unsolicited *unsol;
551 
552         if (bus->unsol) /* already initialized */
553                 return 0;
554 
555         unsol = kzalloc(sizeof(*unsol), GFP_KERNEL);
556         if (!unsol) {
557                 snd_printk(KERN_ERR "hda_codec: "
558                            "can't allocate unsolicited queue\n");
559                 return -ENOMEM;
560         }
561         INIT_WORK(&unsol->work, process_unsol_events);
562         unsol->bus = bus;
563         bus->unsol = unsol;
564         return 0;
565 }
566 
567 /*
568  * destructor
569  */
570 static void snd_hda_codec_free(struct hda_codec *codec);
571 
572 static int snd_hda_bus_free(struct hda_bus *bus)
573 {
574         struct hda_codec *codec, *n;
575 
576         if (!bus)
577                 return 0;
578         if (bus->workq)
579                 flush_workqueue(bus->workq);
580         if (bus->unsol)
581                 kfree(bus->unsol);
582         list_for_each_entry_safe(codec, n, &bus->codec_list, list) {
583                 snd_hda_codec_free(codec);
584         }
585         if (bus->ops.private_free)
586                 bus->ops.private_free(bus);
587         if (bus->workq)
588                 destroy_workqueue(bus->workq);
589         kfree(bus);
590         return 0;
591 }
592 
593 static int snd_hda_bus_dev_free(struct snd_device *device)
594 {
595         struct hda_bus *bus = device->device_data;
596         bus->shutdown = 1;
597         return snd_hda_bus_free(bus);
598 }
599 
600 #ifdef CONFIG_SND_HDA_HWDEP
601 static int snd_hda_bus_dev_register(struct snd_device *device)
602 {
603         struct hda_bus *bus = device->device_data;
604         struct hda_codec *codec;
605         list_for_each_entry(codec, &bus->codec_list, list) {
606                 snd_hda_hwdep_add_sysfs(codec);
607                 snd_hda_hwdep_add_power_sysfs(codec);
608         }
609         return 0;
610 }
611 #else
612 #define snd_hda_bus_dev_register        NULL
613 #endif
614 
615 /**
616  * snd_hda_bus_new - create a HDA bus
617  * @card: the card entry
618  * @temp: the template for hda_bus information
619  * @busp: the pointer to store the created bus instance
620  *
621  * Returns 0 if successful, or a negative error code.
622  */
623 int /*__devinit*/ snd_hda_bus_new(struct snd_card *card,
624                               const struct hda_bus_template *temp,
625                               struct hda_bus **busp)
626 {
627         struct hda_bus *bus;
628         int err;
629         static struct snd_device_ops dev_ops = {
630                 .dev_register = snd_hda_bus_dev_register,
631                 .dev_free = snd_hda_bus_dev_free,
632         };
633 
634         if (snd_BUG_ON(!temp))
635                 return -EINVAL;
636         if (snd_BUG_ON(!temp->ops.command || !temp->ops.get_response))
637                 return -EINVAL;
638 
639         if (busp)
640                 *busp = NULL;
641 
642         bus = kzalloc(sizeof(*bus), GFP_KERNEL);
643         if (bus == NULL) {
644                 snd_printk(KERN_ERR "can't allocate struct hda_bus\n");
645                 return -ENOMEM;
646         }
647 
648         bus->card = card;
649         bus->private_data = temp->private_data;
650         bus->pci = temp->pci;
651         bus->modelname = temp->modelname;
652         bus->power_save = temp->power_save;
653         bus->ops = temp->ops;
654 
655         mutex_init(&bus->cmd_mutex);
656         mutex_init(&bus->prepare_mutex);
657         INIT_LIST_HEAD(&bus->codec_list);
658 
659         snprintf(bus->workq_name, sizeof(bus->workq_name),
660                  "hd-audio%d", card->number);
661         bus->workq = create_singlethread_workqueue(bus->workq_name);
662         if (!bus->workq) {
663                 snd_printk(KERN_ERR "cannot create workqueue %s\n",
664                            bus->workq_name);
665                 kfree(bus);
666                 return -ENOMEM;
667         }
668 
669         err = snd_device_new(card, SNDRV_DEV_BUS, bus, &dev_ops);
670         if (err < 0) {
671                 snd_hda_bus_free(bus);
672                 return err;
673         }
674         if (busp)
675                 *busp = bus;
676         return 0;
677 }
678 EXPORT_SYMBOL_HDA(snd_hda_bus_new);
679 
680 #ifdef CONFIG_SND_HDA_GENERIC
681 #define is_generic_config(codec) \
682         (codec->modelname && !strcmp(codec->modelname, "generic"))
683 #else
684 #define is_generic_config(codec)        0
685 #endif
686 
687 #ifdef MODULE
688 #define HDA_MODREQ_MAX_COUNT    2       /* two request_modules()'s */
689 #else
690 #define HDA_MODREQ_MAX_COUNT    0       /* all presets are statically linked */
691 #endif
692 
693 /*
694  * find a matching codec preset
695  */
696 static const struct hda_codec_preset *
697 find_codec_preset(struct hda_codec *codec)
698 {
699         struct hda_codec_preset_list *tbl;
700         const struct hda_codec_preset *preset;
701         int mod_requested = 0;
702 
703         if (is_generic_config(codec))
704                 return NULL; /* use the generic parser */
705 
706  again:
707         mutex_lock(&preset_mutex);
708         list_for_each_entry(tbl, &hda_preset_tables, list) {
709                 if (!try_module_get(tbl->owner)) {
710                         snd_printk(KERN_ERR "hda_codec: cannot module_get\n");
711                         continue;
712                 }
713                 for (preset = tbl->preset; preset->id; preset++) {
714                         u32 mask = preset->mask;
715                         if (preset->afg && preset->afg != codec->afg)
716                                 continue;
717                         if (preset->mfg && preset->mfg != codec->mfg)
718                                 continue;
719                         if (!mask)
720                                 mask = ~0;
721                         if (preset->id == (codec->vendor_id & mask) &&
722                             (!preset->rev ||
723                              preset->rev == codec->revision_id)) {
724                                 mutex_unlock(&preset_mutex);
725                                 codec->owner = tbl->owner;
726                                 return preset;
727                         }
728                 }
729                 module_put(tbl->owner);
730         }
731         mutex_unlock(&preset_mutex);
732 
733         if (mod_requested < HDA_MODREQ_MAX_COUNT) {
734                 char name[32];
735                 if (!mod_requested)
736                         snprintf(name, sizeof(name), "snd-hda-codec-id:%08x",
737                                  codec->vendor_id);
738                 else
739                         snprintf(name, sizeof(name), "snd-hda-codec-id:%04x*",
740                                  (codec->vendor_id >> 16) & 0xffff);
741                 request_module(name);
742                 mod_requested++;
743                 goto again;
744         }
745         return NULL;
746 }
747 
748 /*
749  * get_codec_name - store the codec name
750  */
751 static int get_codec_name(struct hda_codec *codec)
752 {
753         const struct hda_vendor_id *c;
754         const char *vendor = NULL;
755         u16 vendor_id = codec->vendor_id >> 16;
756         char tmp[16];
757 
758         if (codec->vendor_name)
759                 goto get_chip_name;
760 
761         for (c = hda_vendor_ids; c->id; c++) {
762                 if (c->id == vendor_id) {
763                         vendor = c->name;
764                         break;
765                 }
766         }
767         if (!vendor) {
768                 sprintf(tmp, "Generic %04x", vendor_id);
769                 vendor = tmp;
770         }
771         codec->vendor_name = kstrdup(vendor, GFP_KERNEL);
772         if (!codec->vendor_name)
773                 return -ENOMEM;
774 
775  get_chip_name:
776         if (codec->chip_name)
777                 return 0;
778 
779         if (codec->preset && codec->preset->name)
780                 codec->chip_name = kstrdup(codec->preset->name, GFP_KERNEL);
781         else {
782                 sprintf(tmp, "ID %x", codec->vendor_id & 0xffff);
783                 codec->chip_name = kstrdup(tmp, GFP_KERNEL);
784         }
785         if (!codec->chip_name)
786                 return -ENOMEM;
787         return 0;
788 }
789 
790 /*
791  * look for an AFG and MFG nodes
792  */
793 static void /*__devinit*/ setup_fg_nodes(struct hda_codec *codec)
794 {
795         int i, total_nodes, function_id;
796         hda_nid_t nid;
797 
798         total_nodes = snd_hda_get_sub_nodes(codec, AC_NODE_ROOT, &nid);
799         for (i = 0; i < total_nodes; i++, nid++) {
800                 function_id = snd_hda_param_read(codec, nid,
801                                                 AC_PAR_FUNCTION_TYPE);
802                 switch (function_id & 0xff) {
803                 case AC_GRP_AUDIO_FUNCTION:
804                         codec->afg = nid;
805                         codec->afg_function_id = function_id & 0xff;
806                         codec->afg_unsol = (function_id >> 8) & 1;
807                         break;
808                 case AC_GRP_MODEM_FUNCTION:
809                         codec->mfg = nid;
810                         codec->mfg_function_id = function_id & 0xff;
811                         codec->mfg_unsol = (function_id >> 8) & 1;
812                         break;
813                 default:
814                         break;
815                 }
816         }
817 }
818 
819 /*
820  * read widget caps for each widget and store in cache
821  */
822 static int read_widget_caps(struct hda_codec *codec, hda_nid_t fg_node)
823 {
824         int i;
825         hda_nid_t nid;
826 
827         codec->num_nodes = snd_hda_get_sub_nodes(codec, fg_node,
828                                                  &codec->start_nid);
829         codec->wcaps = kmalloc(codec->num_nodes * 4, GFP_KERNEL);
830         if (!codec->wcaps)
831                 return -ENOMEM;
832         nid = codec->start_nid;
833         for (i = 0; i < codec->num_nodes; i++, nid++)
834                 codec->wcaps[i] = snd_hda_param_read(codec, nid,
835                                                      AC_PAR_AUDIO_WIDGET_CAP);
836         return 0;
837 }
838 
839 /* read all pin default configurations and save codec->init_pins */
840 static int read_pin_defaults(struct hda_codec *codec)
841 {
842         int i;
843         hda_nid_t nid = codec->start_nid;
844 
845         for (i = 0; i < codec->num_nodes; i++, nid++) {
846                 struct hda_pincfg *pin;
847                 unsigned int wcaps = get_wcaps(codec, nid);
848                 unsigned int wid_type = get_wcaps_type(wcaps);
849                 if (wid_type != AC_WID_PIN)
850                         continue;
851                 pin = snd_array_new(&codec->init_pins);
852                 if (!pin)
853                         return -ENOMEM;
854                 pin->nid = nid;
855                 pin->cfg = snd_hda_codec_read(codec, nid, 0,
856                                               AC_VERB_GET_CONFIG_DEFAULT, 0);
857                 pin->ctrl = snd_hda_codec_read(codec, nid, 0,
858                                                AC_VERB_GET_PIN_WIDGET_CONTROL,
859                                                0);
860         }
861         return 0;
862 }
863 
864 /* look up the given pin config list and return the item matching with NID */
865 static struct hda_pincfg *look_up_pincfg(struct hda_codec *codec,
866                                          struct snd_array *array,
867                                          hda_nid_t nid)
868 {
869         int i;
870         for (i = 0; i < array->used; i++) {
871                 struct hda_pincfg *pin = snd_array_elem(array, i);
872                 if (pin->nid == nid)
873                         return pin;
874         }
875         return NULL;
876 }
877 
878 /* write a config value for the given NID */
879 static void set_pincfg(struct hda_codec *codec, hda_nid_t nid,
880                        unsigned int cfg)
881 {
882         int i;
883         for (i = 0; i < 4; i++) {
884                 snd_hda_codec_write(codec, nid, 0,
885                                     AC_VERB_SET_CONFIG_DEFAULT_BYTES_0 + i,
886                                     cfg & 0xff);
887                 cfg >>= 8;
888         }
889 }
890 
891 /* set the current pin config value for the given NID.
892  * the value is cached, and read via snd_hda_codec_get_pincfg()
893  */
894 int snd_hda_add_pincfg(struct hda_codec *codec, struct snd_array *list,
895                        hda_nid_t nid, unsigned int cfg)
896 {
897         struct hda_pincfg *pin;
898         unsigned int oldcfg;
899 
900         if (get_wcaps_type(get_wcaps(codec, nid)) != AC_WID_PIN)
901                 return -EINVAL;
902 
903         oldcfg = snd_hda_codec_get_pincfg(codec, nid);
904         pin = look_up_pincfg(codec, list, nid);
905         if (!pin) {
906                 pin = snd_array_new(list);
907                 if (!pin)
908                         return -ENOMEM;
909                 pin->nid = nid;
910         }
911         pin->cfg = cfg;
912 
913         /* change only when needed; e.g. if the pincfg is already present
914          * in user_pins[], don't write it
915          */
916         cfg = snd_hda_codec_get_pincfg(codec, nid);
917         if (oldcfg != cfg)
918                 set_pincfg(codec, nid, cfg);
919         return 0;
920 }
921 
922 /**
923  * snd_hda_codec_set_pincfg - Override a pin default configuration
924  * @codec: the HDA codec
925  * @nid: NID to set the pin config
926  * @cfg: the pin default config value
927  *
928  * Override a pin default configuration value in the cache.
929  * This value can be read by snd_hda_codec_get_pincfg() in a higher
930  * priority than the real hardware value.
931  */
932 int snd_hda_codec_set_pincfg(struct hda_codec *codec,
933                              hda_nid_t nid, unsigned int cfg)
934 {
935         return snd_hda_add_pincfg(codec, &codec->driver_pins, nid, cfg);
936 }
937 EXPORT_SYMBOL_HDA(snd_hda_codec_set_pincfg);
938 
939 /**
940  * snd_hda_codec_get_pincfg - Obtain a pin-default configuration
941  * @codec: the HDA codec
942  * @nid: NID to get the pin config
943  *
944  * Get the current pin config value of the given pin NID.
945  * If the pincfg value is cached or overridden via sysfs or driver,
946  * returns the cached value.
947  */
948 unsigned int snd_hda_codec_get_pincfg(struct hda_codec *codec, hda_nid_t nid)
949 {
950         struct hda_pincfg *pin;
951 
952 #ifdef CONFIG_SND_HDA_HWDEP
953         pin = look_up_pincfg(codec, &codec->user_pins, nid);
954         if (pin)
955                 return pin->cfg;
956 #endif
957         pin = look_up_pincfg(codec, &codec->driver_pins, nid);
958         if (pin)
959                 return pin->cfg;
960         pin = look_up_pincfg(codec, &codec->init_pins, nid);
961         if (pin)
962                 return pin->cfg;
963         return 0;
964 }
965 EXPORT_SYMBOL_HDA(snd_hda_codec_get_pincfg);
966 
967 /* restore all current pin configs */
968 static void restore_pincfgs(struct hda_codec *codec)
969 {
970         int i;
971         for (i = 0; i < codec->init_pins.used; i++) {
972                 struct hda_pincfg *pin = snd_array_elem(&codec->init_pins, i);
973                 set_pincfg(codec, pin->nid,
974                            snd_hda_codec_get_pincfg(codec, pin->nid));
975         }
976 }
977 
978 /**
979  * snd_hda_shutup_pins - Shut up all pins
980  * @codec: the HDA codec
981  *
982  * Clear all pin controls to shup up before suspend for avoiding click noise.
983  * The controls aren't cached so that they can be resumed properly.
984  */
985 void snd_hda_shutup_pins(struct hda_codec *codec)
986 {
987         int i;
988         /* don't shut up pins when unloading the driver; otherwise it breaks
989          * the default pin setup at the next load of the driver
990          */
991         if (codec->bus->shutdown)
992                 return;
993         for (i = 0; i < codec->init_pins.used; i++) {
994                 struct hda_pincfg *pin = snd_array_elem(&codec->init_pins, i);
995                 /* use read here for syncing after issuing each verb */
996                 snd_hda_codec_read(codec, pin->nid, 0,
997                                    AC_VERB_SET_PIN_WIDGET_CONTROL, 0);
998         }
999         codec->pins_shutup = 1;
1000 }
1001 EXPORT_SYMBOL_HDA(snd_hda_shutup_pins);
1002 
1003 #ifdef SND_HDA_NEEDS_RESUME
1004 /* Restore the pin controls cleared previously via snd_hda_shutup_pins() */
1005 static void restore_shutup_pins(struct hda_codec *codec)
1006 {
1007         int i;
1008         if (!codec->pins_shutup)
1009                 return;
1010         if (codec->bus->shutdown)
1011                 return;
1012         for (i = 0; i < codec->init_pins.used; i++) {
1013                 struct hda_pincfg *pin = snd_array_elem(&codec->init_pins, i);
1014                 snd_hda_codec_write(codec, pin->nid, 0,
1015                                     AC_VERB_SET_PIN_WIDGET_CONTROL,
1016                                     pin->ctrl);
1017         }
1018         codec->pins_shutup = 0;
1019 }
1020 #endif
1021 
1022 static void init_hda_cache(struct hda_cache_rec *cache,
1023                            unsigned int record_size);
1024 static void free_hda_cache(struct hda_cache_rec *cache);
1025 
1026 /* restore the initial pin cfgs and release all pincfg lists */
1027 static void restore_init_pincfgs(struct hda_codec *codec)
1028 {
1029         /* first free driver_pins and user_pins, then call restore_pincfg
1030          * so that only the values in init_pins are restored
1031          */
1032         snd_array_free(&codec->driver_pins);
1033 #ifdef CONFIG_SND_HDA_HWDEP
1034         snd_array_free(&codec->user_pins);
1035 #endif
1036         restore_pincfgs(codec);
1037         snd_array_free(&codec->init_pins);
1038 }
1039 
1040 /*
1041  * audio-converter setup caches
1042  */
1043 struct hda_cvt_setup {
1044         hda_nid_t nid;
1045         u8 stream_tag;
1046         u8 channel_id;
1047         u16 format_id;
1048         unsigned char active;   /* cvt is currently used */
1049         unsigned char dirty;    /* setups should be cleared */
1050 };
1051 
1052 /* get or create a cache entry for the given audio converter NID */
1053 static struct hda_cvt_setup *
1054 get_hda_cvt_setup(struct hda_codec *codec, hda_nid_t nid)
1055 {
1056         struct hda_cvt_setup *p;
1057         int i;
1058 
1059         for (i = 0; i < codec->cvt_setups.used; i++) {
1060                 p = snd_array_elem(&codec->cvt_setups, i);
1061                 if (p->nid == nid)
1062                         return p;
1063         }
1064         p = snd_array_new(&codec->cvt_setups);
1065         if (p)
1066                 p->nid = nid;
1067         return p;
1068 }
1069 
1070 /*
1071  * codec destructor
1072  */
1073 static void snd_hda_codec_free(struct hda_codec *codec)
1074 {
1075         if (!codec)
1076                 return;
1077         restore_init_pincfgs(codec);
1078 #ifdef CONFIG_SND_HDA_POWER_SAVE
1079         cancel_delayed_work(&codec->power_work);
1080         flush_workqueue(codec->bus->workq);
1081 #endif
1082         list_del(&codec->list);
1083         snd_array_free(&codec->mixers);
1084         snd_array_free(&codec->nids);
1085         snd_array_free(&codec->conn_lists);
1086         codec->bus->caddr_tbl[codec->addr] = NULL;
1087         if (codec->patch_ops.free)
1088                 codec->patch_ops.free(codec);
1089         module_put(codec->owner);
1090         free_hda_cache(&codec->amp_cache);
1091         free_hda_cache(&codec->cmd_cache);
1092         kfree(codec->vendor_name);
1093         kfree(codec->chip_name);
1094         kfree(codec->modelname);
1095         kfree(codec->wcaps);
1096         kfree(codec);
1097 }
1098 
1099 static void hda_set_power_state(struct hda_codec *codec, hda_nid_t fg,
1100                                 unsigned int power_state);
1101 
1102 /**
1103  * snd_hda_codec_new - create a HDA codec
1104  * @bus: the bus to assign
1105  * @codec_addr: the codec address
1106  * @codecp: the pointer to store the generated codec
1107  *
1108  * Returns 0 if successful, or a negative error code.
1109  */
1110 int /*__devinit*/ snd_hda_codec_new(struct hda_bus *bus,
1111                                 unsigned int codec_addr,
1112                                 struct hda_codec **codecp)
1113 {
1114         struct hda_codec *codec;
1115         char component[31];
1116         int err;
1117 
1118         if (snd_BUG_ON(!bus))
1119                 return -EINVAL;
1120         if (snd_BUG_ON(codec_addr > HDA_MAX_CODEC_ADDRESS))
1121                 return -EINVAL;
1122 
1123         if (bus->caddr_tbl[codec_addr]) {
1124                 snd_printk(KERN_ERR "hda_codec: "
1125                            "address 0x%x is already occupied\n", codec_addr);
1126                 return -EBUSY;
1127         }
1128 
1129         codec = kzalloc(sizeof(*codec), GFP_KERNEL);
1130         if (codec == NULL) {
1131                 snd_printk(KERN_ERR "can't allocate struct hda_codec\n");
1132                 return -ENOMEM;
1133         }
1134 
1135         codec->bus = bus;
1136         codec->addr = codec_addr;
1137         mutex_init(&codec->spdif_mutex);
1138         mutex_init(&codec->control_mutex);
1139         init_hda_cache(&codec->amp_cache, sizeof(struct hda_amp_info));
1140         init_hda_cache(&codec->cmd_cache, sizeof(struct hda_cache_head));
1141         snd_array_init(&codec->mixers, sizeof(struct hda_nid_item), 32);
1142         snd_array_init(&codec->nids, sizeof(struct hda_nid_item), 32);
1143         snd_array_init(&codec->init_pins, sizeof(struct hda_pincfg), 16);
1144         snd_array_init(&codec->driver_pins, sizeof(struct hda_pincfg), 16);
1145         snd_array_init(&codec->cvt_setups, sizeof(struct hda_cvt_setup), 8);
1146         snd_array_init(&codec->conn_lists, sizeof(hda_nid_t), 64);
1147         if (codec->bus->modelname) {
1148                 codec->modelname = kstrdup(codec->bus->modelname, GFP_KERNEL);
1149                 if (!codec->modelname) {
1150                         snd_hda_codec_free(codec);
1151                         return -ENODEV;
1152                 }
1153         }
1154 
1155 #ifdef CONFIG_SND_HDA_POWER_SAVE
1156         INIT_DELAYED_WORK(&codec->power_work, hda_power_work);
1157         /* snd_hda_codec_new() marks the codec as power-up, and leave it as is.
1158          * the caller has to power down appropriatley after initialization
1159          * phase.
1160          */
1161         hda_keep_power_on(codec);
1162 #endif
1163 
1164         list_add_tail(&codec->list, &bus->codec_list);
1165         bus->caddr_tbl[codec_addr] = codec;
1166 
1167         codec->vendor_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1168                                               AC_PAR_VENDOR_ID);
1169         if (codec->vendor_id == -1)
1170                 /* read again, hopefully the access method was corrected
1171                  * in the last read...
1172                  */
1173                 codec->vendor_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1174                                                       AC_PAR_VENDOR_ID);
1175         codec->subsystem_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1176                                                  AC_PAR_SUBSYSTEM_ID);
1177         codec->revision_id = snd_hda_param_read(codec, AC_NODE_ROOT,
1178                                                 AC_PAR_REV_ID);
1179 
1180         setup_fg_nodes(codec);
1181         if (!codec->afg && !codec->mfg) {
1182                 snd_printdd("hda_codec: no AFG or MFG node found\n");
1183                 err = -ENODEV;
1184                 goto error;
1185         }
1186 
1187         err = read_widget_caps(codec, codec->afg ? codec->afg : codec->mfg);
1188         if (err < 0) {
1189                 snd_printk(KERN_ERR "hda_codec: cannot malloc\n");
1190                 goto error;
1191         }
1192         err = read_pin_defaults(codec);
1193         if (err < 0)
1194                 goto error;
1195 
1196         if (!codec->subsystem_id) {
1197                 hda_nid_t nid = codec->afg ? codec->afg : codec->mfg;
1198                 codec->subsystem_id =
1199                         snd_hda_codec_read(codec, nid, 0,
1200                                            AC_VERB_GET_SUBSYSTEM_ID, 0);
1201         }
1202 
1203         /* power-up all before initialization */
1204         hda_set_power_state(codec,
1205                             codec->afg ? codec->afg : codec->mfg,
1206                             AC_PWRST_D0);
1207 
1208         snd_hda_codec_proc_new(codec);
1209 
1210         snd_hda_create_hwdep(codec);
1211 
1212         sprintf(component, "HDA:%08x,%08x,%08x", codec->vendor_id,
1213                 codec->subsystem_id, codec->revision_id);
1214         snd_component_add(codec->bus->card, component);
1215 
1216         if (codecp)
1217                 *codecp = codec;
1218         return 0;
1219 
1220  error:
1221         snd_hda_codec_free(codec);
1222         return err;
1223 }
1224 EXPORT_SYMBOL_HDA(snd_hda_codec_new);
1225 
1226 /**
1227  * snd_hda_codec_configure - (Re-)configure the HD-audio codec
1228  * @codec: the HDA codec
1229  *
1230  * Start parsing of the given codec tree and (re-)initialize the whole
1231  * patch instance.
1232  *
1233  * Returns 0 if successful or a negative error code.
1234  */
1235 int snd_hda_codec_configure(struct hda_codec *codec)
1236 {
1237         int err;
1238 
1239         codec->preset = find_codec_preset(codec);
1240         if (!codec->vendor_name || !codec->chip_name) {
1241                 err = get_codec_name(codec);
1242                 if (err < 0)
1243                         return err;
1244         }
1245 
1246         if (is_generic_config(codec)) {
1247                 err = snd_hda_parse_generic_codec(codec);
1248                 goto patched;
1249         }
1250         if (codec->preset && codec->preset->patch) {
1251                 err = codec->preset->patch(codec);
1252                 goto patched;
1253         }
1254 
1255         /* call the default parser */
1256         err = snd_hda_parse_generic_codec(codec);
1257         if (err < 0)
1258                 printk(KERN_ERR "hda-codec: No codec parser is available\n");
1259 
1260  patched:
1261         if (!err && codec->patch_ops.unsol_event)
1262                 err = init_unsol_queue(codec->bus);
1263         /* audio codec should override the mixer name */
1264         if (!err && (codec->afg || !*codec->bus->card->mixername))
1265                 snprintf(codec->bus->card->mixername,
1266                          sizeof(codec->bus->card->mixername),
1267                          "%s %s", codec->vendor_name, codec->chip_name);
1268         return err;
1269 }
1270 EXPORT_SYMBOL_HDA(snd_hda_codec_configure);
1271 
1272 /**
1273  * snd_hda_codec_setup_stream - set up the codec for streaming
1274  * @codec: the CODEC to set up
1275  * @nid: the NID to set up
1276  * @stream_tag: stream tag to pass, it's between 0x1 and 0xf.
1277  * @channel_id: channel id to pass, zero based.
1278  * @format: stream format.
1279  */
1280 void snd_hda_codec_setup_stream(struct hda_codec *codec, hda_nid_t nid,
1281                                 u32 stream_tag,
1282                                 int channel_id, int format)
1283 {
1284         struct hda_codec *c;
1285         struct hda_cvt_setup *p;
1286         unsigned int oldval, newval;
1287         int type;
1288         int i;
1289 
1290         if (!nid)
1291                 return;
1292 
1293         snd_printdd("hda_codec_setup_stream: "
1294                     "NID=0x%x, stream=0x%x, channel=%d, format=0x%x\n",
1295                     nid, stream_tag, channel_id, format);
1296         p = get_hda_cvt_setup(codec, nid);
1297         if (!p)
1298                 return;
1299         /* update the stream-id if changed */
1300         if (p->stream_tag != stream_tag || p->channel_id != channel_id) {
1301                 oldval = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_CONV, 0);
1302                 newval = (stream_tag << 4) | channel_id;
1303                 if (oldval != newval)
1304                         snd_hda_codec_write(codec, nid, 0,
1305                                             AC_VERB_SET_CHANNEL_STREAMID,
1306                                             newval);
1307                 p->stream_tag = stream_tag;
1308                 p->channel_id = channel_id;
1309         }
1310         /* update the format-id if changed */
1311         if (p->format_id != format) {
1312                 oldval = snd_hda_codec_read(codec, nid, 0,
1313                                             AC_VERB_GET_STREAM_FORMAT, 0);
1314                 if (oldval != format) {
1315                         msleep(1);
1316                         snd_hda_codec_write(codec, nid, 0,
1317                                             AC_VERB_SET_STREAM_FORMAT,
1318                                             format);
1319                 }
1320                 p->format_id = format;
1321         }
1322         p->active = 1;
1323         p->dirty = 0;
1324 
1325         /* make other inactive cvts with the same stream-tag dirty */
1326         type = get_wcaps_type(get_wcaps(codec, nid));
1327         list_for_each_entry(c, &codec->bus->codec_list, list) {
1328                 for (i = 0; i < c->cvt_setups.used; i++) {
1329                         p = snd_array_elem(&c->cvt_setups, i);
1330                         if (!p->active && p->stream_tag == stream_tag &&
1331                             get_wcaps_type(get_wcaps(c, p->nid)) == type)
1332                                 p->dirty = 1;
1333                 }
1334         }
1335 }
1336 EXPORT_SYMBOL_HDA(snd_hda_codec_setup_stream);
1337 
1338 static void really_cleanup_stream(struct hda_codec *codec,
1339                                   struct hda_cvt_setup *q);
1340 
1341 /**
1342  * __snd_hda_codec_cleanup_stream - clean up the codec for closing
1343  * @codec: the CODEC to clean up
1344  * @nid: the NID to clean up
1345  * @do_now: really clean up the stream instead of clearing the active flag
1346  */
1347 void __snd_hda_codec_cleanup_stream(struct hda_codec *codec, hda_nid_t nid,
1348                                     int do_now)
1349 {
1350         struct hda_cvt_setup *p;
1351 
1352         if (!nid)
1353                 return;
1354 
1355         if (codec->no_sticky_stream)
1356                 do_now = 1;
1357 
1358         snd_printdd("hda_codec_cleanup_stream: NID=0x%x\n", nid);
1359         p = get_hda_cvt_setup(codec, nid);
1360         if (p) {
1361                 /* here we just clear the active flag when do_now isn't set;
1362                  * actual clean-ups will be done later in
1363                  * purify_inactive_streams() called from snd_hda_codec_prpapre()
1364                  */
1365                 if (do_now)
1366                         really_cleanup_stream(codec, p);
1367                 else
1368                         p->active = 0;
1369         }
1370 }
1371 EXPORT_SYMBOL_HDA(__snd_hda_codec_cleanup_stream);
1372 
1373 static void really_cleanup_stream(struct hda_codec *codec,
1374                                   struct hda_cvt_setup *q)
1375 {
1376         hda_nid_t nid = q->nid;
1377         snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_CHANNEL_STREAMID, 0);
1378         snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_STREAM_FORMAT, 0);
1379         memset(q, 0, sizeof(*q));
1380         q->nid = nid;
1381 }
1382 
1383 /* clean up the all conflicting obsolete streams */
1384 static void purify_inactive_streams(struct hda_codec *codec)
1385 {
1386         struct hda_codec *c;
1387         int i;
1388 
1389         list_for_each_entry(c, &codec->bus->codec_list, list) {
1390                 for (i = 0; i < c->cvt_setups.used; i++) {
1391                         struct hda_cvt_setup *p;
1392                         p = snd_array_elem(&c->cvt_setups, i);
1393                         if (p->dirty)
1394                                 really_cleanup_stream(c, p);
1395                 }
1396         }
1397 }
1398 
1399 #ifdef SND_HDA_NEEDS_RESUME
1400 /* clean up all streams; called from suspend */
1401 static void hda_cleanup_all_streams(struct hda_codec *codec)
1402 {
1403         int i;
1404 
1405         for (i = 0; i < codec->cvt_setups.used; i++) {
1406                 struct hda_cvt_setup *p = snd_array_elem(&codec->cvt_setups, i);
1407                 if (p->stream_tag)
1408                         really_cleanup_stream(codec, p);
1409         }
1410 }
1411 #endif
1412 
1413 /*
1414  * amp access functions
1415  */
1416 
1417 /* FIXME: more better hash key? */
1418 #define HDA_HASH_KEY(nid, dir, idx) (u32)((nid) + ((idx) << 16) + ((dir) << 24))
1419 #define HDA_HASH_PINCAP_KEY(nid) (u32)((nid) + (0x02 << 24))
1420 #define HDA_HASH_PARPCM_KEY(nid) (u32)((nid) + (0x03 << 24))
1421 #define HDA_HASH_PARSTR_KEY(nid) (u32)((nid) + (0x04 << 24))
1422 #define INFO_AMP_CAPS   (1<<0)
1423 #define INFO_AMP_VOL(ch)        (1 << (1 + (ch)))
1424 
1425 /* initialize the hash table */
1426 static void /*__devinit*/ init_hda_cache(struct hda_cache_rec *cache,
1427                                      unsigned int record_size)
1428 {
1429         memset(cache, 0, sizeof(*cache));
1430         memset(cache->hash, 0xff, sizeof(cache->hash));
1431         snd_array_init(&cache->buf, record_size, 64);
1432 }
1433 
1434 static void free_hda_cache(struct hda_cache_rec *cache)
1435 {
1436         snd_array_free(&cache->buf);
1437 }
1438 
1439 /* query the hash.  allocate an entry if not found. */
1440 static struct hda_cache_head  *get_hash(struct hda_cache_rec *cache, u32 key)
1441 {
1442         u16 idx = key % (u16)ARRAY_SIZE(cache->hash);
1443         u16 cur = cache->hash[idx];
1444         struct hda_cache_head *info;
1445 
1446         while (cur != 0xffff) {
1447                 info = snd_array_elem(&cache->buf, cur);
1448                 if (info->key == key)
1449                         return info;
1450                 cur = info->next;
1451         }
1452         return NULL;
1453 }
1454 
1455 /* query the hash.  allocate an entry if not found. */
1456 static struct hda_cache_head  *get_alloc_hash(struct hda_cache_rec *cache,
1457                                               u32 key)
1458 {
1459         struct hda_cache_head *info = get_hash(cache, key);
1460         if (!info) {
1461                 u16 idx, cur;
1462                 /* add a new hash entry */
1463                 info = snd_array_new(&cache->buf);
1464                 if (!info)
1465                         return NULL;
1466                 cur = snd_array_index(&cache->buf, info);
1467                 info->key = key;
1468                 info->val = 0;
1469                 idx = key % (u16)ARRAY_SIZE(cache->hash);
1470                 info->next = cache->hash[idx];
1471                 cache->hash[idx] = cur;
1472         }
1473         return info;
1474 }
1475 
1476 /* query and allocate an amp hash entry */
1477 static inline struct hda_amp_info *
1478 get_alloc_amp_hash(struct hda_codec *codec, u32 key)
1479 {
1480         return (struct hda_amp_info *)get_alloc_hash(&codec->amp_cache, key);
1481 }
1482 
1483 /**
1484  * query_amp_caps - query AMP capabilities
1485  * @codec: the HD-auio codec
1486  * @nid: the NID to query
1487  * @direction: either #HDA_INPUT or #HDA_OUTPUT
1488  *
1489  * Query AMP capabilities for the given widget and direction.
1490  * Returns the obtained capability bits.
1491  *
1492  * When cap bits have been already read, this doesn't read again but
1493  * returns the cached value.
1494  */
1495 u32 query_amp_caps(struct hda_codec *codec, hda_nid_t nid, int direction)
1496 {
1497         struct hda_amp_info *info;
1498 
1499         info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, direction, 0));
1500         if (!info)
1501                 return 0;
1502         if (!(info->head.val & INFO_AMP_CAPS)) {
1503                 if (!(get_wcaps(codec, nid) & AC_WCAP_AMP_OVRD))
1504                         nid = codec->afg;
1505                 info->amp_caps = snd_hda_param_read(codec, nid,
1506                                                     direction == HDA_OUTPUT ?
1507                                                     AC_PAR_AMP_OUT_CAP :
1508                                                     AC_PAR_AMP_IN_CAP);
1509                 if (info->amp_caps)
1510                         info->head.val |= INFO_AMP_CAPS;
1511         }
1512         return info->amp_caps;
1513 }
1514 EXPORT_SYMBOL_HDA(query_amp_caps);
1515 
1516 /**
1517  * snd_hda_override_amp_caps - Override the AMP capabilities
1518  * @codec: the CODEC to clean up
1519  * @nid: the NID to clean up
1520  * @direction: either #HDA_INPUT or #HDA_OUTPUT
1521  * @caps: the capability bits to set
1522  *
1523  * Override the cached AMP caps bits value by the given one.
1524  * This function is useful if the driver needs to adjust the AMP ranges,
1525  * e.g. limit to 0dB, etc.
1526  *
1527  * Returns zero if successful or a negative error code.
1528  */
1529 int snd_hda_override_amp_caps(struct hda_codec *codec, hda_nid_t nid, int dir,
1530                               unsigned int caps)
1531 {
1532         struct hda_amp_info *info;
1533 
1534         info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, dir, 0));
1535         if (!info)
1536                 return -EINVAL;
1537         info->amp_caps = caps;
1538         info->head.val |= INFO_AMP_CAPS;
1539         return 0;
1540 }
1541 EXPORT_SYMBOL_HDA(snd_hda_override_amp_caps);
1542 
1543 static unsigned int
1544 query_caps_hash(struct hda_codec *codec, hda_nid_t nid, u32 key,
1545                 unsigned int (*func)(struct hda_codec *, hda_nid_t))
1546 {
1547         struct hda_amp_info *info;
1548 
1549         info = get_alloc_amp_hash(codec, key);
1550         if (!info)
1551                 return 0;
1552         if (!info->head.val) {
1553                 info->head.val |= INFO_AMP_CAPS;
1554                 info->amp_caps = func(codec, nid);
1555         }
1556         return info->amp_caps;
1557 }
1558 
1559 static unsigned int read_pin_cap(struct hda_codec *codec, hda_nid_t nid)
1560 {
1561         return snd_hda_param_read(codec, nid, AC_PAR_PIN_CAP);
1562 }
1563 
1564 /**
1565  * snd_hda_query_pin_caps - Query PIN capabilities
1566  * @codec: the HD-auio codec
1567  * @nid: the NID to query
1568  *
1569  * Query PIN capabilities for the given widget.
1570  * Returns the obtained capability bits.
1571  *
1572  * When cap bits have been already read, this doesn't read again but
1573  * returns the cached value.
1574  */
1575 u32 snd_hda_query_pin_caps(struct hda_codec *codec, hda_nid_t nid)
1576 {
1577         return query_caps_hash(codec, nid, HDA_HASH_PINCAP_KEY(nid),
1578                                read_pin_cap);
1579 }
1580 EXPORT_SYMBOL_HDA(snd_hda_query_pin_caps);
1581 
1582 /**
1583  * snd_hda_pin_sense - execute pin sense measurement
1584  * @codec: the CODEC to sense
1585  * @nid: the pin NID to sense
1586  *
1587  * Execute necessary pin sense measurement and return its Presence Detect,
1588  * Impedance, ELD Valid etc. status bits.
1589  */
1590 u32 snd_hda_pin_sense(struct hda_codec *codec, hda_nid_t nid)
1591 {
1592         u32 pincap;
1593 
1594         if (!codec->no_trigger_sense) {
1595                 pincap = snd_hda_query_pin_caps(codec, nid);
1596                 if (pincap & AC_PINCAP_TRIG_REQ) /* need trigger? */
1597                         snd_hda_codec_read(codec, nid, 0,
1598                                         AC_VERB_SET_PIN_SENSE, 0);
1599         }
1600         return snd_hda_codec_read(codec, nid, 0,
1601                                   AC_VERB_GET_PIN_SENSE, 0);
1602 }
1603 EXPORT_SYMBOL_HDA(snd_hda_pin_sense);
1604 
1605 /**
1606  * snd_hda_jack_detect - query pin Presence Detect status
1607  * @codec: the CODEC to sense
1608  * @nid: the pin NID to sense
1609  *
1610  * Query and return the pin's Presence Detect status.
1611  */
1612 int snd_hda_jack_detect(struct hda_codec *codec, hda_nid_t nid)
1613 {
1614         u32 sense = snd_hda_pin_sense(codec, nid);
1615         return !!(sense & AC_PINSENSE_PRESENCE);
1616 }
1617 EXPORT_SYMBOL_HDA(snd_hda_jack_detect);
1618 
1619 /*
1620  * read the current volume to info
1621  * if the cache exists, read the cache value.
1622  */
1623 static unsigned int get_vol_mute(struct hda_codec *codec,
1624                                  struct hda_amp_info *info, hda_nid_t nid,
1625                                  int ch, int direction, int index)
1626 {
1627         u32 val, parm;
1628 
1629         if (info->head.val & INFO_AMP_VOL(ch))
1630                 return info->vol[ch];
1631 
1632         parm = ch ? AC_AMP_GET_RIGHT : AC_AMP_GET_LEFT;
1633         parm |= direction == HDA_OUTPUT ? AC_AMP_GET_OUTPUT : AC_AMP_GET_INPUT;
1634         parm |= index;
1635         val = snd_hda_codec_read(codec, nid, 0,
1636                                  AC_VERB_GET_AMP_GAIN_MUTE, parm);
1637         info->vol[ch] = val & 0xff;
1638         info->head.val |= INFO_AMP_VOL(ch);
1639         return info->vol[ch];
1640 }
1641 
1642 /*
1643  * write the current volume in info to the h/w and update the cache
1644  */
1645 static void put_vol_mute(struct hda_codec *codec, struct hda_amp_info *info,
1646                          hda_nid_t nid, int ch, int direction, int index,
1647                          int val)
1648 {
1649         u32 parm;
1650 
1651         parm = ch ? AC_AMP_SET_RIGHT : AC_AMP_SET_LEFT;
1652         parm |= direction == HDA_OUTPUT ? AC_AMP_SET_OUTPUT : AC_AMP_SET_INPUT;
1653         parm |= index << AC_AMP_SET_INDEX_SHIFT;
1654         if ((val & HDA_AMP_MUTE) && !(info->amp_caps & AC_AMPCAP_MUTE) &&
1655             (info->amp_caps & AC_AMPCAP_MIN_MUTE))
1656                 ; /* set the zero value as a fake mute */
1657         else
1658                 parm |= val;
1659         snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_AMP_GAIN_MUTE, parm);
1660         info->vol[ch] = val;
1661 }
1662 
1663 /**
1664  * snd_hda_codec_amp_read - Read AMP value
1665  * @codec: HD-audio codec
1666  * @nid: NID to read the AMP value
1667  * @ch: channel (left=0 or right=1)
1668  * @direction: #HDA_INPUT or #HDA_OUTPUT
1669  * @index: the index value (only for input direction)
1670  *
1671  * Read AMP value.  The volume is between 0 to 0x7f, 0x80 = mute bit.
1672  */
1673 int snd_hda_codec_amp_read(struct hda_codec *codec, hda_nid_t nid, int ch,
1674                            int direction, int index)
1675 {
1676         struct hda_amp_info *info;
1677         info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, direction, index));
1678         if (!info)
1679                 return 0;
1680         return get_vol_mute(codec, info, nid, ch, direction, index);
1681 }
1682 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_read);
1683 
1684 /**
1685  * snd_hda_codec_amp_update - update the AMP value
1686  * @codec: HD-audio codec
1687  * @nid: NID to read the AMP value
1688  * @ch: channel (left=0 or right=1)
1689  * @direction: #HDA_INPUT or #HDA_OUTPUT
1690  * @idx: the index value (only for input direction)
1691  * @mask: bit mask to set
1692  * @val: the bits value to set
1693  *
1694  * Update the AMP value with a bit mask.
1695  * Returns 0 if the value is unchanged, 1 if changed.
1696  */
1697 int snd_hda_codec_amp_update(struct hda_codec *codec, hda_nid_t nid, int ch,
1698                              int direction, int idx, int mask, int val)
1699 {
1700         struct hda_amp_info *info;
1701 
1702         info = get_alloc_amp_hash(codec, HDA_HASH_KEY(nid, direction, idx));
1703         if (!info)
1704                 return 0;
1705         if (snd_BUG_ON(mask & ~0xff))
1706                 mask &= 0xff;
1707         val &= mask;
1708         val |= get_vol_mute(codec, info, nid, ch, direction, idx) & ~mask;
1709         if (info->vol[ch] == val)
1710                 return 0;
1711         put_vol_mute(codec, info, nid, ch, direction, idx, val);
1712         return 1;
1713 }
1714 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_update);
1715 
1716 /**
1717  * snd_hda_codec_amp_stereo - update the AMP stereo values
1718  * @codec: HD-audio codec
1719  * @nid: NID to read the AMP value
1720  * @direction: #HDA_INPUT or #HDA_OUTPUT
1721  * @idx: the index value (only for input direction)
1722  * @mask: bit mask to set
1723  * @val: the bits value to set
1724  *
1725  * Update the AMP values like snd_hda_codec_amp_update(), but for a
1726  * stereo widget with the same mask and value.
1727  */
1728 int snd_hda_codec_amp_stereo(struct hda_codec *codec, hda_nid_t nid,
1729                              int direction, int idx, int mask, int val)
1730 {
1731         int ch, ret = 0;
1732 
1733         if (snd_BUG_ON(mask & ~0xff))
1734                 mask &= 0xff;
1735         for (ch = 0; ch < 2; ch++)
1736                 ret |= snd_hda_codec_amp_update(codec, nid, ch, direction,
1737                                                 idx, mask, val);
1738         return ret;
1739 }
1740 EXPORT_SYMBOL_HDA(snd_hda_codec_amp_stereo);
1741 
1742 #ifdef SND_HDA_NEEDS_RESUME
1743 /**
1744  * snd_hda_codec_resume_amp - Resume all AMP commands from the cache
1745  * @codec: HD-audio codec
1746  *
1747  * Resume the all amp commands from the cache.
1748  */
1749 void snd_hda_codec_resume_amp(struct hda_codec *codec)
1750 {
1751         struct hda_amp_info *buffer = codec->amp_cache.buf.list;
1752         int i;
1753 
1754         for (i = 0; i < codec->amp_cache.buf.used; i++, buffer++) {
1755                 u32 key = buffer->head.key;
1756                 hda_nid_t nid;
1757                 unsigned int idx, dir, ch;
1758                 if (!key)
1759                         continue;
1760                 nid = key & 0xff;
1761                 idx = (key >> 16) & 0xff;
1762                 dir = (key >> 24) & 0xff;
1763                 for (ch = 0; ch < 2; ch++) {
1764                         if (!(buffer->head.val & INFO_AMP_VOL(ch)))
1765                                 continue;
1766                         put_vol_mute(codec, buffer, nid, ch, dir, idx,
1767                                      buffer->vol[ch]);
1768                 }
1769         }
1770 }
1771 EXPORT_SYMBOL_HDA(snd_hda_codec_resume_amp);
1772 #endif /* SND_HDA_NEEDS_RESUME */
1773 
1774 static u32 get_amp_max_value(struct hda_codec *codec, hda_nid_t nid, int dir,
1775                              unsigned int ofs)
1776 {
1777         u32 caps = query_amp_caps(codec, nid, dir);
1778         /* get num steps */
1779         caps = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
1780         if (ofs < caps)
1781                 caps -= ofs;
1782         return caps;
1783 }
1784 
1785 /**
1786  * snd_hda_mixer_amp_volume_info - Info callback for a standard AMP mixer
1787  *
1788  * The control element is supposed to have the private_value field
1789  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1790  */
1791 int snd_hda_mixer_amp_volume_info(struct snd_kcontrol *kcontrol,
1792                                   struct snd_ctl_elem_info *uinfo)
1793 {
1794         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1795         u16 nid = get_amp_nid(kcontrol);
1796         u8 chs = get_amp_channels(kcontrol);
1797         int dir = get_amp_direction(kcontrol);
1798         unsigned int ofs = get_amp_offset(kcontrol);
1799 
1800         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1801         uinfo->count = chs == 3 ? 2 : 1;
1802         uinfo->value.integer.min = 0;
1803         uinfo->value.integer.max = get_amp_max_value(codec, nid, dir, ofs);
1804         if (!uinfo->value.integer.max) {
1805                 printk(KERN_WARNING "hda_codec: "
1806                        "num_steps = 0 for NID=0x%x (ctl = %s)\n", nid,
1807                        kcontrol->id.name);
1808                 return -EINVAL;
1809         }
1810         return 0;
1811 }
1812 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_volume_info);
1813 
1814 
1815 static inline unsigned int
1816 read_amp_value(struct hda_codec *codec, hda_nid_t nid,
1817                int ch, int dir, int idx, unsigned int ofs)
1818 {
1819         unsigned int val;
1820         val = snd_hda_codec_amp_read(codec, nid, ch, dir, idx);
1821         val &= HDA_AMP_VOLMASK;
1822         if (val >= ofs)
1823                 val -= ofs;
1824         else
1825                 val = 0;
1826         return val;
1827 }
1828 
1829 static inline int
1830 update_amp_value(struct hda_codec *codec, hda_nid_t nid,
1831                  int ch, int dir, int idx, unsigned int ofs,
1832                  unsigned int val)
1833 {
1834         unsigned int maxval;
1835 
1836         if (val > 0)
1837                 val += ofs;
1838         /* ofs = 0: raw max value */
1839         maxval = get_amp_max_value(codec, nid, dir, 0);
1840         if (val > maxval)
1841                 val = maxval;
1842         return snd_hda_codec_amp_update(codec, nid, ch, dir, idx,
1843                                         HDA_AMP_VOLMASK, val);
1844 }
1845 
1846 /**
1847  * snd_hda_mixer_amp_volume_get - Get callback for a standard AMP mixer volume
1848  *
1849  * The control element is supposed to have the private_value field
1850  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1851  */
1852 int snd_hda_mixer_amp_volume_get(struct snd_kcontrol *kcontrol,
1853                                  struct snd_ctl_elem_value *ucontrol)
1854 {
1855         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1856         hda_nid_t nid = get_amp_nid(kcontrol);
1857         int chs = get_amp_channels(kcontrol);
1858         int dir = get_amp_direction(kcontrol);
1859         int idx = get_amp_index(kcontrol);
1860         unsigned int ofs = get_amp_offset(kcontrol);
1861         long *valp = ucontrol->value.integer.value;
1862 
1863         if (chs & 1)
1864                 *valp++ = read_amp_value(codec, nid, 0, dir, idx, ofs);
1865         if (chs & 2)
1866                 *valp = read_amp_value(codec, nid, 1, dir, idx, ofs);
1867         return 0;
1868 }
1869 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_volume_get);
1870 
1871 /**
1872  * snd_hda_mixer_amp_volume_put - Put callback for a standard AMP mixer volume
1873  *
1874  * The control element is supposed to have the private_value field
1875  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1876  */
1877 int snd_hda_mixer_amp_volume_put(struct snd_kcontrol *kcontrol,
1878                                  struct snd_ctl_elem_value *ucontrol)
1879 {
1880         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1881         hda_nid_t nid = get_amp_nid(kcontrol);
1882         int chs = get_amp_channels(kcontrol);
1883         int dir = get_amp_direction(kcontrol);
1884         int idx = get_amp_index(kcontrol);
1885         unsigned int ofs = get_amp_offset(kcontrol);
1886         long *valp = ucontrol->value.integer.value;
1887         int change = 0;
1888 
1889         snd_hda_power_up(codec);
1890         if (chs & 1) {
1891                 change = update_amp_value(codec, nid, 0, dir, idx, ofs, *valp);
1892                 valp++;
1893         }
1894         if (chs & 2)
1895                 change |= update_amp_value(codec, nid, 1, dir, idx, ofs, *valp);
1896         snd_hda_power_down(codec);
1897         return change;
1898 }
1899 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_volume_put);
1900 
1901 /**
1902  * snd_hda_mixer_amp_volume_put - TLV callback for a standard AMP mixer volume
1903  *
1904  * The control element is supposed to have the private_value field
1905  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
1906  */
1907 int snd_hda_mixer_amp_tlv(struct snd_kcontrol *kcontrol, int op_flag,
1908                           unsigned int size, unsigned int __user *_tlv)
1909 {
1910         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
1911         hda_nid_t nid = get_amp_nid(kcontrol);
1912         int dir = get_amp_direction(kcontrol);
1913         unsigned int ofs = get_amp_offset(kcontrol);
1914         bool min_mute = get_amp_min_mute(kcontrol);
1915         u32 caps, val1, val2;
1916 
1917         if (size < 4 * sizeof(unsigned int))
1918                 return -ENOMEM;
1919         caps = query_amp_caps(codec, nid, dir);
1920         val2 = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT;
1921         val2 = (val2 + 1) * 25;
1922         val1 = -((caps & AC_AMPCAP_OFFSET) >> AC_AMPCAP_OFFSET_SHIFT);
1923         val1 += ofs;
1924         val1 = ((int)val1) * ((int)val2);
1925         if (min_mute || (caps & AC_AMPCAP_MIN_MUTE))
1926                 val2 |= TLV_DB_SCALE_MUTE;
1927         if (put_user(SNDRV_CTL_TLVT_DB_SCALE, _tlv))
1928                 return -EFAULT;
1929         if (put_user(2 * sizeof(unsigned int), _tlv + 1))
1930                 return -EFAULT;
1931         if (put_user(val1, _tlv + 2))
1932                 return -EFAULT;
1933         if (put_user(val2, _tlv + 3))
1934                 return -EFAULT;
1935         return 0;
1936 }
1937 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_tlv);
1938 
1939 /**
1940  * snd_hda_set_vmaster_tlv - Set TLV for a virtual master control
1941  * @codec: HD-audio codec
1942  * @nid: NID of a reference widget
1943  * @dir: #HDA_INPUT or #HDA_OUTPUT
1944  * @tlv: TLV data to be stored, at least 4 elements
1945  *
1946  * Set (static) TLV data for a virtual master volume using the AMP caps
1947  * obtained from the reference NID.
1948  * The volume range is recalculated as if the max volume is 0dB.
1949  */
1950 void snd_hda_set_vmaster_tlv(struct hda_codec *codec, hda_nid_t nid, int dir,
1951                              unsigned int *tlv)
1952 {
1953         u32 caps;
1954         int nums, step;
1955 
1956         caps = query_amp_caps(codec, nid, dir);
1957         nums = (caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
1958         step = (caps & AC_AMPCAP_STEP_SIZE) >> AC_AMPCAP_STEP_SIZE_SHIFT;
1959         step = (step + 1) * 25;
1960         tlv[0] = SNDRV_CTL_TLVT_DB_SCALE;
1961         tlv[1] = 2 * sizeof(unsigned int);
1962         tlv[2] = -nums * step;
1963         tlv[3] = step;
1964 }
1965 EXPORT_SYMBOL_HDA(snd_hda_set_vmaster_tlv);
1966 
1967 /* find a mixer control element with the given name */
1968 static struct snd_kcontrol *
1969 _snd_hda_find_mixer_ctl(struct hda_codec *codec,
1970                         const char *name, int idx)
1971 {
1972         struct snd_ctl_elem_id id;
1973         memset(&id, 0, sizeof(id));
1974         id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
1975         id.index = idx;
1976         if (snd_BUG_ON(strlen(name) >= sizeof(id.name)))
1977                 return NULL;
1978         strcpy(id.name, name);
1979         return snd_ctl_find_id(codec->bus->card, &id);
1980 }
1981 
1982 /**
1983  * snd_hda_find_mixer_ctl - Find a mixer control element with the given name
1984  * @codec: HD-audio codec
1985  * @name: ctl id name string
1986  *
1987  * Get the control element with the given id string and IFACE_MIXER.
1988  */
1989 struct snd_kcontrol *snd_hda_find_mixer_ctl(struct hda_codec *codec,
1990                                             const char *name)
1991 {
1992         return _snd_hda_find_mixer_ctl(codec, name, 0);
1993 }
1994 EXPORT_SYMBOL_HDA(snd_hda_find_mixer_ctl);
1995 
1996 static int find_empty_mixer_ctl_idx(struct hda_codec *codec, const char *name)
1997 {
1998         int idx;
1999         for (idx = 0; idx < 16; idx++) { /* 16 ctlrs should be large enough */
2000                 if (!_snd_hda_find_mixer_ctl(codec, name, idx))
2001                         return idx;
2002         }
2003         return -EBUSY;
2004 }
2005 
2006 /**
2007  * snd_hda_ctl_add - Add a control element and assign to the codec
2008  * @codec: HD-audio codec
2009  * @nid: corresponding NID (optional)
2010  * @kctl: the control element to assign
2011  *
2012  * Add the given control element to an array inside the codec instance.
2013  * All control elements belonging to a codec are supposed to be added
2014  * by this function so that a proper clean-up works at the free or
2015  * reconfiguration time.
2016  *
2017  * If non-zero @nid is passed, the NID is assigned to the control element.
2018  * The assignment is shown in the codec proc file.
2019  *
2020  * snd_hda_ctl_add() checks the control subdev id field whether
2021  * #HDA_SUBDEV_NID_FLAG bit is set.  If set (and @nid is zero), the lower
2022  * bits value is taken as the NID to assign. The #HDA_NID_ITEM_AMP bit
2023  * specifies if kctl->private_value is a HDA amplifier value.
2024  */
2025 int snd_hda_ctl_add(struct hda_codec *codec, hda_nid_t nid,
2026                     struct snd_kcontrol *kctl)
2027 {
2028         int err;
2029         unsigned short flags = 0;
2030         struct hda_nid_item *item;
2031 
2032         if (kctl->id.subdevice & HDA_SUBDEV_AMP_FLAG) {
2033                 flags |= HDA_NID_ITEM_AMP;
2034                 if (nid == 0)
2035                         nid = get_amp_nid_(kctl->private_value);
2036         }
2037         if ((kctl->id.subdevice & HDA_SUBDEV_NID_FLAG) != 0 && nid == 0)
2038                 nid = kctl->id.subdevice & 0xffff;
2039         if (kctl->id.subdevice & (HDA_SUBDEV_NID_FLAG|HDA_SUBDEV_AMP_FLAG))
2040                 kctl->id.subdevice = 0;
2041         err = snd_ctl_add(codec->bus->card, kctl);
2042         if (err < 0)
2043                 return err;
2044         item = snd_array_new(&codec->mixers);
2045         if (!item)
2046                 return -ENOMEM;
2047         item->kctl = kctl;
2048         item->nid = nid;
2049         item->flags = flags;
2050         return 0;
2051 }
2052 EXPORT_SYMBOL_HDA(snd_hda_ctl_add);
2053 
2054 /**
2055  * snd_hda_add_nid - Assign a NID to a control element
2056  * @codec: HD-audio codec
2057  * @nid: corresponding NID (optional)
2058  * @kctl: the control element to assign
2059  * @index: index to kctl
2060  *
2061  * Add the given control element to an array inside the codec instance.
2062  * This function is used when #snd_hda_ctl_add cannot be used for 1:1
2063  * NID:KCTL mapping - for example "Capture Source" selector.
2064  */
2065 int snd_hda_add_nid(struct hda_codec *codec, struct snd_kcontrol *kctl,
2066                     unsigned int index, hda_nid_t nid)
2067 {
2068         struct hda_nid_item *item;
2069 
2070         if (nid > 0) {
2071                 item = snd_array_new(&codec->nids);
2072                 if (!item)
2073                         return -ENOMEM;
2074                 item->kctl = kctl;
2075                 item->index = index;
2076                 item->nid = nid;
2077                 return 0;
2078         }
2079         printk(KERN_ERR "hda-codec: no NID for mapping control %s:%d:%d\n",
2080                kctl->id.name, kctl->id.index, index);
2081         return -EINVAL;
2082 }
2083 EXPORT_SYMBOL_HDA(snd_hda_add_nid);
2084 
2085 /**
2086  * snd_hda_ctls_clear - Clear all controls assigned to the given codec
2087  * @codec: HD-audio codec
2088  */
2089 void snd_hda_ctls_clear(struct hda_codec *codec)
2090 {
2091         int i;
2092         struct hda_nid_item *items = codec->mixers.list;
2093         for (i = 0; i < codec->mixers.used; i++)
2094                 snd_ctl_remove(codec->bus->card, items[i].kctl);
2095         snd_array_free(&codec->mixers);
2096         snd_array_free(&codec->nids);
2097 }
2098 
2099 /* pseudo device locking
2100  * toggle card->shutdown to allow/disallow the device access (as a hack)
2101  */
2102 static int hda_lock_devices(struct snd_card *card)
2103 {
2104         spin_lock(&card->files_lock);
2105         if (card->shutdown) {
2106                 spin_unlock(&card->files_lock);
2107                 return -EINVAL;
2108         }
2109         card->shutdown = 1;
2110         spin_unlock(&card->files_lock);
2111         return 0;
2112 }
2113 
2114 static void hda_unlock_devices(struct snd_card *card)
2115 {
2116         spin_lock(&card->files_lock);
2117         card->shutdown = 0;
2118         spin_unlock(&card->files_lock);
2119 }
2120 
2121 /**
2122  * snd_hda_codec_reset - Clear all objects assigned to the codec
2123  * @codec: HD-audio codec
2124  *
2125  * This frees the all PCM and control elements assigned to the codec, and
2126  * clears the caches and restores the pin default configurations.
2127  *
2128  * When a device is being used, it returns -EBSY.  If successfully freed,
2129  * returns zero.
2130  */
2131 int snd_hda_codec_reset(struct hda_codec *codec)
2132 {
2133         struct snd_card *card = codec->bus->card;
2134         int i, pcm;
2135 
2136         if (hda_lock_devices(card) < 0)
2137                 return -EBUSY;
2138         /* check whether the codec isn't used by any mixer or PCM streams */
2139         if (!list_empty(&card->ctl_files)) {
2140                 hda_unlock_devices(card);
2141                 return -EBUSY;
2142         }
2143         for (pcm = 0; pcm < codec->num_pcms; pcm++) {
2144                 struct hda_pcm *cpcm = &codec->pcm_info[pcm];
2145                 if (!cpcm->pcm)
2146                         continue;
2147                 if (cpcm->pcm->streams[0].substream_opened ||
2148                     cpcm->pcm->streams[1].substream_opened) {
2149                         hda_unlock_devices(card);
2150                         return -EBUSY;
2151                 }
2152         }
2153 
2154         /* OK, let it free */
2155 
2156 #ifdef CONFIG_SND_HDA_POWER_SAVE
2157         cancel_delayed_work(&codec->power_work);
2158         flush_workqueue(codec->bus->workq);
2159 #endif
2160         snd_hda_ctls_clear(codec);
2161         /* relase PCMs */
2162         for (i = 0; i < codec->num_pcms; i++) {
2163                 if (codec->pcm_info[i].pcm) {
2164                         snd_device_free(card, codec->pcm_info[i].pcm);
2165                         clear_bit(codec->pcm_info[i].device,
2166                                   codec->bus->pcm_dev_bits);
2167                 }
2168         }
2169         if (codec->patch_ops.free)
2170                 codec->patch_ops.free(codec);
2171         codec->proc_widget_hook = NULL;
2172         codec->spec = NULL;
2173         free_hda_cache(&codec->amp_cache);
2174         free_hda_cache(&codec->cmd_cache);
2175         init_hda_cache(&codec->amp_cache, sizeof(struct hda_amp_info));
2176         init_hda_cache(&codec->cmd_cache, sizeof(struct hda_cache_head));
2177         /* free only driver_pins so that init_pins + user_pins are restored */
2178         snd_array_free(&codec->driver_pins);
2179         restore_pincfgs(codec);
2180         codec->num_pcms = 0;
2181         codec->pcm_info = NULL;
2182         codec->preset = NULL;
2183         memset(&codec->patch_ops, 0, sizeof(codec->patch_ops));
2184         codec->slave_dig_outs = NULL;
2185         codec->spdif_status_reset = 0;
2186         module_put(codec->owner);
2187         codec->owner = NULL;
2188 
2189         /* allow device access again */
2190         hda_unlock_devices(card);
2191         return 0;
2192 }
2193 
2194 typedef int (*map_slave_func_t)(void *, struct snd_kcontrol *);
2195 
2196 /* apply the function to all matching slave ctls in the mixer list */
2197 static int map_slaves(struct hda_codec *codec, const char * const *slaves,
2198                       map_slave_func_t func, void *data)
2199 {
2200         struct hda_nid_item *items;
2201         const char * const *s;
2202         int i, err;
2203 
2204         items = codec->mixers.list;
2205         for (i = 0; i < codec->mixers.used; i++) {
2206                 struct snd_kcontrol *sctl = items[i].kctl;
2207                 if (!sctl || !sctl->id.name ||
2208                     sctl->id.iface != SNDRV_CTL_ELEM_IFACE_MIXER)
2209                         continue;
2210                 for (s = slaves; *s; s++) {
2211                         if (!strcmp(sctl->id.name, *s)) {
2212                                 err = func(data, sctl);
2213                                 if (err)
2214                                         return err;
2215                                 break;
2216                         }
2217                 }
2218         }
2219         return 0;
2220 }
2221 
2222 static int check_slave_present(void *data, struct snd_kcontrol *sctl)
2223 {
2224         return 1;
2225 }
2226 
2227 /**
2228  * snd_hda_add_vmaster - create a virtual master control and add slaves
2229  * @codec: HD-audio codec
2230  * @name: vmaster control name
2231  * @tlv: TLV data (optional)
2232  * @slaves: slave control names (optional)
2233  *
2234  * Create a virtual master control with the given name.  The TLV data
2235  * must be either NULL or a valid data.
2236  *
2237  * @slaves is a NULL-terminated array of strings, each of which is a
2238  * slave control name.  All controls with these names are assigned to
2239  * the new virtual master control.
2240  *
2241  * This function returns zero if successful or a negative error code.
2242  */
2243 int snd_hda_add_vmaster(struct hda_codec *codec, char *name,
2244                         unsigned int *tlv, const char * const *slaves)
2245 {
2246         struct snd_kcontrol *kctl;
2247         int err;
2248 
2249         err = map_slaves(codec, slaves, check_slave_present, NULL);
2250         if (err != 1) {
2251                 snd_printdd("No slave found for %s\n", name);
2252                 return 0;
2253         }
2254         kctl = snd_ctl_make_virtual_master(name, tlv);
2255         if (!kctl)
2256                 return -ENOMEM;
2257         err = snd_hda_ctl_add(codec, 0, kctl);
2258         if (err < 0)
2259                 return err;
2260 
2261         err = map_slaves(codec, slaves, (map_slave_func_t)snd_ctl_add_slave,
2262                          kctl);
2263         if (err < 0)
2264                 return err;
2265         return 0;
2266 }
2267 EXPORT_SYMBOL_HDA(snd_hda_add_vmaster);
2268 
2269 /**
2270  * snd_hda_mixer_amp_switch_info - Info callback for a standard AMP mixer switch
2271  *
2272  * The control element is supposed to have the private_value field
2273  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2274  */
2275 int snd_hda_mixer_amp_switch_info(struct snd_kcontrol *kcontrol,
2276                                   struct snd_ctl_elem_info *uinfo)
2277 {
2278         int chs = get_amp_channels(kcontrol);
2279 
2280         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2281         uinfo->count = chs == 3 ? 2 : 1;
2282         uinfo->value.integer.min = 0;
2283         uinfo->value.integer.max = 1;
2284         return 0;
2285 }
2286 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_info);
2287 
2288 /**
2289  * snd_hda_mixer_amp_switch_get - Get callback for a standard AMP mixer switch
2290  *
2291  * The control element is supposed to have the private_value field
2292  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2293  */
2294 int snd_hda_mixer_amp_switch_get(struct snd_kcontrol *kcontrol,
2295                                  struct snd_ctl_elem_value *ucontrol)
2296 {
2297         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2298         hda_nid_t nid = get_amp_nid(kcontrol);
2299         int chs = get_amp_channels(kcontrol);
2300         int dir = get_amp_direction(kcontrol);
2301         int idx = get_amp_index(kcontrol);
2302         long *valp = ucontrol->value.integer.value;
2303 
2304         if (chs & 1)
2305                 *valp++ = (snd_hda_codec_amp_read(codec, nid, 0, dir, idx) &
2306                            HDA_AMP_MUTE) ? 0 : 1;
2307         if (chs & 2)
2308                 *valp = (snd_hda_codec_amp_read(codec, nid, 1, dir, idx) &
2309                          HDA_AMP_MUTE) ? 0 : 1;
2310         return 0;
2311 }
2312 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_get);
2313 
2314 /**
2315  * snd_hda_mixer_amp_switch_put - Put callback for a standard AMP mixer switch
2316  *
2317  * The control element is supposed to have the private_value field
2318  * set up via HDA_COMPOSE_AMP_VAL*() or related macros.
2319  */
2320 int snd_hda_mixer_amp_switch_put(struct snd_kcontrol *kcontrol,
2321                                  struct snd_ctl_elem_value *ucontrol)
2322 {
2323         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2324         hda_nid_t nid = get_amp_nid(kcontrol);
2325         int chs = get_amp_channels(kcontrol);
2326         int dir = get_amp_direction(kcontrol);
2327         int idx = get_amp_index(kcontrol);
2328         long *valp = ucontrol->value.integer.value;
2329         int change = 0;
2330 
2331         snd_hda_power_up(codec);
2332         if (chs & 1) {
2333                 change = snd_hda_codec_amp_update(codec, nid, 0, dir, idx,
2334                                                   HDA_AMP_MUTE,
2335                                                   *valp ? 0 : HDA_AMP_MUTE);
2336                 valp++;
2337         }
2338         if (chs & 2)
2339                 change |= snd_hda_codec_amp_update(codec, nid, 1, dir, idx,
2340                                                    HDA_AMP_MUTE,
2341                                                    *valp ? 0 : HDA_AMP_MUTE);
2342         hda_call_check_power_status(codec, nid);
2343         snd_hda_power_down(codec);
2344         return change;
2345 }
2346 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_put);
2347 
2348 #ifdef CONFIG_SND_HDA_INPUT_BEEP
2349 /**
2350  * snd_hda_mixer_amp_switch_put_beep - Put callback for a beep AMP switch
2351  *
2352  * This function calls snd_hda_enable_beep_device(), which behaves differently
2353  * depending on beep_mode option.
2354  */
2355 int snd_hda_mixer_amp_switch_put_beep(struct snd_kcontrol *kcontrol,
2356                                       struct snd_ctl_elem_value *ucontrol)
2357 {
2358         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2359         long *valp = ucontrol->value.integer.value;
2360 
2361         snd_hda_enable_beep_device(codec, *valp);
2362         return snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
2363 }
2364 EXPORT_SYMBOL_HDA(snd_hda_mixer_amp_switch_put_beep);
2365 #endif /* CONFIG_SND_HDA_INPUT_BEEP */
2366 
2367 /*
2368  * bound volume controls
2369  *
2370  * bind multiple volumes (# indices, from 0)
2371  */
2372 
2373 #define AMP_VAL_IDX_SHIFT       19
2374 #define AMP_VAL_IDX_MASK        (0x0f<<19)
2375 
2376 /**
2377  * snd_hda_mixer_bind_switch_get - Get callback for a bound volume control
2378  *
2379  * The control element is supposed to have the private_value field
2380  * set up via HDA_BIND_MUTE*() macros.
2381  */
2382 int snd_hda_mixer_bind_switch_get(struct snd_kcontrol *kcontrol,
2383                                   struct snd_ctl_elem_value *ucontrol)
2384 {
2385         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2386         unsigned long pval;
2387         int err;
2388 
2389         mutex_lock(&codec->control_mutex);
2390         pval = kcontrol->private_value;
2391         kcontrol->private_value = pval & ~AMP_VAL_IDX_MASK; /* index 0 */
2392         err = snd_hda_mixer_amp_switch_get(kcontrol, ucontrol);
2393         kcontrol->private_value = pval;
2394         mutex_unlock(&codec->control_mutex);
2395         return err;
2396 }
2397 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_switch_get);
2398 
2399 /**
2400  * snd_hda_mixer_bind_switch_put - Put callback for a bound volume control
2401  *
2402  * The control element is supposed to have the private_value field
2403  * set up via HDA_BIND_MUTE*() macros.
2404  */
2405 int snd_hda_mixer_bind_switch_put(struct snd_kcontrol *kcontrol,
2406                                   struct snd_ctl_elem_value *ucontrol)
2407 {
2408         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2409         unsigned long pval;
2410         int i, indices, err = 0, change = 0;
2411 
2412         mutex_lock(&codec->control_mutex);
2413         pval = kcontrol->private_value;
2414         indices = (pval & AMP_VAL_IDX_MASK) >> AMP_VAL_IDX_SHIFT;
2415         for (i = 0; i < indices; i++) {
2416                 kcontrol->private_value = (pval & ~AMP_VAL_IDX_MASK) |
2417                         (i << AMP_VAL_IDX_SHIFT);
2418                 err = snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
2419                 if (err < 0)
2420                         break;
2421                 change |= err;
2422         }
2423         kcontrol->private_value = pval;
2424         mutex_unlock(&codec->control_mutex);
2425         return err < 0 ? err : change;
2426 }
2427 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_switch_put);
2428 
2429 /**
2430  * snd_hda_mixer_bind_ctls_info - Info callback for a generic bound control
2431  *
2432  * The control element is supposed to have the private_value field
2433  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
2434  */
2435 int snd_hda_mixer_bind_ctls_info(struct snd_kcontrol *kcontrol,
2436                                  struct snd_ctl_elem_info *uinfo)
2437 {
2438         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2439         struct hda_bind_ctls *c;
2440         int err;
2441 
2442         mutex_lock(&codec->control_mutex);
2443         c = (struct hda_bind_ctls *)kcontrol->private_value;
2444         kcontrol->private_value = *c->values;
2445         err = c->ops->info(kcontrol, uinfo);
2446         kcontrol->private_value = (long)c;
2447         mutex_unlock(&codec->control_mutex);
2448         return err;
2449 }
2450 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_ctls_info);
2451 
2452 /**
2453  * snd_hda_mixer_bind_ctls_get - Get callback for a generic bound control
2454  *
2455  * The control element is supposed to have the private_value field
2456  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
2457  */
2458 int snd_hda_mixer_bind_ctls_get(struct snd_kcontrol *kcontrol,
2459                                 struct snd_ctl_elem_value *ucontrol)
2460 {
2461         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2462         struct hda_bind_ctls *c;
2463         int err;
2464 
2465         mutex_lock(&codec->control_mutex);
2466         c = (struct hda_bind_ctls *)kcontrol->private_value;
2467         kcontrol->private_value = *c->values;
2468         err = c->ops->get(kcontrol, ucontrol);
2469         kcontrol->private_value = (long)c;
2470         mutex_unlock(&codec->control_mutex);
2471         return err;
2472 }
2473 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_ctls_get);
2474 
2475 /**
2476  * snd_hda_mixer_bind_ctls_put - Put callback for a generic bound control
2477  *
2478  * The control element is supposed to have the private_value field
2479  * set up via HDA_BIND_VOL() or HDA_BIND_SW() macros.
2480  */
2481 int snd_hda_mixer_bind_ctls_put(struct snd_kcontrol *kcontrol,
2482                                 struct snd_ctl_elem_value *ucontrol)
2483 {
2484         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2485         struct hda_bind_ctls *c;
2486         unsigned long *vals;
2487         int err = 0, change = 0;
2488 
2489         mutex_lock(&codec->control_mutex);
2490         c = (struct hda_bind_ctls *)kcontrol->private_value;
2491         for (vals = c->values; *vals; vals++) {
2492                 kcontrol->private_value = *vals;
2493                 err = c->ops->put(kcontrol, ucontrol);
2494                 if (err < 0)
2495                         break;
2496                 change |= err;
2497         }
2498         kcontrol->private_value = (long)c;
2499         mutex_unlock(&codec->control_mutex);
2500         return err < 0 ? err : change;
2501 }
2502 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_ctls_put);
2503 
2504 /**
2505  * snd_hda_mixer_bind_tlv - TLV callback for a generic bound control
2506  *
2507  * The control element is supposed to have the private_value field
2508  * set up via HDA_BIND_VOL() macro.
2509  */
2510 int snd_hda_mixer_bind_tlv(struct snd_kcontrol *kcontrol, int op_flag,
2511                            unsigned int size, unsigned int __user *tlv)
2512 {
2513         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2514         struct hda_bind_ctls *c;
2515         int err;
2516 
2517         mutex_lock(&codec->control_mutex);
2518         c = (struct hda_bind_ctls *)kcontrol->private_value;
2519         kcontrol->private_value = *c->values;
2520         err = c->ops->tlv(kcontrol, op_flag, size, tlv);
2521         kcontrol->private_value = (long)c;
2522         mutex_unlock(&codec->control_mutex);
2523         return err;
2524 }
2525 EXPORT_SYMBOL_HDA(snd_hda_mixer_bind_tlv);
2526 
2527 struct hda_ctl_ops snd_hda_bind_vol = {
2528         .info = snd_hda_mixer_amp_volume_info,
2529         .get = snd_hda_mixer_amp_volume_get,
2530         .put = snd_hda_mixer_amp_volume_put,
2531         .tlv = snd_hda_mixer_amp_tlv
2532 };
2533 EXPORT_SYMBOL_HDA(snd_hda_bind_vol);
2534 
2535 struct hda_ctl_ops snd_hda_bind_sw = {
2536         .info = snd_hda_mixer_amp_switch_info,
2537         .get = snd_hda_mixer_amp_switch_get,
2538         .put = snd_hda_mixer_amp_switch_put,
2539         .tlv = snd_hda_mixer_amp_tlv
2540 };
2541 EXPORT_SYMBOL_HDA(snd_hda_bind_sw);
2542 
2543 /*
2544  * SPDIF out controls
2545  */
2546 
2547 static int snd_hda_spdif_mask_info(struct snd_kcontrol *kcontrol,
2548                                    struct snd_ctl_elem_info *uinfo)
2549 {
2550         uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
2551         uinfo->count = 1;
2552         return 0;
2553 }
2554 
2555 static int snd_hda_spdif_cmask_get(struct snd_kcontrol *kcontrol,
2556                                    struct snd_ctl_elem_value *ucontrol)
2557 {
2558         ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
2559                                            IEC958_AES0_NONAUDIO |
2560                                            IEC958_AES0_CON_EMPHASIS_5015 |
2561                                            IEC958_AES0_CON_NOT_COPYRIGHT;
2562         ucontrol->value.iec958.status[1] = IEC958_AES1_CON_CATEGORY |
2563                                            IEC958_AES1_CON_ORIGINAL;
2564         return 0;
2565 }
2566 
2567 static int snd_hda_spdif_pmask_get(struct snd_kcontrol *kcontrol,
2568                                    struct snd_ctl_elem_value *ucontrol)
2569 {
2570         ucontrol->value.iec958.status[0] = IEC958_AES0_PROFESSIONAL |
2571                                            IEC958_AES0_NONAUDIO |
2572                                            IEC958_AES0_PRO_EMPHASIS_5015;
2573         return 0;
2574 }
2575 
2576 static int snd_hda_spdif_default_get(struct snd_kcontrol *kcontrol,
2577                                      struct snd_ctl_elem_value *ucontrol)
2578 {
2579         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2580 
2581         ucontrol->value.iec958.status[0] = codec->spdif_status & 0xff;
2582         ucontrol->value.iec958.status[1] = (codec->spdif_status >> 8) & 0xff;
2583         ucontrol->value.iec958.status[2] = (codec->spdif_status >> 16) & 0xff;
2584         ucontrol->value.iec958.status[3] = (codec->spdif_status >> 24) & 0xff;
2585 
2586         return 0;
2587 }
2588 
2589 /* convert from SPDIF status bits to HDA SPDIF bits
2590  * bit 0 (DigEn) is always set zero (to be filled later)
2591  */
2592 static unsigned short convert_from_spdif_status(unsigned int sbits)
2593 {
2594         unsigned short val = 0;
2595 
2596         if (sbits & IEC958_AES0_PROFESSIONAL)
2597                 val |= AC_DIG1_PROFESSIONAL;
2598         if (sbits & IEC958_AES0_NONAUDIO)
2599                 val |= AC_DIG1_NONAUDIO;
2600         if (sbits & IEC958_AES0_PROFESSIONAL) {
2601                 if ((sbits & IEC958_AES0_PRO_EMPHASIS) ==
2602                     IEC958_AES0_PRO_EMPHASIS_5015)
2603                         val |= AC_DIG1_EMPHASIS;
2604         } else {
2605                 if ((sbits & IEC958_AES0_CON_EMPHASIS) ==
2606                     IEC958_AES0_CON_EMPHASIS_5015)
2607                         val |= AC_DIG1_EMPHASIS;
2608                 if (!(sbits & IEC958_AES0_CON_NOT_COPYRIGHT))
2609                         val |= AC_DIG1_COPYRIGHT;
2610                 if (sbits & (IEC958_AES1_CON_ORIGINAL << 8))
2611                         val |= AC_DIG1_LEVEL;
2612                 val |= sbits & (IEC958_AES1_CON_CATEGORY << 8);
2613         }
2614         return val;
2615 }
2616 
2617 /* convert to SPDIF status bits from HDA SPDIF bits
2618  */
2619 static unsigned int convert_to_spdif_status(unsigned short val)
2620 {
2621         unsigned int sbits = 0;
2622 
2623         if (val & AC_DIG1_NONAUDIO)
2624                 sbits |= IEC958_AES0_NONAUDIO;
2625         if (val & AC_DIG1_PROFESSIONAL)
2626                 sbits |= IEC958_AES0_PROFESSIONAL;
2627         if (sbits & IEC958_AES0_PROFESSIONAL) {
2628                 if (val & AC_DIG1_EMPHASIS)
2629                         sbits |= IEC958_AES0_PRO_EMPHASIS_5015;
2630         } else {
2631                 if (val & AC_DIG1_EMPHASIS)
2632                         sbits |= IEC958_AES0_CON_EMPHASIS_5015;
2633                 if (!(val & AC_DIG1_COPYRIGHT))
2634                         sbits |= IEC958_AES0_CON_NOT_COPYRIGHT;
2635                 if (val & AC_DIG1_LEVEL)
2636                         sbits |= (IEC958_AES1_CON_ORIGINAL << 8);
2637                 sbits |= val & (0x7f << 8);
2638         }
2639         return sbits;
2640 }
2641 
2642 /* set digital convert verbs both for the given NID and its slaves */
2643 static void set_dig_out(struct hda_codec *codec, hda_nid_t nid,
2644                         int verb, int val)
2645 {
2646         const hda_nid_t *d;
2647 
2648         snd_hda_codec_write_cache(codec, nid, 0, verb, val);
2649         d = codec->slave_dig_outs;
2650         if (!d)
2651                 return;
2652         for (; *d; d++)
2653                 snd_hda_codec_write_cache(codec, *d, 0, verb, val);
2654 }
2655 
2656 static inline void set_dig_out_convert(struct hda_codec *codec, hda_nid_t nid,
2657                                        int dig1, int dig2)
2658 {
2659         if (dig1 != -1)
2660                 set_dig_out(codec, nid, AC_VERB_SET_DIGI_CONVERT_1, dig1);
2661         if (dig2 != -1)
2662                 set_dig_out(codec, nid, AC_VERB_SET_DIGI_CONVERT_2, dig2);
2663 }
2664 
2665 static int snd_hda_spdif_default_put(struct snd_kcontrol *kcontrol,
2666                                      struct snd_ctl_elem_value *ucontrol)
2667 {
2668         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2669         hda_nid_t nid = kcontrol->private_value;
2670         unsigned short val;
2671         int change;
2672 
2673         mutex_lock(&codec->spdif_mutex);
2674         codec->spdif_status = ucontrol->value.iec958.status[0] |
2675                 ((unsigned int)ucontrol->value.iec958.status[1] << 8) |
2676                 ((unsigned int)ucontrol->value.iec958.status[2] << 16) |
2677                 ((unsigned int)ucontrol->value.iec958.status[3] << 24);
2678         val = convert_from_spdif_status(codec->spdif_status);
2679         val |= codec->spdif_ctls & 1;
2680         change = codec->spdif_ctls != val;
2681         codec->spdif_ctls = val;
2682 
2683         if (change)
2684                 set_dig_out_convert(codec, nid, val & 0xff, (val >> 8) & 0xff);
2685 
2686         mutex_unlock(&codec->spdif_mutex);
2687         return change;
2688 }
2689 
2690 #define snd_hda_spdif_out_switch_info   snd_ctl_boolean_mono_info
2691 
2692 static int snd_hda_spdif_out_switch_get(struct snd_kcontrol *kcontrol,
2693                                         struct snd_ctl_elem_value *ucontrol)
2694 {
2695         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2696 
2697         ucontrol->value.integer.value[0] = codec->spdif_ctls & AC_DIG1_ENABLE;
2698         return 0;
2699 }
2700 
2701 static int snd_hda_spdif_out_switch_put(struct snd_kcontrol *kcontrol,
2702                                         struct snd_ctl_elem_value *ucontrol)
2703 {
2704         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2705         hda_nid_t nid = kcontrol->private_value;
2706         unsigned short val;
2707         int change;
2708 
2709         mutex_lock(&codec->spdif_mutex);
2710         val = codec->spdif_ctls & ~AC_DIG1_ENABLE;
2711         if (ucontrol->value.integer.value[0])
2712                 val |= AC_DIG1_ENABLE;
2713         change = codec->spdif_ctls != val;
2714         if (change) {
2715                 codec->spdif_ctls = val;
2716                 set_dig_out_convert(codec, nid, val & 0xff, -1);
2717                 /* unmute amp switch (if any) */
2718                 if ((get_wcaps(codec, nid) & AC_WCAP_OUT_AMP) &&
2719                     (val & AC_DIG1_ENABLE))
2720                         snd_hda_codec_amp_stereo(codec, nid, HDA_OUTPUT, 0,
2721                                                  HDA_AMP_MUTE, 0);
2722         }
2723         mutex_unlock(&codec->spdif_mutex);
2724         return change;
2725 }
2726 
2727 static struct snd_kcontrol_new dig_mixes[] = {
2728         {
2729                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
2730                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2731                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, CON_MASK),
2732                 .info = snd_hda_spdif_mask_info,
2733                 .get = snd_hda_spdif_cmask_get,
2734         },
2735         {
2736                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
2737                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2738                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, PRO_MASK),
2739                 .info = snd_hda_spdif_mask_info,
2740                 .get = snd_hda_spdif_pmask_get,
2741         },
2742         {
2743                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2744                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, DEFAULT),
2745                 .info = snd_hda_spdif_mask_info,
2746                 .get = snd_hda_spdif_default_get,
2747                 .put = snd_hda_spdif_default_put,
2748         },
2749         {
2750                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2751                 .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, SWITCH),
2752                 .info = snd_hda_spdif_out_switch_info,
2753                 .get = snd_hda_spdif_out_switch_get,
2754                 .put = snd_hda_spdif_out_switch_put,
2755         },
2756         { } /* end */
2757 };
2758 
2759 /**
2760  * snd_hda_create_spdif_out_ctls - create Output SPDIF-related controls
2761  * @codec: the HDA codec
2762  * @nid: audio out widget NID
2763  *
2764  * Creates controls related with the SPDIF output.
2765  * Called from each patch supporting the SPDIF out.
2766  *
2767  * Returns 0 if successful, or a negative error code.
2768  */
2769 int snd_hda_create_spdif_out_ctls(struct hda_codec *codec, hda_nid_t nid)
2770 {
2771         int err;
2772         struct snd_kcontrol *kctl;
2773         struct snd_kcontrol_new *dig_mix;
2774         int idx;
2775 
2776         idx = find_empty_mixer_ctl_idx(codec, "IEC958 Playback Switch");
2777         if (idx < 0) {
2778                 printk(KERN_ERR "hda_codec: too many IEC958 outputs\n");
2779                 return -EBUSY;
2780         }
2781         for (dig_mix = dig_mixes; dig_mix->name; dig_mix++) {
2782                 kctl = snd_ctl_new1(dig_mix, codec);
2783                 if (!kctl)
2784                         return -ENOMEM;
2785                 kctl->id.index = idx;
2786                 kctl->private_value = nid;
2787                 err = snd_hda_ctl_add(codec, nid, kctl);
2788                 if (err < 0)
2789                         return err;
2790         }
2791         codec->spdif_ctls =
2792                 snd_hda_codec_read(codec, nid, 0,
2793                                    AC_VERB_GET_DIGI_CONVERT_1, 0);
2794         codec->spdif_status = convert_to_spdif_status(codec->spdif_ctls);
2795         return 0;
2796 }
2797 EXPORT_SYMBOL_HDA(snd_hda_create_spdif_out_ctls);
2798 
2799 /*
2800  * SPDIF sharing with analog output
2801  */
2802 static int spdif_share_sw_get(struct snd_kcontrol *kcontrol,
2803                               struct snd_ctl_elem_value *ucontrol)
2804 {
2805         struct hda_multi_out *mout = snd_kcontrol_chip(kcontrol);
2806         ucontrol->value.integer.value[0] = mout->share_spdif;
2807         return 0;
2808 }
2809 
2810 static int spdif_share_sw_put(struct snd_kcontrol *kcontrol,
2811                               struct snd_ctl_elem_value *ucontrol)
2812 {
2813         struct hda_multi_out *mout = snd_kcontrol_chip(kcontrol);
2814         mout->share_spdif = !!ucontrol->value.integer.value[0];
2815         return 0;
2816 }
2817 
2818 static struct snd_kcontrol_new spdif_share_sw = {
2819         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2820         .name = "IEC958 Default PCM Playback Switch",
2821         .info = snd_ctl_boolean_mono_info,
2822         .get = spdif_share_sw_get,
2823         .put = spdif_share_sw_put,
2824 };
2825 
2826 /**
2827  * snd_hda_create_spdif_share_sw - create Default PCM switch
2828  * @codec: the HDA codec
2829  * @mout: multi-out instance
2830  */
2831 int snd_hda_create_spdif_share_sw(struct hda_codec *codec,
2832                                   struct hda_multi_out *mout)
2833 {
2834         if (!mout->dig_out_nid)
2835                 return 0;
2836         /* ATTENTION: here mout is passed as private_data, instead of codec */
2837         return snd_hda_ctl_add(codec, mout->dig_out_nid,
2838                               snd_ctl_new1(&spdif_share_sw, mout));
2839 }
2840 EXPORT_SYMBOL_HDA(snd_hda_create_spdif_share_sw);
2841 
2842 /*
2843  * SPDIF input
2844  */
2845 
2846 #define snd_hda_spdif_in_switch_info    snd_hda_spdif_out_switch_info
2847 
2848 static int snd_hda_spdif_in_switch_get(struct snd_kcontrol *kcontrol,
2849                                        struct snd_ctl_elem_value *ucontrol)
2850 {
2851         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2852 
2853         ucontrol->value.integer.value[0] = codec->spdif_in_enable;
2854         return 0;
2855 }
2856 
2857 static int snd_hda_spdif_in_switch_put(struct snd_kcontrol *kcontrol,
2858                                        struct snd_ctl_elem_value *ucontrol)
2859 {
2860         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2861         hda_nid_t nid = kcontrol->private_value;
2862         unsigned int val = !!ucontrol->value.integer.value[0];
2863         int change;
2864 
2865         mutex_lock(&codec->spdif_mutex);
2866         change = codec->spdif_in_enable != val;
2867         if (change) {
2868                 codec->spdif_in_enable = val;
2869                 snd_hda_codec_write_cache(codec, nid, 0,
2870                                           AC_VERB_SET_DIGI_CONVERT_1, val);
2871         }
2872         mutex_unlock(&codec->spdif_mutex);
2873         return change;
2874 }
2875 
2876 static int snd_hda_spdif_in_status_get(struct snd_kcontrol *kcontrol,
2877                                        struct snd_ctl_elem_value *ucontrol)
2878 {
2879         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2880         hda_nid_t nid = kcontrol->private_value;
2881         unsigned short val;
2882         unsigned int sbits;
2883 
2884         val = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_DIGI_CONVERT_1, 0);
2885         sbits = convert_to_spdif_status(val);
2886         ucontrol->value.iec958.status[0] = sbits;
2887         ucontrol->value.iec958.status[1] = sbits >> 8;
2888         ucontrol->value.iec958.status[2] = sbits >> 16;
2889         ucontrol->value.iec958.status[3] = sbits >> 24;
2890         return 0;
2891 }
2892 
2893 static struct snd_kcontrol_new dig_in_ctls[] = {
2894         {
2895                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2896                 .name = SNDRV_CTL_NAME_IEC958("", CAPTURE, SWITCH),
2897                 .info = snd_hda_spdif_in_switch_info,
2898                 .get = snd_hda_spdif_in_switch_get,
2899                 .put = snd_hda_spdif_in_switch_put,
2900         },
2901         {
2902                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
2903                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2904                 .name = SNDRV_CTL_NAME_IEC958("", CAPTURE, DEFAULT),
2905                 .info = snd_hda_spdif_mask_info,
2906                 .get = snd_hda_spdif_in_status_get,
2907         },
2908         { } /* end */
2909 };
2910 
2911 /**
2912  * snd_hda_create_spdif_in_ctls - create Input SPDIF-related controls
2913  * @codec: the HDA codec
2914  * @nid: audio in widget NID
2915  *
2916  * Creates controls related with the SPDIF input.
2917  * Called from each patch supporting the SPDIF in.
2918  *
2919  * Returns 0 if successful, or a negative error code.
2920  */
2921 int snd_hda_create_spdif_in_ctls(struct hda_codec *codec, hda_nid_t nid)
2922 {
2923         int err;
2924         struct snd_kcontrol *kctl;
2925         struct snd_kcontrol_new *dig_mix;
2926         int idx;
2927 
2928         idx = find_empty_mixer_ctl_idx(codec, "IEC958 Capture Switch");
2929         if (idx < 0) {
2930                 printk(KERN_ERR "hda_codec: too many IEC958 inputs\n");
2931                 return -EBUSY;
2932         }
2933         for (dig_mix = dig_in_ctls; dig_mix->name; dig_mix++) {
2934                 kctl = snd_ctl_new1(dig_mix, codec);
2935                 if (!kctl)
2936                         return -ENOMEM;
2937                 kctl->private_value = nid;
2938                 err = snd_hda_ctl_add(codec, nid, kctl);
2939                 if (err < 0)
2940                         return err;
2941         }
2942         codec->spdif_in_enable =
2943                 snd_hda_codec_read(codec, nid, 0,
2944                                    AC_VERB_GET_DIGI_CONVERT_1, 0) &
2945                 AC_DIG1_ENABLE;
2946         return 0;
2947 }
2948 EXPORT_SYMBOL_HDA(snd_hda_create_spdif_in_ctls);
2949 
2950 #ifdef SND_HDA_NEEDS_RESUME
2951 /*
2952  * command cache
2953  */
2954 
2955 /* build a 32bit cache key with the widget id and the command parameter */
2956 #define build_cmd_cache_key(nid, verb)  ((verb << 8) | nid)
2957 #define get_cmd_cache_nid(key)          ((key) & 0xff)
2958 #define get_cmd_cache_cmd(key)          (((key) >> 8) & 0xffff)
2959 
2960 /**
2961  * snd_hda_codec_write_cache - send a single command with caching
2962  * @codec: the HDA codec
2963  * @nid: NID to send the command
2964  * @direct: direct flag
2965  * @verb: the verb to send
2966  * @parm: the parameter for the verb
2967  *
2968  * Send a single command without waiting for response.
2969  *
2970  * Returns 0 if successful, or a negative error code.
2971  */
2972 int snd_hda_codec_write_cache(struct hda_codec *codec, hda_nid_t nid,
2973                               int direct, unsigned int verb, unsigned int parm)
2974 {
2975         int err = snd_hda_codec_write(codec, nid, direct, verb, parm);
2976         struct hda_cache_head *c;
2977         u32 key;
2978 
2979         if (err < 0)
2980                 return err;
2981         /* parm may contain the verb stuff for get/set amp */
2982         verb = verb | (parm >> 8);
2983         parm &= 0xff;
2984         key = build_cmd_cache_key(nid, verb);
2985         mutex_lock(&codec->bus->cmd_mutex);
2986         c = get_alloc_hash(&codec->cmd_cache, key);
2987         if (c)
2988                 c->val = parm;
2989         mutex_unlock(&codec->bus->cmd_mutex);
2990         return 0;
2991 }
2992 EXPORT_SYMBOL_HDA(snd_hda_codec_write_cache);
2993 
2994 /**
2995  * snd_hda_codec_update_cache - check cache and write the cmd only when needed
2996  * @codec: the HDA codec
2997  * @nid: NID to send the command
2998  * @direct: direct flag
2999  * @verb: the verb to send
3000  * @parm: the parameter for the verb
3001  *
3002  * This function works like snd_hda_codec_write_cache(), but it doesn't send
3003  * command if the parameter is already identical with the cached value.
3004  * If not, it sends the command and refreshes the cache.
3005  *
3006  * Returns 0 if successful, or a negative error code.
3007  */
3008 int snd_hda_codec_update_cache(struct hda_codec *codec, hda_nid_t nid,
3009                                int direct, unsigned int verb, unsigned int parm)
3010 {
3011         struct hda_cache_head *c;
3012         u32 key;
3013 
3014         /* parm may contain the verb stuff for get/set amp */
3015         verb = verb | (parm >> 8);
3016         parm &= 0xff;
3017         key = build_cmd_cache_key(nid, verb);
3018         mutex_lock(&codec->bus->cmd_mutex);
3019         c = get_hash(&codec->cmd_cache, key);
3020         if (c && c->val == parm) {
3021                 mutex_unlock(&codec->bus->cmd_mutex);
3022                 return 0;
3023         }
3024         mutex_unlock(&codec->bus->cmd_mutex);
3025         return snd_hda_codec_write_cache(codec, nid, direct, verb, parm);
3026 }
3027 EXPORT_SYMBOL_HDA(snd_hda_codec_update_cache);
3028 
3029 /**
3030  * snd_hda_codec_resume_cache - Resume the all commands from the cache
3031  * @codec: HD-audio codec
3032  *
3033  * Execute all verbs recorded in the command caches to resume.
3034  */
3035 void snd_hda_codec_resume_cache(struct hda_codec *codec)
3036 {
3037         struct hda_cache_head *buffer = codec->cmd_cache.buf.list;
3038         int i;
3039 
3040         for (i = 0; i < codec->cmd_cache.buf.used; i++, buffer++) {
3041                 u32 key = buffer->key;
3042                 if (!key)
3043                         continue;
3044                 snd_hda_codec_write(codec, get_cmd_cache_nid(key), 0,
3045                                     get_cmd_cache_cmd(key), buffer->val);
3046         }
3047 }
3048 EXPORT_SYMBOL_HDA(snd_hda_codec_resume_cache);
3049 
3050 /**
3051  * snd_hda_sequence_write_cache - sequence writes with caching
3052  * @codec: the HDA codec
3053  * @seq: VERB array to send
3054  *
3055  * Send the commands sequentially from the given array.
3056  * Thte commands are recorded on cache for power-save and resume.
3057  * The array must be terminated with NID=0.
3058  */
3059 void snd_hda_sequence_write_cache(struct hda_codec *codec,
3060                                   const struct hda_verb *seq)
3061 {
3062         for (; seq->nid; seq++)
3063                 snd_hda_codec_write_cache(codec, seq->nid, 0, seq->verb,
3064                                           seq->param);
3065 }
3066 EXPORT_SYMBOL_HDA(snd_hda_sequence_write_cache);
3067 #endif /* SND_HDA_NEEDS_RESUME */
3068 
3069 /*
3070  * set power state of the codec
3071  */
3072 static void hda_set_power_state(struct hda_codec *codec, hda_nid_t fg,
3073                                 unsigned int power_state)
3074 {
3075         hda_nid_t nid;
3076         int i;
3077 
3078         /* this delay seems necessary to avoid click noise at power-down */
3079         if (power_state == AC_PWRST_D3)
3080                 msleep(100);
3081         snd_hda_codec_read(codec, fg, 0, AC_VERB_SET_POWER_STATE,
3082                             power_state);
3083         /* partial workaround for "azx_get_response timeout" */
3084         if (power_state == AC_PWRST_D0 &&
3085             (codec->vendor_id & 0xffff0000) == 0x14f10000)
3086                 msleep(10);
3087 
3088         nid = codec->start_nid;
3089         for (i = 0; i < codec->num_nodes; i++, nid++) {
3090                 unsigned int wcaps = get_wcaps(codec, nid);
3091                 if (wcaps & AC_WCAP_POWER) {
3092                         unsigned int wid_type = get_wcaps_type(wcaps);
3093                         if (power_state == AC_PWRST_D3 &&
3094                             wid_type == AC_WID_PIN) {
3095                                 unsigned int pincap;
3096                                 /*
3097                                  * don't power down the widget if it controls
3098                                  * eapd and EAPD_BTLENABLE is set.
3099                                  */
3100                                 pincap = snd_hda_query_pin_caps(codec, nid);
3101                                 if (pincap & AC_PINCAP_EAPD) {
3102                                         int eapd = snd_hda_codec_read(codec,
3103                                                 nid, 0,
3104                                                 AC_VERB_GET_EAPD_BTLENABLE, 0);
3105                                         eapd &= 0x02;
3106                                         if (eapd)
3107                                                 continue;
3108                                 }
3109                         }
3110                         snd_hda_codec_write(codec, nid, 0,
3111                                             AC_VERB_SET_POWER_STATE,
3112                                             power_state);
3113                 }
3114         }
3115 
3116         if (power_state == AC_PWRST_D0) {
3117                 unsigned long end_time;
3118                 int state;
3119                 /* wait until the codec reachs to D0 */
3120                 end_time = jiffies + msecs_to_jiffies(500);
3121                 do {
3122                         state = snd_hda_codec_read(codec, fg, 0,
3123                                                    AC_VERB_GET_POWER_STATE, 0);
3124                         if (state == power_state)
3125                                 break;
3126                         msleep(1);
3127                 } while (time_after_eq(end_time, jiffies));
3128         }
3129 }
3130 
3131 #ifdef CONFIG_SND_HDA_HWDEP
3132 /* execute additional init verbs */
3133 static void hda_exec_init_verbs(struct hda_codec *codec)
3134 {
3135         if (codec->init_verbs.list)
3136                 snd_hda_sequence_write(codec, codec->init_verbs.list);
3137 }
3138 #else
3139 static inline void hda_exec_init_verbs(struct hda_codec *codec) {}
3140 #endif
3141 
3142 #ifdef SND_HDA_NEEDS_RESUME
3143 /*
3144  * call suspend and power-down; used both from PM and power-save
3145  */
3146 static void hda_call_codec_suspend(struct hda_codec *codec)
3147 {
3148         if (codec->patch_ops.suspend)
3149                 codec->patch_ops.suspend(codec, PMSG_SUSPEND);
3150         hda_cleanup_all_streams(codec);
3151         hda_set_power_state(codec,
3152                             codec->afg ? codec->afg : codec->mfg,
3153                             AC_PWRST_D3);
3154 #ifdef CONFIG_SND_HDA_POWER_SAVE
3155         snd_hda_update_power_acct(codec);
3156         cancel_delayed_work(&codec->power_work);
3157         codec->power_on = 0;
3158         codec->power_transition = 0;
3159         codec->power_jiffies = jiffies;
3160 #endif
3161 }
3162 
3163 /*
3164  * kick up codec; used both from PM and power-save
3165  */
3166 static void hda_call_codec_resume(struct hda_codec *codec)
3167 {
3168         hda_set_power_state(codec,
3169                             codec->afg ? codec->afg : codec->mfg,
3170                             AC_PWRST_D0);
3171         restore_pincfgs(codec); /* restore all current pin configs */
3172         restore_shutup_pins(codec);
3173         hda_exec_init_verbs(codec);
3174         if (codec->patch_ops.resume)
3175                 codec->patch_ops.resume(codec);
3176         else {
3177                 if (codec->patch_ops.init)
3178                         codec->patch_ops.init(codec);
3179                 snd_hda_codec_resume_amp(codec);
3180                 snd_hda_codec_resume_cache(codec);
3181         }
3182 }
3183 #endif /* SND_HDA_NEEDS_RESUME */
3184 
3185 
3186 /**
3187  * snd_hda_build_controls - build mixer controls
3188  * @bus: the BUS
3189  *
3190  * Creates mixer controls for each codec included in the bus.
3191  *
3192  * Returns 0 if successful, otherwise a negative error code.
3193  */
3194 int /*__devinit*/ snd_hda_build_controls(struct hda_bus *bus)
3195 {
3196         struct hda_codec *codec;
3197 
3198         list_for_each_entry(codec, &bus->codec_list, list) {
3199                 int err = snd_hda_codec_build_controls(codec);
3200                 if (err < 0) {
3201                         printk(KERN_ERR "hda_codec: cannot build controls "
3202                                "for #%d (error %d)\n", codec->addr, err);
3203                         err = snd_hda_codec_reset(codec);
3204                         if (err < 0) {
3205                                 printk(KERN_ERR
3206                                        "hda_codec: cannot revert codec\n");
3207                                 return err;
3208                         }
3209                 }
3210         }
3211         return 0;
3212 }
3213 EXPORT_SYMBOL_HDA(snd_hda_build_controls);
3214 
3215 int snd_hda_codec_build_controls(struct hda_codec *codec)
3216 {
3217         int err = 0;
3218         hda_exec_init_verbs(codec);
3219         /* continue to initialize... */
3220         if (codec->patch_ops.init)
3221                 err = codec->patch_ops.init(codec);
3222         if (!err && codec->patch_ops.build_controls)
3223                 err = codec->patch_ops.build_controls(codec);
3224         if (err < 0)
3225                 return err;
3226         return 0;
3227 }
3228 
3229 /*
3230  * stream formats
3231  */
3232 struct hda_rate_tbl {
3233         unsigned int hz;
3234         unsigned int alsa_bits;
3235         unsigned int hda_fmt;
3236 };
3237 
3238 /* rate = base * mult / div */
3239 #define HDA_RATE(base, mult, div) \
3240         (AC_FMT_BASE_##base##K | (((mult) - 1) << AC_FMT_MULT_SHIFT) | \
3241          (((div) - 1) << AC_FMT_DIV_SHIFT))
3242 
3243 static struct hda_rate_tbl rate_bits[] = {
3244         /* rate in Hz, ALSA rate bitmask, HDA format value */
3245 
3246         /* autodetected value used in snd_hda_query_supported_pcm */
3247         { 8000, SNDRV_PCM_RATE_8000, HDA_RATE(48, 1, 6) },
3248         { 11025, SNDRV_PCM_RATE_11025, HDA_RATE(44, 1, 4) },
3249         { 16000, SNDRV_PCM_RATE_16000, HDA_RATE(48, 1, 3) },
3250         { 22050, SNDRV_PCM_RATE_22050, HDA_RATE(44, 1, 2) },
3251         { 32000, SNDRV_PCM_RATE_32000, HDA_RATE(48, 2, 3) },
3252         { 44100, SNDRV_PCM_RATE_44100, HDA_RATE(44, 1, 1) },
3253         { 48000, SNDRV_PCM_RATE_48000, HDA_RATE(48, 1, 1) },
3254         { 88200, SNDRV_PCM_RATE_88200, HDA_RATE(44, 2, 1) },
3255         { 96000, SNDRV_PCM_RATE_96000, HDA_RATE(48, 2, 1) },
3256         { 176400, SNDRV_PCM_RATE_176400, HDA_RATE(44, 4, 1) },
3257         { 192000, SNDRV_PCM_RATE_192000, HDA_RATE(48, 4, 1) },
3258 #define AC_PAR_PCM_RATE_BITS    11
3259         /* up to bits 10, 384kHZ isn't supported properly */
3260 
3261         /* not autodetected value */
3262         { 9600, SNDRV_PCM_RATE_KNOT, HDA_RATE(48, 1, 5) },
3263 
3264         { 0 } /* terminator */
3265 };
3266 
3267 /**
3268  * snd_hda_calc_stream_format - calculate format bitset
3269  * @rate: the sample rate
3270  * @channels: the number of channels
3271  * @format: the PCM format (SNDRV_PCM_FORMAT_XXX)
3272  * @maxbps: the max. bps
3273  *
3274  * Calculate the format bitset from the given rate, channels and th PCM format.
3275  *
3276  * Return zero if invalid.
3277  */
3278 unsigned int snd_hda_calc_stream_format(unsigned int rate,
3279                                         unsigned int channels,
3280                                         unsigned int format,
3281                                         unsigned int maxbps,
3282                                         unsigned short spdif_ctls)
3283 {
3284         int i;
3285         unsigned int val = 0;
3286 
3287         for (i = 0; rate_bits[i].hz; i++)
3288                 if (rate_bits[i].hz == rate) {
3289                         val = rate_bits[i].hda_fmt;
3290                         break;
3291                 }
3292         if (!rate_bits[i].hz) {
3293                 snd_printdd("invalid rate %d\n", rate);
3294                 return 0;
3295         }
3296 
3297         if (channels == 0 || channels > 8) {
3298                 snd_printdd("invalid channels %d\n", channels);
3299                 return 0;
3300         }
3301         val |= channels - 1;
3302 
3303         switch (snd_pcm_format_width(format)) {
3304         case 8:
3305                 val |= AC_FMT_BITS_8;
3306                 break;
3307         case 16:
3308                 val |= AC_FMT_BITS_16;
3309                 break;
3310         case 20:
3311         case 24:
3312         case 32:
3313                 if (maxbps >= 32 || format == SNDRV_PCM_FORMAT_FLOAT_LE)
3314                         val |= AC_FMT_BITS_32;
3315                 else if (maxbps >= 24)
3316                         val |= AC_FMT_BITS_24;
3317                 else
3318                         val |= AC_FMT_BITS_20;
3319                 break;
3320         default:
3321                 snd_printdd("invalid format width %d\n",
3322                             snd_pcm_format_width(format));
3323                 return 0;
3324         }
3325 
3326         if (spdif_ctls & AC_DIG1_NONAUDIO)
3327                 val |= AC_FMT_TYPE_NON_PCM;
3328 
3329         return val;
3330 }
3331 EXPORT_SYMBOL_HDA(snd_hda_calc_stream_format);
3332 
3333 static unsigned int get_pcm_param(struct hda_codec *codec, hda_nid_t nid)
3334 {
3335         unsigned int val = 0;
3336         if (nid != codec->afg &&
3337             (get_wcaps(codec, nid) & AC_WCAP_FORMAT_OVRD))
3338                 val = snd_hda_param_read(codec, nid, AC_PAR_PCM);
3339         if (!val || val == -1)
3340                 val = snd_hda_param_read(codec, codec->afg, AC_PAR_PCM);
3341         if (!val || val == -1)
3342                 return 0;
3343         return val;
3344 }
3345 
3346 static unsigned int query_pcm_param(struct hda_codec *codec, hda_nid_t nid)
3347 {
3348         return query_caps_hash(codec, nid, HDA_HASH_PARPCM_KEY(nid),
3349                                get_pcm_param);
3350 }
3351 
3352 static unsigned int get_stream_param(struct hda_codec *codec, hda_nid_t nid)
3353 {
3354         unsigned int streams = snd_hda_param_read(codec, nid, AC_PAR_STREAM);
3355         if (!streams || streams == -1)
3356                 streams = snd_hda_param_read(codec, codec->afg, AC_PAR_STREAM);
3357         if (!streams || streams == -1)
3358                 return 0;
3359         return streams;
3360 }
3361 
3362 static unsigned int query_stream_param(struct hda_codec *codec, hda_nid_t nid)
3363 {
3364         return query_caps_hash(codec, nid, HDA_HASH_PARSTR_KEY(nid),
3365                                get_stream_param);
3366 }
3367 
3368 /**
3369  * snd_hda_query_supported_pcm - query the supported PCM rates and formats
3370  * @codec: the HDA codec
3371  * @nid: NID to query
3372  * @ratesp: the pointer to store the detected rate bitflags
3373  * @formatsp: the pointer to store the detected formats
3374  * @bpsp: the pointer to store the detected format widths
3375  *
3376  * Queries the supported PCM rates and formats.  The NULL @ratesp, @formatsp
3377  * or @bsps argument is ignored.
3378  *
3379  * Returns 0 if successful, otherwise a negative error code.
3380  */
3381 static int snd_hda_query_supported_pcm(struct hda_codec *codec, hda_nid_t nid,
3382                                 u32 *ratesp, u64 *formatsp, unsigned int *bpsp)
3383 {
3384         unsigned int i, val, wcaps;
3385 
3386         wcaps = get_wcaps(codec, nid);
3387         val = query_pcm_param(codec, nid);
3388 
3389         if (ratesp) {
3390                 u32 rates = 0;
3391                 for (i = 0; i < AC_PAR_PCM_RATE_BITS; i++) {
3392                         if (val & (1 << i))
3393                                 rates |= rate_bits[i].alsa_bits;
3394                 }
3395                 if (rates == 0) {
3396                         snd_printk(KERN_ERR "hda_codec: rates == 0 "
3397                                    "(nid=0x%x, val=0x%x, ovrd=%i)\n",
3398                                         nid, val,
3399                                         (wcaps & AC_WCAP_FORMAT_OVRD) ? 1 : 0);
3400                         return -EIO;
3401                 }
3402                 *ratesp = rates;
3403         }
3404 
3405         if (formatsp || bpsp) {
3406                 u64 formats = 0;
3407                 unsigned int streams, bps;
3408 
3409                 streams = query_stream_param(codec, nid);
3410                 if (!streams)
3411                         return -EIO;
3412 
3413                 bps = 0;
3414                 if (streams & AC_SUPFMT_PCM) {
3415                         if (val & AC_SUPPCM_BITS_8) {
3416                                 formats |= SNDRV_PCM_FMTBIT_U8;
3417                                 bps = 8;
3418                         }
3419                         if (val & AC_SUPPCM_BITS_16) {
3420                                 formats |= SNDRV_PCM_FMTBIT_S16_LE;
3421                                 bps = 16;
3422                         }
3423                         if (wcaps & AC_WCAP_DIGITAL) {
3424                                 if (val & AC_SUPPCM_BITS_32)
3425                                         formats |= SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE;
3426                                 if (val & (AC_SUPPCM_BITS_20|AC_SUPPCM_BITS_24))
3427                                         formats |= SNDRV_PCM_FMTBIT_S32_LE;
3428                                 if (val & AC_SUPPCM_BITS_24)
3429                                         bps = 24;
3430                                 else if (val & AC_SUPPCM_BITS_20)
3431                                         bps = 20;
3432                         } else if (val & (AC_SUPPCM_BITS_20|AC_SUPPCM_BITS_24|
3433                                           AC_SUPPCM_BITS_32)) {
3434                                 formats |= SNDRV_PCM_FMTBIT_S32_LE;
3435                                 if (val & AC_SUPPCM_BITS_32)
3436                                         bps = 32;
3437                                 else if (val & AC_SUPPCM_BITS_24)
3438                                         bps = 24;
3439                                 else if (val & AC_SUPPCM_BITS_20)
3440                                         bps = 20;
3441                         }
3442                 }
3443                 if (streams & AC_SUPFMT_FLOAT32) {
3444                         formats |= SNDRV_PCM_FMTBIT_FLOAT_LE;
3445                         if (!bps)
3446                                 bps = 32;
3447                 }
3448                 if (streams == AC_SUPFMT_AC3) {
3449                         /* should be exclusive */
3450                         /* temporary hack: we have still no proper support
3451                          * for the direct AC3 stream...
3452                          */
3453                         formats |= SNDRV_PCM_FMTBIT_U8;
3454                         bps = 8;
3455                 }
3456                 if (formats == 0) {
3457                         snd_printk(KERN_ERR "hda_codec: formats == 0 "
3458                                    "(nid=0x%x, val=0x%x, ovrd=%i, "
3459                                    "streams=0x%x)\n",
3460                                         nid, val,
3461                                         (wcaps & AC_WCAP_FORMAT_OVRD) ? 1 : 0,
3462                                         streams);
3463                         return -EIO;
3464                 }
3465                 if (formatsp)
3466                         *formatsp = formats;
3467                 if (bpsp)
3468                         *bpsp = bps;
3469         }
3470 
3471         return 0;
3472 }
3473 
3474 /**
3475  * snd_hda_is_supported_format - Check the validity of the format
3476  * @codec: HD-audio codec
3477  * @nid: NID to check
3478  * @format: the HD-audio format value to check
3479  *
3480  * Check whether the given node supports the format value.
3481  *
3482  * Returns 1 if supported, 0 if not.
3483  */
3484 int snd_hda_is_supported_format(struct hda_codec *codec, hda_nid_t nid,
3485                                 unsigned int format)
3486 {
3487         int i;
3488         unsigned int val = 0, rate, stream;
3489 
3490         val = query_pcm_param(codec, nid);
3491         if (!val)
3492                 return 0;
3493 
3494         rate = format & 0xff00;
3495         for (i = 0; i < AC_PAR_PCM_RATE_BITS; i++)
3496                 if (rate_bits[i].hda_fmt == rate) {
3497                         if (val & (1 << i))
3498                                 break;
3499                         return 0;
3500                 }
3501         if (i >= AC_PAR_PCM_RATE_BITS)
3502                 return 0;
3503 
3504         stream = query_stream_param(codec, nid);
3505         if (!stream)
3506                 return 0;
3507 
3508         if (stream & AC_SUPFMT_PCM) {
3509                 switch (format & 0xf0) {
3510                 case 0x00:
3511                         if (!(val & AC_SUPPCM_BITS_8))
3512                                 return 0;
3513                         break;
3514                 case 0x10:
3515                         if (!(val & AC_SUPPCM_BITS_16))
3516                                 return 0;
3517                         break;
3518                 case 0x20:
3519                         if (!(val & AC_SUPPCM_BITS_20))
3520                                 return 0;
3521                         break;
3522                 case 0x30:
3523                         if (!(val & AC_SUPPCM_BITS_24))
3524                                 return 0;
3525                         break;
3526                 case 0x40:
3527                         if (!(val & AC_SUPPCM_BITS_32))
3528                                 return 0;
3529                         break;
3530                 default:
3531                         return 0;
3532                 }
3533         } else {
3534                 /* FIXME: check for float32 and AC3? */
3535         }
3536 
3537         return 1;
3538 }
3539 EXPORT_SYMBOL_HDA(snd_hda_is_supported_format);
3540 
3541 /*
3542  * PCM stuff
3543  */
3544 static int hda_pcm_default_open_close(struct hda_pcm_stream *hinfo,
3545                                       struct hda_codec *codec,
3546                                       struct snd_pcm_substream *substream)
3547 {
3548         return 0;
3549 }
3550 
3551 static int hda_pcm_default_prepare(struct hda_pcm_stream *hinfo,
3552                                    struct hda_codec *codec,
3553                                    unsigned int stream_tag,
3554                                    unsigned int format,
3555                                    struct snd_pcm_substream *substream)
3556 {
3557         snd_hda_codec_setup_stream(codec, hinfo->nid, stream_tag, 0, format);
3558         return 0;
3559 }
3560 
3561 static int hda_pcm_default_cleanup(struct hda_pcm_stream *hinfo,
3562                                    struct hda_codec *codec,
3563                                    struct snd_pcm_substream *substream)
3564 {
3565         snd_hda_codec_cleanup_stream(codec, hinfo->nid);
3566         return 0;
3567 }
3568 
3569 static int set_pcm_default_values(struct hda_codec *codec,
3570                                   struct hda_pcm_stream *info)
3571 {
3572         int err;
3573 
3574         /* query support PCM information from the given NID */
3575         if (info->nid && (!info->rates || !info->formats)) {
3576                 err = snd_hda_query_supported_pcm(codec, info->nid,
3577                                 info->rates ? NULL : &info->rates,
3578                                 info->formats ? NULL : &info->formats,
3579                                 info->maxbps ? NULL : &info->maxbps);
3580                 if (err < 0)
3581                         return err;
3582         }
3583         if (info->ops.open == NULL)
3584                 info->ops.open = hda_pcm_default_open_close;
3585         if (info->ops.close == NULL)
3586                 info->ops.close = hda_pcm_default_open_close;
3587         if (info->ops.prepare == NULL) {
3588                 if (snd_BUG_ON(!info->nid))
3589                         return -EINVAL;
3590                 info->ops.prepare = hda_pcm_default_prepare;
3591         }
3592         if (info->ops.cleanup == NULL) {
3593                 if (snd_BUG_ON(!info->nid))
3594                         return -EINVAL;
3595                 info->ops.cleanup = hda_pcm_default_cleanup;
3596         }
3597         return 0;
3598 }
3599 
3600 /*
3601  * codec prepare/cleanup entries
3602  */
3603 int snd_hda_codec_prepare(struct hda_codec *codec,
3604                           struct hda_pcm_stream *hinfo,
3605                           unsigned int stream,
3606                           unsigned int format,
3607                           struct snd_pcm_substream *substream)
3608 {
3609         int ret;
3610         mutex_lock(&codec->bus->prepare_mutex);
3611         ret = hinfo->ops.prepare(hinfo, codec, stream, format, substream);
3612         if (ret >= 0)
3613                 purify_inactive_streams(codec);
3614         mutex_unlock(&codec->bus->prepare_mutex);
3615         return ret;
3616 }
3617 EXPORT_SYMBOL_HDA(snd_hda_codec_prepare);
3618 
3619 void snd_hda_codec_cleanup(struct hda_codec *codec,
3620                            struct hda_pcm_stream *hinfo,
3621                            struct snd_pcm_substream *substream)
3622 {
3623         mutex_lock(&codec->bus->prepare_mutex);
3624         hinfo->ops.cleanup(hinfo, codec, substream);
3625         mutex_unlock(&codec->bus->prepare_mutex);
3626 }
3627 EXPORT_SYMBOL_HDA(snd_hda_codec_cleanup);
3628 
3629 /* global */
3630 const char *snd_hda_pcm_type_name[HDA_PCM_NTYPES] = {
3631         "Audio", "SPDIF", "HDMI", "Modem"
3632 };
3633 
3634 /*
3635  * get the empty PCM device number to assign
3636  *
3637  * note the max device number is limited by HDA_MAX_PCMS, currently 10
3638  */
3639 static int get_empty_pcm_device(struct hda_bus *bus, int type)
3640 {
3641         /* audio device indices; not linear to keep compatibility */
3642         static int audio_idx[HDA_PCM_NTYPES][5] = {
3643                 [HDA_PCM_TYPE_AUDIO] = { 0, 2, 4, 5, -1 },
3644                 [HDA_PCM_TYPE_SPDIF] = { 1, -1 },
3645                 [HDA_PCM_TYPE_HDMI]  = { 3, 7, 8, 9, -1 },
3646                 [HDA_PCM_TYPE_MODEM] = { 6, -1 },
3647         };
3648         int i;
3649 
3650         if (type >= HDA_PCM_NTYPES) {
3651                 snd_printk(KERN_WARNING "Invalid PCM type %d\n", type);
3652                 return -EINVAL;
3653         }
3654 
3655         for (i = 0; audio_idx[type][i] >= 0 ; i++)
3656                 if (!test_and_set_bit(audio_idx[type][i], bus->pcm_dev_bits))
3657                         return audio_idx[type][i];
3658 
3659         snd_printk(KERN_WARNING "Too many %s devices\n",
3660                 snd_hda_pcm_type_name[type]);
3661         return -EAGAIN;
3662 }
3663 
3664 /*
3665  * attach a new PCM stream
3666  */
3667 static int snd_hda_attach_pcm(struct hda_codec *codec, struct hda_pcm *pcm)
3668 {
3669         struct hda_bus *bus = codec->bus;
3670         struct hda_pcm_stream *info;
3671         int stream, err;
3672 
3673         if (snd_BUG_ON(!pcm->name))
3674                 return -EINVAL;
3675         for (stream = 0; stream < 2; stream++) {
3676                 info = &pcm->stream[stream];
3677                 if (info->substreams) {
3678                         err = set_pcm_default_values(codec, info);
3679                         if (err < 0)
3680                                 return err;
3681                 }
3682         }
3683         return bus->ops.attach_pcm(bus, codec, pcm);
3684 }
3685 
3686 /* assign all PCMs of the given codec */
3687 int snd_hda_codec_build_pcms(struct hda_codec *codec)
3688 {
3689         unsigned int pcm;
3690         int err;
3691 
3692         if (!codec->num_pcms) {
3693                 if (!codec->patch_ops.build_pcms)
3694                         return 0;
3695                 err = codec->patch_ops.build_pcms(codec);
3696                 if (err < 0) {
3697                         printk(KERN_ERR "hda_codec: cannot build PCMs"
3698                                "for #%d (error %d)\n", codec->addr, err);
3699                         err = snd_hda_codec_reset(codec);
3700                         if (err < 0) {
3701                                 printk(KERN_ERR
3702                                        "hda_codec: cannot revert codec\n");
3703                                 return err;
3704                         }
3705                 }
3706         }
3707         for (pcm = 0; pcm < codec->num_pcms; pcm++) {
3708                 struct hda_pcm *cpcm = &codec->pcm_info[pcm];
3709                 int dev;
3710 
3711                 if (!cpcm->stream[0].substreams && !cpcm->stream[1].substreams)
3712                         continue; /* no substreams assigned */
3713 
3714                 if (!cpcm->pcm) {
3715                         dev = get_empty_pcm_device(codec->bus, cpcm->pcm_type);
3716                         if (dev < 0)
3717                                 continue; /* no fatal error */
3718                         cpcm->device = dev;
3719                         err = snd_hda_attach_pcm(codec, cpcm);
3720                         if (err < 0) {
3721                                 printk(KERN_ERR "hda_codec: cannot attach "
3722                                        "PCM stream %d for codec #%d\n",
3723                                        dev, codec->addr);
3724                                 continue; /* no fatal error */
3725                         }
3726                 }
3727         }
3728         return 0;
3729 }
3730 
3731 /**
3732  * snd_hda_build_pcms - build PCM information
3733  * @bus: the BUS
3734  *
3735  * Create PCM information for each codec included in the bus.
3736  *
3737  * The build_pcms codec patch is requested to set up codec->num_pcms and
3738  * codec->pcm_info properly.  The array is referred by the top-level driver
3739  * to create its PCM instances.
3740  * The allocated codec->pcm_info should be released in codec->patch_ops.free
3741  * callback.
3742  *
3743  * At least, substreams, channels_min and channels_max must be filled for
3744  * each stream.  substreams = 0 indicates that the stream doesn't exist.
3745  * When rates and/or formats are zero, the supported values are queried
3746  * from the given nid.  The nid is used also by the default ops.prepare
3747  * and ops.cleanup callbacks.
3748  *
3749  * The driver needs to call ops.open in its open callback.  Similarly,
3750  * ops.close is supposed to be called in the close callback.
3751  * ops.prepare should be called in the prepare or hw_params callback
3752  * with the proper parameters for set up.
3753  * ops.cleanup should be called in hw_free for clean up of streams.
3754  *
3755  * This function returns 0 if successful, or a negative error code.
3756  */
3757 int __devinit snd_hda_build_pcms(struct hda_bus *bus)
3758 {
3759         struct hda_codec *codec;
3760 
3761         list_for_each_entry(codec, &bus->codec_list, list) {
3762                 int err = snd_hda_codec_build_pcms(codec);
3763                 if (err < 0)
3764                         return err;
3765         }
3766         return 0;
3767 }
3768 EXPORT_SYMBOL_HDA(snd_hda_build_pcms);
3769 
3770 /**
3771  * snd_hda_check_board_config - compare the current codec with the config table
3772  * @codec: the HDA codec
3773  * @num_configs: number of config enums
3774  * @models: array of model name strings
3775  * @tbl: configuration table, terminated by null entries
3776  *
3777  * Compares the modelname or PCI subsystem id of the current codec with the
3778  * given configuration table.  If a matching entry is found, returns its
3779  * config value (supposed to be 0 or positive).
3780  *
3781  * If no entries are matching, the function returns a negative value.
3782  */
3783 int snd_hda_check_board_config(struct hda_codec *codec,
3784                                int num_configs, const char * const *models,
3785                                const struct snd_pci_quirk *tbl)
3786 {
3787         if (codec->modelname && models) {
3788                 int i;
3789                 for (i = 0; i < num_configs; i++) {
3790                         if (models[i] &&
3791                             !strcmp(codec->modelname, models[i])) {
3792                                 snd_printd(KERN_INFO "hda_codec: model '%s' is "
3793                                            "selected\n", models[i]);
3794                                 return i;
3795                         }
3796                 }
3797         }
3798 
3799         if (!codec->bus->pci || !tbl)
3800                 return -1;
3801 
3802         tbl = snd_pci_quirk_lookup(codec->bus->pci, tbl);
3803         if (!tbl)
3804                 return -1;
3805         if (tbl->value >= 0 && tbl->value < num_configs) {
3806 #ifdef CONFIG_SND_DEBUG_VERBOSE
3807                 char tmp[10];
3808                 const char *model = NULL;
3809                 if (models)
3810                         model = models[tbl->value];
3811                 if (!model) {
3812                         sprintf(tmp, "#%d", tbl->value);
3813                         model = tmp;
3814                 }
3815                 snd_printdd(KERN_INFO "hda_codec: model '%s' is selected "
3816                             "for config %x:%x (%s)\n",
3817                             model, tbl->subvendor, tbl->subdevice,
3818                             (tbl->name ? tbl->name : "Unknown device"));
3819 #endif
3820                 return tbl->value;
3821         }
3822         return -1;
3823 }
3824 EXPORT_SYMBOL_HDA(snd_hda_check_board_config);
3825 
3826 /**
3827  * snd_hda_check_board_codec_sid_config - compare the current codec
3828                                         subsystem ID with the
3829                                         config table
3830 
3831            This is important for Gateway notebooks with SB450 HDA Audio
3832            where the vendor ID of the PCI device is:
3833                 ATI Technologies Inc SB450 HDA Audio [1002:437b]
3834            and the vendor/subvendor are found only at the codec.
3835 
3836  * @codec: the HDA codec
3837  * @num_configs: number of config enums
3838  * @models: array of model name strings
3839  * @tbl: configuration table, terminated by null entries
3840  *
3841  * Compares the modelname or PCI subsystem id of the current codec with the
3842  * given configuration table.  If a matching entry is found, returns its
3843  * config value (supposed to be 0 or positive).
3844  *
3845  * If no entries are matching, the function returns a negative value.
3846  */
3847 int snd_hda_check_board_codec_sid_config(struct hda_codec *codec,
3848                                int num_configs, const char * const *models,
3849                                const struct snd_pci_quirk *tbl)
3850 {
3851         const struct snd_pci_quirk *q;
3852 
3853         /* Search for codec ID */
3854         for (q = tbl; q->subvendor; q++) {
3855                 unsigned long vendorid = (q->subdevice) | (q->subvendor << 16);
3856 
3857                 if (vendorid == codec->subsystem_id)
3858                         break;
3859         }
3860 
3861         if (!q->subvendor)
3862                 return -1;
3863 
3864         tbl = q;
3865 
3866         if (tbl->value >= 0 && tbl->value < num_configs) {
3867 #ifdef CONFIG_SND_DEBUG_VERBOSE
3868                 char tmp[10];
3869                 const char *model = NULL;
3870                 if (models)
3871                         model = models[tbl->value];
3872                 if (!model) {
3873                         sprintf(tmp, "#%d", tbl->value);
3874                         model = tmp;
3875                 }
3876                 snd_printdd(KERN_INFO "hda_codec: model '%s' is selected "
3877                             "for config %x:%x (%s)\n",
3878                             model, tbl->subvendor, tbl->subdevice,
3879                             (tbl->name ? tbl->name : "Unknown device"));
3880 #endif
3881                 return tbl->value;
3882         }
3883         return -1;
3884 }
3885 EXPORT_SYMBOL_HDA(snd_hda_check_board_codec_sid_config);
3886 
3887 /**
3888  * snd_hda_add_new_ctls - create controls from the array
3889  * @codec: the HDA codec
3890  * @knew: the array of struct snd_kcontrol_new
3891  *
3892  * This helper function creates and add new controls in the given array.
3893  * The array must be terminated with an empty entry as terminator.
3894  *
3895  * Returns 0 if successful, or a negative error code.
3896  */
3897 int snd_hda_add_new_ctls(struct hda_codec *codec,
3898                          const struct snd_kcontrol_new *knew)
3899 {
3900         int err;
3901 
3902         for (; knew->name; knew++) {
3903                 struct snd_kcontrol *kctl;
3904                 int addr = 0, idx = 0;
3905                 if (knew->iface == -1)  /* skip this codec private value */
3906                         continue;
3907                 for (;;) {
3908                         kctl = snd_ctl_new1(knew, codec);
3909                         if (!kctl)
3910                                 return -ENOMEM;
3911                         if (addr > 0)
3912                                 kctl->id.device = addr;
3913                         if (idx > 0)
3914                                 kctl->id.index = idx;
3915                         err = snd_hda_ctl_add(codec, 0, kctl);
3916                         if (!err)
3917                                 break;
3918                         /* try first with another device index corresponding to
3919                          * the codec addr; if it still fails (or it's the
3920                          * primary codec), then try another control index
3921                          */
3922                         if (!addr && codec->addr)
3923                                 addr = codec->addr;
3924                         else if (!idx && !knew->index) {
3925                                 idx = find_empty_mixer_ctl_idx(codec,
3926                                                                knew->name);
3927                                 if (idx <= 0)
3928                                         return err;
3929                         } else
3930                                 return err;
3931                 }
3932         }
3933         return 0;
3934 }
3935 EXPORT_SYMBOL_HDA(snd_hda_add_new_ctls);
3936 
3937 #ifdef CONFIG_SND_HDA_POWER_SAVE
3938 static void hda_set_power_state(struct hda_codec *codec, hda_nid_t fg,
3939                                 unsigned int power_state);
3940 
3941 static void hda_power_work(struct work_struct *work)
3942 {
3943         struct hda_codec *codec =
3944                 container_of(work, struct hda_codec, power_work.work);
3945         struct hda_bus *bus = codec->bus;
3946 
3947         if (!codec->power_on || codec->power_count) {
3948                 codec->power_transition = 0;
3949                 return;
3950         }
3951 
3952         hda_call_codec_suspend(codec);
3953         if (bus->ops.pm_notify)
3954                 bus->ops.pm_notify(bus);
3955 }
3956 
3957 static void hda_keep_power_on(struct hda_codec *codec)
3958 {
3959         codec->power_count++;
3960         codec->power_on = 1;
3961         codec->power_jiffies = jiffies;
3962 }
3963 
3964 /* update the power on/off account with the current jiffies */
3965 void snd_hda_update_power_acct(struct hda_codec *codec)
3966 {
3967         unsigned long delta = jiffies - codec->power_jiffies;
3968         if (codec->power_on)
3969                 codec->power_on_acct += delta;
3970         else
3971                 codec->power_off_acct += delta;
3972         codec->power_jiffies += delta;
3973 }
3974 
3975 /**
3976  * snd_hda_power_up - Power-up the codec
3977  * @codec: HD-audio codec
3978  *
3979  * Increment the power-up counter and power up the hardware really when
3980  * not turned on yet.
3981  */
3982 void snd_hda_power_up(struct hda_codec *codec)
3983 {
3984         struct hda_bus *bus = codec->bus;
3985 
3986         codec->power_count++;
3987         if (codec->power_on || codec->power_transition)
3988                 return;
3989 
3990         snd_hda_update_power_acct(codec);
3991         codec->power_on = 1;
3992         codec->power_jiffies = jiffies;
3993         if (bus->ops.pm_notify)
3994                 bus->ops.pm_notify(bus);
3995         hda_call_codec_resume(codec);
3996         cancel_delayed_work(&codec->power_work);
3997         codec->power_transition = 0;
3998 }
3999 EXPORT_SYMBOL_HDA(snd_hda_power_up);
4000 
4001 #define power_save(codec)       \
4002         ((codec)->bus->power_save ? *(codec)->bus->power_save : 0)
4003 
4004 /**
4005  * snd_hda_power_down - Power-down the codec
4006  * @codec: HD-audio codec
4007  *
4008  * Decrement the power-up counter and schedules the power-off work if
4009  * the counter rearches to zero.
4010  */
4011 void snd_hda_power_down(struct hda_codec *codec)
4012 {
4013         --codec->power_count;
4014         if (!codec->power_on || codec->power_count || codec->power_transition)
4015                 return;
4016         if (power_save(codec)) {
4017                 codec->power_transition = 1; /* avoid reentrance */
4018                 queue_delayed_work(codec->bus->workq, &codec->power_work,
4019                                 msecs_to_jiffies(power_save(codec) * 1000));
4020         }
4021 }
4022 EXPORT_SYMBOL_HDA(snd_hda_power_down);
4023 
4024 /**
4025  * snd_hda_check_amp_list_power - Check the amp list and update the power
4026  * @codec: HD-audio codec
4027  * @check: the object containing an AMP list and the status
4028  * @nid: NID to check / update
4029  *
4030  * Check whether the given NID is in the amp list.  If it's in the list,
4031  * check the current AMP status, and update the the power-status according
4032  * to the mute status.
4033  *
4034  * This function is supposed to be set or called from the check_power_status
4035  * patch ops.
4036  */
4037 int snd_hda_check_amp_list_power(struct hda_codec *codec,
4038                                  struct hda_loopback_check *check,
4039                                  hda_nid_t nid)
4040 {
4041         const struct hda_amp_list *p;
4042         int ch, v;
4043 
4044         if (!check->amplist)
4045                 return 0;
4046         for (p = check->amplist; p->nid; p++) {
4047                 if (p->nid == nid)
4048                         break;
4049         }
4050         if (!p->nid)
4051                 return 0; /* nothing changed */
4052 
4053         for (p = check->amplist; p->nid; p++) {
4054                 for (ch = 0; ch < 2; ch++) {
4055                         v = snd_hda_codec_amp_read(codec, p->nid, ch, p->dir,
4056                                                    p->idx);
4057                         if (!(v & HDA_AMP_MUTE) && v > 0) {
4058                                 if (!check->power_on) {
4059                                         check->power_on = 1;
4060                                         snd_hda_power_up(codec);
4061                                 }
4062                                 return 1;
4063                         }
4064                 }
4065         }
4066         if (check->power_on) {
4067                 check->power_on = 0;
4068                 snd_hda_power_down(codec);
4069         }
4070         return 0;
4071 }
4072 EXPORT_SYMBOL_HDA(snd_hda_check_amp_list_power);
4073 #endif
4074 
4075 /*
4076  * Channel mode helper
4077  */
4078 
4079 /**
4080  * snd_hda_ch_mode_info - Info callback helper for the channel mode enum
4081  */
4082 int snd_hda_ch_mode_info(struct hda_codec *codec,
4083                          struct snd_ctl_elem_info *uinfo,
4084                          const struct hda_channel_mode *chmode,
4085                          int num_chmodes)
4086 {
4087         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
4088         uinfo->count = 1;
4089         uinfo->value.enumerated.items = num_chmodes;
4090         if (uinfo->value.enumerated.item >= num_chmodes)
4091                 uinfo->value.enumerated.item = num_chmodes - 1;
4092         sprintf(uinfo->value.enumerated.name, "%dch",
4093                 chmode[uinfo->value.enumerated.item].channels);
4094         return 0;
4095 }
4096 EXPORT_SYMBOL_HDA(snd_hda_ch_mode_info);
4097 
4098 /**
4099  * snd_hda_ch_mode_get - Get callback helper for the channel mode enum
4100  */
4101 int snd_hda_ch_mode_get(struct hda_codec *codec,
4102                         struct snd_ctl_elem_value *ucontrol,
4103                         const struct hda_channel_mode *chmode,
4104                         int num_chmodes,
4105                         int max_channels)
4106 {
4107         int i;
4108 
4109         for (i = 0; i < num_chmodes; i++) {
4110                 if (max_channels == chmode[i].channels) {
4111                         ucontrol->value.enumerated.item[0] = i;
4112                         break;
4113                 }
4114         }
4115         return 0;
4116 }
4117 EXPORT_SYMBOL_HDA(snd_hda_ch_mode_get);
4118 
4119 /**
4120  * snd_hda_ch_mode_put - Put callback helper for the channel mode enum
4121  */
4122 int snd_hda_ch_mode_put(struct hda_codec *codec,
4123                         struct snd_ctl_elem_value *ucontrol,
4124                         const struct hda_channel_mode *chmode,
4125                         int num_chmodes,
4126                         int *max_channelsp)
4127 {
4128         unsigned int mode;
4129 
4130         mode = ucontrol->value.enumerated.item[0];
4131         if (mode >= num_chmodes)
4132                 return -EINVAL;
4133         if (*max_channelsp == chmode[mode].channels)
4134                 return 0;
4135         /* change the current channel setting */
4136         *max_channelsp = chmode[mode].channels;
4137         if (chmode[mode].sequence)
4138                 snd_hda_sequence_write_cache(codec, chmode[mode].sequence);
4139         return 1;
4140 }
4141 EXPORT_SYMBOL_HDA(snd_hda_ch_mode_put);
4142 
4143 /*
4144  * input MUX helper
4145  */
4146 
4147 /**
4148  * snd_hda_input_mux_info_info - Info callback helper for the input-mux enum
4149  */
4150 int snd_hda_input_mux_info(const struct hda_input_mux *imux,
4151                            struct snd_ctl_elem_info *uinfo)
4152 {
4153         unsigned int index;
4154 
4155         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
4156         uinfo->count = 1;
4157         uinfo->value.enumerated.items = imux->num_items;
4158         if (!imux->num_items)
4159                 return 0;
4160         index = uinfo->value.enumerated.item;
4161         if (index >= imux->num_items)
4162                 index = imux->num_items - 1;
4163         strcpy(uinfo->value.enumerated.name, imux->items[index].label);
4164         return 0;
4165 }
4166 EXPORT_SYMBOL_HDA(snd_hda_input_mux_info);
4167 
4168 /**
4169  * snd_hda_input_mux_info_put - Put callback helper for the input-mux enum
4170  */
4171 int snd_hda_input_mux_put(struct hda_codec *codec,
4172                           const struct hda_input_mux *imux,
4173                           struct snd_ctl_elem_value *ucontrol,
4174                           hda_nid_t nid,
4175                           unsigned int *cur_val)
4176 {
4177         unsigned int idx;
4178 
4179         if (!imux->num_items)
4180                 return 0;
4181         idx = ucontrol->value.enumerated.item[0];
4182         if (idx >= imux->num_items)
4183                 idx = imux->num_items - 1;
4184         if (*cur_val == idx)
4185                 return 0;
4186         snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_CONNECT_SEL,
4187                                   imux->items[idx].index);
4188         *cur_val = idx;
4189         return 1;
4190 }
4191 EXPORT_SYMBOL_HDA(snd_hda_input_mux_put);
4192 
4193 
4194 /*
4195  * Multi-channel / digital-out PCM helper functions
4196  */
4197 
4198 /* setup SPDIF output stream */
4199 static void setup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid,
4200                                  unsigned int stream_tag, unsigned int format)
4201 {
4202         /* turn off SPDIF once; otherwise the IEC958 bits won't be updated */
4203         if (codec->spdif_status_reset && (codec->spdif_ctls & AC_DIG1_ENABLE))
4204                 set_dig_out_convert(codec, nid,
4205                                     codec->spdif_ctls & ~AC_DIG1_ENABLE & 0xff,
4206                                     -1);
4207         snd_hda_codec_setup_stream(codec, nid, stream_tag, 0, format);
4208         if (codec->slave_dig_outs) {
4209                 const hda_nid_t *d;
4210                 for (d = codec->slave_dig_outs; *d; d++)
4211                         snd_hda_codec_setup_stream(codec, *d, stream_tag, 0,
4212                                                    format);
4213         }
4214         /* turn on again (if needed) */
4215         if (codec->spdif_status_reset && (codec->spdif_ctls & AC_DIG1_ENABLE))
4216                 set_dig_out_convert(codec, nid,
4217                                     codec->spdif_ctls & 0xff, -1);
4218 }
4219 
4220 static void cleanup_dig_out_stream(struct hda_codec *codec, hda_nid_t nid)
4221 {
4222         snd_hda_codec_cleanup_stream(codec, nid);
4223         if (codec->slave_dig_outs) {
4224                 const hda_nid_t *d;
4225                 for (d = codec->slave_dig_outs; *d; d++)
4226                         snd_hda_codec_cleanup_stream(codec, *d);
4227         }
4228 }
4229 
4230 /**
4231  * snd_hda_bus_reboot_notify - call the reboot notifier of each codec
4232  * @bus: HD-audio bus
4233  */
4234 void snd_hda_bus_reboot_notify(struct hda_bus *bus)
4235 {
4236         struct hda_codec *codec;
4237 
4238         if (!bus)
4239                 return;
4240         list_for_each_entry(codec, &bus->codec_list, list) {
4241 #ifdef CONFIG_SND_HDA_POWER_SAVE
4242                 if (!codec->power_on)
4243                         continue;
4244 #endif
4245                 if (codec->patch_ops.reboot_notify)
4246                         codec->patch_ops.reboot_notify(codec);
4247         }
4248 }
4249 EXPORT_SYMBOL_HDA(snd_hda_bus_reboot_notify);
4250 
4251 /**
4252  * snd_hda_multi_out_dig_open - open the digital out in the exclusive mode
4253  */
4254 int snd_hda_multi_out_dig_open(struct hda_codec *codec,
4255                                struct hda_multi_out *mout)
4256 {
4257         mutex_lock(&codec->spdif_mutex);
4258         if (mout->dig_out_used == HDA_DIG_ANALOG_DUP)
4259                 /* already opened as analog dup; reset it once */
4260                 cleanup_dig_out_stream(codec, mout->dig_out_nid);
4261         mout->dig_out_used = HDA_DIG_EXCLUSIVE;
4262         mutex_unlock(&codec->spdif_mutex);
4263         return 0;
4264 }
4265 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_open);
4266 
4267 /**
4268  * snd_hda_multi_out_dig_prepare - prepare the digital out stream
4269  */
4270 int snd_hda_multi_out_dig_prepare(struct hda_codec *codec,
4271                                   struct hda_multi_out *mout,
4272                                   unsigned int stream_tag,
4273                                   unsigned int format,
4274                                   struct snd_pcm_substream *substream)
4275 {
4276         mutex_lock(&codec->spdif_mutex);
4277         setup_dig_out_stream(codec, mout->dig_out_nid, stream_tag, format);
4278         mutex_unlock(&codec->spdif_mutex);
4279         return 0;
4280 }
4281 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_prepare);
4282 
4283 /**
4284  * snd_hda_multi_out_dig_cleanup - clean-up the digital out stream
4285  */
4286 int snd_hda_multi_out_dig_cleanup(struct hda_codec *codec,
4287                                   struct hda_multi_out *mout)
4288 {
4289         mutex_lock(&codec->spdif_mutex);
4290         cleanup_dig_out_stream(codec, mout->dig_out_nid);
4291         mutex_unlock(&codec->spdif_mutex);
4292         return 0;
4293 }
4294 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_cleanup);
4295 
4296 /**
4297  * snd_hda_multi_out_dig_close - release the digital out stream
4298  */
4299 int snd_hda_multi_out_dig_close(struct hda_codec *codec,
4300                                 struct hda_multi_out *mout)
4301 {
4302         mutex_lock(&codec->spdif_mutex);
4303         mout->dig_out_used = 0;
4304         mutex_unlock(&codec->spdif_mutex);
4305         return 0;
4306 }
4307 EXPORT_SYMBOL_HDA(snd_hda_multi_out_dig_close);
4308 
4309 /**
4310  * snd_hda_multi_out_analog_open - open analog outputs
4311  *
4312  * Open analog outputs and set up the hw-constraints.
4313  * If the digital outputs can be opened as slave, open the digital
4314  * outputs, too.
4315  */
4316 int snd_hda_multi_out_analog_open(struct hda_codec *codec,
4317                                   struct hda_multi_out *mout,
4318                                   struct snd_pcm_substream *substream,
4319                                   struct hda_pcm_stream *hinfo)
4320 {
4321         struct snd_pcm_runtime *runtime = substream->runtime;
4322         runtime->hw.channels_max = mout->max_channels;
4323         if (mout->dig_out_nid) {
4324                 if (!mout->analog_rates) {
4325                         mout->analog_rates = hinfo->rates;
4326                         mout->analog_formats = hinfo->formats;
4327                         mout->analog_maxbps = hinfo->maxbps;
4328                 } else {
4329                         runtime->hw.rates = mout->analog_rates;
4330                         runtime->hw.formats = mout->analog_formats;
4331                         hinfo->maxbps = mout->analog_maxbps;
4332                 }
4333                 if (!mout->spdif_rates) {
4334                         snd_hda_query_supported_pcm(codec, mout->dig_out_nid,
4335                                                     &mout->spdif_rates,
4336                                                     &mout->spdif_formats,
4337                                                     &mout->spdif_maxbps);
4338                 }
4339                 mutex_lock(&codec->spdif_mutex);
4340                 if (mout->share_spdif) {
4341                         if ((runtime->hw.rates & mout->spdif_rates) &&
4342                             (runtime->hw.formats & mout->spdif_formats)) {
4343                                 runtime->hw.rates &= mout->spdif_rates;
4344                                 runtime->hw.formats &= mout->spdif_formats;
4345                                 if (mout->spdif_maxbps < hinfo->maxbps)
4346                                         hinfo->maxbps = mout->spdif_maxbps;
4347                         } else {
4348                                 mout->share_spdif = 0;
4349                                 /* FIXME: need notify? */
4350                         }
4351                 }
4352                 mutex_unlock(&codec->spdif_mutex);
4353         }
4354         return snd_pcm_hw_constraint_step(substream->runtime, 0,
4355                                           SNDRV_PCM_HW_PARAM_CHANNELS, 2);
4356 }
4357 EXPORT_SYMBOL_HDA(snd_hda_multi_out_analog_open);
4358 
4359 /**
4360  * snd_hda_multi_out_analog_prepare - Preapre the analog outputs.
4361  *
4362  * Set up the i/o for analog out.
4363  * When the digital out is available, copy the front out to digital out, too.
4364  */
4365 int snd_hda_multi_out_analog_prepare(struct hda_codec *codec,
4366                                      struct hda_multi_out *mout,
4367                                      unsigned int stream_tag,
4368                                      unsigned int format,
4369                                      struct snd_pcm_substream *substream)
4370 {
4371         const hda_nid_t *nids = mout->dac_nids;
4372         int chs = substream->runtime->channels;
4373         int i;
4374 
4375         mutex_lock(&codec->spdif_mutex);
4376         if (mout->dig_out_nid && mout->share_spdif &&
4377             mout->dig_out_used != HDA_DIG_EXCLUSIVE) {
4378                 if (chs == 2 &&
4379                     snd_hda_is_supported_format(codec, mout->dig_out_nid,
4380                                                 format) &&
4381                     !(codec->spdif_status & IEC958_AES0_NONAUDIO)) {
4382                         mout->dig_out_used = HDA_DIG_ANALOG_DUP;
4383                         setup_dig_out_stream(codec, mout->dig_out_nid,
4384                                              stream_tag, format);
4385                 } else {
4386                         mout->dig_out_used = 0;
4387                         cleanup_dig_out_stream(codec, mout->dig_out_nid);
4388                 }
4389         }
4390         mutex_unlock(&codec->spdif_mutex);
4391 
4392         /* front */
4393         snd_hda_codec_setup_stream(codec, nids[HDA_FRONT], stream_tag,
4394                                    0, format);
4395         if (!mout->no_share_stream &&
4396             mout->hp_nid && mout->hp_nid != nids[HDA_FRONT])
4397                 /* headphone out will just decode front left/right (stereo) */
4398                 snd_hda_codec_setup_stream(codec, mout->hp_nid, stream_tag,
4399                                            0, format);
4400         /* extra outputs copied from front */
4401         for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
4402                 if (!mout->no_share_stream && mout->extra_out_nid[i])
4403                         snd_hda_codec_setup_stream(codec,
4404                                                    mout->extra_out_nid[i],
4405                                                    stream_tag, 0, format);
4406 
4407         /* surrounds */
4408         for (i = 1; i < mout->num_dacs; i++) {
4409                 if (chs >= (i + 1) * 2) /* independent out */
4410                         snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
4411                                                    i * 2, format);
4412                 else if (!mout->no_share_stream) /* copy front */
4413                         snd_hda_codec_setup_stream(codec, nids[i], stream_tag,
4414                                                    0, format);
4415         }
4416         return 0;
4417 }
4418 EXPORT_SYMBOL_HDA(snd_hda_multi_out_analog_prepare);
4419 
4420 /**
4421  * snd_hda_multi_out_analog_cleanup - clean up the setting for analog out
4422  */
4423 int snd_hda_multi_out_analog_cleanup(struct hda_codec *codec,
4424                                      struct hda_multi_out *mout)
4425 {
4426         const hda_nid_t *nids = mout->dac_nids;
4427         int i;
4428 
4429         for (i = 0; i < mout->num_dacs; i++)
4430                 snd_hda_codec_cleanup_stream(codec, nids[i]);
4431         if (mout->hp_nid)
4432                 snd_hda_codec_cleanup_stream(codec, mout->hp_nid);
4433         for (i = 0; i < ARRAY_SIZE(mout->extra_out_nid); i++)
4434                 if (mout->extra_out_nid[i])
4435                         snd_hda_codec_cleanup_stream(codec,
4436                                                      mout->extra_out_nid[i]);
4437         mutex_lock(&codec->spdif_mutex);
4438         if (mout->dig_out_nid && mout->dig_out_used == HDA_DIG_ANALOG_DUP) {
4439                 cleanup_dig_out_stream(codec, mout->dig_out_nid);
4440                 mout->dig_out_used = 0;
4441         }
4442         mutex_unlock(&codec->spdif_mutex);
4443         return 0;
4444 }
4445 EXPORT_SYMBOL_HDA(snd_hda_multi_out_analog_cleanup);
4446 
4447 /*
4448  * Helper for automatic pin configuration
4449  */
4450 
4451 static int is_in_nid_list(hda_nid_t nid, const hda_nid_t *list)
4452 {
4453         for (; *list; list++)
4454                 if (*list == nid)
4455                         return 1;
4456         return 0;
4457 }
4458 
4459 
4460 /*
4461  * Sort an associated group of pins according to their sequence numbers.
4462  */
4463 static void sort_pins_by_sequence(hda_nid_t *pins, short *sequences,
4464                                   int num_pins)
4465 {
4466         int i, j;
4467         short seq;
4468         hda_nid_t nid;
4469 
4470         for (i = 0; i < num_pins; i++) {
4471                 for (j = i + 1; j < num_pins; j++) {
4472                         if (sequences[i] > sequences[j]) {
4473                                 seq = sequences[i];
4474                                 sequences[i] = sequences[j];
4475                                 sequences[j] = seq;
4476                                 nid = pins[i];
4477                                 pins[i] = pins[j];
4478                                 pins[j] = nid;
4479                         }
4480                 }
4481         }
4482 }
4483 
4484 
4485 /* add the found input-pin to the cfg->inputs[] table */
4486 static void add_auto_cfg_input_pin(struct auto_pin_cfg *cfg, hda_nid_t nid,
4487                                    int type)
4488 {
4489         if (cfg->num_inputs < AUTO_CFG_MAX_INS) {
4490                 cfg->inputs[cfg->num_inputs].pin = nid;
4491                 cfg->inputs[cfg->num_inputs].type = type;
4492                 cfg->num_inputs++;
4493         }
4494 }
4495 
4496 /* sort inputs in the order of AUTO_PIN_* type */
4497 static void sort_autocfg_input_pins(struct auto_pin_cfg *cfg)
4498 {
4499         int i, j;
4500 
4501         for (i = 0; i < cfg->num_inputs; i++) {
4502                 for (j = i + 1; j < cfg->num_inputs; j++) {
4503                         if (cfg->inputs[i].type > cfg->inputs[j].type) {
4504                                 struct auto_pin_cfg_item tmp;
4505                                 tmp = cfg->inputs[i];
4506                                 cfg->inputs[i] = cfg->inputs[j];
4507                                 cfg->inputs[j] = tmp;
4508                         }
4509                 }
4510         }
4511 }
4512 
4513 /*
4514  * Parse all pin widgets and store the useful pin nids to cfg
4515  *
4516  * The number of line-outs or any primary output is stored in line_outs,
4517  * and the corresponding output pins are assigned to line_out_pins[],
4518  * in the order of front, rear, CLFE, side, ...
4519  *
4520  * If more extra outputs (speaker and headphone) are found, the pins are
4521  * assisnged to hp_pins[] and speaker_pins[], respectively.  If no line-out jack
4522  * is detected, one of speaker of HP pins is assigned as the primary
4523  * output, i.e. to line_out_pins[0].  So, line_outs is always positive
4524  * if any analog output exists.
4525  *
4526  * The analog input pins are assigned to inputs array.
4527  * The digital input/output pins are assigned to dig_in_pin and dig_out_pin,
4528  * respectively.
4529  */
4530 int snd_hda_parse_pin_def_config(struct hda_codec *codec,
4531                                  struct auto_pin_cfg *cfg,
4532                                  const hda_nid_t *ignore_nids)
4533 {
4534         hda_nid_t nid, end_nid;
4535         short seq, assoc_line_out, assoc_speaker;
4536         short sequences_line_out[ARRAY_SIZE(cfg->line_out_pins)];
4537         short sequences_speaker[ARRAY_SIZE(cfg->speaker_pins)];
4538         short sequences_hp[ARRAY_SIZE(cfg->hp_pins)];
4539         int i;
4540 
4541         memset(cfg, 0, sizeof(*cfg));
4542 
4543         memset(sequences_line_out, 0, sizeof(sequences_line_out));
4544         memset(sequences_speaker, 0, sizeof(sequences_speaker));
4545         memset(sequences_hp, 0, sizeof(sequences_hp));
4546         assoc_line_out = assoc_speaker = 0;
4547 
4548         end_nid = codec->start_nid + codec->num_nodes;
4549         for (nid = codec->start_nid; nid < end_nid; nid++) {
4550                 unsigned int wid_caps = get_wcaps(codec, nid);
4551                 unsigned int wid_type = get_wcaps_type(wid_caps);
4552                 unsigned int def_conf;
4553                 short assoc, loc;
4554 
4555                 /* read all default configuration for pin complex */
4556                 if (wid_type != AC_WID_PIN)
4557                         continue;
4558                 /* ignore the given nids (e.g. pc-beep returns error) */
4559                 if (ignore_nids && is_in_nid_list(nid, ignore_nids))
4560                         continue;
4561 
4562                 def_conf = snd_hda_codec_get_pincfg(codec, nid);
4563                 if (get_defcfg_connect(def_conf) == AC_JACK_PORT_NONE)
4564                         continue;
4565                 loc = get_defcfg_location(def_conf);
4566                 switch (get_defcfg_device(def_conf)) {
4567                 case AC_JACK_LINE_OUT:
4568                         seq = get_defcfg_sequence(def_conf);
4569                         assoc = get_defcfg_association(def_conf);
4570 
4571                         if (!(wid_caps & AC_WCAP_STEREO))
4572                                 if (!cfg->mono_out_pin)
4573                                         cfg->mono_out_pin = nid;
4574                         if (!assoc)
4575                                 continue;
4576                         if (!assoc_line_out)
4577                                 assoc_line_out = assoc;
4578                         else if (assoc_line_out != assoc)
4579                                 continue;
4580                         if (cfg->line_outs >= ARRAY_SIZE(cfg->line_out_pins))
4581                                 continue;
4582                         cfg->line_out_pins[cfg->line_outs] = nid;
4583                         sequences_line_out[cfg->line_outs] = seq;
4584                         cfg->line_outs++;
4585                         break;
4586                 case AC_JACK_SPEAKER:
4587                         seq = get_defcfg_sequence(def_conf);
4588                         assoc = get_defcfg_association(def_conf);
4589                         if (!assoc)
4590                                 continue;
4591                         if (!assoc_speaker)
4592                                 assoc_speaker = assoc;
4593                         else if (assoc_speaker != assoc)
4594                                 continue;
4595                         if (cfg->speaker_outs >= ARRAY_SIZE(cfg->speaker_pins))
4596                                 continue;
4597                         cfg->speaker_pins[cfg->speaker_outs] = nid;
4598                         sequences_speaker[cfg->speaker_outs] = seq;
4599                         cfg->speaker_outs++;
4600                         break;
4601                 case AC_JACK_HP_OUT:
4602                         seq = get_defcfg_sequence(def_conf);
4603                         assoc = get_defcfg_association(def_conf);
4604                         if (cfg->hp_outs >= ARRAY_SIZE(cfg->hp_pins))
4605                                 continue;
4606                         cfg->hp_pins[cfg->hp_outs] = nid;
4607                         sequences_hp[cfg->hp_outs] = (assoc << 4) | seq;
4608                         cfg->hp_outs++;
4609                         break;
4610                 case AC_JACK_MIC_IN:
4611                         add_auto_cfg_input_pin(cfg, nid, AUTO_PIN_MIC);
4612                         break;
4613                 case AC_JACK_LINE_IN:
4614                         add_auto_cfg_input_pin(cfg, nid, AUTO_PIN_LINE_IN);
4615                         break;
4616                 case AC_JACK_CD:
4617                         add_auto_cfg_input_pin(cfg, nid, AUTO_PIN_CD);
4618                         break;
4619                 case AC_JACK_AUX:
4620                         add_auto_cfg_input_pin(cfg, nid, AUTO_PIN_AUX);
4621                         break;
4622                 case AC_JACK_SPDIF_OUT:
4623                 case AC_JACK_DIG_OTHER_OUT:
4624                         if (cfg->dig_outs >= ARRAY_SIZE(cfg->dig_out_pins))
4625                                 continue;
4626                         cfg->dig_out_pins[cfg->dig_outs] = nid;
4627                         cfg->dig_out_type[cfg->dig_outs] =
4628                                 (loc == AC_JACK_LOC_HDMI) ?
4629                                 HDA_PCM_TYPE_HDMI : HDA_PCM_TYPE_SPDIF;
4630                         cfg->dig_outs++;
4631                         break;
4632                 case AC_JACK_SPDIF_IN:
4633                 case AC_JACK_DIG_OTHER_IN:
4634                         cfg->dig_in_pin = nid;
4635                         if (loc == AC_JACK_LOC_HDMI)
4636                                 cfg->dig_in_type = HDA_PCM_TYPE_HDMI;
4637                         else
4638                                 cfg->dig_in_type = HDA_PCM_TYPE_SPDIF;
4639                         break;
4640                 }
4641         }
4642 
4643         /* FIX-UP:
4644          * If no line-out is defined but multiple HPs are found,
4645          * some of them might be the real line-outs.
4646          */
4647         if (!cfg->line_outs && cfg->hp_outs > 1) {
4648                 int i = 0;
4649                 while (i < cfg->hp_outs) {
4650                         /* The real HPs should have the sequence 0x0f */
4651                         if ((sequences_hp[i] & 0x0f) == 0x0f) {
4652                                 i++;
4653                                 continue;
4654                         }
4655                         /* Move it to the line-out table */
4656                         cfg->line_out_pins[cfg->line_outs] = cfg->hp_pins[i];
4657                         sequences_line_out[cfg->line_outs] = sequences_hp[i];
4658                         cfg->line_outs++;
4659                         cfg->hp_outs--;
4660                         memmove(cfg->hp_pins + i, cfg->hp_pins + i + 1,
4661                                 sizeof(cfg->hp_pins[0]) * (cfg->hp_outs - i));
4662                         memmove(sequences_hp + i, sequences_hp + i + 1,
4663                                 sizeof(sequences_hp[0]) * (cfg->hp_outs - i));
4664                 }
4665                 memset(cfg->hp_pins + cfg->hp_outs, 0,
4666                        sizeof(hda_nid_t) * (AUTO_CFG_MAX_OUTS - cfg->hp_outs));
4667                 if (!cfg->hp_outs)
4668                         cfg->line_out_type = AUTO_PIN_HP_OUT;
4669 
4670         }
4671 
4672         /* sort by sequence */
4673         sort_pins_by_sequence(cfg->line_out_pins, sequences_line_out,
4674                               cfg->line_outs);
4675         sort_pins_by_sequence(cfg->speaker_pins, sequences_speaker,
4676                               cfg->speaker_outs);
4677         sort_pins_by_sequence(cfg->hp_pins, sequences_hp,
4678                               cfg->hp_outs);
4679 
4680         /*
4681          * FIX-UP: if no line-outs are detected, try to use speaker or HP pin
4682          * as a primary output
4683          */
4684         if (!cfg->line_outs) {
4685                 if (cfg->speaker_outs) {
4686                         cfg->line_outs = cfg->speaker_outs;
4687                         memcpy(cfg->line_out_pins, cfg->speaker_pins,
4688                                sizeof(cfg->speaker_pins));
4689                         cfg->speaker_outs = 0;
4690                         memset(cfg->speaker_pins, 0, sizeof(cfg->speaker_pins));
4691                         cfg->line_out_type = AUTO_PIN_SPEAKER_OUT;
4692                 } else if (cfg->hp_outs) {
4693                         cfg->line_outs = cfg->hp_outs;
4694                         memcpy(cfg->line_out_pins, cfg->hp_pins,
4695                                sizeof(cfg->hp_pins));
4696                         cfg->hp_outs = 0;
4697                         memset(cfg->hp_pins, 0, sizeof(cfg->hp_pins));
4698                         cfg->line_out_type = AUTO_PIN_HP_OUT;
4699                 }
4700         }
4701 
4702         /* Reorder the surround channels
4703          * ALSA sequence is front/surr/clfe/side
4704          * HDA sequence is:
4705          *    4-ch: front/surr  =>  OK as it is
4706          *    6-ch: front/clfe/surr
4707          *    8-ch: front/clfe/rear/side|fc
4708          */
4709         switch (cfg->line_outs) {
4710         case 3:
4711         case 4:
4712                 nid = cfg->line_out_pins[1];
4713                 cfg->line_out_pins[1] = cfg->line_out_pins[2];
4714                 cfg->line_out_pins[2] = nid;
4715                 break;
4716         }
4717 
4718         sort_autocfg_input_pins(cfg);
4719 
4720         /*
4721          * debug prints of the parsed results
4722          */
4723         snd_printd("autoconfig: line_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x) type:%s\n",
4724                    cfg->line_outs, cfg->line_out_pins[0], cfg->line_out_pins[1],
4725                    cfg->line_out_pins[2], cfg->line_out_pins[3],
4726                    cfg->line_out_pins[4],
4727                    cfg->line_out_type == AUTO_PIN_HP_OUT ? "hp" :
4728                    (cfg->line_out_type == AUTO_PIN_SPEAKER_OUT ?
4729                     "speaker" : "line"));
4730         snd_printd("   speaker_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x)\n",
4731                    cfg->speaker_outs, cfg->speaker_pins[0],
4732                    cfg->speaker_pins[1], cfg->speaker_pins[2],
4733                    cfg->speaker_pins[3], cfg->speaker_pins[4]);
4734         snd_printd("   hp_outs=%d (0x%x/0x%x/0x%x/0x%x/0x%x)\n",
4735                    cfg->hp_outs, cfg->hp_pins[0],
4736                    cfg->hp_pins[1], cfg->hp_pins[2],
4737                    cfg->hp_pins[3], cfg->hp_pins[4]);
4738         snd_printd("   mono: mono_out=0x%x\n", cfg->mono_out_pin);
4739         if (cfg->dig_outs)
4740                 snd_printd("   dig-out=0x%x/0x%x\n",
4741                            cfg->dig_out_pins[0], cfg->dig_out_pins[1]);
4742         snd_printd("   inputs:");
4743         for (i = 0; i < cfg->num_inputs; i++) {
4744                 snd_printd(" %s=0x%x",
4745                             hda_get_autocfg_input_label(codec, cfg, i),
4746                             cfg->inputs[i].pin);
4747         }
4748         snd_printd("\n");
4749         if (cfg->dig_in_pin)
4750                 snd_printd("   dig-in=0x%x\n", cfg->dig_in_pin);
4751 
4752         return 0;
4753 }
4754 EXPORT_SYMBOL_HDA(snd_hda_parse_pin_def_config);
4755 
4756 int snd_hda_get_input_pin_attr(unsigned int def_conf)
4757 {
4758         unsigned int loc = get_defcfg_location(def_conf);
4759         unsigned int conn = get_defcfg_connect(def_conf);
4760         if (conn == AC_JACK_PORT_NONE)
4761                 return INPUT_PIN_ATTR_UNUSED;
4762         /* Windows may claim the internal mic to be BOTH, too */
4763         if (conn == AC_JACK_PORT_FIXED || conn == AC_JACK_PORT_BOTH)
4764                 return INPUT_PIN_ATTR_INT;
4765         if ((loc & 0x30) == AC_JACK_LOC_INTERNAL)
4766                 return INPUT_PIN_ATTR_INT;
4767         if ((loc & 0x30) == AC_JACK_LOC_SEPARATE)
4768                 return INPUT_PIN_ATTR_DOCK;
4769         if (loc == AC_JACK_LOC_REAR)
4770                 return INPUT_PIN_ATTR_REAR;
4771         if (loc == AC_JACK_LOC_FRONT)
4772                 return INPUT_PIN_ATTR_FRONT;
4773         return INPUT_PIN_ATTR_NORMAL;
4774 }
4775 EXPORT_SYMBOL_HDA(snd_hda_get_input_pin_attr);
4776 
4777 /**
4778  * hda_get_input_pin_label - Give a label for the given input pin
4779  *
4780  * When check_location is true, the function checks the pin location
4781  * for mic and line-in pins, and set an appropriate prefix like "Front",
4782  * "Rear", "Internal".
4783  */
4784 
4785 const char *hda_get_input_pin_label(struct hda_codec *codec, hda_nid_t pin,
4786                                         int check_location)
4787 {
4788         unsigned int def_conf;
4789         static const char * const mic_names[] = {
4790                 "Internal Mic", "Dock Mic", "Mic", "Front Mic", "Rear Mic",
4791         };
4792         int attr;
4793 
4794         def_conf = snd_hda_codec_get_pincfg(codec, pin);
4795 
4796         switch (get_defcfg_device(def_conf)) {
4797         case AC_JACK_MIC_IN:
4798                 if (!check_location)
4799                         return "Mic";
4800                 attr = snd_hda_get_input_pin_attr(def_conf);
4801                 if (!attr)
4802                         return "None";
4803                 return mic_names[attr - 1];
4804         case AC_JACK_LINE_IN:
4805                 if (!check_location)
4806                         return "Line";
4807                 attr = snd_hda_get_input_pin_attr(def_conf);
4808                 if (!attr)
4809                         return "None";
4810                 if (attr == INPUT_PIN_ATTR_DOCK)
4811                         return "Dock Line";
4812                 return "Line";
4813         case AC_JACK_AUX:
4814                 return "Aux";
4815         case AC_JACK_CD:
4816                 return "CD";
4817         case AC_JACK_SPDIF_IN:
4818                 return "SPDIF In";
4819         case AC_JACK_DIG_OTHER_IN:
4820                 return "Digital In";
4821         default:
4822                 return "Misc";
4823         }
4824 }
4825 EXPORT_SYMBOL_HDA(hda_get_input_pin_label);
4826 
4827 /* Check whether the location prefix needs to be added to the label.
4828  * If all mic-jacks are in the same location (e.g. rear panel), we don't
4829  * have to put "Front" prefix to each label.  In such a case, returns false.
4830  */
4831 static int check_mic_location_need(struct hda_codec *codec,
4832                                    const struct auto_pin_cfg *cfg,
4833                                    int input)
4834 {
4835         unsigned int defc;
4836         int i, attr, attr2;
4837 
4838         defc = snd_hda_codec_get_pincfg(codec, cfg->inputs[input].pin);
4839         attr = snd_hda_get_input_pin_attr(defc);
4840         /* for internal or docking mics, we need locations */
4841         if (attr <= INPUT_PIN_ATTR_NORMAL)
4842                 return 1;
4843 
4844         attr = 0;
4845         for (i = 0; i < cfg->num_inputs; i++) {
4846                 defc = snd_hda_codec_get_pincfg(codec, cfg->inputs[i].pin);
4847                 attr2 = snd_hda_get_input_pin_attr(defc);
4848                 if (attr2 >= INPUT_PIN_ATTR_NORMAL) {
4849                         if (attr && attr != attr2)
4850                                 return 1; /* different locations found */
4851                         attr = attr2;
4852                 }
4853         }
4854         return 0;
4855 }
4856 
4857 /**
4858  * hda_get_autocfg_input_label - Get a label for the given input
4859  *
4860  * Get a label for the given input pin defined by the autocfg item.
4861  * Unlike hda_get_input_pin_label(), this function checks all inputs
4862  * defined in autocfg and avoids the redundant mic/line prefix as much as
4863  * possible.
4864  */
4865 const char *hda_get_autocfg_input_label(struct hda_codec *codec,
4866                                         const struct auto_pin_cfg *cfg,
4867                                         int input)
4868 {
4869         int type = cfg->inputs[input].type;
4870         int has_multiple_pins = 0;
4871 
4872         if ((input > 0 && cfg->inputs[input - 1].type == type) ||
4873             (input < cfg->num_inputs - 1 && cfg->inputs[input + 1].type == type))
4874                 has_multiple_pins = 1;
4875         if (has_multiple_pins && type == AUTO_PIN_MIC)
4876                 has_multiple_pins &= check_mic_location_need(codec, cfg, input);
4877         return hda_get_input_pin_label(codec, cfg->inputs[input].pin,
4878                                        has_multiple_pins);
4879 }
4880 EXPORT_SYMBOL_HDA(hda_get_autocfg_input_label);
4881 
4882 /**
4883  * snd_hda_add_imux_item - Add an item to input_mux
4884  *
4885  * When the same label is used already in the existing items, the number
4886  * suffix is appended to the label.  This label index number is stored
4887  * to type_idx when non-NULL pointer is given.
4888  */
4889 int snd_hda_add_imux_item(struct hda_input_mux *imux, const char *label,
4890                           int index, int *type_idx)
4891 {
4892         int i, label_idx = 0;
4893         if (imux->num_items >= HDA_MAX_NUM_INPUTS) {
4894                 snd_printd(KERN_ERR "hda_codec: Too many imux items!\n");
4895                 return -EINVAL;
4896         }
4897         for (i = 0; i < imux->num_items; i++) {
4898                 if (!strncmp(label, imux->items[i].label, strlen(label)))
4899                         label_idx++;
4900         }
4901         if (type_idx)
4902                 *type_idx = label_idx;
4903         if (label_idx > 0)
4904                 snprintf(imux->items[imux->num_items].label,
4905                          sizeof(imux->items[imux->num_items].label),
4906                          "%s %d", label, label_idx);
4907         else
4908                 strlcpy(imux->items[imux->num_items].label, label,
4909                         sizeof(imux->items[imux->num_items].label));
4910         imux->items[imux->num_items].index = index;
4911         imux->num_items++;
4912         return 0;
4913 }
4914 EXPORT_SYMBOL_HDA(snd_hda_add_imux_item);
4915 
4916 
4917 #ifdef CONFIG_PM
4918 /*
4919  * power management
4920  */
4921 
4922 /**
4923  * snd_hda_suspend - suspend the codecs
4924  * @bus: the HDA bus
4925  *
4926  * Returns 0 if successful.
4927  */
4928 int snd_hda_suspend(struct hda_bus *bus)
4929 {
4930         struct hda_codec *codec;
4931 
4932         list_for_each_entry(codec, &bus->codec_list, list) {
4933 #ifdef CONFIG_SND_HDA_POWER_SAVE
4934                 if (!codec->power_on)
4935                         continue;
4936 #endif
4937                 hda_call_codec_suspend(codec);
4938         }
4939         return 0;
4940 }
4941 EXPORT_SYMBOL_HDA(snd_hda_suspend);
4942 
4943 /**
4944  * snd_hda_resume - resume the codecs
4945  * @bus: the HDA bus
4946  *
4947  * Returns 0 if successful.
4948  *
4949  * This function is defined only when POWER_SAVE isn't set.
4950  * In the power-save mode, the codec is resumed dynamically.
4951  */
4952 int snd_hda_resume(struct hda_bus *bus)
4953 {
4954         struct hda_codec *codec;
4955 
4956         list_for_each_entry(codec, &bus->codec_list, list) {
4957                 if (snd_hda_codec_needs_resume(codec))
4958                         hda_call_codec_resume(codec);
4959         }
4960         return 0;
4961 }
4962 EXPORT_SYMBOL_HDA(snd_hda_resume);
4963 #endif /* CONFIG_PM */
4964 
4965 /*
4966  * generic arrays
4967  */
4968 
4969 /**
4970  * snd_array_new - get a new element from the given array
4971  * @array: the array object
4972  *
4973  * Get a new element from the given array.  If it exceeds the
4974  * pre-allocated array size, re-allocate the array.
4975  *
4976  * Returns NULL if allocation failed.
4977  */
4978 void *snd_array_new(struct snd_array *array)
4979 {
4980         if (array->used >= array->alloced) {
4981                 int num = array->alloced + array->alloc_align;
4982                 void *nlist;
4983                 if (snd_BUG_ON(num >= 4096))
4984                         return NULL;
4985                 nlist = kcalloc(num + 1, array->elem_size, GFP_KERNEL);
4986                 if (!nlist)
4987                         return NULL;
4988                 if (array->list) {
4989                         memcpy(nlist, array->list,
4990                                array->elem_size * array->alloced);
4991                         kfree(array->list);
4992                 }
4993                 array->list = nlist;
4994                 array->alloced = num;
4995         }
4996         return snd_array_elem(array, array->used++);
4997 }
4998 EXPORT_SYMBOL_HDA(snd_array_new);
4999 
5000 /**
5001  * snd_array_free - free the given array elements
5002  * @array: the array object
5003  */
5004 void snd_array_free(struct snd_array *array)
5005 {
5006         kfree(array->list);
5007         array->used = 0;
5008         array->alloced = 0;
5009         array->list = NULL;
5010 }
5011 EXPORT_SYMBOL_HDA(snd_array_free);
5012 
5013 /**
5014  * snd_print_pcm_rates - Print the supported PCM rates to the string buffer
5015  * @pcm: PCM caps bits
5016  * @buf: the string buffer to write
5017  * @buflen: the max buffer length
5018  *
5019  * used by hda_proc.c and hda_eld.c
5020  */
5021 void snd_print_pcm_rates(int pcm, char *buf, int buflen)
5022 {
5023         static unsigned int rates[] = {
5024                 8000, 11025, 16000, 22050, 32000, 44100, 48000, 88200,
5025                 96000, 176400, 192000, 384000
5026         };
5027         int i, j;
5028 
5029         for (i = 0, j = 0; i < ARRAY_SIZE(rates); i++)
5030                 if (pcm & (1 << i))
5031                         j += snprintf(buf + j, buflen - j,  " %d", rates[i]);
5032 
5033         buf[j] = '\0'; /* necessary when j == 0 */
5034 }
5035 EXPORT_SYMBOL_HDA(snd_print_pcm_rates);
5036 
5037 /**
5038  * snd_print_pcm_bits - Print the supported PCM fmt bits to the string buffer
5039  * @pcm: PCM caps bits
5040  * @buf: the string buffer to write
5041  * @buflen: the max buffer length
5042  *
5043  * used by hda_proc.c and hda_eld.c
5044  */
5045 void snd_print_pcm_bits(int pcm, char *buf, int buflen)
5046 {
5047         static unsigned int bits[] = { 8, 16, 20, 24, 32 };
5048         int i, j;
5049 
5050         for (i = 0, j = 0; i < ARRAY_SIZE(bits); i++)
5051                 if (pcm & (AC_SUPPCM_BITS_8 << i))
5052                         j += snprintf(buf + j, buflen - j,  " %d", bits[i]);
5053 
5054         buf[j] = '\0'; /* necessary when j == 0 */
5055 }
5056 EXPORT_SYMBOL_HDA(snd_print_pcm_bits);
5057 
5058 #ifdef CONFIG_SND_HDA_INPUT_JACK
5059 /*
5060  * Input-jack notification support
5061  */
5062 struct hda_jack_item {
5063         hda_nid_t nid;
5064         int type;
5065         struct snd_jack *jack;
5066 };
5067 
5068 static const char *get_jack_default_name(struct hda_codec *codec, hda_nid_t nid,
5069                                          int type)
5070 {
5071         switch (type) {
5072         case SND_JACK_HEADPHONE:
5073                 return "Headphone";
5074         case SND_JACK_MICROPHONE:
5075                 return "Mic";
5076         case SND_JACK_LINEOUT:
5077                 return "Line-out";
5078         case SND_JACK_HEADSET:
5079                 return "Headset";
5080         case SND_JACK_VIDEOOUT:
5081                 return "HDMI/DP";
5082         default:
5083                 return "Misc";
5084         }
5085 }
5086 
5087 static void hda_free_jack_priv(struct snd_jack *jack)
5088 {
5089         struct hda_jack_item *jacks = jack->private_data;
5090         jacks->nid = 0;
5091         jacks->jack = NULL;
5092 }
5093 
5094 int snd_hda_input_jack_add(struct hda_codec *codec, hda_nid_t nid, int type,
5095                            const char *name)
5096 {
5097         struct hda_jack_item *jack;
5098         int err;
5099 
5100         snd_array_init(&codec->jacks, sizeof(*jack), 32);
5101         jack = snd_array_new(&codec->jacks);
5102         if (!jack)
5103                 return -ENOMEM;
5104 
5105         jack->nid = nid;
5106         jack->type = type;
5107         if (!name)
5108                 name = get_jack_default_name(codec, nid, type);
5109         err = snd_jack_new(codec->bus->card, name, type, &jack->jack);
5110         if (err < 0) {
5111                 jack->nid = 0;
5112                 return err;
5113         }
5114         jack->jack->private_data = jack;
5115         jack->jack->private_free = hda_free_jack_priv;
5116         return 0;
5117 }
5118 EXPORT_SYMBOL_HDA(snd_hda_input_jack_add);
5119 
5120 void snd_hda_input_jack_report(struct hda_codec *codec, hda_nid_t nid)
5121 {
5122         struct hda_jack_item *jacks = codec->jacks.list;
5123         int i;
5124 
5125         if (!jacks)
5126                 return;
5127 
5128         for (i = 0; i < codec->jacks.used; i++, jacks++) {
5129                 unsigned int pin_ctl;
5130                 unsigned int present;
5131                 int type;
5132 
5133                 if (jacks->nid != nid)
5134                         continue;
5135                 present = snd_hda_jack_detect(codec, nid);
5136                 type = jacks->type;
5137                 if (type == (SND_JACK_HEADPHONE | SND_JACK_LINEOUT)) {
5138                         pin_ctl = snd_hda_codec_read(codec, nid, 0,
5139                                              AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
5140                         type = (pin_ctl & AC_PINCTL_HP_EN) ?
5141                                 SND_JACK_HEADPHONE : SND_JACK_LINEOUT;
5142                 }
5143                 snd_jack_report(jacks->jack, present ? type : 0);
5144         }
5145 }
5146 EXPORT_SYMBOL_HDA(snd_hda_input_jack_report);
5147 
5148 /* free jack instances manually when clearing/reconfiguring */
5149 void snd_hda_input_jack_free(struct hda_codec *codec)
5150 {
5151         if (!codec->bus->shutdown && codec->jacks.list) {
5152                 struct hda_jack_item *jacks = codec->jacks.list;
5153                 int i;
5154                 for (i = 0; i < codec->jacks.used; i++, jacks++) {
5155                         if (jacks->jack)
5156                                 snd_device_free(codec->bus->card, jacks->jack);
5157                 }
5158         }
5159         snd_array_free(&codec->jacks);
5160 }
5161 EXPORT_SYMBOL_HDA(snd_hda_input_jack_free);
5162 #endif /* CONFIG_SND_HDA_INPUT_JACK */
5163 
5164 MODULE_DESCRIPTION("HDA codec core");
5165 MODULE_LICENSE("GPL");
5166 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp