xref: /linux/sound/hda/core/device.c (revision eb6237f64909d54540267581967293f2d423bb4c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * HD-audio codec core device
4  */
5 
6 #include <linux/init.h>
7 #include <linux/delay.h>
8 #include <linux/device.h>
9 #include <linux/slab.h>
10 #include <linux/module.h>
11 #include <linux/export.h>
12 #include <linux/pm_runtime.h>
13 #include <sound/hdaudio.h>
14 #include <sound/hda_regmap.h>
15 #include <sound/pcm.h>
16 #include <sound/pcm_params.h>
17 #include "local.h"
18 
19 static void setup_fg_nodes(struct hdac_device *codec);
20 static int get_codec_vendor_name(struct hdac_device *codec);
21 
22 static void default_release(struct device *dev)
23 {
24 	snd_hdac_device_exit(dev_to_hdac_dev(dev));
25 }
26 
27 /**
28  * snd_hdac_device_init - initialize the HD-audio codec base device
29  * @codec: device to initialize
30  * @bus: but to attach
31  * @name: device name string
32  * @addr: codec address
33  *
34  * Returns zero for success or a negative error code.
35  *
36  * This function increments the runtime PM counter and marks it active.
37  * The caller needs to turn it off appropriately later.
38  *
39  * The caller needs to set the device's release op properly by itself.
40  */
41 int snd_hdac_device_init(struct hdac_device *codec, struct hdac_bus *bus,
42 			 const char *name, unsigned int addr)
43 {
44 	struct device *dev;
45 	hda_nid_t fg;
46 	int err;
47 
48 	dev = &codec->dev;
49 	device_initialize(dev);
50 	dev->parent = bus->dev;
51 	dev->bus = &snd_hda_bus_type;
52 	dev->release = default_release;
53 	dev->groups = hdac_dev_attr_groups;
54 	dev_set_name(dev, "%s", name);
55 	device_enable_async_suspend(dev);
56 
57 	codec->bus = bus;
58 	codec->addr = addr;
59 	codec->type = HDA_DEV_CORE;
60 	mutex_init(&codec->widget_lock);
61 	mutex_init(&codec->regmap_lock);
62 	pm_runtime_set_active(&codec->dev);
63 	pm_runtime_get_noresume(&codec->dev);
64 	atomic_set(&codec->in_pm, 0);
65 
66 	err = snd_hdac_bus_add_device(bus, codec);
67 	if (err < 0)
68 		goto error;
69 
70 	/* fill parameters */
71 	codec->vendor_id = snd_hdac_read_parm(codec, AC_NODE_ROOT,
72 					      AC_PAR_VENDOR_ID);
73 	if (codec->vendor_id == -1) {
74 		/* read again, hopefully the access method was corrected
75 		 * in the last read...
76 		 */
77 		codec->vendor_id = snd_hdac_read_parm(codec, AC_NODE_ROOT,
78 						      AC_PAR_VENDOR_ID);
79 	}
80 
81 	codec->subsystem_id = snd_hdac_read_parm(codec, AC_NODE_ROOT,
82 						 AC_PAR_SUBSYSTEM_ID);
83 	codec->revision_id = snd_hdac_read_parm(codec, AC_NODE_ROOT,
84 						AC_PAR_REV_ID);
85 
86 	setup_fg_nodes(codec);
87 	if (!codec->afg && !codec->mfg) {
88 		dev_err(dev, "no AFG or MFG node found\n");
89 		err = -ENODEV;
90 		goto error;
91 	}
92 
93 	fg = codec->afg ? codec->afg : codec->mfg;
94 
95 	err = snd_hdac_refresh_widgets(codec);
96 	if (err < 0)
97 		goto error;
98 
99 	codec->power_caps = snd_hdac_read_parm(codec, fg, AC_PAR_POWER_STATE);
100 	/* reread ssid if not set by parameter */
101 	if (codec->subsystem_id == -1 || codec->subsystem_id == 0)
102 		snd_hdac_read(codec, fg, AC_VERB_GET_SUBSYSTEM_ID, 0,
103 			      &codec->subsystem_id);
104 
105 	err = get_codec_vendor_name(codec);
106 	if (err < 0)
107 		goto error;
108 
109 	codec->chip_name = kasprintf(GFP_KERNEL, "ID %x",
110 				     codec->vendor_id & 0xffff);
111 	if (!codec->chip_name) {
112 		err = -ENOMEM;
113 		goto error;
114 	}
115 
116 	return 0;
117 
118  error:
119 	put_device(&codec->dev);
120 	return err;
121 }
122 EXPORT_SYMBOL_GPL(snd_hdac_device_init);
123 
124 /**
125  * snd_hdac_device_exit - clean up the HD-audio codec base device
126  * @codec: device to clean up
127  */
128 void snd_hdac_device_exit(struct hdac_device *codec)
129 {
130 	pm_runtime_put_noidle(&codec->dev);
131 	/* keep balance of runtime PM child_count in parent device */
132 	pm_runtime_set_suspended(&codec->dev);
133 	snd_hdac_bus_remove_device(codec->bus, codec);
134 	kfree(codec->vendor_name);
135 	kfree(codec->chip_name);
136 }
137 EXPORT_SYMBOL_GPL(snd_hdac_device_exit);
138 
139 /**
140  * snd_hdac_device_register - register the hd-audio codec base device
141  * @codec: the device to register
142  */
143 int snd_hdac_device_register(struct hdac_device *codec)
144 {
145 	int err;
146 
147 	err = device_add(&codec->dev);
148 	if (err < 0)
149 		return err;
150 	scoped_guard(mutex, &codec->widget_lock) {
151 		err = hda_widget_sysfs_init(codec);
152 	}
153 	if (err < 0) {
154 		device_del(&codec->dev);
155 		return err;
156 	}
157 
158 	return 0;
159 }
160 EXPORT_SYMBOL_GPL(snd_hdac_device_register);
161 
162 /**
163  * snd_hdac_device_unregister - unregister the hd-audio codec base device
164  * @codec: the device to unregister
165  */
166 void snd_hdac_device_unregister(struct hdac_device *codec)
167 {
168 	if (device_is_registered(&codec->dev)) {
169 		scoped_guard(mutex, &codec->widget_lock) {
170 			hda_widget_sysfs_exit(codec);
171 		}
172 		device_del(&codec->dev);
173 		snd_hdac_bus_remove_device(codec->bus, codec);
174 	}
175 }
176 EXPORT_SYMBOL_GPL(snd_hdac_device_unregister);
177 
178 /**
179  * snd_hdac_device_set_chip_name - set/update the codec name
180  * @codec: the HDAC device
181  * @name: name string to set
182  *
183  * Returns 0 if the name is set or updated, or a negative error code.
184  */
185 int snd_hdac_device_set_chip_name(struct hdac_device *codec, const char *name)
186 {
187 	char *newname;
188 
189 	if (!name)
190 		return 0;
191 	newname = kstrdup(name, GFP_KERNEL);
192 	if (!newname)
193 		return -ENOMEM;
194 	kfree(codec->chip_name);
195 	codec->chip_name = newname;
196 	return 0;
197 }
198 EXPORT_SYMBOL_GPL(snd_hdac_device_set_chip_name);
199 
200 /**
201  * snd_hdac_codec_modalias - give the module alias name
202  * @codec: HDAC device
203  * @buf: string buffer to store
204  * @size: string buffer size
205  *
206  * Returns the size of string, like snprintf(), or a negative error code.
207  */
208 int snd_hdac_codec_modalias(const struct hdac_device *codec, char *buf, size_t size)
209 {
210 	return scnprintf(buf, size, "hdaudio:v%08Xr%08Xa%02X\n",
211 			codec->vendor_id, codec->revision_id, codec->type);
212 }
213 EXPORT_SYMBOL_GPL(snd_hdac_codec_modalias);
214 
215 /**
216  * snd_hdac_make_cmd - compose a 32bit command word to be sent to the
217  *	HD-audio controller
218  * @codec: the codec object
219  * @nid: NID to encode
220  * @verb: verb to encode
221  * @parm: parameter to encode
222  *
223  * Return an encoded command verb or -1 for error.
224  */
225 static unsigned int snd_hdac_make_cmd(struct hdac_device *codec, hda_nid_t nid,
226 				      unsigned int verb, unsigned int parm)
227 {
228 	u32 val, addr;
229 
230 	addr = codec->addr;
231 	if ((addr & ~0xf) || (nid & ~0x7f) ||
232 	    (verb & ~0xfff) || (parm & ~0xffff)) {
233 		dev_err(&codec->dev, "out of range cmd %x:%x:%x:%x\n",
234 			addr, nid, verb, parm);
235 		return -1;
236 	}
237 
238 	val = addr << 28;
239 	val |= (u32)nid << 20;
240 	val |= verb << 8;
241 	val |= parm;
242 	return val;
243 }
244 
245 /**
246  * snd_hdac_exec_verb - execute an encoded verb
247  * @codec: the codec object
248  * @cmd: encoded verb to execute
249  * @flags: optional flags, pass zero for default
250  * @res: the pointer to store the result, NULL if running async
251  *
252  * Returns zero if successful, or a negative error code.
253  *
254  * This calls the exec_verb op when set in hdac_codec.  If not,
255  * call the default snd_hdac_bus_exec_verb().
256  */
257 int snd_hdac_exec_verb(struct hdac_device *codec, unsigned int cmd,
258 		       unsigned int flags, unsigned int *res)
259 {
260 	if (codec->exec_verb)
261 		return codec->exec_verb(codec, cmd, flags, res);
262 	return snd_hdac_bus_exec_verb(codec->bus, codec->addr, cmd, res);
263 }
264 
265 
266 /**
267  * snd_hdac_read - execute a verb
268  * @codec: the codec object
269  * @nid: NID to execute a verb
270  * @verb: verb to execute
271  * @parm: parameter for a verb
272  * @res: the pointer to store the result, NULL if running async
273  *
274  * Returns zero if successful, or a negative error code.
275  */
276 int snd_hdac_read(struct hdac_device *codec, hda_nid_t nid,
277 		  unsigned int verb, unsigned int parm, unsigned int *res)
278 {
279 	unsigned int cmd = snd_hdac_make_cmd(codec, nid, verb, parm);
280 
281 	return snd_hdac_exec_verb(codec, cmd, 0, res);
282 }
283 EXPORT_SYMBOL_GPL(snd_hdac_read);
284 
285 /**
286  * _snd_hdac_read_parm - read a parmeter
287  * @codec: the codec object
288  * @nid: NID to read a parameter
289  * @parm: parameter to read
290  * @res: pointer to store the read value
291  *
292  * This function returns zero or an error unlike snd_hdac_read_parm().
293  */
294 int _snd_hdac_read_parm(struct hdac_device *codec, hda_nid_t nid, int parm,
295 			unsigned int *res)
296 {
297 	unsigned int cmd;
298 
299 	cmd = snd_hdac_regmap_encode_verb(nid, AC_VERB_PARAMETERS) | parm;
300 	return snd_hdac_regmap_read_raw(codec, cmd, res);
301 }
302 EXPORT_SYMBOL_GPL(_snd_hdac_read_parm);
303 
304 /**
305  * snd_hdac_read_parm_uncached - read a codec parameter without caching
306  * @codec: the codec object
307  * @nid: NID to read a parameter
308  * @parm: parameter to read
309  *
310  * Returns -1 for error.  If you need to distinguish the error more
311  * strictly, use snd_hdac_read() directly.
312  */
313 int snd_hdac_read_parm_uncached(struct hdac_device *codec, hda_nid_t nid,
314 				int parm)
315 {
316 	unsigned int cmd, val;
317 
318 	cmd = snd_hdac_regmap_encode_verb(nid, AC_VERB_PARAMETERS) | parm;
319 	if (snd_hdac_regmap_read_raw_uncached(codec, cmd, &val) < 0)
320 		return -1;
321 	return val;
322 }
323 EXPORT_SYMBOL_GPL(snd_hdac_read_parm_uncached);
324 
325 /**
326  * snd_hdac_override_parm - override read-only parameters
327  * @codec: the codec object
328  * @nid: NID for the parameter
329  * @parm: the parameter to change
330  * @val: the parameter value to overwrite
331  */
332 int snd_hdac_override_parm(struct hdac_device *codec, hda_nid_t nid,
333 			   unsigned int parm, unsigned int val)
334 {
335 	unsigned int verb = (AC_VERB_PARAMETERS << 8) | (nid << 20) | parm;
336 	int err;
337 
338 	if (!codec->regmap)
339 		return -EINVAL;
340 
341 	codec->caps_overwriting = true;
342 	err = snd_hdac_regmap_write_raw(codec, verb, val);
343 	codec->caps_overwriting = false;
344 	return err;
345 }
346 EXPORT_SYMBOL_GPL(snd_hdac_override_parm);
347 
348 /**
349  * snd_hdac_get_sub_nodes - get start NID and number of subtree nodes
350  * @codec: the codec object
351  * @nid: NID to inspect
352  * @start_id: the pointer to store the starting NID
353  *
354  * Returns the number of subtree nodes or zero if not found.
355  * This function reads parameters always without caching.
356  */
357 int snd_hdac_get_sub_nodes(struct hdac_device *codec, hda_nid_t nid,
358 			   hda_nid_t *start_id)
359 {
360 	unsigned int parm;
361 
362 	parm = snd_hdac_read_parm_uncached(codec, nid, AC_PAR_NODE_COUNT);
363 	if (parm == -1) {
364 		*start_id = 0;
365 		return 0;
366 	}
367 	*start_id = (parm >> 16) & 0x7fff;
368 	return (int)(parm & 0x7fff);
369 }
370 EXPORT_SYMBOL_GPL(snd_hdac_get_sub_nodes);
371 
372 /*
373  * look for an AFG and MFG nodes
374  */
375 static void setup_fg_nodes(struct hdac_device *codec)
376 {
377 	int i, total_nodes, function_id;
378 	hda_nid_t nid;
379 
380 	total_nodes = snd_hdac_get_sub_nodes(codec, AC_NODE_ROOT, &nid);
381 	for (i = 0; i < total_nodes; i++, nid++) {
382 		function_id = snd_hdac_read_parm(codec, nid,
383 						 AC_PAR_FUNCTION_TYPE);
384 		switch (function_id & 0xff) {
385 		case AC_GRP_AUDIO_FUNCTION:
386 			codec->afg = nid;
387 			codec->afg_function_id = function_id & 0xff;
388 			codec->afg_unsol = (function_id >> 8) & 1;
389 			break;
390 		case AC_GRP_MODEM_FUNCTION:
391 			codec->mfg = nid;
392 			codec->mfg_function_id = function_id & 0xff;
393 			codec->mfg_unsol = (function_id >> 8) & 1;
394 			break;
395 		default:
396 			break;
397 		}
398 	}
399 }
400 
401 /**
402  * snd_hdac_refresh_widgets - Reset the widget start/end nodes
403  * @codec: the codec object
404  */
405 int snd_hdac_refresh_widgets(struct hdac_device *codec)
406 {
407 	hda_nid_t fg = codec->afg ? codec->afg : codec->mfg;
408 	hda_nid_t start_nid;
409 	int nums, err = 0;
410 
411 	/*
412 	 * Serialize against multiple threads trying to update the sysfs
413 	 * widgets array.
414 	 */
415 	guard(mutex)(&codec->widget_lock);
416 	nums = snd_hdac_get_sub_nodes(codec, fg, &start_nid);
417 	if (!start_nid || nums <= 0 || nums >= 0xff) {
418 		dev_err(&codec->dev, "cannot read sub nodes for FG 0x%02x\n",
419 			fg);
420 		return -EINVAL;
421 	}
422 
423 	err = hda_widget_sysfs_reinit(codec, start_nid, nums);
424 	if (err < 0)
425 		return err;
426 
427 	codec->num_nodes = nums;
428 	codec->start_nid = start_nid;
429 	codec->end_nid = start_nid + nums;
430 	return 0;
431 }
432 EXPORT_SYMBOL_GPL(snd_hdac_refresh_widgets);
433 
434 /* return CONNLIST_LEN parameter of the given widget */
435 static unsigned int get_num_conns(struct hdac_device *codec, hda_nid_t nid)
436 {
437 	unsigned int wcaps = snd_hdac_get_wcaps(codec, nid);
438 	unsigned int parm;
439 
440 	if (!(wcaps & AC_WCAP_CONN_LIST) &&
441 	    snd_hdac_get_wcaps_type(wcaps) != AC_WID_VOL_KNB)
442 		return 0;
443 
444 	parm = snd_hdac_read_parm(codec, nid, AC_PAR_CONNLIST_LEN);
445 	if (parm == -1)
446 		parm = 0;
447 	return parm;
448 }
449 
450 /**
451  * snd_hdac_get_connections - get a widget connection list
452  * @codec: the codec object
453  * @nid: NID
454  * @conn_list: the array to store the results, can be NULL
455  * @max_conns: the max size of the given array
456  *
457  * Returns the number of connected widgets, zero for no connection, or a
458  * negative error code.  When the number of elements don't fit with the
459  * given array size, it returns -ENOSPC.
460  *
461  * When @conn_list is NULL, it just checks the number of connections.
462  */
463 int snd_hdac_get_connections(struct hdac_device *codec, hda_nid_t nid,
464 			     hda_nid_t *conn_list, int max_conns)
465 {
466 	unsigned int parm;
467 	int i, conn_len, conns, err;
468 	unsigned int shift, num_elems, mask;
469 	hda_nid_t prev_nid;
470 	int null_count = 0;
471 
472 	parm = get_num_conns(codec, nid);
473 	if (!parm)
474 		return 0;
475 
476 	if (parm & AC_CLIST_LONG) {
477 		/* long form */
478 		shift = 16;
479 		num_elems = 2;
480 	} else {
481 		/* short form */
482 		shift = 8;
483 		num_elems = 4;
484 	}
485 	conn_len = parm & AC_CLIST_LENGTH;
486 	mask = (1 << (shift-1)) - 1;
487 
488 	if (!conn_len)
489 		return 0; /* no connection */
490 
491 	if (conn_len == 1) {
492 		/* single connection */
493 		err = snd_hdac_read(codec, nid, AC_VERB_GET_CONNECT_LIST, 0,
494 				    &parm);
495 		if (err < 0)
496 			return err;
497 		if (conn_list)
498 			conn_list[0] = parm & mask;
499 		return 1;
500 	}
501 
502 	/* multi connection */
503 	conns = 0;
504 	prev_nid = 0;
505 	for (i = 0; i < conn_len; i++) {
506 		int range_val;
507 		hda_nid_t val, n;
508 
509 		if (i % num_elems == 0) {
510 			err = snd_hdac_read(codec, nid,
511 					    AC_VERB_GET_CONNECT_LIST, i,
512 					    &parm);
513 			if (err < 0)
514 				return -EIO;
515 		}
516 		range_val = !!(parm & (1 << (shift-1))); /* ranges */
517 		val = parm & mask;
518 		if (val == 0 && null_count++) {  /* no second chance */
519 			dev_dbg(&codec->dev,
520 				"invalid CONNECT_LIST verb %x[%i]:%x\n",
521 				nid, i, parm);
522 			return 0;
523 		}
524 		parm >>= shift;
525 		if (range_val) {
526 			/* ranges between the previous and this one */
527 			if (!prev_nid || prev_nid >= val) {
528 				dev_warn(&codec->dev,
529 					 "invalid dep_range_val %x:%x\n",
530 					 prev_nid, val);
531 				continue;
532 			}
533 			for (n = prev_nid + 1; n <= val; n++) {
534 				if (conn_list) {
535 					if (conns >= max_conns)
536 						return -ENOSPC;
537 					conn_list[conns] = n;
538 				}
539 				conns++;
540 			}
541 		} else {
542 			if (conn_list) {
543 				if (conns >= max_conns)
544 					return -ENOSPC;
545 				conn_list[conns] = val;
546 			}
547 			conns++;
548 		}
549 		prev_nid = val;
550 	}
551 	return conns;
552 }
553 EXPORT_SYMBOL_GPL(snd_hdac_get_connections);
554 
555 #ifdef CONFIG_PM
556 /**
557  * snd_hdac_power_up - power up the codec
558  * @codec: the codec object
559  *
560  * This function calls the runtime PM helper to power up the given codec.
561  * Unlike snd_hdac_power_up_pm(), you should call this only for the code
562  * path that isn't included in PM path.  Otherwise it gets stuck.
563  *
564  * Returns zero if successful, or a negative error code.
565  */
566 int snd_hdac_power_up(struct hdac_device *codec)
567 {
568 	return pm_runtime_get_sync(&codec->dev);
569 }
570 EXPORT_SYMBOL_GPL(snd_hdac_power_up);
571 
572 /**
573  * snd_hdac_power_down - power down the codec
574  * @codec: the codec object
575  */
576 void snd_hdac_power_down(struct hdac_device *codec)
577 {
578 	struct device *dev = &codec->dev;
579 
580 	pm_runtime_put_autosuspend(dev);
581 }
582 EXPORT_SYMBOL_GPL(snd_hdac_power_down);
583 
584 /**
585  * snd_hdac_power_up_pm - power up the codec
586  * @codec: the codec object
587  *
588  * This function can be called in a recursive code path like init code
589  * which may be called by PM suspend/resume again.  OTOH, if a power-up
590  * call must wake up the sleeper (e.g. in a kctl callback), use
591  * snd_hdac_power_up() instead.
592  *
593  * Returns zero if successful, or a negative error code.
594  */
595 int snd_hdac_power_up_pm(struct hdac_device *codec)
596 {
597 	if (!atomic_inc_not_zero(&codec->in_pm))
598 		return snd_hdac_power_up(codec);
599 	return 0;
600 }
601 EXPORT_SYMBOL_GPL(snd_hdac_power_up_pm);
602 
603 /* like snd_hdac_power_up_pm(), but only increment the pm count when
604  * already powered up.  Returns -1 if not powered up, 1 if incremented
605  * or 0 if unchanged.  Only used in hdac_regmap.c
606  */
607 int snd_hdac_keep_power_up(struct hdac_device *codec)
608 {
609 	if (!atomic_inc_not_zero(&codec->in_pm)) {
610 		int ret = pm_runtime_get_if_active(&codec->dev);
611 		if (!ret)
612 			return -1;
613 		if (ret < 0)
614 			return 0;
615 	}
616 	return 1;
617 }
618 
619 /**
620  * snd_hdac_power_down_pm - power down the codec
621  * @codec: the codec object
622  *
623  * Like snd_hdac_power_up_pm(), this function is used in a recursive
624  * code path like init code which may be called by PM suspend/resume again.
625  */
626 void snd_hdac_power_down_pm(struct hdac_device *codec)
627 {
628 	if (atomic_dec_if_positive(&codec->in_pm) < 0)
629 		snd_hdac_power_down(codec);
630 }
631 EXPORT_SYMBOL_GPL(snd_hdac_power_down_pm);
632 #endif
633 
634 /* codec vendor labels */
635 struct hda_vendor_id {
636 	unsigned int id;
637 	const char *name;
638 };
639 
640 static const struct hda_vendor_id hda_vendor_ids[] = {
641 	{ 0x0014, "Loongson" },
642 	{ 0x1002, "ATI" },
643 	{ 0x1013, "Cirrus Logic" },
644 	{ 0x1057, "Motorola" },
645 	{ 0x1095, "Silicon Image" },
646 	{ 0x10de, "Nvidia" },
647 	{ 0x10ec, "Realtek" },
648 	{ 0x1102, "Creative" },
649 	{ 0x1106, "VIA" },
650 	{ 0x111d, "IDT" },
651 	{ 0x11c1, "LSI" },
652 	{ 0x11d4, "Analog Devices" },
653 	{ 0x13f6, "C-Media" },
654 	{ 0x14f1, "Conexant" },
655 	{ 0x17e8, "Chrontel" },
656 	{ 0x1854, "LG" },
657 	{ 0x19e5, "Huawei" },
658 	{ 0x1aec, "Wolfson Microelectronics" },
659 	{ 0x1af4, "QEMU" },
660 	{ 0x1fa8, "Senarytech" },
661 	{ 0x434d, "C-Media" },
662 	{ 0x4c54, "Lisuan" },
663 	{ 0x8086, "Intel" },
664 	{ 0x8384, "SigmaTel" },
665 	{} /* terminator */
666 };
667 
668 /* store the codec vendor name */
669 static int get_codec_vendor_name(struct hdac_device *codec)
670 {
671 	const struct hda_vendor_id *c;
672 	u16 vendor_id = codec->vendor_id >> 16;
673 
674 	for (c = hda_vendor_ids; c->id; c++) {
675 		if (c->id == vendor_id) {
676 			codec->vendor_name = kstrdup(c->name, GFP_KERNEL);
677 			return codec->vendor_name ? 0 : -ENOMEM;
678 		}
679 	}
680 
681 	codec->vendor_name = kasprintf(GFP_KERNEL, "Generic %04x", vendor_id);
682 	return codec->vendor_name ? 0 : -ENOMEM;
683 }
684 
685 /*
686  * stream formats
687  */
688 struct hda_rate_tbl {
689 	unsigned int hz;
690 	unsigned int alsa_bits;
691 	unsigned int hda_fmt;
692 };
693 
694 /* rate = base * mult / div */
695 #define HDA_RATE(base, mult, div) \
696 	(AC_FMT_BASE_##base##K | (((mult) - 1) << AC_FMT_MULT_SHIFT) | \
697 	 (((div) - 1) << AC_FMT_DIV_SHIFT))
698 
699 static const struct hda_rate_tbl rate_bits[] = {
700 	/* rate in Hz, ALSA rate bitmask, HDA format value */
701 
702 	/* autodetected value used in snd_hda_query_supported_pcm */
703 	{ 8000, SNDRV_PCM_RATE_8000, HDA_RATE(48, 1, 6) },
704 	{ 11025, SNDRV_PCM_RATE_11025, HDA_RATE(44, 1, 4) },
705 	{ 16000, SNDRV_PCM_RATE_16000, HDA_RATE(48, 1, 3) },
706 	{ 22050, SNDRV_PCM_RATE_22050, HDA_RATE(44, 1, 2) },
707 	{ 32000, SNDRV_PCM_RATE_32000, HDA_RATE(48, 2, 3) },
708 	{ 44100, SNDRV_PCM_RATE_44100, HDA_RATE(44, 1, 1) },
709 	{ 48000, SNDRV_PCM_RATE_48000, HDA_RATE(48, 1, 1) },
710 	{ 88200, SNDRV_PCM_RATE_88200, HDA_RATE(44, 2, 1) },
711 	{ 96000, SNDRV_PCM_RATE_96000, HDA_RATE(48, 2, 1) },
712 	{ 176400, SNDRV_PCM_RATE_176400, HDA_RATE(44, 4, 1) },
713 	{ 192000, SNDRV_PCM_RATE_192000, HDA_RATE(48, 4, 1) },
714 #define AC_PAR_PCM_RATE_BITS	11
715 	/* up to bits 10, 384kHZ isn't supported properly */
716 
717 	/* not autodetected value */
718 	{ 9600, SNDRV_PCM_RATE_KNOT, HDA_RATE(48, 1, 5) },
719 
720 	{ 0 } /* terminator */
721 };
722 
723 static snd_pcm_format_t snd_hdac_format_normalize(snd_pcm_format_t format)
724 {
725 	switch (format) {
726 	case SNDRV_PCM_FORMAT_S20_LE:
727 	case SNDRV_PCM_FORMAT_S24_LE:
728 		return SNDRV_PCM_FORMAT_S32_LE;
729 
730 	case SNDRV_PCM_FORMAT_U20_LE:
731 	case SNDRV_PCM_FORMAT_U24_LE:
732 		return SNDRV_PCM_FORMAT_U32_LE;
733 
734 	case SNDRV_PCM_FORMAT_S20_BE:
735 	case SNDRV_PCM_FORMAT_S24_BE:
736 		return SNDRV_PCM_FORMAT_S32_BE;
737 
738 	case SNDRV_PCM_FORMAT_U20_BE:
739 	case SNDRV_PCM_FORMAT_U24_BE:
740 		return SNDRV_PCM_FORMAT_U32_BE;
741 
742 	default:
743 		return format;
744 	}
745 }
746 
747 /**
748  * snd_hdac_stream_format_bits - obtain bits per sample value.
749  * @format:	the PCM format.
750  * @subformat:	the PCM subformat.
751  * @maxbits:	the maximum bits per sample.
752  *
753  * Return: The number of bits per sample.
754  */
755 unsigned int snd_hdac_stream_format_bits(snd_pcm_format_t format, snd_pcm_subformat_t subformat,
756 					 unsigned int maxbits)
757 {
758 	struct snd_pcm_hw_params params;
759 	unsigned int bits;
760 
761 	memset(&params, 0, sizeof(params));
762 
763 	params_set_format(&params, snd_hdac_format_normalize(format));
764 	snd_mask_set(hw_param_mask(&params, SNDRV_PCM_HW_PARAM_SUBFORMAT),
765 		     subformat);
766 
767 	bits = snd_pcm_hw_params_bits(&params);
768 	if (maxbits)
769 		return min(bits, maxbits);
770 	return bits;
771 }
772 EXPORT_SYMBOL_GPL(snd_hdac_stream_format_bits);
773 
774 /**
775  * snd_hdac_stream_format - convert format parameters to SDxFMT value.
776  * @channels:	the number of channels.
777  * @bits:	bits per sample.
778  * @rate:	the sample rate.
779  *
780  * Return: The format bitset or zero if invalid.
781  */
782 unsigned int snd_hdac_stream_format(unsigned int channels, unsigned int bits, unsigned int rate)
783 {
784 	unsigned int val = 0;
785 	int i;
786 
787 	for (i = 0; rate_bits[i].hz; i++) {
788 		if (rate_bits[i].hz == rate) {
789 			val = rate_bits[i].hda_fmt;
790 			break;
791 		}
792 	}
793 
794 	if (!rate_bits[i].hz)
795 		return 0;
796 
797 	if (channels == 0 || channels > 16)
798 		return 0;
799 	val |= channels - 1;
800 
801 	switch (bits) {
802 	case 8:
803 		val |= AC_FMT_BITS_8;
804 		break;
805 	case 16:
806 		val |= AC_FMT_BITS_16;
807 		break;
808 	case 20:
809 		val |= AC_FMT_BITS_20;
810 		break;
811 	case 24:
812 		val |= AC_FMT_BITS_24;
813 		break;
814 	case 32:
815 		val |= AC_FMT_BITS_32;
816 		break;
817 	default:
818 		return 0;
819 	}
820 
821 	return val;
822 }
823 EXPORT_SYMBOL_GPL(snd_hdac_stream_format);
824 
825 /**
826  * snd_hdac_spdif_stream_format - convert format parameters to SDxFMT value.
827  * @channels:	the number of channels.
828  * @bits:	bits per sample.
829  * @rate:	the sample rate.
830  * @spdif_ctls:	HD-audio SPDIF status bits (0 if irrelevant).
831  *
832  * Return: The format bitset or zero if invalid.
833  */
834 unsigned int snd_hdac_spdif_stream_format(unsigned int channels, unsigned int bits,
835 					  unsigned int rate, unsigned short spdif_ctls)
836 {
837 	unsigned int val = snd_hdac_stream_format(channels, bits, rate);
838 
839 	if (val && spdif_ctls & AC_DIG1_NONAUDIO)
840 		val |= AC_FMT_TYPE_NON_PCM;
841 
842 	return val;
843 }
844 EXPORT_SYMBOL_GPL(snd_hdac_spdif_stream_format);
845 
846 static unsigned int query_pcm_param(struct hdac_device *codec, hda_nid_t nid)
847 {
848 	unsigned int val = 0;
849 
850 	if (nid != codec->afg &&
851 	    (snd_hdac_get_wcaps(codec, nid) & AC_WCAP_FORMAT_OVRD))
852 		val = snd_hdac_read_parm(codec, nid, AC_PAR_PCM);
853 	if (!val || val == -1)
854 		val = snd_hdac_read_parm(codec, codec->afg, AC_PAR_PCM);
855 	if (!val || val == -1)
856 		return 0;
857 	return val;
858 }
859 
860 static unsigned int query_stream_param(struct hdac_device *codec, hda_nid_t nid)
861 {
862 	unsigned int streams = snd_hdac_read_parm(codec, nid, AC_PAR_STREAM);
863 
864 	if (!streams || streams == -1)
865 		streams = snd_hdac_read_parm(codec, codec->afg, AC_PAR_STREAM);
866 	if (!streams || streams == -1)
867 		return 0;
868 	return streams;
869 }
870 
871 /**
872  * snd_hdac_query_supported_pcm - query the supported PCM rates and formats
873  * @codec: the codec object
874  * @nid: NID to query
875  * @ratesp: the pointer to store the detected rate bitflags
876  * @formatsp: the pointer to store the detected formats
877  * @subformatsp: the pointer to store the detected subformats for S32_LE format
878  * @bpsp: the pointer to store the detected format widths
879  *
880  * Queries the supported PCM rates and formats.  The NULL @ratesp, @formatsp,
881  * @subformatsp or @bpsp argument is ignored.
882  *
883  * Returns 0 if successful, otherwise a negative error code.
884  */
885 int snd_hdac_query_supported_pcm(struct hdac_device *codec, hda_nid_t nid,
886 				 u32 *ratesp, u64 *formatsp, u32 *subformatsp,
887 				 unsigned int *bpsp)
888 {
889 	unsigned int i, val, wcaps;
890 
891 	wcaps = snd_hdac_get_wcaps(codec, nid);
892 	val = query_pcm_param(codec, nid);
893 
894 	if (ratesp) {
895 		u32 rates = 0;
896 		for (i = 0; i < AC_PAR_PCM_RATE_BITS; i++) {
897 			if (val & (1 << i))
898 				rates |= rate_bits[i].alsa_bits;
899 		}
900 		if (rates == 0) {
901 			dev_err(&codec->dev,
902 				"rates == 0 (nid=0x%x, val=0x%x, ovrd=%i)\n",
903 				nid, val,
904 				(wcaps & AC_WCAP_FORMAT_OVRD) ? 1 : 0);
905 			return -EIO;
906 		}
907 		*ratesp = rates;
908 	}
909 
910 	if (formatsp || subformatsp || bpsp) {
911 		unsigned int streams, bps;
912 		u32 subformats = 0;
913 		u64 formats = 0;
914 
915 		streams = query_stream_param(codec, nid);
916 		if (!streams)
917 			return -EIO;
918 
919 		bps = 0;
920 		if (streams & AC_SUPFMT_PCM) {
921 			if (val & AC_SUPPCM_BITS_8) {
922 				formats |= SNDRV_PCM_FMTBIT_U8;
923 				bps = 8;
924 			}
925 			if (val & AC_SUPPCM_BITS_16) {
926 				formats |= SNDRV_PCM_FMTBIT_S16_LE;
927 				bps = 16;
928 			}
929 			if (val & AC_SUPPCM_BITS_20) {
930 				formats |= SNDRV_PCM_FMTBIT_S32_LE;
931 				subformats |= SNDRV_PCM_SUBFMTBIT_MSBITS_20;
932 				bps = 20;
933 			}
934 			if (val & AC_SUPPCM_BITS_24) {
935 				formats |= SNDRV_PCM_FMTBIT_S32_LE;
936 				subformats |= SNDRV_PCM_SUBFMTBIT_MSBITS_24;
937 				bps = 24;
938 			}
939 			if (val & AC_SUPPCM_BITS_32) {
940 				if (wcaps & AC_WCAP_DIGITAL) {
941 					formats |= SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE;
942 				} else {
943 					formats |= SNDRV_PCM_FMTBIT_S32_LE;
944 					subformats |= SNDRV_PCM_SUBFMTBIT_MSBITS_MAX;
945 					bps = 32;
946 				}
947 			}
948 		}
949 #if 0 /* FIXME: CS4206 doesn't work, which is the only codec supporting float */
950 		if (streams & AC_SUPFMT_FLOAT32) {
951 			formats |= SNDRV_PCM_FMTBIT_FLOAT_LE;
952 			if (!bps)
953 				bps = 32;
954 		}
955 #endif
956 		if (streams == AC_SUPFMT_AC3) {
957 			/* should be exclusive */
958 			/* temporary hack: we have still no proper support
959 			 * for the direct AC3 stream...
960 			 */
961 			formats |= SNDRV_PCM_FMTBIT_U8;
962 			bps = 8;
963 		}
964 		if (formats == 0) {
965 			dev_err(&codec->dev,
966 				"formats == 0 (nid=0x%x, val=0x%x, ovrd=%i, streams=0x%x)\n",
967 				nid, val,
968 				(wcaps & AC_WCAP_FORMAT_OVRD) ? 1 : 0,
969 				streams);
970 			return -EIO;
971 		}
972 		if (formatsp)
973 			*formatsp = formats;
974 		if (subformatsp)
975 			*subformatsp = subformats;
976 		if (bpsp)
977 			*bpsp = bps;
978 	}
979 
980 	return 0;
981 }
982 EXPORT_SYMBOL_GPL(snd_hdac_query_supported_pcm);
983 
984 /**
985  * snd_hdac_is_supported_format - Check the validity of the format
986  * @codec: the codec object
987  * @nid: NID to check
988  * @format: the HD-audio format value to check
989  *
990  * Check whether the given node supports the format value.
991  *
992  * Returns true if supported, false if not.
993  */
994 bool snd_hdac_is_supported_format(struct hdac_device *codec, hda_nid_t nid,
995 				  unsigned int format)
996 {
997 	int i;
998 	unsigned int val = 0, rate, stream;
999 
1000 	val = query_pcm_param(codec, nid);
1001 	if (!val)
1002 		return false;
1003 
1004 	rate = format & 0xff00;
1005 	for (i = 0; i < AC_PAR_PCM_RATE_BITS; i++)
1006 		if (rate_bits[i].hda_fmt == rate) {
1007 			if (val & (1 << i))
1008 				break;
1009 			return false;
1010 		}
1011 	if (i >= AC_PAR_PCM_RATE_BITS)
1012 		return false;
1013 
1014 	stream = query_stream_param(codec, nid);
1015 	if (!stream)
1016 		return false;
1017 
1018 	if (stream & AC_SUPFMT_PCM) {
1019 		switch (format & 0xf0) {
1020 		case 0x00:
1021 			if (!(val & AC_SUPPCM_BITS_8))
1022 				return false;
1023 			break;
1024 		case 0x10:
1025 			if (!(val & AC_SUPPCM_BITS_16))
1026 				return false;
1027 			break;
1028 		case 0x20:
1029 			if (!(val & AC_SUPPCM_BITS_20))
1030 				return false;
1031 			break;
1032 		case 0x30:
1033 			if (!(val & AC_SUPPCM_BITS_24))
1034 				return false;
1035 			break;
1036 		case 0x40:
1037 			if (!(val & AC_SUPPCM_BITS_32))
1038 				return false;
1039 			break;
1040 		default:
1041 			return false;
1042 		}
1043 	} else {
1044 		/* FIXME: check for float32 and AC3? */
1045 	}
1046 
1047 	return true;
1048 }
1049 EXPORT_SYMBOL_GPL(snd_hdac_is_supported_format);
1050 
1051 static unsigned int codec_read(struct hdac_device *hdac, hda_nid_t nid,
1052 			int flags, unsigned int verb, unsigned int parm)
1053 {
1054 	unsigned int cmd = snd_hdac_make_cmd(hdac, nid, verb, parm);
1055 	unsigned int res;
1056 
1057 	if (snd_hdac_exec_verb(hdac, cmd, flags, &res))
1058 		return -1;
1059 
1060 	return res;
1061 }
1062 
1063 static int codec_write(struct hdac_device *hdac, hda_nid_t nid,
1064 			int flags, unsigned int verb, unsigned int parm)
1065 {
1066 	unsigned int cmd = snd_hdac_make_cmd(hdac, nid, verb, parm);
1067 
1068 	return snd_hdac_exec_verb(hdac, cmd, flags, NULL);
1069 }
1070 
1071 /**
1072  * snd_hdac_codec_read - send a command and get the response
1073  * @hdac: the HDAC device
1074  * @nid: NID to send the command
1075  * @flags: optional bit flags
1076  * @verb: the verb to send
1077  * @parm: the parameter for the verb
1078  *
1079  * Send a single command and read the corresponding response.
1080  *
1081  * Returns the obtained response value, or -1 for an error.
1082  */
1083 int snd_hdac_codec_read(struct hdac_device *hdac, hda_nid_t nid,
1084 			int flags, unsigned int verb, unsigned int parm)
1085 {
1086 	return codec_read(hdac, nid, flags, verb, parm);
1087 }
1088 EXPORT_SYMBOL_GPL(snd_hdac_codec_read);
1089 
1090 /**
1091  * snd_hdac_codec_write - send a single command without waiting for response
1092  * @hdac: the HDAC device
1093  * @nid: NID to send the command
1094  * @flags: optional bit flags
1095  * @verb: the verb to send
1096  * @parm: the parameter for the verb
1097  *
1098  * Send a single command without waiting for response.
1099  *
1100  * Returns 0 if successful, or a negative error code.
1101  */
1102 int snd_hdac_codec_write(struct hdac_device *hdac, hda_nid_t nid,
1103 			int flags, unsigned int verb, unsigned int parm)
1104 {
1105 	return codec_write(hdac, nid, flags, verb, parm);
1106 }
1107 EXPORT_SYMBOL_GPL(snd_hdac_codec_write);
1108 
1109 /**
1110  * snd_hdac_check_power_state - check whether the actual power state matches
1111  * with the target state
1112  *
1113  * @hdac: the HDAC device
1114  * @nid: NID to send the command
1115  * @target_state: target state to check for
1116  *
1117  * Return true if state matches, false if not
1118  */
1119 bool snd_hdac_check_power_state(struct hdac_device *hdac,
1120 		hda_nid_t nid, unsigned int target_state)
1121 {
1122 	unsigned int state = codec_read(hdac, nid, 0,
1123 				AC_VERB_GET_POWER_STATE, 0);
1124 
1125 	if (state & AC_PWRST_ERROR)
1126 		return true;
1127 	state = (state >> 4) & 0x0f;
1128 	return (state == target_state);
1129 }
1130 EXPORT_SYMBOL_GPL(snd_hdac_check_power_state);
1131 /**
1132  * snd_hdac_sync_power_state - wait until actual power state matches
1133  * with the target state
1134  *
1135  * @codec: the HDAC device
1136  * @nid: NID to send the command
1137  * @power_state: target power state to wait for
1138  *
1139  * Return power state or PS_ERROR if codec rejects GET verb.
1140  */
1141 unsigned int snd_hdac_sync_power_state(struct hdac_device *codec,
1142 			hda_nid_t nid, unsigned int power_state)
1143 {
1144 	unsigned long end_time = jiffies + msecs_to_jiffies(500);
1145 	unsigned int state, actual_state, count;
1146 
1147 	for (count = 0; count < 500; count++) {
1148 		state = snd_hdac_codec_read(codec, nid, 0,
1149 				AC_VERB_GET_POWER_STATE, 0);
1150 		if (state & AC_PWRST_ERROR) {
1151 			msleep(20);
1152 			break;
1153 		}
1154 		actual_state = (state >> 4) & 0x0f;
1155 		if (actual_state == power_state)
1156 			break;
1157 		if (time_after_eq(jiffies, end_time))
1158 			break;
1159 		/* wait until the codec reachs to the target state */
1160 		msleep(1);
1161 	}
1162 	return state;
1163 }
1164 EXPORT_SYMBOL_GPL(snd_hdac_sync_power_state);
1165