Merge branch 'topic/jack' into for-next
[firefly-linux-kernel-4.4.55.git] / sound / pci / hda / patch_ca0132.c
1 /*
2  * HD audio interface patch for Creative CA0132 chip
3  *
4  * Copyright (c) 2011, Creative Technology Ltd.
5  *
6  * Based on patch_ca0110.c
7  * Copyright (c) 2008 Takashi Iwai <tiwai@suse.de>
8  *
9  *  This driver is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This driver is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
22  */
23
24 #include <linux/init.h>
25 #include <linux/delay.h>
26 #include <linux/slab.h>
27 #include <linux/mutex.h>
28 #include <linux/module.h>
29 #include <linux/firmware.h>
30 #include <sound/core.h>
31 #include "hda_codec.h"
32 #include "hda_local.h"
33 #include "hda_auto_parser.h"
34 #include "hda_jack.h"
35
36 #include "ca0132_regs.h"
37
38 /* Enable this to see controls for tuning purpose. */
39 /*#define ENABLE_TUNING_CONTROLS*/
40
41 #define FLOAT_ZERO      0x00000000
42 #define FLOAT_ONE       0x3f800000
43 #define FLOAT_TWO       0x40000000
44 #define FLOAT_MINUS_5   0xc0a00000
45
46 #define UNSOL_TAG_HP    0x10
47 #define UNSOL_TAG_AMIC1 0x12
48 #define UNSOL_TAG_DSP   0x16
49
50 #define DSP_DMA_WRITE_BUFLEN_INIT (1UL<<18)
51 #define DSP_DMA_WRITE_BUFLEN_OVLY (1UL<<15)
52
53 #define DMA_TRANSFER_FRAME_SIZE_NWORDS          8
54 #define DMA_TRANSFER_MAX_FRAME_SIZE_NWORDS      32
55 #define DMA_OVERLAY_FRAME_SIZE_NWORDS           2
56
57 #define MASTERCONTROL                           0x80
58 #define MASTERCONTROL_ALLOC_DMA_CHAN            10
59 #define MASTERCONTROL_QUERY_SPEAKER_EQ_ADDRESS  60
60
61 #define WIDGET_CHIP_CTRL      0x15
62 #define WIDGET_DSP_CTRL       0x16
63
64 #define MEM_CONNID_MICIN1     3
65 #define MEM_CONNID_MICIN2     5
66 #define MEM_CONNID_MICOUT1    12
67 #define MEM_CONNID_MICOUT2    14
68 #define MEM_CONNID_WUH        10
69 #define MEM_CONNID_DSP        16
70 #define MEM_CONNID_DMIC       100
71
72 #define SCP_SET    0
73 #define SCP_GET    1
74
75 #define EFX_FILE   "ctefx.bin"
76
77 #ifdef CONFIG_SND_HDA_CODEC_CA0132_DSP
78 MODULE_FIRMWARE(EFX_FILE);
79 #endif
80
81 static char *dirstr[2] = { "Playback", "Capture" };
82
83 enum {
84         SPEAKER_OUT,
85         HEADPHONE_OUT
86 };
87
88 enum {
89         DIGITAL_MIC,
90         LINE_MIC_IN
91 };
92
93 enum {
94 #define VNODE_START_NID    0x80
95         VNID_SPK = VNODE_START_NID,                     /* Speaker vnid */
96         VNID_MIC,
97         VNID_HP_SEL,
98         VNID_AMIC1_SEL,
99         VNID_HP_ASEL,
100         VNID_AMIC1_ASEL,
101         VNODE_END_NID,
102 #define VNODES_COUNT  (VNODE_END_NID - VNODE_START_NID)
103
104 #define EFFECT_START_NID    0x90
105 #define OUT_EFFECT_START_NID    EFFECT_START_NID
106         SURROUND = OUT_EFFECT_START_NID,
107         CRYSTALIZER,
108         DIALOG_PLUS,
109         SMART_VOLUME,
110         X_BASS,
111         EQUALIZER,
112         OUT_EFFECT_END_NID,
113 #define OUT_EFFECTS_COUNT  (OUT_EFFECT_END_NID - OUT_EFFECT_START_NID)
114
115 #define IN_EFFECT_START_NID  OUT_EFFECT_END_NID
116         ECHO_CANCELLATION = IN_EFFECT_START_NID,
117         VOICE_FOCUS,
118         MIC_SVM,
119         NOISE_REDUCTION,
120         IN_EFFECT_END_NID,
121 #define IN_EFFECTS_COUNT  (IN_EFFECT_END_NID - IN_EFFECT_START_NID)
122
123         VOICEFX = IN_EFFECT_END_NID,
124         PLAY_ENHANCEMENT,
125         CRYSTAL_VOICE,
126         EFFECT_END_NID
127 #define EFFECTS_COUNT  (EFFECT_END_NID - EFFECT_START_NID)
128 };
129
130 /* Effects values size*/
131 #define EFFECT_VALS_MAX_COUNT 12
132
133 /* Latency introduced by DSP blocks in milliseconds. */
134 #define DSP_CAPTURE_INIT_LATENCY        0
135 #define DSP_CRYSTAL_VOICE_LATENCY       124
136 #define DSP_PLAYBACK_INIT_LATENCY       13
137 #define DSP_PLAY_ENHANCEMENT_LATENCY    30
138 #define DSP_SPEAKER_OUT_LATENCY         7
139
140 struct ct_effect {
141         char name[SNDRV_CTL_ELEM_ID_NAME_MAXLEN];
142         hda_nid_t nid;
143         int mid; /*effect module ID*/
144         int reqs[EFFECT_VALS_MAX_COUNT]; /*effect module request*/
145         int direct; /* 0:output; 1:input*/
146         int params; /* number of default non-on/off params */
147         /*effect default values, 1st is on/off. */
148         unsigned int def_vals[EFFECT_VALS_MAX_COUNT];
149 };
150
151 #define EFX_DIR_OUT 0
152 #define EFX_DIR_IN  1
153
154 static struct ct_effect ca0132_effects[EFFECTS_COUNT] = {
155         { .name = "Surround",
156           .nid = SURROUND,
157           .mid = 0x96,
158           .reqs = {0, 1},
159           .direct = EFX_DIR_OUT,
160           .params = 1,
161           .def_vals = {0x3F800000, 0x3F2B851F}
162         },
163         { .name = "Crystalizer",
164           .nid = CRYSTALIZER,
165           .mid = 0x96,
166           .reqs = {7, 8},
167           .direct = EFX_DIR_OUT,
168           .params = 1,
169           .def_vals = {0x3F800000, 0x3F266666}
170         },
171         { .name = "Dialog Plus",
172           .nid = DIALOG_PLUS,
173           .mid = 0x96,
174           .reqs = {2, 3},
175           .direct = EFX_DIR_OUT,
176           .params = 1,
177           .def_vals = {0x00000000, 0x3F000000}
178         },
179         { .name = "Smart Volume",
180           .nid = SMART_VOLUME,
181           .mid = 0x96,
182           .reqs = {4, 5, 6},
183           .direct = EFX_DIR_OUT,
184           .params = 2,
185           .def_vals = {0x3F800000, 0x3F3D70A4, 0x00000000}
186         },
187         { .name = "X-Bass",
188           .nid = X_BASS,
189           .mid = 0x96,
190           .reqs = {24, 23, 25},
191           .direct = EFX_DIR_OUT,
192           .params = 2,
193           .def_vals = {0x3F800000, 0x42A00000, 0x3F000000}
194         },
195         { .name = "Equalizer",
196           .nid = EQUALIZER,
197           .mid = 0x96,
198           .reqs = {9, 10, 11, 12, 13, 14,
199                         15, 16, 17, 18, 19, 20},
200           .direct = EFX_DIR_OUT,
201           .params = 11,
202           .def_vals = {0x00000000, 0x00000000, 0x00000000, 0x00000000,
203                        0x00000000, 0x00000000, 0x00000000, 0x00000000,
204                        0x00000000, 0x00000000, 0x00000000, 0x00000000}
205         },
206         { .name = "Echo Cancellation",
207           .nid = ECHO_CANCELLATION,
208           .mid = 0x95,
209           .reqs = {0, 1, 2, 3},
210           .direct = EFX_DIR_IN,
211           .params = 3,
212           .def_vals = {0x00000000, 0x3F3A9692, 0x00000000, 0x00000000}
213         },
214         { .name = "Voice Focus",
215           .nid = VOICE_FOCUS,
216           .mid = 0x95,
217           .reqs = {6, 7, 8, 9},
218           .direct = EFX_DIR_IN,
219           .params = 3,
220           .def_vals = {0x3F800000, 0x3D7DF3B6, 0x41F00000, 0x41F00000}
221         },
222         { .name = "Mic SVM",
223           .nid = MIC_SVM,
224           .mid = 0x95,
225           .reqs = {44, 45},
226           .direct = EFX_DIR_IN,
227           .params = 1,
228           .def_vals = {0x00000000, 0x3F3D70A4}
229         },
230         { .name = "Noise Reduction",
231           .nid = NOISE_REDUCTION,
232           .mid = 0x95,
233           .reqs = {4, 5},
234           .direct = EFX_DIR_IN,
235           .params = 1,
236           .def_vals = {0x3F800000, 0x3F000000}
237         },
238         { .name = "VoiceFX",
239           .nid = VOICEFX,
240           .mid = 0x95,
241           .reqs = {10, 11, 12, 13, 14, 15, 16, 17, 18},
242           .direct = EFX_DIR_IN,
243           .params = 8,
244           .def_vals = {0x00000000, 0x43C80000, 0x44AF0000, 0x44FA0000,
245                        0x3F800000, 0x3F800000, 0x3F800000, 0x00000000,
246                        0x00000000}
247         }
248 };
249
250 /* Tuning controls */
251 #ifdef ENABLE_TUNING_CONTROLS
252
253 enum {
254 #define TUNING_CTL_START_NID  0xC0
255         WEDGE_ANGLE = TUNING_CTL_START_NID,
256         SVM_LEVEL,
257         EQUALIZER_BAND_0,
258         EQUALIZER_BAND_1,
259         EQUALIZER_BAND_2,
260         EQUALIZER_BAND_3,
261         EQUALIZER_BAND_4,
262         EQUALIZER_BAND_5,
263         EQUALIZER_BAND_6,
264         EQUALIZER_BAND_7,
265         EQUALIZER_BAND_8,
266         EQUALIZER_BAND_9,
267         TUNING_CTL_END_NID
268 #define TUNING_CTLS_COUNT  (TUNING_CTL_END_NID - TUNING_CTL_START_NID)
269 };
270
271 struct ct_tuning_ctl {
272         char name[SNDRV_CTL_ELEM_ID_NAME_MAXLEN];
273         hda_nid_t parent_nid;
274         hda_nid_t nid;
275         int mid; /*effect module ID*/
276         int req; /*effect module request*/
277         int direct; /* 0:output; 1:input*/
278         unsigned int def_val;/*effect default values*/
279 };
280
281 static struct ct_tuning_ctl ca0132_tuning_ctls[] = {
282         { .name = "Wedge Angle",
283           .parent_nid = VOICE_FOCUS,
284           .nid = WEDGE_ANGLE,
285           .mid = 0x95,
286           .req = 8,
287           .direct = EFX_DIR_IN,
288           .def_val = 0x41F00000
289         },
290         { .name = "SVM Level",
291           .parent_nid = MIC_SVM,
292           .nid = SVM_LEVEL,
293           .mid = 0x95,
294           .req = 45,
295           .direct = EFX_DIR_IN,
296           .def_val = 0x3F3D70A4
297         },
298         { .name = "EQ Band0",
299           .parent_nid = EQUALIZER,
300           .nid = EQUALIZER_BAND_0,
301           .mid = 0x96,
302           .req = 11,
303           .direct = EFX_DIR_OUT,
304           .def_val = 0x00000000
305         },
306         { .name = "EQ Band1",
307           .parent_nid = EQUALIZER,
308           .nid = EQUALIZER_BAND_1,
309           .mid = 0x96,
310           .req = 12,
311           .direct = EFX_DIR_OUT,
312           .def_val = 0x00000000
313         },
314         { .name = "EQ Band2",
315           .parent_nid = EQUALIZER,
316           .nid = EQUALIZER_BAND_2,
317           .mid = 0x96,
318           .req = 13,
319           .direct = EFX_DIR_OUT,
320           .def_val = 0x00000000
321         },
322         { .name = "EQ Band3",
323           .parent_nid = EQUALIZER,
324           .nid = EQUALIZER_BAND_3,
325           .mid = 0x96,
326           .req = 14,
327           .direct = EFX_DIR_OUT,
328           .def_val = 0x00000000
329         },
330         { .name = "EQ Band4",
331           .parent_nid = EQUALIZER,
332           .nid = EQUALIZER_BAND_4,
333           .mid = 0x96,
334           .req = 15,
335           .direct = EFX_DIR_OUT,
336           .def_val = 0x00000000
337         },
338         { .name = "EQ Band5",
339           .parent_nid = EQUALIZER,
340           .nid = EQUALIZER_BAND_5,
341           .mid = 0x96,
342           .req = 16,
343           .direct = EFX_DIR_OUT,
344           .def_val = 0x00000000
345         },
346         { .name = "EQ Band6",
347           .parent_nid = EQUALIZER,
348           .nid = EQUALIZER_BAND_6,
349           .mid = 0x96,
350           .req = 17,
351           .direct = EFX_DIR_OUT,
352           .def_val = 0x00000000
353         },
354         { .name = "EQ Band7",
355           .parent_nid = EQUALIZER,
356           .nid = EQUALIZER_BAND_7,
357           .mid = 0x96,
358           .req = 18,
359           .direct = EFX_DIR_OUT,
360           .def_val = 0x00000000
361         },
362         { .name = "EQ Band8",
363           .parent_nid = EQUALIZER,
364           .nid = EQUALIZER_BAND_8,
365           .mid = 0x96,
366           .req = 19,
367           .direct = EFX_DIR_OUT,
368           .def_val = 0x00000000
369         },
370         { .name = "EQ Band9",
371           .parent_nid = EQUALIZER,
372           .nid = EQUALIZER_BAND_9,
373           .mid = 0x96,
374           .req = 20,
375           .direct = EFX_DIR_OUT,
376           .def_val = 0x00000000
377         }
378 };
379 #endif
380
381 /* Voice FX Presets */
382 #define VOICEFX_MAX_PARAM_COUNT 9
383
384 struct ct_voicefx {
385         char *name;
386         hda_nid_t nid;
387         int mid;
388         int reqs[VOICEFX_MAX_PARAM_COUNT]; /*effect module request*/
389 };
390
391 struct ct_voicefx_preset {
392         char *name; /*preset name*/
393         unsigned int vals[VOICEFX_MAX_PARAM_COUNT];
394 };
395
396 static struct ct_voicefx ca0132_voicefx = {
397         .name = "VoiceFX Capture Switch",
398         .nid = VOICEFX,
399         .mid = 0x95,
400         .reqs = {10, 11, 12, 13, 14, 15, 16, 17, 18}
401 };
402
403 static struct ct_voicefx_preset ca0132_voicefx_presets[] = {
404         { .name = "Neutral",
405           .vals = { 0x00000000, 0x43C80000, 0x44AF0000,
406                     0x44FA0000, 0x3F800000, 0x3F800000,
407                     0x3F800000, 0x00000000, 0x00000000 }
408         },
409         { .name = "Female2Male",
410           .vals = { 0x3F800000, 0x43C80000, 0x44AF0000,
411                     0x44FA0000, 0x3F19999A, 0x3F866666,
412                     0x3F800000, 0x00000000, 0x00000000 }
413         },
414         { .name = "Male2Female",
415           .vals = { 0x3F800000, 0x43C80000, 0x44AF0000,
416                     0x450AC000, 0x4017AE14, 0x3F6B851F,
417                     0x3F800000, 0x00000000, 0x00000000 }
418         },
419         { .name = "ScrappyKid",
420           .vals = { 0x3F800000, 0x43C80000, 0x44AF0000,
421                     0x44FA0000, 0x40400000, 0x3F28F5C3,
422                     0x3F800000, 0x00000000, 0x00000000 }
423         },
424         { .name = "Elderly",
425           .vals = { 0x3F800000, 0x44324000, 0x44BB8000,
426                     0x44E10000, 0x3FB33333, 0x3FB9999A,
427                     0x3F800000, 0x3E3A2E43, 0x00000000 }
428         },
429         { .name = "Orc",
430           .vals = { 0x3F800000, 0x43EA0000, 0x44A52000,
431                     0x45098000, 0x3F266666, 0x3FC00000,
432                     0x3F800000, 0x00000000, 0x00000000 }
433         },
434         { .name = "Elf",
435           .vals = { 0x3F800000, 0x43C70000, 0x44AE6000,
436                     0x45193000, 0x3F8E147B, 0x3F75C28F,
437                     0x3F800000, 0x00000000, 0x00000000 }
438         },
439         { .name = "Dwarf",
440           .vals = { 0x3F800000, 0x43930000, 0x44BEE000,
441                     0x45007000, 0x3F451EB8, 0x3F7851EC,
442                     0x3F800000, 0x00000000, 0x00000000 }
443         },
444         { .name = "AlienBrute",
445           .vals = { 0x3F800000, 0x43BFC5AC, 0x44B28FDF,
446                     0x451F6000, 0x3F266666, 0x3FA7D945,
447                     0x3F800000, 0x3CF5C28F, 0x00000000 }
448         },
449         { .name = "Robot",
450           .vals = { 0x3F800000, 0x43C80000, 0x44AF0000,
451                     0x44FA0000, 0x3FB2718B, 0x3F800000,
452                     0xBC07010E, 0x00000000, 0x00000000 }
453         },
454         { .name = "Marine",
455           .vals = { 0x3F800000, 0x43C20000, 0x44906000,
456                     0x44E70000, 0x3F4CCCCD, 0x3F8A3D71,
457                     0x3F0A3D71, 0x00000000, 0x00000000 }
458         },
459         { .name = "Emo",
460           .vals = { 0x3F800000, 0x43C80000, 0x44AF0000,
461                     0x44FA0000, 0x3F800000, 0x3F800000,
462                     0x3E4CCCCD, 0x00000000, 0x00000000 }
463         },
464         { .name = "DeepVoice",
465           .vals = { 0x3F800000, 0x43A9C5AC, 0x44AA4FDF,
466                     0x44FFC000, 0x3EDBB56F, 0x3F99C4CA,
467                     0x3F800000, 0x00000000, 0x00000000 }
468         },
469         { .name = "Munchkin",
470           .vals = { 0x3F800000, 0x43C80000, 0x44AF0000,
471                     0x44FA0000, 0x3F800000, 0x3F1A043C,
472                     0x3F800000, 0x00000000, 0x00000000 }
473         }
474 };
475
476 enum hda_cmd_vendor_io {
477         /* for DspIO node */
478         VENDOR_DSPIO_SCP_WRITE_DATA_LOW      = 0x000,
479         VENDOR_DSPIO_SCP_WRITE_DATA_HIGH     = 0x100,
480
481         VENDOR_DSPIO_STATUS                  = 0xF01,
482         VENDOR_DSPIO_SCP_POST_READ_DATA      = 0x702,
483         VENDOR_DSPIO_SCP_READ_DATA           = 0xF02,
484         VENDOR_DSPIO_DSP_INIT                = 0x703,
485         VENDOR_DSPIO_SCP_POST_COUNT_QUERY    = 0x704,
486         VENDOR_DSPIO_SCP_READ_COUNT          = 0xF04,
487
488         /* for ChipIO node */
489         VENDOR_CHIPIO_ADDRESS_LOW            = 0x000,
490         VENDOR_CHIPIO_ADDRESS_HIGH           = 0x100,
491         VENDOR_CHIPIO_STREAM_FORMAT          = 0x200,
492         VENDOR_CHIPIO_DATA_LOW               = 0x300,
493         VENDOR_CHIPIO_DATA_HIGH              = 0x400,
494
495         VENDOR_CHIPIO_GET_PARAMETER          = 0xF00,
496         VENDOR_CHIPIO_STATUS                 = 0xF01,
497         VENDOR_CHIPIO_HIC_POST_READ          = 0x702,
498         VENDOR_CHIPIO_HIC_READ_DATA          = 0xF03,
499
500         VENDOR_CHIPIO_8051_DATA_WRITE        = 0x707,
501         VENDOR_CHIPIO_8051_DATA_READ         = 0xF07,
502
503         VENDOR_CHIPIO_CT_EXTENSIONS_ENABLE   = 0x70A,
504         VENDOR_CHIPIO_CT_EXTENSIONS_GET      = 0xF0A,
505
506         VENDOR_CHIPIO_PLL_PMU_WRITE          = 0x70C,
507         VENDOR_CHIPIO_PLL_PMU_READ           = 0xF0C,
508         VENDOR_CHIPIO_8051_ADDRESS_LOW       = 0x70D,
509         VENDOR_CHIPIO_8051_ADDRESS_HIGH      = 0x70E,
510         VENDOR_CHIPIO_FLAG_SET               = 0x70F,
511         VENDOR_CHIPIO_FLAGS_GET              = 0xF0F,
512         VENDOR_CHIPIO_PARAM_SET              = 0x710,
513         VENDOR_CHIPIO_PARAM_GET              = 0xF10,
514
515         VENDOR_CHIPIO_PORT_ALLOC_CONFIG_SET  = 0x711,
516         VENDOR_CHIPIO_PORT_ALLOC_SET         = 0x712,
517         VENDOR_CHIPIO_PORT_ALLOC_GET         = 0xF12,
518         VENDOR_CHIPIO_PORT_FREE_SET          = 0x713,
519
520         VENDOR_CHIPIO_PARAM_EX_ID_GET        = 0xF17,
521         VENDOR_CHIPIO_PARAM_EX_ID_SET        = 0x717,
522         VENDOR_CHIPIO_PARAM_EX_VALUE_GET     = 0xF18,
523         VENDOR_CHIPIO_PARAM_EX_VALUE_SET     = 0x718,
524
525         VENDOR_CHIPIO_DMIC_CTL_SET           = 0x788,
526         VENDOR_CHIPIO_DMIC_CTL_GET           = 0xF88,
527         VENDOR_CHIPIO_DMIC_PIN_SET           = 0x789,
528         VENDOR_CHIPIO_DMIC_PIN_GET           = 0xF89,
529         VENDOR_CHIPIO_DMIC_MCLK_SET          = 0x78A,
530         VENDOR_CHIPIO_DMIC_MCLK_GET          = 0xF8A,
531
532         VENDOR_CHIPIO_EAPD_SEL_SET           = 0x78D
533 };
534
535 /*
536  *  Control flag IDs
537  */
538 enum control_flag_id {
539         /* Connection manager stream setup is bypassed/enabled */
540         CONTROL_FLAG_C_MGR                  = 0,
541         /* DSP DMA is bypassed/enabled */
542         CONTROL_FLAG_DMA                    = 1,
543         /* 8051 'idle' mode is disabled/enabled */
544         CONTROL_FLAG_IDLE_ENABLE            = 2,
545         /* Tracker for the SPDIF-in path is bypassed/enabled */
546         CONTROL_FLAG_TRACKER                = 3,
547         /* DigitalOut to Spdif2Out connection is disabled/enabled */
548         CONTROL_FLAG_SPDIF2OUT              = 4,
549         /* Digital Microphone is disabled/enabled */
550         CONTROL_FLAG_DMIC                   = 5,
551         /* ADC_B rate is 48 kHz/96 kHz */
552         CONTROL_FLAG_ADC_B_96KHZ            = 6,
553         /* ADC_C rate is 48 kHz/96 kHz */
554         CONTROL_FLAG_ADC_C_96KHZ            = 7,
555         /* DAC rate is 48 kHz/96 kHz (affects all DACs) */
556         CONTROL_FLAG_DAC_96KHZ              = 8,
557         /* DSP rate is 48 kHz/96 kHz */
558         CONTROL_FLAG_DSP_96KHZ              = 9,
559         /* SRC clock is 98 MHz/196 MHz (196 MHz forces rate to 96 KHz) */
560         CONTROL_FLAG_SRC_CLOCK_196MHZ       = 10,
561         /* SRC rate is 48 kHz/96 kHz (48 kHz disabled when clock is 196 MHz) */
562         CONTROL_FLAG_SRC_RATE_96KHZ         = 11,
563         /* Decode Loop (DSP->SRC->DSP) is disabled/enabled */
564         CONTROL_FLAG_DECODE_LOOP            = 12,
565         /* De-emphasis filter on DAC-1 disabled/enabled */
566         CONTROL_FLAG_DAC1_DEEMPHASIS        = 13,
567         /* De-emphasis filter on DAC-2 disabled/enabled */
568         CONTROL_FLAG_DAC2_DEEMPHASIS        = 14,
569         /* De-emphasis filter on DAC-3 disabled/enabled */
570         CONTROL_FLAG_DAC3_DEEMPHASIS        = 15,
571         /* High-pass filter on ADC_B disabled/enabled */
572         CONTROL_FLAG_ADC_B_HIGH_PASS        = 16,
573         /* High-pass filter on ADC_C disabled/enabled */
574         CONTROL_FLAG_ADC_C_HIGH_PASS        = 17,
575         /* Common mode on Port_A disabled/enabled */
576         CONTROL_FLAG_PORT_A_COMMON_MODE     = 18,
577         /* Common mode on Port_D disabled/enabled */
578         CONTROL_FLAG_PORT_D_COMMON_MODE     = 19,
579         /* Impedance for ramp generator on Port_A 16 Ohm/10K Ohm */
580         CONTROL_FLAG_PORT_A_10KOHM_LOAD     = 20,
581         /* Impedance for ramp generator on Port_D, 16 Ohm/10K Ohm */
582         CONTROL_FLAG_PORT_D_10KOHM_LOAD     = 21,
583         /* ASI rate is 48kHz/96kHz */
584         CONTROL_FLAG_ASI_96KHZ              = 22,
585         /* DAC power settings able to control attached ports no/yes */
586         CONTROL_FLAG_DACS_CONTROL_PORTS     = 23,
587         /* Clock Stop OK reporting is disabled/enabled */
588         CONTROL_FLAG_CONTROL_STOP_OK_ENABLE = 24,
589         /* Number of control flags */
590         CONTROL_FLAGS_MAX = (CONTROL_FLAG_CONTROL_STOP_OK_ENABLE+1)
591 };
592
593 /*
594  * Control parameter IDs
595  */
596 enum control_param_id {
597         /* 0: None, 1: Mic1In*/
598         CONTROL_PARAM_VIP_SOURCE               = 1,
599         /* 0: force HDA, 1: allow DSP if HDA Spdif1Out stream is idle */
600         CONTROL_PARAM_SPDIF1_SOURCE            = 2,
601         /* Port A output stage gain setting to use when 16 Ohm output
602          * impedance is selected*/
603         CONTROL_PARAM_PORTA_160OHM_GAIN        = 8,
604         /* Port D output stage gain setting to use when 16 Ohm output
605          * impedance is selected*/
606         CONTROL_PARAM_PORTD_160OHM_GAIN        = 10,
607
608         /* Stream Control */
609
610         /* Select stream with the given ID */
611         CONTROL_PARAM_STREAM_ID                = 24,
612         /* Source connection point for the selected stream */
613         CONTROL_PARAM_STREAM_SOURCE_CONN_POINT = 25,
614         /* Destination connection point for the selected stream */
615         CONTROL_PARAM_STREAM_DEST_CONN_POINT   = 26,
616         /* Number of audio channels in the selected stream */
617         CONTROL_PARAM_STREAMS_CHANNELS         = 27,
618         /*Enable control for the selected stream */
619         CONTROL_PARAM_STREAM_CONTROL           = 28,
620
621         /* Connection Point Control */
622
623         /* Select connection point with the given ID */
624         CONTROL_PARAM_CONN_POINT_ID            = 29,
625         /* Connection point sample rate */
626         CONTROL_PARAM_CONN_POINT_SAMPLE_RATE   = 30,
627
628         /* Node Control */
629
630         /* Select HDA node with the given ID */
631         CONTROL_PARAM_NODE_ID                  = 31
632 };
633
634 /*
635  *  Dsp Io Status codes
636  */
637 enum hda_vendor_status_dspio {
638         /* Success */
639         VENDOR_STATUS_DSPIO_OK                       = 0x00,
640         /* Busy, unable to accept new command, the host must retry */
641         VENDOR_STATUS_DSPIO_BUSY                     = 0x01,
642         /* SCP command queue is full */
643         VENDOR_STATUS_DSPIO_SCP_COMMAND_QUEUE_FULL   = 0x02,
644         /* SCP response queue is empty */
645         VENDOR_STATUS_DSPIO_SCP_RESPONSE_QUEUE_EMPTY = 0x03
646 };
647
648 /*
649  *  Chip Io Status codes
650  */
651 enum hda_vendor_status_chipio {
652         /* Success */
653         VENDOR_STATUS_CHIPIO_OK   = 0x00,
654         /* Busy, unable to accept new command, the host must retry */
655         VENDOR_STATUS_CHIPIO_BUSY = 0x01
656 };
657
658 /*
659  *  CA0132 sample rate
660  */
661 enum ca0132_sample_rate {
662         SR_6_000        = 0x00,
663         SR_8_000        = 0x01,
664         SR_9_600        = 0x02,
665         SR_11_025       = 0x03,
666         SR_16_000       = 0x04,
667         SR_22_050       = 0x05,
668         SR_24_000       = 0x06,
669         SR_32_000       = 0x07,
670         SR_44_100       = 0x08,
671         SR_48_000       = 0x09,
672         SR_88_200       = 0x0A,
673         SR_96_000       = 0x0B,
674         SR_144_000      = 0x0C,
675         SR_176_400      = 0x0D,
676         SR_192_000      = 0x0E,
677         SR_384_000      = 0x0F,
678
679         SR_COUNT        = 0x10,
680
681         SR_RATE_UNKNOWN = 0x1F
682 };
683
684 enum dsp_download_state {
685         DSP_DOWNLOAD_FAILED = -1,
686         DSP_DOWNLOAD_INIT   = 0,
687         DSP_DOWNLOADING     = 1,
688         DSP_DOWNLOADED      = 2
689 };
690
691 /* retrieve parameters from hda format */
692 #define get_hdafmt_chs(fmt)     (fmt & 0xf)
693 #define get_hdafmt_bits(fmt)    ((fmt >> 4) & 0x7)
694 #define get_hdafmt_rate(fmt)    ((fmt >> 8) & 0x7f)
695 #define get_hdafmt_type(fmt)    ((fmt >> 15) & 0x1)
696
697 /*
698  * CA0132 specific
699  */
700
701 struct ca0132_spec {
702         struct snd_kcontrol_new *mixers[5];
703         unsigned int num_mixers;
704         const struct hda_verb *base_init_verbs;
705         const struct hda_verb *base_exit_verbs;
706         const struct hda_verb *init_verbs[5];
707         unsigned int num_init_verbs;  /* exclude base init verbs */
708         struct auto_pin_cfg autocfg;
709
710         /* Nodes configurations */
711         struct hda_multi_out multiout;
712         hda_nid_t out_pins[AUTO_CFG_MAX_OUTS];
713         hda_nid_t dacs[AUTO_CFG_MAX_OUTS];
714         unsigned int num_outputs;
715         hda_nid_t input_pins[AUTO_PIN_LAST];
716         hda_nid_t adcs[AUTO_PIN_LAST];
717         hda_nid_t dig_out;
718         hda_nid_t dig_in;
719         unsigned int num_inputs;
720         hda_nid_t shared_mic_nid;
721         hda_nid_t shared_out_nid;
722
723         /* chip access */
724         struct mutex chipio_mutex; /* chip access mutex */
725         u32 curr_chip_addx;
726
727         /* DSP download related */
728         enum dsp_download_state dsp_state;
729         unsigned int dsp_stream_id;
730         unsigned int wait_scp;
731         unsigned int wait_scp_header;
732         unsigned int wait_num_data;
733         unsigned int scp_resp_header;
734         unsigned int scp_resp_data[4];
735         unsigned int scp_resp_count;
736
737         /* mixer and effects related */
738         unsigned char dmic_ctl;
739         int cur_out_type;
740         int cur_mic_type;
741         long vnode_lvol[VNODES_COUNT];
742         long vnode_rvol[VNODES_COUNT];
743         long vnode_lswitch[VNODES_COUNT];
744         long vnode_rswitch[VNODES_COUNT];
745         long effects_switch[EFFECTS_COUNT];
746         long voicefx_val;
747         long cur_mic_boost;
748
749         struct hda_codec *codec;
750         struct delayed_work unsol_hp_work;
751
752 #ifdef ENABLE_TUNING_CONTROLS
753         long cur_ctl_vals[TUNING_CTLS_COUNT];
754 #endif
755 };
756
757 /*
758  * CA0132 codec access
759  */
760 static unsigned int codec_send_command(struct hda_codec *codec, hda_nid_t nid,
761                 unsigned int verb, unsigned int parm, unsigned int *res)
762 {
763         unsigned int response;
764         response = snd_hda_codec_read(codec, nid, 0, verb, parm);
765         *res = response;
766
767         return ((response == -1) ? -1 : 0);
768 }
769
770 static int codec_set_converter_format(struct hda_codec *codec, hda_nid_t nid,
771                 unsigned short converter_format, unsigned int *res)
772 {
773         return codec_send_command(codec, nid, VENDOR_CHIPIO_STREAM_FORMAT,
774                                 converter_format & 0xffff, res);
775 }
776
777 static int codec_set_converter_stream_channel(struct hda_codec *codec,
778                                 hda_nid_t nid, unsigned char stream,
779                                 unsigned char channel, unsigned int *res)
780 {
781         unsigned char converter_stream_channel = 0;
782
783         converter_stream_channel = (stream << 4) | (channel & 0x0f);
784         return codec_send_command(codec, nid, AC_VERB_SET_CHANNEL_STREAMID,
785                                 converter_stream_channel, res);
786 }
787
788 /* Chip access helper function */
789 static int chipio_send(struct hda_codec *codec,
790                        unsigned int reg,
791                        unsigned int data)
792 {
793         unsigned int res;
794         unsigned long timeout = jiffies + msecs_to_jiffies(1000);
795
796         /* send bits of data specified by reg */
797         do {
798                 res = snd_hda_codec_read(codec, WIDGET_CHIP_CTRL, 0,
799                                          reg, data);
800                 if (res == VENDOR_STATUS_CHIPIO_OK)
801                         return 0;
802                 msleep(20);
803         } while (time_before(jiffies, timeout));
804
805         return -EIO;
806 }
807
808 /*
809  * Write chip address through the vendor widget -- NOT protected by the Mutex!
810  */
811 static int chipio_write_address(struct hda_codec *codec,
812                                 unsigned int chip_addx)
813 {
814         struct ca0132_spec *spec = codec->spec;
815         int res;
816
817         if (spec->curr_chip_addx == chip_addx)
818                         return 0;
819
820         /* send low 16 bits of the address */
821         res = chipio_send(codec, VENDOR_CHIPIO_ADDRESS_LOW,
822                           chip_addx & 0xffff);
823
824         if (res != -EIO) {
825                 /* send high 16 bits of the address */
826                 res = chipio_send(codec, VENDOR_CHIPIO_ADDRESS_HIGH,
827                                   chip_addx >> 16);
828         }
829
830         spec->curr_chip_addx = (res < 0) ? ~0UL : chip_addx;
831
832         return res;
833 }
834
835 /*
836  * Write data through the vendor widget -- NOT protected by the Mutex!
837  */
838 static int chipio_write_data(struct hda_codec *codec, unsigned int data)
839 {
840         struct ca0132_spec *spec = codec->spec;
841         int res;
842
843         /* send low 16 bits of the data */
844         res = chipio_send(codec, VENDOR_CHIPIO_DATA_LOW, data & 0xffff);
845
846         if (res != -EIO) {
847                 /* send high 16 bits of the data */
848                 res = chipio_send(codec, VENDOR_CHIPIO_DATA_HIGH,
849                                   data >> 16);
850         }
851
852         /*If no error encountered, automatically increment the address
853         as per chip behaviour*/
854         spec->curr_chip_addx = (res != -EIO) ?
855                                         (spec->curr_chip_addx + 4) : ~0UL;
856         return res;
857 }
858
859 /*
860  * Write multiple data through the vendor widget -- NOT protected by the Mutex!
861  */
862 static int chipio_write_data_multiple(struct hda_codec *codec,
863                                       const u32 *data,
864                                       unsigned int count)
865 {
866         int status = 0;
867
868         if (data == NULL) {
869                 codec_dbg(codec, "chipio_write_data null ptr\n");
870                 return -EINVAL;
871         }
872
873         while ((count-- != 0) && (status == 0))
874                 status = chipio_write_data(codec, *data++);
875
876         return status;
877 }
878
879
880 /*
881  * Read data through the vendor widget -- NOT protected by the Mutex!
882  */
883 static int chipio_read_data(struct hda_codec *codec, unsigned int *data)
884 {
885         struct ca0132_spec *spec = codec->spec;
886         int res;
887
888         /* post read */
889         res = chipio_send(codec, VENDOR_CHIPIO_HIC_POST_READ, 0);
890
891         if (res != -EIO) {
892                 /* read status */
893                 res = chipio_send(codec, VENDOR_CHIPIO_STATUS, 0);
894         }
895
896         if (res != -EIO) {
897                 /* read data */
898                 *data = snd_hda_codec_read(codec, WIDGET_CHIP_CTRL, 0,
899                                            VENDOR_CHIPIO_HIC_READ_DATA,
900                                            0);
901         }
902
903         /*If no error encountered, automatically increment the address
904         as per chip behaviour*/
905         spec->curr_chip_addx = (res != -EIO) ?
906                                         (spec->curr_chip_addx + 4) : ~0UL;
907         return res;
908 }
909
910 /*
911  * Write given value to the given address through the chip I/O widget.
912  * protected by the Mutex
913  */
914 static int chipio_write(struct hda_codec *codec,
915                 unsigned int chip_addx, const unsigned int data)
916 {
917         struct ca0132_spec *spec = codec->spec;
918         int err;
919
920         mutex_lock(&spec->chipio_mutex);
921
922         /* write the address, and if successful proceed to write data */
923         err = chipio_write_address(codec, chip_addx);
924         if (err < 0)
925                 goto exit;
926
927         err = chipio_write_data(codec, data);
928         if (err < 0)
929                 goto exit;
930
931 exit:
932         mutex_unlock(&spec->chipio_mutex);
933         return err;
934 }
935
936 /*
937  * Write multiple values to the given address through the chip I/O widget.
938  * protected by the Mutex
939  */
940 static int chipio_write_multiple(struct hda_codec *codec,
941                                  u32 chip_addx,
942                                  const u32 *data,
943                                  unsigned int count)
944 {
945         struct ca0132_spec *spec = codec->spec;
946         int status;
947
948         mutex_lock(&spec->chipio_mutex);
949         status = chipio_write_address(codec, chip_addx);
950         if (status < 0)
951                 goto error;
952
953         status = chipio_write_data_multiple(codec, data, count);
954 error:
955         mutex_unlock(&spec->chipio_mutex);
956
957         return status;
958 }
959
960 /*
961  * Read the given address through the chip I/O widget
962  * protected by the Mutex
963  */
964 static int chipio_read(struct hda_codec *codec,
965                 unsigned int chip_addx, unsigned int *data)
966 {
967         struct ca0132_spec *spec = codec->spec;
968         int err;
969
970         mutex_lock(&spec->chipio_mutex);
971
972         /* write the address, and if successful proceed to write data */
973         err = chipio_write_address(codec, chip_addx);
974         if (err < 0)
975                 goto exit;
976
977         err = chipio_read_data(codec, data);
978         if (err < 0)
979                 goto exit;
980
981 exit:
982         mutex_unlock(&spec->chipio_mutex);
983         return err;
984 }
985
986 /*
987  * Set chip control flags through the chip I/O widget.
988  */
989 static void chipio_set_control_flag(struct hda_codec *codec,
990                                     enum control_flag_id flag_id,
991                                     bool flag_state)
992 {
993         unsigned int val;
994         unsigned int flag_bit;
995
996         flag_bit = (flag_state ? 1 : 0);
997         val = (flag_bit << 7) | (flag_id);
998         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
999                             VENDOR_CHIPIO_FLAG_SET, val);
1000 }
1001
1002 /*
1003  * Set chip parameters through the chip I/O widget.
1004  */
1005 static void chipio_set_control_param(struct hda_codec *codec,
1006                 enum control_param_id param_id, int param_val)
1007 {
1008         struct ca0132_spec *spec = codec->spec;
1009         int val;
1010
1011         if ((param_id < 32) && (param_val < 8)) {
1012                 val = (param_val << 5) | (param_id);
1013                 snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1014                                     VENDOR_CHIPIO_PARAM_SET, val);
1015         } else {
1016                 mutex_lock(&spec->chipio_mutex);
1017                 if (chipio_send(codec, VENDOR_CHIPIO_STATUS, 0) == 0) {
1018                         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1019                                             VENDOR_CHIPIO_PARAM_EX_ID_SET,
1020                                             param_id);
1021                         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1022                                             VENDOR_CHIPIO_PARAM_EX_VALUE_SET,
1023                                             param_val);
1024                 }
1025                 mutex_unlock(&spec->chipio_mutex);
1026         }
1027 }
1028
1029 /*
1030  * Set sampling rate of the connection point.
1031  */
1032 static void chipio_set_conn_rate(struct hda_codec *codec,
1033                                 int connid, enum ca0132_sample_rate rate)
1034 {
1035         chipio_set_control_param(codec, CONTROL_PARAM_CONN_POINT_ID, connid);
1036         chipio_set_control_param(codec, CONTROL_PARAM_CONN_POINT_SAMPLE_RATE,
1037                                  rate);
1038 }
1039
1040 /*
1041  * Enable clocks.
1042  */
1043 static void chipio_enable_clocks(struct hda_codec *codec)
1044 {
1045         struct ca0132_spec *spec = codec->spec;
1046
1047         mutex_lock(&spec->chipio_mutex);
1048         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1049                             VENDOR_CHIPIO_8051_ADDRESS_LOW, 0);
1050         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1051                             VENDOR_CHIPIO_PLL_PMU_WRITE, 0xff);
1052         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1053                             VENDOR_CHIPIO_8051_ADDRESS_LOW, 5);
1054         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1055                             VENDOR_CHIPIO_PLL_PMU_WRITE, 0x0b);
1056         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1057                             VENDOR_CHIPIO_8051_ADDRESS_LOW, 6);
1058         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1059                             VENDOR_CHIPIO_PLL_PMU_WRITE, 0xff);
1060         mutex_unlock(&spec->chipio_mutex);
1061 }
1062
1063 /*
1064  * CA0132 DSP IO stuffs
1065  */
1066 static int dspio_send(struct hda_codec *codec, unsigned int reg,
1067                       unsigned int data)
1068 {
1069         int res;
1070         unsigned long timeout = jiffies + msecs_to_jiffies(1000);
1071
1072         /* send bits of data specified by reg to dsp */
1073         do {
1074                 res = snd_hda_codec_read(codec, WIDGET_DSP_CTRL, 0, reg, data);
1075                 if ((res >= 0) && (res != VENDOR_STATUS_DSPIO_BUSY))
1076                         return res;
1077                 msleep(20);
1078         } while (time_before(jiffies, timeout));
1079
1080         return -EIO;
1081 }
1082
1083 /*
1084  * Wait for DSP to be ready for commands
1085  */
1086 static void dspio_write_wait(struct hda_codec *codec)
1087 {
1088         int status;
1089         unsigned long timeout = jiffies + msecs_to_jiffies(1000);
1090
1091         do {
1092                 status = snd_hda_codec_read(codec, WIDGET_DSP_CTRL, 0,
1093                                                 VENDOR_DSPIO_STATUS, 0);
1094                 if ((status == VENDOR_STATUS_DSPIO_OK) ||
1095                     (status == VENDOR_STATUS_DSPIO_SCP_RESPONSE_QUEUE_EMPTY))
1096                         break;
1097                 msleep(1);
1098         } while (time_before(jiffies, timeout));
1099 }
1100
1101 /*
1102  * Write SCP data to DSP
1103  */
1104 static int dspio_write(struct hda_codec *codec, unsigned int scp_data)
1105 {
1106         struct ca0132_spec *spec = codec->spec;
1107         int status;
1108
1109         dspio_write_wait(codec);
1110
1111         mutex_lock(&spec->chipio_mutex);
1112         status = dspio_send(codec, VENDOR_DSPIO_SCP_WRITE_DATA_LOW,
1113                             scp_data & 0xffff);
1114         if (status < 0)
1115                 goto error;
1116
1117         status = dspio_send(codec, VENDOR_DSPIO_SCP_WRITE_DATA_HIGH,
1118                                     scp_data >> 16);
1119         if (status < 0)
1120                 goto error;
1121
1122         /* OK, now check if the write itself has executed*/
1123         status = snd_hda_codec_read(codec, WIDGET_DSP_CTRL, 0,
1124                                     VENDOR_DSPIO_STATUS, 0);
1125 error:
1126         mutex_unlock(&spec->chipio_mutex);
1127
1128         return (status == VENDOR_STATUS_DSPIO_SCP_COMMAND_QUEUE_FULL) ?
1129                         -EIO : 0;
1130 }
1131
1132 /*
1133  * Write multiple SCP data to DSP
1134  */
1135 static int dspio_write_multiple(struct hda_codec *codec,
1136                                 unsigned int *buffer, unsigned int size)
1137 {
1138         int status = 0;
1139         unsigned int count;
1140
1141         if ((buffer == NULL))
1142                 return -EINVAL;
1143
1144         count = 0;
1145         while (count < size) {
1146                 status = dspio_write(codec, *buffer++);
1147                 if (status != 0)
1148                         break;
1149                 count++;
1150         }
1151
1152         return status;
1153 }
1154
1155 static int dspio_read(struct hda_codec *codec, unsigned int *data)
1156 {
1157         int status;
1158
1159         status = dspio_send(codec, VENDOR_DSPIO_SCP_POST_READ_DATA, 0);
1160         if (status == -EIO)
1161                 return status;
1162
1163         status = dspio_send(codec, VENDOR_DSPIO_STATUS, 0);
1164         if (status == -EIO ||
1165             status == VENDOR_STATUS_DSPIO_SCP_RESPONSE_QUEUE_EMPTY)
1166                 return -EIO;
1167
1168         *data = snd_hda_codec_read(codec, WIDGET_DSP_CTRL, 0,
1169                                    VENDOR_DSPIO_SCP_READ_DATA, 0);
1170
1171         return 0;
1172 }
1173
1174 static int dspio_read_multiple(struct hda_codec *codec, unsigned int *buffer,
1175                                unsigned int *buf_size, unsigned int size_count)
1176 {
1177         int status = 0;
1178         unsigned int size = *buf_size;
1179         unsigned int count;
1180         unsigned int skip_count;
1181         unsigned int dummy;
1182
1183         if ((buffer == NULL))
1184                 return -1;
1185
1186         count = 0;
1187         while (count < size && count < size_count) {
1188                 status = dspio_read(codec, buffer++);
1189                 if (status != 0)
1190                         break;
1191                 count++;
1192         }
1193
1194         skip_count = count;
1195         if (status == 0) {
1196                 while (skip_count < size) {
1197                         status = dspio_read(codec, &dummy);
1198                         if (status != 0)
1199                                 break;
1200                         skip_count++;
1201                 }
1202         }
1203         *buf_size = count;
1204
1205         return status;
1206 }
1207
1208 /*
1209  * Construct the SCP header using corresponding fields
1210  */
1211 static inline unsigned int
1212 make_scp_header(unsigned int target_id, unsigned int source_id,
1213                 unsigned int get_flag, unsigned int req,
1214                 unsigned int device_flag, unsigned int resp_flag,
1215                 unsigned int error_flag, unsigned int data_size)
1216 {
1217         unsigned int header = 0;
1218
1219         header = (data_size & 0x1f) << 27;
1220         header |= (error_flag & 0x01) << 26;
1221         header |= (resp_flag & 0x01) << 25;
1222         header |= (device_flag & 0x01) << 24;
1223         header |= (req & 0x7f) << 17;
1224         header |= (get_flag & 0x01) << 16;
1225         header |= (source_id & 0xff) << 8;
1226         header |= target_id & 0xff;
1227
1228         return header;
1229 }
1230
1231 /*
1232  * Extract corresponding fields from SCP header
1233  */
1234 static inline void
1235 extract_scp_header(unsigned int header,
1236                    unsigned int *target_id, unsigned int *source_id,
1237                    unsigned int *get_flag, unsigned int *req,
1238                    unsigned int *device_flag, unsigned int *resp_flag,
1239                    unsigned int *error_flag, unsigned int *data_size)
1240 {
1241         if (data_size)
1242                 *data_size = (header >> 27) & 0x1f;
1243         if (error_flag)
1244                 *error_flag = (header >> 26) & 0x01;
1245         if (resp_flag)
1246                 *resp_flag = (header >> 25) & 0x01;
1247         if (device_flag)
1248                 *device_flag = (header >> 24) & 0x01;
1249         if (req)
1250                 *req = (header >> 17) & 0x7f;
1251         if (get_flag)
1252                 *get_flag = (header >> 16) & 0x01;
1253         if (source_id)
1254                 *source_id = (header >> 8) & 0xff;
1255         if (target_id)
1256                 *target_id = header & 0xff;
1257 }
1258
1259 #define SCP_MAX_DATA_WORDS  (16)
1260
1261 /* Structure to contain any SCP message */
1262 struct scp_msg {
1263         unsigned int hdr;
1264         unsigned int data[SCP_MAX_DATA_WORDS];
1265 };
1266
1267 static void dspio_clear_response_queue(struct hda_codec *codec)
1268 {
1269         unsigned int dummy = 0;
1270         int status = -1;
1271
1272         /* clear all from the response queue */
1273         do {
1274                 status = dspio_read(codec, &dummy);
1275         } while (status == 0);
1276 }
1277
1278 static int dspio_get_response_data(struct hda_codec *codec)
1279 {
1280         struct ca0132_spec *spec = codec->spec;
1281         unsigned int data = 0;
1282         unsigned int count;
1283
1284         if (dspio_read(codec, &data) < 0)
1285                 return -EIO;
1286
1287         if ((data & 0x00ffffff) == spec->wait_scp_header) {
1288                 spec->scp_resp_header = data;
1289                 spec->scp_resp_count = data >> 27;
1290                 count = spec->wait_num_data;
1291                 dspio_read_multiple(codec, spec->scp_resp_data,
1292                                     &spec->scp_resp_count, count);
1293                 return 0;
1294         }
1295
1296         return -EIO;
1297 }
1298
1299 /*
1300  * Send SCP message to DSP
1301  */
1302 static int dspio_send_scp_message(struct hda_codec *codec,
1303                                   unsigned char *send_buf,
1304                                   unsigned int send_buf_size,
1305                                   unsigned char *return_buf,
1306                                   unsigned int return_buf_size,
1307                                   unsigned int *bytes_returned)
1308 {
1309         struct ca0132_spec *spec = codec->spec;
1310         int status = -1;
1311         unsigned int scp_send_size = 0;
1312         unsigned int total_size;
1313         bool waiting_for_resp = false;
1314         unsigned int header;
1315         struct scp_msg *ret_msg;
1316         unsigned int resp_src_id, resp_target_id;
1317         unsigned int data_size, src_id, target_id, get_flag, device_flag;
1318
1319         if (bytes_returned)
1320                 *bytes_returned = 0;
1321
1322         /* get scp header from buffer */
1323         header = *((unsigned int *)send_buf);
1324         extract_scp_header(header, &target_id, &src_id, &get_flag, NULL,
1325                            &device_flag, NULL, NULL, &data_size);
1326         scp_send_size = data_size + 1;
1327         total_size = (scp_send_size * 4);
1328
1329         if (send_buf_size < total_size)
1330                 return -EINVAL;
1331
1332         if (get_flag || device_flag) {
1333                 if (!return_buf || return_buf_size < 4 || !bytes_returned)
1334                         return -EINVAL;
1335
1336                 spec->wait_scp_header = *((unsigned int *)send_buf);
1337
1338                 /* swap source id with target id */
1339                 resp_target_id = src_id;
1340                 resp_src_id = target_id;
1341                 spec->wait_scp_header &= 0xffff0000;
1342                 spec->wait_scp_header |= (resp_src_id << 8) | (resp_target_id);
1343                 spec->wait_num_data = return_buf_size/sizeof(unsigned int) - 1;
1344                 spec->wait_scp = 1;
1345                 waiting_for_resp = true;
1346         }
1347
1348         status = dspio_write_multiple(codec, (unsigned int *)send_buf,
1349                                       scp_send_size);
1350         if (status < 0) {
1351                 spec->wait_scp = 0;
1352                 return status;
1353         }
1354
1355         if (waiting_for_resp) {
1356                 unsigned long timeout = jiffies + msecs_to_jiffies(1000);
1357                 memset(return_buf, 0, return_buf_size);
1358                 do {
1359                         msleep(20);
1360                 } while (spec->wait_scp && time_before(jiffies, timeout));
1361                 waiting_for_resp = false;
1362                 if (!spec->wait_scp) {
1363                         ret_msg = (struct scp_msg *)return_buf;
1364                         memcpy(&ret_msg->hdr, &spec->scp_resp_header, 4);
1365                         memcpy(&ret_msg->data, spec->scp_resp_data,
1366                                spec->wait_num_data);
1367                         *bytes_returned = (spec->scp_resp_count + 1) * 4;
1368                         status = 0;
1369                 } else {
1370                         status = -EIO;
1371                 }
1372                 spec->wait_scp = 0;
1373         }
1374
1375         return status;
1376 }
1377
1378 /**
1379  * Prepare and send the SCP message to DSP
1380  * @codec: the HDA codec
1381  * @mod_id: ID of the DSP module to send the command
1382  * @req: ID of request to send to the DSP module
1383  * @dir: SET or GET
1384  * @data: pointer to the data to send with the request, request specific
1385  * @len: length of the data, in bytes
1386  * @reply: point to the buffer to hold data returned for a reply
1387  * @reply_len: length of the reply buffer returned from GET
1388  *
1389  * Returns zero or a negative error code.
1390  */
1391 static int dspio_scp(struct hda_codec *codec,
1392                 int mod_id, int req, int dir, void *data, unsigned int len,
1393                 void *reply, unsigned int *reply_len)
1394 {
1395         int status = 0;
1396         struct scp_msg scp_send, scp_reply;
1397         unsigned int ret_bytes, send_size, ret_size;
1398         unsigned int send_get_flag, reply_resp_flag, reply_error_flag;
1399         unsigned int reply_data_size;
1400
1401         memset(&scp_send, 0, sizeof(scp_send));
1402         memset(&scp_reply, 0, sizeof(scp_reply));
1403
1404         if ((len != 0 && data == NULL) || (len > SCP_MAX_DATA_WORDS))
1405                 return -EINVAL;
1406
1407         if (dir == SCP_GET && reply == NULL) {
1408                 codec_dbg(codec, "dspio_scp get but has no buffer\n");
1409                 return -EINVAL;
1410         }
1411
1412         if (reply != NULL && (reply_len == NULL || (*reply_len == 0))) {
1413                 codec_dbg(codec, "dspio_scp bad resp buf len parms\n");
1414                 return -EINVAL;
1415         }
1416
1417         scp_send.hdr = make_scp_header(mod_id, 0x20, (dir == SCP_GET), req,
1418                                        0, 0, 0, len/sizeof(unsigned int));
1419         if (data != NULL && len > 0) {
1420                 len = min((unsigned int)(sizeof(scp_send.data)), len);
1421                 memcpy(scp_send.data, data, len);
1422         }
1423
1424         ret_bytes = 0;
1425         send_size = sizeof(unsigned int) + len;
1426         status = dspio_send_scp_message(codec, (unsigned char *)&scp_send,
1427                                         send_size, (unsigned char *)&scp_reply,
1428                                         sizeof(scp_reply), &ret_bytes);
1429
1430         if (status < 0) {
1431                 codec_dbg(codec, "dspio_scp: send scp msg failed\n");
1432                 return status;
1433         }
1434
1435         /* extract send and reply headers members */
1436         extract_scp_header(scp_send.hdr, NULL, NULL, &send_get_flag,
1437                            NULL, NULL, NULL, NULL, NULL);
1438         extract_scp_header(scp_reply.hdr, NULL, NULL, NULL, NULL, NULL,
1439                            &reply_resp_flag, &reply_error_flag,
1440                            &reply_data_size);
1441
1442         if (!send_get_flag)
1443                 return 0;
1444
1445         if (reply_resp_flag && !reply_error_flag) {
1446                 ret_size = (ret_bytes - sizeof(scp_reply.hdr))
1447                                         / sizeof(unsigned int);
1448
1449                 if (*reply_len < ret_size*sizeof(unsigned int)) {
1450                         codec_dbg(codec, "reply too long for buf\n");
1451                         return -EINVAL;
1452                 } else if (ret_size != reply_data_size) {
1453                         codec_dbg(codec, "RetLen and HdrLen .NE.\n");
1454                         return -EINVAL;
1455                 } else {
1456                         *reply_len = ret_size*sizeof(unsigned int);
1457                         memcpy(reply, scp_reply.data, *reply_len);
1458                 }
1459         } else {
1460                 codec_dbg(codec, "reply ill-formed or errflag set\n");
1461                 return -EIO;
1462         }
1463
1464         return status;
1465 }
1466
1467 /*
1468  * Set DSP parameters
1469  */
1470 static int dspio_set_param(struct hda_codec *codec, int mod_id,
1471                         int req, void *data, unsigned int len)
1472 {
1473         return dspio_scp(codec, mod_id, req, SCP_SET, data, len, NULL, NULL);
1474 }
1475
1476 static int dspio_set_uint_param(struct hda_codec *codec, int mod_id,
1477                         int req, unsigned int data)
1478 {
1479         return dspio_set_param(codec, mod_id, req, &data, sizeof(unsigned int));
1480 }
1481
1482 /*
1483  * Allocate a DSP DMA channel via an SCP message
1484  */
1485 static int dspio_alloc_dma_chan(struct hda_codec *codec, unsigned int *dma_chan)
1486 {
1487         int status = 0;
1488         unsigned int size = sizeof(dma_chan);
1489
1490         codec_dbg(codec, "     dspio_alloc_dma_chan() -- begin\n");
1491         status = dspio_scp(codec, MASTERCONTROL, MASTERCONTROL_ALLOC_DMA_CHAN,
1492                         SCP_GET, NULL, 0, dma_chan, &size);
1493
1494         if (status < 0) {
1495                 codec_dbg(codec, "dspio_alloc_dma_chan: SCP Failed\n");
1496                 return status;
1497         }
1498
1499         if ((*dma_chan + 1) == 0) {
1500                 codec_dbg(codec, "no free dma channels to allocate\n");
1501                 return -EBUSY;
1502         }
1503
1504         codec_dbg(codec, "dspio_alloc_dma_chan: chan=%d\n", *dma_chan);
1505         codec_dbg(codec, "     dspio_alloc_dma_chan() -- complete\n");
1506
1507         return status;
1508 }
1509
1510 /*
1511  * Free a DSP DMA via an SCP message
1512  */
1513 static int dspio_free_dma_chan(struct hda_codec *codec, unsigned int dma_chan)
1514 {
1515         int status = 0;
1516         unsigned int dummy = 0;
1517
1518         codec_dbg(codec, "     dspio_free_dma_chan() -- begin\n");
1519         codec_dbg(codec, "dspio_free_dma_chan: chan=%d\n", dma_chan);
1520
1521         status = dspio_scp(codec, MASTERCONTROL, MASTERCONTROL_ALLOC_DMA_CHAN,
1522                            SCP_SET, &dma_chan, sizeof(dma_chan), NULL, &dummy);
1523
1524         if (status < 0) {
1525                 codec_dbg(codec, "dspio_free_dma_chan: SCP Failed\n");
1526                 return status;
1527         }
1528
1529         codec_dbg(codec, "     dspio_free_dma_chan() -- complete\n");
1530
1531         return status;
1532 }
1533
1534 /*
1535  * (Re)start the DSP
1536  */
1537 static int dsp_set_run_state(struct hda_codec *codec)
1538 {
1539         unsigned int dbg_ctrl_reg;
1540         unsigned int halt_state;
1541         int err;
1542
1543         err = chipio_read(codec, DSP_DBGCNTL_INST_OFFSET, &dbg_ctrl_reg);
1544         if (err < 0)
1545                 return err;
1546
1547         halt_state = (dbg_ctrl_reg & DSP_DBGCNTL_STATE_MASK) >>
1548                       DSP_DBGCNTL_STATE_LOBIT;
1549
1550         if (halt_state != 0) {
1551                 dbg_ctrl_reg &= ~((halt_state << DSP_DBGCNTL_SS_LOBIT) &
1552                                   DSP_DBGCNTL_SS_MASK);
1553                 err = chipio_write(codec, DSP_DBGCNTL_INST_OFFSET,
1554                                    dbg_ctrl_reg);
1555                 if (err < 0)
1556                         return err;
1557
1558                 dbg_ctrl_reg |= (halt_state << DSP_DBGCNTL_EXEC_LOBIT) &
1559                                 DSP_DBGCNTL_EXEC_MASK;
1560                 err = chipio_write(codec, DSP_DBGCNTL_INST_OFFSET,
1561                                    dbg_ctrl_reg);
1562                 if (err < 0)
1563                         return err;
1564         }
1565
1566         return 0;
1567 }
1568
1569 /*
1570  * Reset the DSP
1571  */
1572 static int dsp_reset(struct hda_codec *codec)
1573 {
1574         unsigned int res;
1575         int retry = 20;
1576
1577         codec_dbg(codec, "dsp_reset\n");
1578         do {
1579                 res = dspio_send(codec, VENDOR_DSPIO_DSP_INIT, 0);
1580                 retry--;
1581         } while (res == -EIO && retry);
1582
1583         if (!retry) {
1584                 codec_dbg(codec, "dsp_reset timeout\n");
1585                 return -EIO;
1586         }
1587
1588         return 0;
1589 }
1590
1591 /*
1592  * Convert chip address to DSP address
1593  */
1594 static unsigned int dsp_chip_to_dsp_addx(unsigned int chip_addx,
1595                                         bool *code, bool *yram)
1596 {
1597         *code = *yram = false;
1598
1599         if (UC_RANGE(chip_addx, 1)) {
1600                 *code = true;
1601                 return UC_OFF(chip_addx);
1602         } else if (X_RANGE_ALL(chip_addx, 1)) {
1603                 return X_OFF(chip_addx);
1604         } else if (Y_RANGE_ALL(chip_addx, 1)) {
1605                 *yram = true;
1606                 return Y_OFF(chip_addx);
1607         }
1608
1609         return INVALID_CHIP_ADDRESS;
1610 }
1611
1612 /*
1613  * Check if the DSP DMA is active
1614  */
1615 static bool dsp_is_dma_active(struct hda_codec *codec, unsigned int dma_chan)
1616 {
1617         unsigned int dma_chnlstart_reg;
1618
1619         chipio_read(codec, DSPDMAC_CHNLSTART_INST_OFFSET, &dma_chnlstart_reg);
1620
1621         return ((dma_chnlstart_reg & (1 <<
1622                         (DSPDMAC_CHNLSTART_EN_LOBIT + dma_chan))) != 0);
1623 }
1624
1625 static int dsp_dma_setup_common(struct hda_codec *codec,
1626                                 unsigned int chip_addx,
1627                                 unsigned int dma_chan,
1628                                 unsigned int port_map_mask,
1629                                 bool ovly)
1630 {
1631         int status = 0;
1632         unsigned int chnl_prop;
1633         unsigned int dsp_addx;
1634         unsigned int active;
1635         bool code, yram;
1636
1637         codec_dbg(codec, "-- dsp_dma_setup_common() -- Begin ---------\n");
1638
1639         if (dma_chan >= DSPDMAC_DMA_CFG_CHANNEL_COUNT) {
1640                 codec_dbg(codec, "dma chan num invalid\n");
1641                 return -EINVAL;
1642         }
1643
1644         if (dsp_is_dma_active(codec, dma_chan)) {
1645                 codec_dbg(codec, "dma already active\n");
1646                 return -EBUSY;
1647         }
1648
1649         dsp_addx = dsp_chip_to_dsp_addx(chip_addx, &code, &yram);
1650
1651         if (dsp_addx == INVALID_CHIP_ADDRESS) {
1652                 codec_dbg(codec, "invalid chip addr\n");
1653                 return -ENXIO;
1654         }
1655
1656         chnl_prop = DSPDMAC_CHNLPROP_AC_MASK;
1657         active = 0;
1658
1659         codec_dbg(codec, "   dsp_dma_setup_common()    start reg pgm\n");
1660
1661         if (ovly) {
1662                 status = chipio_read(codec, DSPDMAC_CHNLPROP_INST_OFFSET,
1663                                      &chnl_prop);
1664
1665                 if (status < 0) {
1666                         codec_dbg(codec, "read CHNLPROP Reg fail\n");
1667                         return status;
1668                 }
1669                 codec_dbg(codec, "dsp_dma_setup_common() Read CHNLPROP\n");
1670         }
1671
1672         if (!code)
1673                 chnl_prop &= ~(1 << (DSPDMAC_CHNLPROP_MSPCE_LOBIT + dma_chan));
1674         else
1675                 chnl_prop |=  (1 << (DSPDMAC_CHNLPROP_MSPCE_LOBIT + dma_chan));
1676
1677         chnl_prop &= ~(1 << (DSPDMAC_CHNLPROP_DCON_LOBIT + dma_chan));
1678
1679         status = chipio_write(codec, DSPDMAC_CHNLPROP_INST_OFFSET, chnl_prop);
1680         if (status < 0) {
1681                 codec_dbg(codec, "write CHNLPROP Reg fail\n");
1682                 return status;
1683         }
1684         codec_dbg(codec, "   dsp_dma_setup_common()    Write CHNLPROP\n");
1685
1686         if (ovly) {
1687                 status = chipio_read(codec, DSPDMAC_ACTIVE_INST_OFFSET,
1688                                      &active);
1689
1690                 if (status < 0) {
1691                         codec_dbg(codec, "read ACTIVE Reg fail\n");
1692                         return status;
1693                 }
1694                 codec_dbg(codec, "dsp_dma_setup_common() Read ACTIVE\n");
1695         }
1696
1697         active &= (~(1 << (DSPDMAC_ACTIVE_AAR_LOBIT + dma_chan))) &
1698                 DSPDMAC_ACTIVE_AAR_MASK;
1699
1700         status = chipio_write(codec, DSPDMAC_ACTIVE_INST_OFFSET, active);
1701         if (status < 0) {
1702                 codec_dbg(codec, "write ACTIVE Reg fail\n");
1703                 return status;
1704         }
1705
1706         codec_dbg(codec, "   dsp_dma_setup_common()    Write ACTIVE\n");
1707
1708         status = chipio_write(codec, DSPDMAC_AUDCHSEL_INST_OFFSET(dma_chan),
1709                               port_map_mask);
1710         if (status < 0) {
1711                 codec_dbg(codec, "write AUDCHSEL Reg fail\n");
1712                 return status;
1713         }
1714         codec_dbg(codec, "   dsp_dma_setup_common()    Write AUDCHSEL\n");
1715
1716         status = chipio_write(codec, DSPDMAC_IRQCNT_INST_OFFSET(dma_chan),
1717                         DSPDMAC_IRQCNT_BICNT_MASK | DSPDMAC_IRQCNT_CICNT_MASK);
1718         if (status < 0) {
1719                 codec_dbg(codec, "write IRQCNT Reg fail\n");
1720                 return status;
1721         }
1722         codec_dbg(codec, "   dsp_dma_setup_common()    Write IRQCNT\n");
1723
1724         codec_dbg(codec,
1725                    "ChipA=0x%x,DspA=0x%x,dmaCh=%u, "
1726                    "CHSEL=0x%x,CHPROP=0x%x,Active=0x%x\n",
1727                    chip_addx, dsp_addx, dma_chan,
1728                    port_map_mask, chnl_prop, active);
1729
1730         codec_dbg(codec, "-- dsp_dma_setup_common() -- Complete ------\n");
1731
1732         return 0;
1733 }
1734
1735 /*
1736  * Setup the DSP DMA per-transfer-specific registers
1737  */
1738 static int dsp_dma_setup(struct hda_codec *codec,
1739                         unsigned int chip_addx,
1740                         unsigned int count,
1741                         unsigned int dma_chan)
1742 {
1743         int status = 0;
1744         bool code, yram;
1745         unsigned int dsp_addx;
1746         unsigned int addr_field;
1747         unsigned int incr_field;
1748         unsigned int base_cnt;
1749         unsigned int cur_cnt;
1750         unsigned int dma_cfg = 0;
1751         unsigned int adr_ofs = 0;
1752         unsigned int xfr_cnt = 0;
1753         const unsigned int max_dma_count = 1 << (DSPDMAC_XFRCNT_BCNT_HIBIT -
1754                                                 DSPDMAC_XFRCNT_BCNT_LOBIT + 1);
1755
1756         codec_dbg(codec, "-- dsp_dma_setup() -- Begin ---------\n");
1757
1758         if (count > max_dma_count) {
1759                 codec_dbg(codec, "count too big\n");
1760                 return -EINVAL;
1761         }
1762
1763         dsp_addx = dsp_chip_to_dsp_addx(chip_addx, &code, &yram);
1764         if (dsp_addx == INVALID_CHIP_ADDRESS) {
1765                 codec_dbg(codec, "invalid chip addr\n");
1766                 return -ENXIO;
1767         }
1768
1769         codec_dbg(codec, "   dsp_dma_setup()    start reg pgm\n");
1770
1771         addr_field = dsp_addx << DSPDMAC_DMACFG_DBADR_LOBIT;
1772         incr_field   = 0;
1773
1774         if (!code) {
1775                 addr_field <<= 1;
1776                 if (yram)
1777                         addr_field |= (1 << DSPDMAC_DMACFG_DBADR_LOBIT);
1778
1779                 incr_field  = (1 << DSPDMAC_DMACFG_AINCR_LOBIT);
1780         }
1781
1782         dma_cfg = addr_field + incr_field;
1783         status = chipio_write(codec, DSPDMAC_DMACFG_INST_OFFSET(dma_chan),
1784                                 dma_cfg);
1785         if (status < 0) {
1786                 codec_dbg(codec, "write DMACFG Reg fail\n");
1787                 return status;
1788         }
1789         codec_dbg(codec, "   dsp_dma_setup()    Write DMACFG\n");
1790
1791         adr_ofs = (count - 1) << (DSPDMAC_DSPADROFS_BOFS_LOBIT +
1792                                                         (code ? 0 : 1));
1793
1794         status = chipio_write(codec, DSPDMAC_DSPADROFS_INST_OFFSET(dma_chan),
1795                                 adr_ofs);
1796         if (status < 0) {
1797                 codec_dbg(codec, "write DSPADROFS Reg fail\n");
1798                 return status;
1799         }
1800         codec_dbg(codec, "   dsp_dma_setup()    Write DSPADROFS\n");
1801
1802         base_cnt = (count - 1) << DSPDMAC_XFRCNT_BCNT_LOBIT;
1803
1804         cur_cnt  = (count - 1) << DSPDMAC_XFRCNT_CCNT_LOBIT;
1805
1806         xfr_cnt = base_cnt | cur_cnt;
1807
1808         status = chipio_write(codec,
1809                                 DSPDMAC_XFRCNT_INST_OFFSET(dma_chan), xfr_cnt);
1810         if (status < 0) {
1811                 codec_dbg(codec, "write XFRCNT Reg fail\n");
1812                 return status;
1813         }
1814         codec_dbg(codec, "   dsp_dma_setup()    Write XFRCNT\n");
1815
1816         codec_dbg(codec,
1817                    "ChipA=0x%x, cnt=0x%x, DMACFG=0x%x, "
1818                    "ADROFS=0x%x, XFRCNT=0x%x\n",
1819                    chip_addx, count, dma_cfg, adr_ofs, xfr_cnt);
1820
1821         codec_dbg(codec, "-- dsp_dma_setup() -- Complete ---------\n");
1822
1823         return 0;
1824 }
1825
1826 /*
1827  * Start the DSP DMA
1828  */
1829 static int dsp_dma_start(struct hda_codec *codec,
1830                          unsigned int dma_chan, bool ovly)
1831 {
1832         unsigned int reg = 0;
1833         int status = 0;
1834
1835         codec_dbg(codec, "-- dsp_dma_start() -- Begin ---------\n");
1836
1837         if (ovly) {
1838                 status = chipio_read(codec,
1839                                      DSPDMAC_CHNLSTART_INST_OFFSET, &reg);
1840
1841                 if (status < 0) {
1842                         codec_dbg(codec, "read CHNLSTART reg fail\n");
1843                         return status;
1844                 }
1845                 codec_dbg(codec, "-- dsp_dma_start()    Read CHNLSTART\n");
1846
1847                 reg &= ~(DSPDMAC_CHNLSTART_EN_MASK |
1848                                 DSPDMAC_CHNLSTART_DIS_MASK);
1849         }
1850
1851         status = chipio_write(codec, DSPDMAC_CHNLSTART_INST_OFFSET,
1852                         reg | (1 << (dma_chan + DSPDMAC_CHNLSTART_EN_LOBIT)));
1853         if (status < 0) {
1854                 codec_dbg(codec, "write CHNLSTART reg fail\n");
1855                 return status;
1856         }
1857         codec_dbg(codec, "-- dsp_dma_start() -- Complete ---------\n");
1858
1859         return status;
1860 }
1861
1862 /*
1863  * Stop the DSP DMA
1864  */
1865 static int dsp_dma_stop(struct hda_codec *codec,
1866                         unsigned int dma_chan, bool ovly)
1867 {
1868         unsigned int reg = 0;
1869         int status = 0;
1870
1871         codec_dbg(codec, "-- dsp_dma_stop() -- Begin ---------\n");
1872
1873         if (ovly) {
1874                 status = chipio_read(codec,
1875                                      DSPDMAC_CHNLSTART_INST_OFFSET, &reg);
1876
1877                 if (status < 0) {
1878                         codec_dbg(codec, "read CHNLSTART reg fail\n");
1879                         return status;
1880                 }
1881                 codec_dbg(codec, "-- dsp_dma_stop()    Read CHNLSTART\n");
1882                 reg &= ~(DSPDMAC_CHNLSTART_EN_MASK |
1883                                 DSPDMAC_CHNLSTART_DIS_MASK);
1884         }
1885
1886         status = chipio_write(codec, DSPDMAC_CHNLSTART_INST_OFFSET,
1887                         reg | (1 << (dma_chan + DSPDMAC_CHNLSTART_DIS_LOBIT)));
1888         if (status < 0) {
1889                 codec_dbg(codec, "write CHNLSTART reg fail\n");
1890                 return status;
1891         }
1892         codec_dbg(codec, "-- dsp_dma_stop() -- Complete ---------\n");
1893
1894         return status;
1895 }
1896
1897 /**
1898  * Allocate router ports
1899  *
1900  * @codec: the HDA codec
1901  * @num_chans: number of channels in the stream
1902  * @ports_per_channel: number of ports per channel
1903  * @start_device: start device
1904  * @port_map: pointer to the port list to hold the allocated ports
1905  *
1906  * Returns zero or a negative error code.
1907  */
1908 static int dsp_allocate_router_ports(struct hda_codec *codec,
1909                                      unsigned int num_chans,
1910                                      unsigned int ports_per_channel,
1911                                      unsigned int start_device,
1912                                      unsigned int *port_map)
1913 {
1914         int status = 0;
1915         int res;
1916         u8 val;
1917
1918         status = chipio_send(codec, VENDOR_CHIPIO_STATUS, 0);
1919         if (status < 0)
1920                 return status;
1921
1922         val = start_device << 6;
1923         val |= (ports_per_channel - 1) << 4;
1924         val |= num_chans - 1;
1925
1926         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1927                             VENDOR_CHIPIO_PORT_ALLOC_CONFIG_SET,
1928                             val);
1929
1930         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1931                             VENDOR_CHIPIO_PORT_ALLOC_SET,
1932                             MEM_CONNID_DSP);
1933
1934         status = chipio_send(codec, VENDOR_CHIPIO_STATUS, 0);
1935         if (status < 0)
1936                 return status;
1937
1938         res = snd_hda_codec_read(codec, WIDGET_CHIP_CTRL, 0,
1939                                 VENDOR_CHIPIO_PORT_ALLOC_GET, 0);
1940
1941         *port_map = res;
1942
1943         return (res < 0) ? res : 0;
1944 }
1945
1946 /*
1947  * Free router ports
1948  */
1949 static int dsp_free_router_ports(struct hda_codec *codec)
1950 {
1951         int status = 0;
1952
1953         status = chipio_send(codec, VENDOR_CHIPIO_STATUS, 0);
1954         if (status < 0)
1955                 return status;
1956
1957         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
1958                             VENDOR_CHIPIO_PORT_FREE_SET,
1959                             MEM_CONNID_DSP);
1960
1961         status = chipio_send(codec, VENDOR_CHIPIO_STATUS, 0);
1962
1963         return status;
1964 }
1965
1966 /*
1967  * Allocate DSP ports for the download stream
1968  */
1969 static int dsp_allocate_ports(struct hda_codec *codec,
1970                         unsigned int num_chans,
1971                         unsigned int rate_multi, unsigned int *port_map)
1972 {
1973         int status;
1974
1975         codec_dbg(codec, "     dsp_allocate_ports() -- begin\n");
1976
1977         if ((rate_multi != 1) && (rate_multi != 2) && (rate_multi != 4)) {
1978                 codec_dbg(codec, "bad rate multiple\n");
1979                 return -EINVAL;
1980         }
1981
1982         status = dsp_allocate_router_ports(codec, num_chans,
1983                                            rate_multi, 0, port_map);
1984
1985         codec_dbg(codec, "     dsp_allocate_ports() -- complete\n");
1986
1987         return status;
1988 }
1989
1990 static int dsp_allocate_ports_format(struct hda_codec *codec,
1991                         const unsigned short fmt,
1992                         unsigned int *port_map)
1993 {
1994         int status;
1995         unsigned int num_chans;
1996
1997         unsigned int sample_rate_div = ((get_hdafmt_rate(fmt) >> 0) & 3) + 1;
1998         unsigned int sample_rate_mul = ((get_hdafmt_rate(fmt) >> 3) & 3) + 1;
1999         unsigned int rate_multi = sample_rate_mul / sample_rate_div;
2000
2001         if ((rate_multi != 1) && (rate_multi != 2) && (rate_multi != 4)) {
2002                 codec_dbg(codec, "bad rate multiple\n");
2003                 return -EINVAL;
2004         }
2005
2006         num_chans = get_hdafmt_chs(fmt) + 1;
2007
2008         status = dsp_allocate_ports(codec, num_chans, rate_multi, port_map);
2009
2010         return status;
2011 }
2012
2013 /*
2014  * free DSP ports
2015  */
2016 static int dsp_free_ports(struct hda_codec *codec)
2017 {
2018         int status;
2019
2020         codec_dbg(codec, "     dsp_free_ports() -- begin\n");
2021
2022         status = dsp_free_router_ports(codec);
2023         if (status < 0) {
2024                 codec_dbg(codec, "free router ports fail\n");
2025                 return status;
2026         }
2027         codec_dbg(codec, "     dsp_free_ports() -- complete\n");
2028
2029         return status;
2030 }
2031
2032 /*
2033  *  HDA DMA engine stuffs for DSP code download
2034  */
2035 struct dma_engine {
2036         struct hda_codec *codec;
2037         unsigned short m_converter_format;
2038         struct snd_dma_buffer *dmab;
2039         unsigned int buf_size;
2040 };
2041
2042
2043 enum dma_state {
2044         DMA_STATE_STOP  = 0,
2045         DMA_STATE_RUN   = 1
2046 };
2047
2048 static int dma_convert_to_hda_format(struct hda_codec *codec,
2049                 unsigned int sample_rate,
2050                 unsigned short channels,
2051                 unsigned short *hda_format)
2052 {
2053         unsigned int format_val;
2054
2055         format_val = snd_hdac_calc_stream_format(sample_rate,
2056                                 channels, SNDRV_PCM_FORMAT_S32_LE, 32, 0);
2057
2058         if (hda_format)
2059                 *hda_format = (unsigned short)format_val;
2060
2061         return 0;
2062 }
2063
2064 /*
2065  *  Reset DMA for DSP download
2066  */
2067 static int dma_reset(struct dma_engine *dma)
2068 {
2069         struct hda_codec *codec = dma->codec;
2070         struct ca0132_spec *spec = codec->spec;
2071         int status;
2072
2073         if (dma->dmab->area)
2074                 snd_hda_codec_load_dsp_cleanup(codec, dma->dmab);
2075
2076         status = snd_hda_codec_load_dsp_prepare(codec,
2077                         dma->m_converter_format,
2078                         dma->buf_size,
2079                         dma->dmab);
2080         if (status < 0)
2081                 return status;
2082         spec->dsp_stream_id = status;
2083         return 0;
2084 }
2085
2086 static int dma_set_state(struct dma_engine *dma, enum dma_state state)
2087 {
2088         bool cmd;
2089
2090         switch (state) {
2091         case DMA_STATE_STOP:
2092                 cmd = false;
2093                 break;
2094         case DMA_STATE_RUN:
2095                 cmd = true;
2096                 break;
2097         default:
2098                 return 0;
2099         }
2100
2101         snd_hda_codec_load_dsp_trigger(dma->codec, cmd);
2102         return 0;
2103 }
2104
2105 static unsigned int dma_get_buffer_size(struct dma_engine *dma)
2106 {
2107         return dma->dmab->bytes;
2108 }
2109
2110 static unsigned char *dma_get_buffer_addr(struct dma_engine *dma)
2111 {
2112         return dma->dmab->area;
2113 }
2114
2115 static int dma_xfer(struct dma_engine *dma,
2116                 const unsigned int *data,
2117                 unsigned int count)
2118 {
2119         memcpy(dma->dmab->area, data, count);
2120         return 0;
2121 }
2122
2123 static void dma_get_converter_format(
2124                 struct dma_engine *dma,
2125                 unsigned short *format)
2126 {
2127         if (format)
2128                 *format = dma->m_converter_format;
2129 }
2130
2131 static unsigned int dma_get_stream_id(struct dma_engine *dma)
2132 {
2133         struct ca0132_spec *spec = dma->codec->spec;
2134
2135         return spec->dsp_stream_id;
2136 }
2137
2138 struct dsp_image_seg {
2139         u32 magic;
2140         u32 chip_addr;
2141         u32 count;
2142         u32 data[0];
2143 };
2144
2145 static const u32 g_magic_value = 0x4c46584d;
2146 static const u32 g_chip_addr_magic_value = 0xFFFFFF01;
2147
2148 static bool is_valid(const struct dsp_image_seg *p)
2149 {
2150         return p->magic == g_magic_value;
2151 }
2152
2153 static bool is_hci_prog_list_seg(const struct dsp_image_seg *p)
2154 {
2155         return g_chip_addr_magic_value == p->chip_addr;
2156 }
2157
2158 static bool is_last(const struct dsp_image_seg *p)
2159 {
2160         return p->count == 0;
2161 }
2162
2163 static size_t dsp_sizeof(const struct dsp_image_seg *p)
2164 {
2165         return sizeof(*p) + p->count*sizeof(u32);
2166 }
2167
2168 static const struct dsp_image_seg *get_next_seg_ptr(
2169                                 const struct dsp_image_seg *p)
2170 {
2171         return (struct dsp_image_seg *)((unsigned char *)(p) + dsp_sizeof(p));
2172 }
2173
2174 /*
2175  * CA0132 chip DSP transfer stuffs.  For DSP download.
2176  */
2177 #define INVALID_DMA_CHANNEL (~0U)
2178
2179 /*
2180  * Program a list of address/data pairs via the ChipIO widget.
2181  * The segment data is in the format of successive pairs of words.
2182  * These are repeated as indicated by the segment's count field.
2183  */
2184 static int dspxfr_hci_write(struct hda_codec *codec,
2185                         const struct dsp_image_seg *fls)
2186 {
2187         int status;
2188         const u32 *data;
2189         unsigned int count;
2190
2191         if (fls == NULL || fls->chip_addr != g_chip_addr_magic_value) {
2192                 codec_dbg(codec, "hci_write invalid params\n");
2193                 return -EINVAL;
2194         }
2195
2196         count = fls->count;
2197         data = (u32 *)(fls->data);
2198         while (count >= 2) {
2199                 status = chipio_write(codec, data[0], data[1]);
2200                 if (status < 0) {
2201                         codec_dbg(codec, "hci_write chipio failed\n");
2202                         return status;
2203                 }
2204                 count -= 2;
2205                 data  += 2;
2206         }
2207         return 0;
2208 }
2209
2210 /**
2211  * Write a block of data into DSP code or data RAM using pre-allocated
2212  * DMA engine.
2213  *
2214  * @codec: the HDA codec
2215  * @fls: pointer to a fast load image
2216  * @reloc: Relocation address for loading single-segment overlays, or 0 for
2217  *         no relocation
2218  * @dma_engine: pointer to DMA engine to be used for DSP download
2219  * @dma_chan: The number of DMA channels used for DSP download
2220  * @port_map_mask: port mapping
2221  * @ovly: TRUE if overlay format is required
2222  *
2223  * Returns zero or a negative error code.
2224  */
2225 static int dspxfr_one_seg(struct hda_codec *codec,
2226                         const struct dsp_image_seg *fls,
2227                         unsigned int reloc,
2228                         struct dma_engine *dma_engine,
2229                         unsigned int dma_chan,
2230                         unsigned int port_map_mask,
2231                         bool ovly)
2232 {
2233         int status = 0;
2234         bool comm_dma_setup_done = false;
2235         const unsigned int *data;
2236         unsigned int chip_addx;
2237         unsigned int words_to_write;
2238         unsigned int buffer_size_words;
2239         unsigned char *buffer_addx;
2240         unsigned short hda_format;
2241         unsigned int sample_rate_div;
2242         unsigned int sample_rate_mul;
2243         unsigned int num_chans;
2244         unsigned int hda_frame_size_words;
2245         unsigned int remainder_words;
2246         const u32 *data_remainder;
2247         u32 chip_addx_remainder;
2248         unsigned int run_size_words;
2249         const struct dsp_image_seg *hci_write = NULL;
2250         unsigned long timeout;
2251         bool dma_active;
2252
2253         if (fls == NULL)
2254                 return -EINVAL;
2255         if (is_hci_prog_list_seg(fls)) {
2256                 hci_write = fls;
2257                 fls = get_next_seg_ptr(fls);
2258         }
2259
2260         if (hci_write && (!fls || is_last(fls))) {
2261                 codec_dbg(codec, "hci_write\n");
2262                 return dspxfr_hci_write(codec, hci_write);
2263         }
2264
2265         if (fls == NULL || dma_engine == NULL || port_map_mask == 0) {
2266                 codec_dbg(codec, "Invalid Params\n");
2267                 return -EINVAL;
2268         }
2269
2270         data = fls->data;
2271         chip_addx = fls->chip_addr,
2272         words_to_write = fls->count;
2273
2274         if (!words_to_write)
2275                 return hci_write ? dspxfr_hci_write(codec, hci_write) : 0;
2276         if (reloc)
2277                 chip_addx = (chip_addx & (0xFFFF0000 << 2)) + (reloc << 2);
2278
2279         if (!UC_RANGE(chip_addx, words_to_write) &&
2280             !X_RANGE_ALL(chip_addx, words_to_write) &&
2281             !Y_RANGE_ALL(chip_addx, words_to_write)) {
2282                 codec_dbg(codec, "Invalid chip_addx Params\n");
2283                 return -EINVAL;
2284         }
2285
2286         buffer_size_words = (unsigned int)dma_get_buffer_size(dma_engine) /
2287                                         sizeof(u32);
2288
2289         buffer_addx = dma_get_buffer_addr(dma_engine);
2290
2291         if (buffer_addx == NULL) {
2292                 codec_dbg(codec, "dma_engine buffer NULL\n");
2293                 return -EINVAL;
2294         }
2295
2296         dma_get_converter_format(dma_engine, &hda_format);
2297         sample_rate_div = ((get_hdafmt_rate(hda_format) >> 0) & 3) + 1;
2298         sample_rate_mul = ((get_hdafmt_rate(hda_format) >> 3) & 3) + 1;
2299         num_chans = get_hdafmt_chs(hda_format) + 1;
2300
2301         hda_frame_size_words = ((sample_rate_div == 0) ? 0 :
2302                         (num_chans * sample_rate_mul / sample_rate_div));
2303
2304         if (hda_frame_size_words == 0) {
2305                 codec_dbg(codec, "frmsz zero\n");
2306                 return -EINVAL;
2307         }
2308
2309         buffer_size_words = min(buffer_size_words,
2310                                 (unsigned int)(UC_RANGE(chip_addx, 1) ?
2311                                 65536 : 32768));
2312         buffer_size_words -= buffer_size_words % hda_frame_size_words;
2313         codec_dbg(codec,
2314                    "chpadr=0x%08x frmsz=%u nchan=%u "
2315                    "rate_mul=%u div=%u bufsz=%u\n",
2316                    chip_addx, hda_frame_size_words, num_chans,
2317                    sample_rate_mul, sample_rate_div, buffer_size_words);
2318
2319         if (buffer_size_words < hda_frame_size_words) {
2320                 codec_dbg(codec, "dspxfr_one_seg:failed\n");
2321                 return -EINVAL;
2322         }
2323
2324         remainder_words = words_to_write % hda_frame_size_words;
2325         data_remainder = data;
2326         chip_addx_remainder = chip_addx;
2327
2328         data += remainder_words;
2329         chip_addx += remainder_words*sizeof(u32);
2330         words_to_write -= remainder_words;
2331
2332         while (words_to_write != 0) {
2333                 run_size_words = min(buffer_size_words, words_to_write);
2334                 codec_dbg(codec, "dspxfr (seg loop)cnt=%u rs=%u remainder=%u\n",
2335                             words_to_write, run_size_words, remainder_words);
2336                 dma_xfer(dma_engine, data, run_size_words*sizeof(u32));
2337                 if (!comm_dma_setup_done) {
2338                         status = dsp_dma_stop(codec, dma_chan, ovly);
2339                         if (status < 0)
2340                                 return status;
2341                         status = dsp_dma_setup_common(codec, chip_addx,
2342                                                 dma_chan, port_map_mask, ovly);
2343                         if (status < 0)
2344                                 return status;
2345                         comm_dma_setup_done = true;
2346                 }
2347
2348                 status = dsp_dma_setup(codec, chip_addx,
2349                                                 run_size_words, dma_chan);
2350                 if (status < 0)
2351                         return status;
2352                 status = dsp_dma_start(codec, dma_chan, ovly);
2353                 if (status < 0)
2354                         return status;
2355                 if (!dsp_is_dma_active(codec, dma_chan)) {
2356                         codec_dbg(codec, "dspxfr:DMA did not start\n");
2357                         return -EIO;
2358                 }
2359                 status = dma_set_state(dma_engine, DMA_STATE_RUN);
2360                 if (status < 0)
2361                         return status;
2362                 if (remainder_words != 0) {
2363                         status = chipio_write_multiple(codec,
2364                                                 chip_addx_remainder,
2365                                                 data_remainder,
2366                                                 remainder_words);
2367                         if (status < 0)
2368                                 return status;
2369                         remainder_words = 0;
2370                 }
2371                 if (hci_write) {
2372                         status = dspxfr_hci_write(codec, hci_write);
2373                         if (status < 0)
2374                                 return status;
2375                         hci_write = NULL;
2376                 }
2377
2378                 timeout = jiffies + msecs_to_jiffies(2000);
2379                 do {
2380                         dma_active = dsp_is_dma_active(codec, dma_chan);
2381                         if (!dma_active)
2382                                 break;
2383                         msleep(20);
2384                 } while (time_before(jiffies, timeout));
2385                 if (dma_active)
2386                         break;
2387
2388                 codec_dbg(codec, "+++++ DMA complete\n");
2389                 dma_set_state(dma_engine, DMA_STATE_STOP);
2390                 status = dma_reset(dma_engine);
2391
2392                 if (status < 0)
2393                         return status;
2394
2395                 data += run_size_words;
2396                 chip_addx += run_size_words*sizeof(u32);
2397                 words_to_write -= run_size_words;
2398         }
2399
2400         if (remainder_words != 0) {
2401                 status = chipio_write_multiple(codec, chip_addx_remainder,
2402                                         data_remainder, remainder_words);
2403         }
2404
2405         return status;
2406 }
2407
2408 /**
2409  * Write the entire DSP image of a DSP code/data overlay to DSP memories
2410  *
2411  * @codec: the HDA codec
2412  * @fls_data: pointer to a fast load image
2413  * @reloc: Relocation address for loading single-segment overlays, or 0 for
2414  *         no relocation
2415  * @sample_rate: sampling rate of the stream used for DSP download
2416  * @channels: channels of the stream used for DSP download
2417  * @ovly: TRUE if overlay format is required
2418  *
2419  * Returns zero or a negative error code.
2420  */
2421 static int dspxfr_image(struct hda_codec *codec,
2422                         const struct dsp_image_seg *fls_data,
2423                         unsigned int reloc,
2424                         unsigned int sample_rate,
2425                         unsigned short channels,
2426                         bool ovly)
2427 {
2428         struct ca0132_spec *spec = codec->spec;
2429         int status;
2430         unsigned short hda_format = 0;
2431         unsigned int response;
2432         unsigned char stream_id = 0;
2433         struct dma_engine *dma_engine;
2434         unsigned int dma_chan;
2435         unsigned int port_map_mask;
2436
2437         if (fls_data == NULL)
2438                 return -EINVAL;
2439
2440         dma_engine = kzalloc(sizeof(*dma_engine), GFP_KERNEL);
2441         if (!dma_engine)
2442                 return -ENOMEM;
2443
2444         dma_engine->dmab = kzalloc(sizeof(*dma_engine->dmab), GFP_KERNEL);
2445         if (!dma_engine->dmab) {
2446                 kfree(dma_engine);
2447                 return -ENOMEM;
2448         }
2449
2450         dma_engine->codec = codec;
2451         dma_convert_to_hda_format(codec, sample_rate, channels, &hda_format);
2452         dma_engine->m_converter_format = hda_format;
2453         dma_engine->buf_size = (ovly ? DSP_DMA_WRITE_BUFLEN_OVLY :
2454                         DSP_DMA_WRITE_BUFLEN_INIT) * 2;
2455
2456         dma_chan = ovly ? INVALID_DMA_CHANNEL : 0;
2457
2458         status = codec_set_converter_format(codec, WIDGET_CHIP_CTRL,
2459                                         hda_format, &response);
2460
2461         if (status < 0) {
2462                 codec_dbg(codec, "set converter format fail\n");
2463                 goto exit;
2464         }
2465
2466         status = snd_hda_codec_load_dsp_prepare(codec,
2467                                 dma_engine->m_converter_format,
2468                                 dma_engine->buf_size,
2469                                 dma_engine->dmab);
2470         if (status < 0)
2471                 goto exit;
2472         spec->dsp_stream_id = status;
2473
2474         if (ovly) {
2475                 status = dspio_alloc_dma_chan(codec, &dma_chan);
2476                 if (status < 0) {
2477                         codec_dbg(codec, "alloc dmachan fail\n");
2478                         dma_chan = INVALID_DMA_CHANNEL;
2479                         goto exit;
2480                 }
2481         }
2482
2483         port_map_mask = 0;
2484         status = dsp_allocate_ports_format(codec, hda_format,
2485                                         &port_map_mask);
2486         if (status < 0) {
2487                 codec_dbg(codec, "alloc ports fail\n");
2488                 goto exit;
2489         }
2490
2491         stream_id = dma_get_stream_id(dma_engine);
2492         status = codec_set_converter_stream_channel(codec,
2493                         WIDGET_CHIP_CTRL, stream_id, 0, &response);
2494         if (status < 0) {
2495                 codec_dbg(codec, "set stream chan fail\n");
2496                 goto exit;
2497         }
2498
2499         while ((fls_data != NULL) && !is_last(fls_data)) {
2500                 if (!is_valid(fls_data)) {
2501                         codec_dbg(codec, "FLS check fail\n");
2502                         status = -EINVAL;
2503                         goto exit;
2504                 }
2505                 status = dspxfr_one_seg(codec, fls_data, reloc,
2506                                         dma_engine, dma_chan,
2507                                         port_map_mask, ovly);
2508                 if (status < 0)
2509                         break;
2510
2511                 if (is_hci_prog_list_seg(fls_data))
2512                         fls_data = get_next_seg_ptr(fls_data);
2513
2514                 if ((fls_data != NULL) && !is_last(fls_data))
2515                         fls_data = get_next_seg_ptr(fls_data);
2516         }
2517
2518         if (port_map_mask != 0)
2519                 status = dsp_free_ports(codec);
2520
2521         if (status < 0)
2522                 goto exit;
2523
2524         status = codec_set_converter_stream_channel(codec,
2525                                 WIDGET_CHIP_CTRL, 0, 0, &response);
2526
2527 exit:
2528         if (ovly && (dma_chan != INVALID_DMA_CHANNEL))
2529                 dspio_free_dma_chan(codec, dma_chan);
2530
2531         if (dma_engine->dmab->area)
2532                 snd_hda_codec_load_dsp_cleanup(codec, dma_engine->dmab);
2533         kfree(dma_engine->dmab);
2534         kfree(dma_engine);
2535
2536         return status;
2537 }
2538
2539 /*
2540  * CA0132 DSP download stuffs.
2541  */
2542 static void dspload_post_setup(struct hda_codec *codec)
2543 {
2544         codec_dbg(codec, "---- dspload_post_setup ------\n");
2545
2546         /*set DSP speaker to 2.0 configuration*/
2547         chipio_write(codec, XRAM_XRAM_INST_OFFSET(0x18), 0x08080080);
2548         chipio_write(codec, XRAM_XRAM_INST_OFFSET(0x19), 0x3f800000);
2549
2550         /*update write pointer*/
2551         chipio_write(codec, XRAM_XRAM_INST_OFFSET(0x29), 0x00000002);
2552 }
2553
2554 /**
2555  * dspload_image - Download DSP from a DSP Image Fast Load structure.
2556  *
2557  * @codec: the HDA codec
2558  * @fls: pointer to a fast load image
2559  * @ovly: TRUE if overlay format is required
2560  * @reloc: Relocation address for loading single-segment overlays, or 0 for
2561  *         no relocation
2562  * @autostart: TRUE if DSP starts after loading; ignored if ovly is TRUE
2563  * @router_chans: number of audio router channels to be allocated (0 means use
2564  *                internal defaults; max is 32)
2565  *
2566  * Download DSP from a DSP Image Fast Load structure. This structure is a
2567  * linear, non-constant sized element array of structures, each of which
2568  * contain the count of the data to be loaded, the data itself, and the
2569  * corresponding starting chip address of the starting data location.
2570  * Returns zero or a negative error code.
2571  */
2572 static int dspload_image(struct hda_codec *codec,
2573                         const struct dsp_image_seg *fls,
2574                         bool ovly,
2575                         unsigned int reloc,
2576                         bool autostart,
2577                         int router_chans)
2578 {
2579         int status = 0;
2580         unsigned int sample_rate;
2581         unsigned short channels;
2582
2583         codec_dbg(codec, "---- dspload_image begin ------\n");
2584         if (router_chans == 0) {
2585                 if (!ovly)
2586                         router_chans = DMA_TRANSFER_FRAME_SIZE_NWORDS;
2587                 else
2588                         router_chans = DMA_OVERLAY_FRAME_SIZE_NWORDS;
2589         }
2590
2591         sample_rate = 48000;
2592         channels = (unsigned short)router_chans;
2593
2594         while (channels > 16) {
2595                 sample_rate *= 2;
2596                 channels /= 2;
2597         }
2598
2599         do {
2600                 codec_dbg(codec, "Ready to program DMA\n");
2601                 if (!ovly)
2602                         status = dsp_reset(codec);
2603
2604                 if (status < 0)
2605                         break;
2606
2607                 codec_dbg(codec, "dsp_reset() complete\n");
2608                 status = dspxfr_image(codec, fls, reloc, sample_rate, channels,
2609                                       ovly);
2610
2611                 if (status < 0)
2612                         break;
2613
2614                 codec_dbg(codec, "dspxfr_image() complete\n");
2615                 if (autostart && !ovly) {
2616                         dspload_post_setup(codec);
2617                         status = dsp_set_run_state(codec);
2618                 }
2619
2620                 codec_dbg(codec, "LOAD FINISHED\n");
2621         } while (0);
2622
2623         return status;
2624 }
2625
2626 #ifdef CONFIG_SND_HDA_CODEC_CA0132_DSP
2627 static bool dspload_is_loaded(struct hda_codec *codec)
2628 {
2629         unsigned int data = 0;
2630         int status = 0;
2631
2632         status = chipio_read(codec, 0x40004, &data);
2633         if ((status < 0) || (data != 1))
2634                 return false;
2635
2636         return true;
2637 }
2638 #else
2639 #define dspload_is_loaded(codec)        false
2640 #endif
2641
2642 static bool dspload_wait_loaded(struct hda_codec *codec)
2643 {
2644         unsigned long timeout = jiffies + msecs_to_jiffies(2000);
2645
2646         do {
2647                 if (dspload_is_loaded(codec)) {
2648                         pr_info("ca0132 DOWNLOAD OK :-) DSP IS RUNNING.\n");
2649                         return true;
2650                 }
2651                 msleep(20);
2652         } while (time_before(jiffies, timeout));
2653
2654         pr_err("ca0132 DOWNLOAD FAILED!!! DSP IS NOT RUNNING.\n");
2655         return false;
2656 }
2657
2658 /*
2659  * PCM callbacks
2660  */
2661 static int ca0132_playback_pcm_prepare(struct hda_pcm_stream *hinfo,
2662                         struct hda_codec *codec,
2663                         unsigned int stream_tag,
2664                         unsigned int format,
2665                         struct snd_pcm_substream *substream)
2666 {
2667         struct ca0132_spec *spec = codec->spec;
2668
2669         snd_hda_codec_setup_stream(codec, spec->dacs[0], stream_tag, 0, format);
2670
2671         return 0;
2672 }
2673
2674 static int ca0132_playback_pcm_cleanup(struct hda_pcm_stream *hinfo,
2675                         struct hda_codec *codec,
2676                         struct snd_pcm_substream *substream)
2677 {
2678         struct ca0132_spec *spec = codec->spec;
2679
2680         if (spec->dsp_state == DSP_DOWNLOADING)
2681                 return 0;
2682
2683         /*If Playback effects are on, allow stream some time to flush
2684          *effects tail*/
2685         if (spec->effects_switch[PLAY_ENHANCEMENT - EFFECT_START_NID])
2686                 msleep(50);
2687
2688         snd_hda_codec_cleanup_stream(codec, spec->dacs[0]);
2689
2690         return 0;
2691 }
2692
2693 static unsigned int ca0132_playback_pcm_delay(struct hda_pcm_stream *info,
2694                         struct hda_codec *codec,
2695                         struct snd_pcm_substream *substream)
2696 {
2697         struct ca0132_spec *spec = codec->spec;
2698         unsigned int latency = DSP_PLAYBACK_INIT_LATENCY;
2699         struct snd_pcm_runtime *runtime = substream->runtime;
2700
2701         if (spec->dsp_state != DSP_DOWNLOADED)
2702                 return 0;
2703
2704         /* Add latency if playback enhancement and either effect is enabled. */
2705         if (spec->effects_switch[PLAY_ENHANCEMENT - EFFECT_START_NID]) {
2706                 if ((spec->effects_switch[SURROUND - EFFECT_START_NID]) ||
2707                     (spec->effects_switch[DIALOG_PLUS - EFFECT_START_NID]))
2708                         latency += DSP_PLAY_ENHANCEMENT_LATENCY;
2709         }
2710
2711         /* Applying Speaker EQ adds latency as well. */
2712         if (spec->cur_out_type == SPEAKER_OUT)
2713                 latency += DSP_SPEAKER_OUT_LATENCY;
2714
2715         return (latency * runtime->rate) / 1000;
2716 }
2717
2718 /*
2719  * Digital out
2720  */
2721 static int ca0132_dig_playback_pcm_open(struct hda_pcm_stream *hinfo,
2722                                         struct hda_codec *codec,
2723                                         struct snd_pcm_substream *substream)
2724 {
2725         struct ca0132_spec *spec = codec->spec;
2726         return snd_hda_multi_out_dig_open(codec, &spec->multiout);
2727 }
2728
2729 static int ca0132_dig_playback_pcm_prepare(struct hda_pcm_stream *hinfo,
2730                         struct hda_codec *codec,
2731                         unsigned int stream_tag,
2732                         unsigned int format,
2733                         struct snd_pcm_substream *substream)
2734 {
2735         struct ca0132_spec *spec = codec->spec;
2736         return snd_hda_multi_out_dig_prepare(codec, &spec->multiout,
2737                                              stream_tag, format, substream);
2738 }
2739
2740 static int ca0132_dig_playback_pcm_cleanup(struct hda_pcm_stream *hinfo,
2741                         struct hda_codec *codec,
2742                         struct snd_pcm_substream *substream)
2743 {
2744         struct ca0132_spec *spec = codec->spec;
2745         return snd_hda_multi_out_dig_cleanup(codec, &spec->multiout);
2746 }
2747
2748 static int ca0132_dig_playback_pcm_close(struct hda_pcm_stream *hinfo,
2749                                          struct hda_codec *codec,
2750                                          struct snd_pcm_substream *substream)
2751 {
2752         struct ca0132_spec *spec = codec->spec;
2753         return snd_hda_multi_out_dig_close(codec, &spec->multiout);
2754 }
2755
2756 /*
2757  * Analog capture
2758  */
2759 static int ca0132_capture_pcm_prepare(struct hda_pcm_stream *hinfo,
2760                                         struct hda_codec *codec,
2761                                         unsigned int stream_tag,
2762                                         unsigned int format,
2763                                         struct snd_pcm_substream *substream)
2764 {
2765         snd_hda_codec_setup_stream(codec, hinfo->nid,
2766                                    stream_tag, 0, format);
2767
2768         return 0;
2769 }
2770
2771 static int ca0132_capture_pcm_cleanup(struct hda_pcm_stream *hinfo,
2772                         struct hda_codec *codec,
2773                         struct snd_pcm_substream *substream)
2774 {
2775         struct ca0132_spec *spec = codec->spec;
2776
2777         if (spec->dsp_state == DSP_DOWNLOADING)
2778                 return 0;
2779
2780         snd_hda_codec_cleanup_stream(codec, hinfo->nid);
2781         return 0;
2782 }
2783
2784 static unsigned int ca0132_capture_pcm_delay(struct hda_pcm_stream *info,
2785                         struct hda_codec *codec,
2786                         struct snd_pcm_substream *substream)
2787 {
2788         struct ca0132_spec *spec = codec->spec;
2789         unsigned int latency = DSP_CAPTURE_INIT_LATENCY;
2790         struct snd_pcm_runtime *runtime = substream->runtime;
2791
2792         if (spec->dsp_state != DSP_DOWNLOADED)
2793                 return 0;
2794
2795         if (spec->effects_switch[CRYSTAL_VOICE - EFFECT_START_NID])
2796                 latency += DSP_CRYSTAL_VOICE_LATENCY;
2797
2798         return (latency * runtime->rate) / 1000;
2799 }
2800
2801 /*
2802  * Controls stuffs.
2803  */
2804
2805 /*
2806  * Mixer controls helpers.
2807  */
2808 #define CA0132_CODEC_VOL_MONO(xname, nid, channel, dir) \
2809         { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
2810           .name = xname, \
2811           .subdevice = HDA_SUBDEV_AMP_FLAG, \
2812           .access = SNDRV_CTL_ELEM_ACCESS_READWRITE | \
2813                         SNDRV_CTL_ELEM_ACCESS_TLV_READ | \
2814                         SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK, \
2815           .info = ca0132_volume_info, \
2816           .get = ca0132_volume_get, \
2817           .put = ca0132_volume_put, \
2818           .tlv = { .c = ca0132_volume_tlv }, \
2819           .private_value = HDA_COMPOSE_AMP_VAL(nid, channel, 0, dir) }
2820
2821 #define CA0132_CODEC_MUTE_MONO(xname, nid, channel, dir) \
2822         { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
2823           .name = xname, \
2824           .subdevice = HDA_SUBDEV_AMP_FLAG, \
2825           .info = snd_hda_mixer_amp_switch_info, \
2826           .get = ca0132_switch_get, \
2827           .put = ca0132_switch_put, \
2828           .private_value = HDA_COMPOSE_AMP_VAL(nid, channel, 0, dir) }
2829
2830 /* stereo */
2831 #define CA0132_CODEC_VOL(xname, nid, dir) \
2832         CA0132_CODEC_VOL_MONO(xname, nid, 3, dir)
2833 #define CA0132_CODEC_MUTE(xname, nid, dir) \
2834         CA0132_CODEC_MUTE_MONO(xname, nid, 3, dir)
2835
2836 /* The followings are for tuning of products */
2837 #ifdef ENABLE_TUNING_CONTROLS
2838
2839 static unsigned int voice_focus_vals_lookup[] = {
2840 0x41A00000, 0x41A80000, 0x41B00000, 0x41B80000, 0x41C00000, 0x41C80000,
2841 0x41D00000, 0x41D80000, 0x41E00000, 0x41E80000, 0x41F00000, 0x41F80000,
2842 0x42000000, 0x42040000, 0x42080000, 0x420C0000, 0x42100000, 0x42140000,
2843 0x42180000, 0x421C0000, 0x42200000, 0x42240000, 0x42280000, 0x422C0000,
2844 0x42300000, 0x42340000, 0x42380000, 0x423C0000, 0x42400000, 0x42440000,
2845 0x42480000, 0x424C0000, 0x42500000, 0x42540000, 0x42580000, 0x425C0000,
2846 0x42600000, 0x42640000, 0x42680000, 0x426C0000, 0x42700000, 0x42740000,
2847 0x42780000, 0x427C0000, 0x42800000, 0x42820000, 0x42840000, 0x42860000,
2848 0x42880000, 0x428A0000, 0x428C0000, 0x428E0000, 0x42900000, 0x42920000,
2849 0x42940000, 0x42960000, 0x42980000, 0x429A0000, 0x429C0000, 0x429E0000,
2850 0x42A00000, 0x42A20000, 0x42A40000, 0x42A60000, 0x42A80000, 0x42AA0000,
2851 0x42AC0000, 0x42AE0000, 0x42B00000, 0x42B20000, 0x42B40000, 0x42B60000,
2852 0x42B80000, 0x42BA0000, 0x42BC0000, 0x42BE0000, 0x42C00000, 0x42C20000,
2853 0x42C40000, 0x42C60000, 0x42C80000, 0x42CA0000, 0x42CC0000, 0x42CE0000,
2854 0x42D00000, 0x42D20000, 0x42D40000, 0x42D60000, 0x42D80000, 0x42DA0000,
2855 0x42DC0000, 0x42DE0000, 0x42E00000, 0x42E20000, 0x42E40000, 0x42E60000,
2856 0x42E80000, 0x42EA0000, 0x42EC0000, 0x42EE0000, 0x42F00000, 0x42F20000,
2857 0x42F40000, 0x42F60000, 0x42F80000, 0x42FA0000, 0x42FC0000, 0x42FE0000,
2858 0x43000000, 0x43010000, 0x43020000, 0x43030000, 0x43040000, 0x43050000,
2859 0x43060000, 0x43070000, 0x43080000, 0x43090000, 0x430A0000, 0x430B0000,
2860 0x430C0000, 0x430D0000, 0x430E0000, 0x430F0000, 0x43100000, 0x43110000,
2861 0x43120000, 0x43130000, 0x43140000, 0x43150000, 0x43160000, 0x43170000,
2862 0x43180000, 0x43190000, 0x431A0000, 0x431B0000, 0x431C0000, 0x431D0000,
2863 0x431E0000, 0x431F0000, 0x43200000, 0x43210000, 0x43220000, 0x43230000,
2864 0x43240000, 0x43250000, 0x43260000, 0x43270000, 0x43280000, 0x43290000,
2865 0x432A0000, 0x432B0000, 0x432C0000, 0x432D0000, 0x432E0000, 0x432F0000,
2866 0x43300000, 0x43310000, 0x43320000, 0x43330000, 0x43340000
2867 };
2868
2869 static unsigned int mic_svm_vals_lookup[] = {
2870 0x00000000, 0x3C23D70A, 0x3CA3D70A, 0x3CF5C28F, 0x3D23D70A, 0x3D4CCCCD,
2871 0x3D75C28F, 0x3D8F5C29, 0x3DA3D70A, 0x3DB851EC, 0x3DCCCCCD, 0x3DE147AE,
2872 0x3DF5C28F, 0x3E051EB8, 0x3E0F5C29, 0x3E19999A, 0x3E23D70A, 0x3E2E147B,
2873 0x3E3851EC, 0x3E428F5C, 0x3E4CCCCD, 0x3E570A3D, 0x3E6147AE, 0x3E6B851F,
2874 0x3E75C28F, 0x3E800000, 0x3E851EB8, 0x3E8A3D71, 0x3E8F5C29, 0x3E947AE1,
2875 0x3E99999A, 0x3E9EB852, 0x3EA3D70A, 0x3EA8F5C3, 0x3EAE147B, 0x3EB33333,
2876 0x3EB851EC, 0x3EBD70A4, 0x3EC28F5C, 0x3EC7AE14, 0x3ECCCCCD, 0x3ED1EB85,
2877 0x3ED70A3D, 0x3EDC28F6, 0x3EE147AE, 0x3EE66666, 0x3EEB851F, 0x3EF0A3D7,
2878 0x3EF5C28F, 0x3EFAE148, 0x3F000000, 0x3F028F5C, 0x3F051EB8, 0x3F07AE14,
2879 0x3F0A3D71, 0x3F0CCCCD, 0x3F0F5C29, 0x3F11EB85, 0x3F147AE1, 0x3F170A3D,
2880 0x3F19999A, 0x3F1C28F6, 0x3F1EB852, 0x3F2147AE, 0x3F23D70A, 0x3F266666,
2881 0x3F28F5C3, 0x3F2B851F, 0x3F2E147B, 0x3F30A3D7, 0x3F333333, 0x3F35C28F,
2882 0x3F3851EC, 0x3F3AE148, 0x3F3D70A4, 0x3F400000, 0x3F428F5C, 0x3F451EB8,
2883 0x3F47AE14, 0x3F4A3D71, 0x3F4CCCCD, 0x3F4F5C29, 0x3F51EB85, 0x3F547AE1,
2884 0x3F570A3D, 0x3F59999A, 0x3F5C28F6, 0x3F5EB852, 0x3F6147AE, 0x3F63D70A,
2885 0x3F666666, 0x3F68F5C3, 0x3F6B851F, 0x3F6E147B, 0x3F70A3D7, 0x3F733333,
2886 0x3F75C28F, 0x3F7851EC, 0x3F7AE148, 0x3F7D70A4, 0x3F800000
2887 };
2888
2889 static unsigned int equalizer_vals_lookup[] = {
2890 0xC1C00000, 0xC1B80000, 0xC1B00000, 0xC1A80000, 0xC1A00000, 0xC1980000,
2891 0xC1900000, 0xC1880000, 0xC1800000, 0xC1700000, 0xC1600000, 0xC1500000,
2892 0xC1400000, 0xC1300000, 0xC1200000, 0xC1100000, 0xC1000000, 0xC0E00000,
2893 0xC0C00000, 0xC0A00000, 0xC0800000, 0xC0400000, 0xC0000000, 0xBF800000,
2894 0x00000000, 0x3F800000, 0x40000000, 0x40400000, 0x40800000, 0x40A00000,
2895 0x40C00000, 0x40E00000, 0x41000000, 0x41100000, 0x41200000, 0x41300000,
2896 0x41400000, 0x41500000, 0x41600000, 0x41700000, 0x41800000, 0x41880000,
2897 0x41900000, 0x41980000, 0x41A00000, 0x41A80000, 0x41B00000, 0x41B80000,
2898 0x41C00000
2899 };
2900
2901 static int tuning_ctl_set(struct hda_codec *codec, hda_nid_t nid,
2902                           unsigned int *lookup, int idx)
2903 {
2904         int i = 0;
2905
2906         for (i = 0; i < TUNING_CTLS_COUNT; i++)
2907                 if (nid == ca0132_tuning_ctls[i].nid)
2908                         break;
2909
2910         snd_hda_power_up(codec);
2911         dspio_set_param(codec, ca0132_tuning_ctls[i].mid,
2912                         ca0132_tuning_ctls[i].req,
2913                         &(lookup[idx]), sizeof(unsigned int));
2914         snd_hda_power_down(codec);
2915
2916         return 1;
2917 }
2918
2919 static int tuning_ctl_get(struct snd_kcontrol *kcontrol,
2920                           struct snd_ctl_elem_value *ucontrol)
2921 {
2922         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2923         struct ca0132_spec *spec = codec->spec;
2924         hda_nid_t nid = get_amp_nid(kcontrol);
2925         long *valp = ucontrol->value.integer.value;
2926         int idx = nid - TUNING_CTL_START_NID;
2927
2928         *valp = spec->cur_ctl_vals[idx];
2929         return 0;
2930 }
2931
2932 static int voice_focus_ctl_info(struct snd_kcontrol *kcontrol,
2933                               struct snd_ctl_elem_info *uinfo)
2934 {
2935         int chs = get_amp_channels(kcontrol);
2936         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
2937         uinfo->count = chs == 3 ? 2 : 1;
2938         uinfo->value.integer.min = 20;
2939         uinfo->value.integer.max = 180;
2940         uinfo->value.integer.step = 1;
2941
2942         return 0;
2943 }
2944
2945 static int voice_focus_ctl_put(struct snd_kcontrol *kcontrol,
2946                                 struct snd_ctl_elem_value *ucontrol)
2947 {
2948         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2949         struct ca0132_spec *spec = codec->spec;
2950         hda_nid_t nid = get_amp_nid(kcontrol);
2951         long *valp = ucontrol->value.integer.value;
2952         int idx;
2953
2954         idx = nid - TUNING_CTL_START_NID;
2955         /* any change? */
2956         if (spec->cur_ctl_vals[idx] == *valp)
2957                 return 0;
2958
2959         spec->cur_ctl_vals[idx] = *valp;
2960
2961         idx = *valp - 20;
2962         tuning_ctl_set(codec, nid, voice_focus_vals_lookup, idx);
2963
2964         return 1;
2965 }
2966
2967 static int mic_svm_ctl_info(struct snd_kcontrol *kcontrol,
2968                               struct snd_ctl_elem_info *uinfo)
2969 {
2970         int chs = get_amp_channels(kcontrol);
2971         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
2972         uinfo->count = chs == 3 ? 2 : 1;
2973         uinfo->value.integer.min = 0;
2974         uinfo->value.integer.max = 100;
2975         uinfo->value.integer.step = 1;
2976
2977         return 0;
2978 }
2979
2980 static int mic_svm_ctl_put(struct snd_kcontrol *kcontrol,
2981                                 struct snd_ctl_elem_value *ucontrol)
2982 {
2983         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
2984         struct ca0132_spec *spec = codec->spec;
2985         hda_nid_t nid = get_amp_nid(kcontrol);
2986         long *valp = ucontrol->value.integer.value;
2987         int idx;
2988
2989         idx = nid - TUNING_CTL_START_NID;
2990         /* any change? */
2991         if (spec->cur_ctl_vals[idx] == *valp)
2992                 return 0;
2993
2994         spec->cur_ctl_vals[idx] = *valp;
2995
2996         idx = *valp;
2997         tuning_ctl_set(codec, nid, mic_svm_vals_lookup, idx);
2998
2999         return 0;
3000 }
3001
3002 static int equalizer_ctl_info(struct snd_kcontrol *kcontrol,
3003                               struct snd_ctl_elem_info *uinfo)
3004 {
3005         int chs = get_amp_channels(kcontrol);
3006         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
3007         uinfo->count = chs == 3 ? 2 : 1;
3008         uinfo->value.integer.min = 0;
3009         uinfo->value.integer.max = 48;
3010         uinfo->value.integer.step = 1;
3011
3012         return 0;
3013 }
3014
3015 static int equalizer_ctl_put(struct snd_kcontrol *kcontrol,
3016                                 struct snd_ctl_elem_value *ucontrol)
3017 {
3018         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3019         struct ca0132_spec *spec = codec->spec;
3020         hda_nid_t nid = get_amp_nid(kcontrol);
3021         long *valp = ucontrol->value.integer.value;
3022         int idx;
3023
3024         idx = nid - TUNING_CTL_START_NID;
3025         /* any change? */
3026         if (spec->cur_ctl_vals[idx] == *valp)
3027                 return 0;
3028
3029         spec->cur_ctl_vals[idx] = *valp;
3030
3031         idx = *valp;
3032         tuning_ctl_set(codec, nid, equalizer_vals_lookup, idx);
3033
3034         return 1;
3035 }
3036
3037 static const DECLARE_TLV_DB_SCALE(voice_focus_db_scale, 2000, 100, 0);
3038 static const DECLARE_TLV_DB_SCALE(eq_db_scale, -2400, 100, 0);
3039
3040 static int add_tuning_control(struct hda_codec *codec,
3041                                 hda_nid_t pnid, hda_nid_t nid,
3042                                 const char *name, int dir)
3043 {
3044         char namestr[SNDRV_CTL_ELEM_ID_NAME_MAXLEN];
3045         int type = dir ? HDA_INPUT : HDA_OUTPUT;
3046         struct snd_kcontrol_new knew =
3047                 HDA_CODEC_VOLUME_MONO(namestr, nid, 1, 0, type);
3048
3049         knew.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
3050                         SNDRV_CTL_ELEM_ACCESS_TLV_READ;
3051         knew.tlv.c = 0;
3052         knew.tlv.p = 0;
3053         switch (pnid) {
3054         case VOICE_FOCUS:
3055                 knew.info = voice_focus_ctl_info;
3056                 knew.get = tuning_ctl_get;
3057                 knew.put = voice_focus_ctl_put;
3058                 knew.tlv.p = voice_focus_db_scale;
3059                 break;
3060         case MIC_SVM:
3061                 knew.info = mic_svm_ctl_info;
3062                 knew.get = tuning_ctl_get;
3063                 knew.put = mic_svm_ctl_put;
3064                 break;
3065         case EQUALIZER:
3066                 knew.info = equalizer_ctl_info;
3067                 knew.get = tuning_ctl_get;
3068                 knew.put = equalizer_ctl_put;
3069                 knew.tlv.p = eq_db_scale;
3070                 break;
3071         default:
3072                 return 0;
3073         }
3074         knew.private_value =
3075                 HDA_COMPOSE_AMP_VAL(nid, 1, 0, type);
3076         sprintf(namestr, "%s %s Volume", name, dirstr[dir]);
3077         return snd_hda_ctl_add(codec, nid, snd_ctl_new1(&knew, codec));
3078 }
3079
3080 static int add_tuning_ctls(struct hda_codec *codec)
3081 {
3082         int i;
3083         int err;
3084
3085         for (i = 0; i < TUNING_CTLS_COUNT; i++) {
3086                 err = add_tuning_control(codec,
3087                                         ca0132_tuning_ctls[i].parent_nid,
3088                                         ca0132_tuning_ctls[i].nid,
3089                                         ca0132_tuning_ctls[i].name,
3090                                         ca0132_tuning_ctls[i].direct);
3091                 if (err < 0)
3092                         return err;
3093         }
3094
3095         return 0;
3096 }
3097
3098 static void ca0132_init_tuning_defaults(struct hda_codec *codec)
3099 {
3100         struct ca0132_spec *spec = codec->spec;
3101         int i;
3102
3103         /* Wedge Angle defaults to 30.  10 below is 30 - 20.  20 is min. */
3104         spec->cur_ctl_vals[WEDGE_ANGLE - TUNING_CTL_START_NID] = 10;
3105         /* SVM level defaults to 0.74. */
3106         spec->cur_ctl_vals[SVM_LEVEL - TUNING_CTL_START_NID] = 74;
3107
3108         /* EQ defaults to 0dB. */
3109         for (i = 2; i < TUNING_CTLS_COUNT; i++)
3110                 spec->cur_ctl_vals[i] = 24;
3111 }
3112 #endif /*ENABLE_TUNING_CONTROLS*/
3113
3114 /*
3115  * Select the active output.
3116  * If autodetect is enabled, output will be selected based on jack detection.
3117  * If jack inserted, headphone will be selected, else built-in speakers
3118  * If autodetect is disabled, output will be selected based on selection.
3119  */
3120 static int ca0132_select_out(struct hda_codec *codec)
3121 {
3122         struct ca0132_spec *spec = codec->spec;
3123         unsigned int pin_ctl;
3124         int jack_present;
3125         int auto_jack;
3126         unsigned int tmp;
3127         int err;
3128
3129         codec_dbg(codec, "ca0132_select_out\n");
3130
3131         snd_hda_power_up_pm(codec);
3132
3133         auto_jack = spec->vnode_lswitch[VNID_HP_ASEL - VNODE_START_NID];
3134
3135         if (auto_jack)
3136                 jack_present = snd_hda_jack_detect(codec, spec->out_pins[1]);
3137         else
3138                 jack_present =
3139                         spec->vnode_lswitch[VNID_HP_SEL - VNODE_START_NID];
3140
3141         if (jack_present)
3142                 spec->cur_out_type = HEADPHONE_OUT;
3143         else
3144                 spec->cur_out_type = SPEAKER_OUT;
3145
3146         if (spec->cur_out_type == SPEAKER_OUT) {
3147                 codec_dbg(codec, "ca0132_select_out speaker\n");
3148                 /*speaker out config*/
3149                 tmp = FLOAT_ONE;
3150                 err = dspio_set_uint_param(codec, 0x80, 0x04, tmp);
3151                 if (err < 0)
3152                         goto exit;
3153                 /*enable speaker EQ*/
3154                 tmp = FLOAT_ONE;
3155                 err = dspio_set_uint_param(codec, 0x8f, 0x00, tmp);
3156                 if (err < 0)
3157                         goto exit;
3158
3159                 /* Setup EAPD */
3160                 snd_hda_codec_write(codec, spec->out_pins[1], 0,
3161                                     VENDOR_CHIPIO_EAPD_SEL_SET, 0x02);
3162                 snd_hda_codec_write(codec, spec->out_pins[0], 0,
3163                                     AC_VERB_SET_EAPD_BTLENABLE, 0x00);
3164                 snd_hda_codec_write(codec, spec->out_pins[0], 0,
3165                                     VENDOR_CHIPIO_EAPD_SEL_SET, 0x00);
3166                 snd_hda_codec_write(codec, spec->out_pins[0], 0,
3167                                     AC_VERB_SET_EAPD_BTLENABLE, 0x02);
3168
3169                 /* disable headphone node */
3170                 pin_ctl = snd_hda_codec_read(codec, spec->out_pins[1], 0,
3171                                         AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
3172                 snd_hda_set_pin_ctl(codec, spec->out_pins[1],
3173                                     pin_ctl & ~PIN_HP);
3174                 /* enable speaker node */
3175                 pin_ctl = snd_hda_codec_read(codec, spec->out_pins[0], 0,
3176                                              AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
3177                 snd_hda_set_pin_ctl(codec, spec->out_pins[0],
3178                                     pin_ctl | PIN_OUT);
3179         } else {
3180                 codec_dbg(codec, "ca0132_select_out hp\n");
3181                 /*headphone out config*/
3182                 tmp = FLOAT_ZERO;
3183                 err = dspio_set_uint_param(codec, 0x80, 0x04, tmp);
3184                 if (err < 0)
3185                         goto exit;
3186                 /*disable speaker EQ*/
3187                 tmp = FLOAT_ZERO;
3188                 err = dspio_set_uint_param(codec, 0x8f, 0x00, tmp);
3189                 if (err < 0)
3190                         goto exit;
3191
3192                 /* Setup EAPD */
3193                 snd_hda_codec_write(codec, spec->out_pins[0], 0,
3194                                     VENDOR_CHIPIO_EAPD_SEL_SET, 0x00);
3195                 snd_hda_codec_write(codec, spec->out_pins[0], 0,
3196                                     AC_VERB_SET_EAPD_BTLENABLE, 0x00);
3197                 snd_hda_codec_write(codec, spec->out_pins[1], 0,
3198                                     VENDOR_CHIPIO_EAPD_SEL_SET, 0x02);
3199                 snd_hda_codec_write(codec, spec->out_pins[0], 0,
3200                                     AC_VERB_SET_EAPD_BTLENABLE, 0x02);
3201
3202                 /* disable speaker*/
3203                 pin_ctl = snd_hda_codec_read(codec, spec->out_pins[0], 0,
3204                                         AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
3205                 snd_hda_set_pin_ctl(codec, spec->out_pins[0],
3206                                     pin_ctl & ~PIN_HP);
3207                 /* enable headphone*/
3208                 pin_ctl = snd_hda_codec_read(codec, spec->out_pins[1], 0,
3209                                         AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
3210                 snd_hda_set_pin_ctl(codec, spec->out_pins[1],
3211                                     pin_ctl | PIN_HP);
3212         }
3213
3214 exit:
3215         snd_hda_power_down_pm(codec);
3216
3217         return err < 0 ? err : 0;
3218 }
3219
3220 static void ca0132_unsol_hp_delayed(struct work_struct *work)
3221 {
3222         struct ca0132_spec *spec = container_of(
3223                 to_delayed_work(work), struct ca0132_spec, unsol_hp_work);
3224         struct hda_jack_tbl *jack;
3225
3226         ca0132_select_out(spec->codec);
3227         jack = snd_hda_jack_tbl_get(spec->codec, UNSOL_TAG_HP);
3228         if (jack) {
3229                 jack->block_report = 0;
3230                 snd_hda_jack_report_sync(spec->codec);
3231         }
3232 }
3233
3234 static void ca0132_set_dmic(struct hda_codec *codec, int enable);
3235 static int ca0132_mic_boost_set(struct hda_codec *codec, long val);
3236 static int ca0132_effects_set(struct hda_codec *codec, hda_nid_t nid, long val);
3237
3238 /*
3239  * Select the active VIP source
3240  */
3241 static int ca0132_set_vipsource(struct hda_codec *codec, int val)
3242 {
3243         struct ca0132_spec *spec = codec->spec;
3244         unsigned int tmp;
3245
3246         if (spec->dsp_state != DSP_DOWNLOADED)
3247                 return 0;
3248
3249         /* if CrystalVoice if off, vipsource should be 0 */
3250         if (!spec->effects_switch[CRYSTAL_VOICE - EFFECT_START_NID] ||
3251             (val == 0)) {
3252                 chipio_set_control_param(codec, CONTROL_PARAM_VIP_SOURCE, 0);
3253                 chipio_set_conn_rate(codec, MEM_CONNID_MICIN1, SR_96_000);
3254                 chipio_set_conn_rate(codec, MEM_CONNID_MICOUT1, SR_96_000);
3255                 if (spec->cur_mic_type == DIGITAL_MIC)
3256                         tmp = FLOAT_TWO;
3257                 else
3258                         tmp = FLOAT_ONE;
3259                 dspio_set_uint_param(codec, 0x80, 0x00, tmp);
3260                 tmp = FLOAT_ZERO;
3261                 dspio_set_uint_param(codec, 0x80, 0x05, tmp);
3262         } else {
3263                 chipio_set_conn_rate(codec, MEM_CONNID_MICIN1, SR_16_000);
3264                 chipio_set_conn_rate(codec, MEM_CONNID_MICOUT1, SR_16_000);
3265                 if (spec->cur_mic_type == DIGITAL_MIC)
3266                         tmp = FLOAT_TWO;
3267                 else
3268                         tmp = FLOAT_ONE;
3269                 dspio_set_uint_param(codec, 0x80, 0x00, tmp);
3270                 tmp = FLOAT_ONE;
3271                 dspio_set_uint_param(codec, 0x80, 0x05, tmp);
3272                 msleep(20);
3273                 chipio_set_control_param(codec, CONTROL_PARAM_VIP_SOURCE, val);
3274         }
3275
3276         return 1;
3277 }
3278
3279 /*
3280  * Select the active microphone.
3281  * If autodetect is enabled, mic will be selected based on jack detection.
3282  * If jack inserted, ext.mic will be selected, else built-in mic
3283  * If autodetect is disabled, mic will be selected based on selection.
3284  */
3285 static int ca0132_select_mic(struct hda_codec *codec)
3286 {
3287         struct ca0132_spec *spec = codec->spec;
3288         int jack_present;
3289         int auto_jack;
3290
3291         codec_dbg(codec, "ca0132_select_mic\n");
3292
3293         snd_hda_power_up_pm(codec);
3294
3295         auto_jack = spec->vnode_lswitch[VNID_AMIC1_ASEL - VNODE_START_NID];
3296
3297         if (auto_jack)
3298                 jack_present = snd_hda_jack_detect(codec, spec->input_pins[0]);
3299         else
3300                 jack_present =
3301                         spec->vnode_lswitch[VNID_AMIC1_SEL - VNODE_START_NID];
3302
3303         if (jack_present)
3304                 spec->cur_mic_type = LINE_MIC_IN;
3305         else
3306                 spec->cur_mic_type = DIGITAL_MIC;
3307
3308         if (spec->cur_mic_type == DIGITAL_MIC) {
3309                 /* enable digital Mic */
3310                 chipio_set_conn_rate(codec, MEM_CONNID_DMIC, SR_32_000);
3311                 ca0132_set_dmic(codec, 1);
3312                 ca0132_mic_boost_set(codec, 0);
3313                 /* set voice focus */
3314                 ca0132_effects_set(codec, VOICE_FOCUS,
3315                                    spec->effects_switch
3316                                    [VOICE_FOCUS - EFFECT_START_NID]);
3317         } else {
3318                 /* disable digital Mic */
3319                 chipio_set_conn_rate(codec, MEM_CONNID_DMIC, SR_96_000);
3320                 ca0132_set_dmic(codec, 0);
3321                 ca0132_mic_boost_set(codec, spec->cur_mic_boost);
3322                 /* disable voice focus */
3323                 ca0132_effects_set(codec, VOICE_FOCUS, 0);
3324         }
3325
3326         snd_hda_power_down_pm(codec);
3327
3328         return 0;
3329 }
3330
3331 /*
3332  * Check if VNODE settings take effect immediately.
3333  */
3334 static bool ca0132_is_vnode_effective(struct hda_codec *codec,
3335                                      hda_nid_t vnid,
3336                                      hda_nid_t *shared_nid)
3337 {
3338         struct ca0132_spec *spec = codec->spec;
3339         hda_nid_t nid;
3340
3341         switch (vnid) {
3342         case VNID_SPK:
3343                 nid = spec->shared_out_nid;
3344                 break;
3345         case VNID_MIC:
3346                 nid = spec->shared_mic_nid;
3347                 break;
3348         default:
3349                 return false;
3350         }
3351
3352         if (shared_nid)
3353                 *shared_nid = nid;
3354
3355         return true;
3356 }
3357
3358 /*
3359 * The following functions are control change helpers.
3360 * They return 0 if no changed.  Return 1 if changed.
3361 */
3362 static int ca0132_voicefx_set(struct hda_codec *codec, int enable)
3363 {
3364         struct ca0132_spec *spec = codec->spec;
3365         unsigned int tmp;
3366
3367         /* based on CrystalVoice state to enable VoiceFX. */
3368         if (enable) {
3369                 tmp = spec->effects_switch[CRYSTAL_VOICE - EFFECT_START_NID] ?
3370                         FLOAT_ONE : FLOAT_ZERO;
3371         } else {
3372                 tmp = FLOAT_ZERO;
3373         }
3374
3375         dspio_set_uint_param(codec, ca0132_voicefx.mid,
3376                              ca0132_voicefx.reqs[0], tmp);
3377
3378         return 1;
3379 }
3380
3381 /*
3382  * Set the effects parameters
3383  */
3384 static int ca0132_effects_set(struct hda_codec *codec, hda_nid_t nid, long val)
3385 {
3386         struct ca0132_spec *spec = codec->spec;
3387         unsigned int on;
3388         int num_fx = OUT_EFFECTS_COUNT + IN_EFFECTS_COUNT;
3389         int err = 0;
3390         int idx = nid - EFFECT_START_NID;
3391
3392         if ((idx < 0) || (idx >= num_fx))
3393                 return 0; /* no changed */
3394
3395         /* for out effect, qualify with PE */
3396         if ((nid >= OUT_EFFECT_START_NID) && (nid < OUT_EFFECT_END_NID)) {
3397                 /* if PE if off, turn off out effects. */
3398                 if (!spec->effects_switch[PLAY_ENHANCEMENT - EFFECT_START_NID])
3399                         val = 0;
3400         }
3401
3402         /* for in effect, qualify with CrystalVoice */
3403         if ((nid >= IN_EFFECT_START_NID) && (nid < IN_EFFECT_END_NID)) {
3404                 /* if CrystalVoice if off, turn off in effects. */
3405                 if (!spec->effects_switch[CRYSTAL_VOICE - EFFECT_START_NID])
3406                         val = 0;
3407
3408                 /* Voice Focus applies to 2-ch Mic, Digital Mic */
3409                 if ((nid == VOICE_FOCUS) && (spec->cur_mic_type != DIGITAL_MIC))
3410                         val = 0;
3411         }
3412
3413         codec_dbg(codec, "ca0132_effect_set: nid=0x%x, val=%ld\n",
3414                     nid, val);
3415
3416         on = (val == 0) ? FLOAT_ZERO : FLOAT_ONE;
3417         err = dspio_set_uint_param(codec, ca0132_effects[idx].mid,
3418                                    ca0132_effects[idx].reqs[0], on);
3419
3420         if (err < 0)
3421                 return 0; /* no changed */
3422
3423         return 1;
3424 }
3425
3426 /*
3427  * Turn on/off Playback Enhancements
3428  */
3429 static int ca0132_pe_switch_set(struct hda_codec *codec)
3430 {
3431         struct ca0132_spec *spec = codec->spec;
3432         hda_nid_t nid;
3433         int i, ret = 0;
3434
3435         codec_dbg(codec, "ca0132_pe_switch_set: val=%ld\n",
3436                     spec->effects_switch[PLAY_ENHANCEMENT - EFFECT_START_NID]);
3437
3438         i = OUT_EFFECT_START_NID - EFFECT_START_NID;
3439         nid = OUT_EFFECT_START_NID;
3440         /* PE affects all out effects */
3441         for (; nid < OUT_EFFECT_END_NID; nid++, i++)
3442                 ret |= ca0132_effects_set(codec, nid, spec->effects_switch[i]);
3443
3444         return ret;
3445 }
3446
3447 /* Check if Mic1 is streaming, if so, stop streaming */
3448 static int stop_mic1(struct hda_codec *codec)
3449 {
3450         struct ca0132_spec *spec = codec->spec;
3451         unsigned int oldval = snd_hda_codec_read(codec, spec->adcs[0], 0,
3452                                                  AC_VERB_GET_CONV, 0);
3453         if (oldval != 0)
3454                 snd_hda_codec_write(codec, spec->adcs[0], 0,
3455                                     AC_VERB_SET_CHANNEL_STREAMID,
3456                                     0);
3457         return oldval;
3458 }
3459
3460 /* Resume Mic1 streaming if it was stopped. */
3461 static void resume_mic1(struct hda_codec *codec, unsigned int oldval)
3462 {
3463         struct ca0132_spec *spec = codec->spec;
3464         /* Restore the previous stream and channel */
3465         if (oldval != 0)
3466                 snd_hda_codec_write(codec, spec->adcs[0], 0,
3467                                     AC_VERB_SET_CHANNEL_STREAMID,
3468                                     oldval);
3469 }
3470
3471 /*
3472  * Turn on/off CrystalVoice
3473  */
3474 static int ca0132_cvoice_switch_set(struct hda_codec *codec)
3475 {
3476         struct ca0132_spec *spec = codec->spec;
3477         hda_nid_t nid;
3478         int i, ret = 0;
3479         unsigned int oldval;
3480
3481         codec_dbg(codec, "ca0132_cvoice_switch_set: val=%ld\n",
3482                     spec->effects_switch[CRYSTAL_VOICE - EFFECT_START_NID]);
3483
3484         i = IN_EFFECT_START_NID - EFFECT_START_NID;
3485         nid = IN_EFFECT_START_NID;
3486         /* CrystalVoice affects all in effects */
3487         for (; nid < IN_EFFECT_END_NID; nid++, i++)
3488                 ret |= ca0132_effects_set(codec, nid, spec->effects_switch[i]);
3489
3490         /* including VoiceFX */
3491         ret |= ca0132_voicefx_set(codec, (spec->voicefx_val ? 1 : 0));
3492
3493         /* set correct vipsource */
3494         oldval = stop_mic1(codec);
3495         ret |= ca0132_set_vipsource(codec, 1);
3496         resume_mic1(codec, oldval);
3497         return ret;
3498 }
3499
3500 static int ca0132_mic_boost_set(struct hda_codec *codec, long val)
3501 {
3502         struct ca0132_spec *spec = codec->spec;
3503         int ret = 0;
3504
3505         if (val) /* on */
3506                 ret = snd_hda_codec_amp_update(codec, spec->input_pins[0], 0,
3507                                         HDA_INPUT, 0, HDA_AMP_VOLMASK, 3);
3508         else /* off */
3509                 ret = snd_hda_codec_amp_update(codec, spec->input_pins[0], 0,
3510                                         HDA_INPUT, 0, HDA_AMP_VOLMASK, 0);
3511
3512         return ret;
3513 }
3514
3515 static int ca0132_vnode_switch_set(struct snd_kcontrol *kcontrol,
3516                                 struct snd_ctl_elem_value *ucontrol)
3517 {
3518         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3519         hda_nid_t nid = get_amp_nid(kcontrol);
3520         hda_nid_t shared_nid = 0;
3521         bool effective;
3522         int ret = 0;
3523         struct ca0132_spec *spec = codec->spec;
3524         int auto_jack;
3525
3526         if (nid == VNID_HP_SEL) {
3527                 auto_jack =
3528                         spec->vnode_lswitch[VNID_HP_ASEL - VNODE_START_NID];
3529                 if (!auto_jack)
3530                         ca0132_select_out(codec);
3531                 return 1;
3532         }
3533
3534         if (nid == VNID_AMIC1_SEL) {
3535                 auto_jack =
3536                         spec->vnode_lswitch[VNID_AMIC1_ASEL - VNODE_START_NID];
3537                 if (!auto_jack)
3538                         ca0132_select_mic(codec);
3539                 return 1;
3540         }
3541
3542         if (nid == VNID_HP_ASEL) {
3543                 ca0132_select_out(codec);
3544                 return 1;
3545         }
3546
3547         if (nid == VNID_AMIC1_ASEL) {
3548                 ca0132_select_mic(codec);
3549                 return 1;
3550         }
3551
3552         /* if effective conditions, then update hw immediately. */
3553         effective = ca0132_is_vnode_effective(codec, nid, &shared_nid);
3554         if (effective) {
3555                 int dir = get_amp_direction(kcontrol);
3556                 int ch = get_amp_channels(kcontrol);
3557                 unsigned long pval;
3558
3559                 mutex_lock(&codec->control_mutex);
3560                 pval = kcontrol->private_value;
3561                 kcontrol->private_value = HDA_COMPOSE_AMP_VAL(shared_nid, ch,
3562                                                                 0, dir);
3563                 ret = snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
3564                 kcontrol->private_value = pval;
3565                 mutex_unlock(&codec->control_mutex);
3566         }
3567
3568         return ret;
3569 }
3570 /* End of control change helpers. */
3571
3572 static int ca0132_voicefx_info(struct snd_kcontrol *kcontrol,
3573                                  struct snd_ctl_elem_info *uinfo)
3574 {
3575         unsigned int items = sizeof(ca0132_voicefx_presets)
3576                                 / sizeof(struct ct_voicefx_preset);
3577
3578         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
3579         uinfo->count = 1;
3580         uinfo->value.enumerated.items = items;
3581         if (uinfo->value.enumerated.item >= items)
3582                 uinfo->value.enumerated.item = items - 1;
3583         strcpy(uinfo->value.enumerated.name,
3584                ca0132_voicefx_presets[uinfo->value.enumerated.item].name);
3585         return 0;
3586 }
3587
3588 static int ca0132_voicefx_get(struct snd_kcontrol *kcontrol,
3589                                 struct snd_ctl_elem_value *ucontrol)
3590 {
3591         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3592         struct ca0132_spec *spec = codec->spec;
3593
3594         ucontrol->value.enumerated.item[0] = spec->voicefx_val;
3595         return 0;
3596 }
3597
3598 static int ca0132_voicefx_put(struct snd_kcontrol *kcontrol,
3599                                 struct snd_ctl_elem_value *ucontrol)
3600 {
3601         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3602         struct ca0132_spec *spec = codec->spec;
3603         int i, err = 0;
3604         int sel = ucontrol->value.enumerated.item[0];
3605         unsigned int items = sizeof(ca0132_voicefx_presets)
3606                                 / sizeof(struct ct_voicefx_preset);
3607
3608         if (sel >= items)
3609                 return 0;
3610
3611         codec_dbg(codec, "ca0132_voicefx_put: sel=%d, preset=%s\n",
3612                     sel, ca0132_voicefx_presets[sel].name);
3613
3614         /*
3615          * Idx 0 is default.
3616          * Default needs to qualify with CrystalVoice state.
3617          */
3618         for (i = 0; i < VOICEFX_MAX_PARAM_COUNT; i++) {
3619                 err = dspio_set_uint_param(codec, ca0132_voicefx.mid,
3620                                 ca0132_voicefx.reqs[i],
3621                                 ca0132_voicefx_presets[sel].vals[i]);
3622                 if (err < 0)
3623                         break;
3624         }
3625
3626         if (err >= 0) {
3627                 spec->voicefx_val = sel;
3628                 /* enable voice fx */
3629                 ca0132_voicefx_set(codec, (sel ? 1 : 0));
3630         }
3631
3632         return 1;
3633 }
3634
3635 static int ca0132_switch_get(struct snd_kcontrol *kcontrol,
3636                                 struct snd_ctl_elem_value *ucontrol)
3637 {
3638         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3639         struct ca0132_spec *spec = codec->spec;
3640         hda_nid_t nid = get_amp_nid(kcontrol);
3641         int ch = get_amp_channels(kcontrol);
3642         long *valp = ucontrol->value.integer.value;
3643
3644         /* vnode */
3645         if ((nid >= VNODE_START_NID) && (nid < VNODE_END_NID)) {
3646                 if (ch & 1) {
3647                         *valp = spec->vnode_lswitch[nid - VNODE_START_NID];
3648                         valp++;
3649                 }
3650                 if (ch & 2) {
3651                         *valp = spec->vnode_rswitch[nid - VNODE_START_NID];
3652                         valp++;
3653                 }
3654                 return 0;
3655         }
3656
3657         /* effects, include PE and CrystalVoice */
3658         if ((nid >= EFFECT_START_NID) && (nid < EFFECT_END_NID)) {
3659                 *valp = spec->effects_switch[nid - EFFECT_START_NID];
3660                 return 0;
3661         }
3662
3663         /* mic boost */
3664         if (nid == spec->input_pins[0]) {
3665                 *valp = spec->cur_mic_boost;
3666                 return 0;
3667         }
3668
3669         return 0;
3670 }
3671
3672 static int ca0132_switch_put(struct snd_kcontrol *kcontrol,
3673                              struct snd_ctl_elem_value *ucontrol)
3674 {
3675         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3676         struct ca0132_spec *spec = codec->spec;
3677         hda_nid_t nid = get_amp_nid(kcontrol);
3678         int ch = get_amp_channels(kcontrol);
3679         long *valp = ucontrol->value.integer.value;
3680         int changed = 1;
3681
3682         codec_dbg(codec, "ca0132_switch_put: nid=0x%x, val=%ld\n",
3683                     nid, *valp);
3684
3685         snd_hda_power_up(codec);
3686         /* vnode */
3687         if ((nid >= VNODE_START_NID) && (nid < VNODE_END_NID)) {
3688                 if (ch & 1) {
3689                         spec->vnode_lswitch[nid - VNODE_START_NID] = *valp;
3690                         valp++;
3691                 }
3692                 if (ch & 2) {
3693                         spec->vnode_rswitch[nid - VNODE_START_NID] = *valp;
3694                         valp++;
3695                 }
3696                 changed = ca0132_vnode_switch_set(kcontrol, ucontrol);
3697                 goto exit;
3698         }
3699
3700         /* PE */
3701         if (nid == PLAY_ENHANCEMENT) {
3702                 spec->effects_switch[nid - EFFECT_START_NID] = *valp;
3703                 changed = ca0132_pe_switch_set(codec);
3704                 goto exit;
3705         }
3706
3707         /* CrystalVoice */
3708         if (nid == CRYSTAL_VOICE) {
3709                 spec->effects_switch[nid - EFFECT_START_NID] = *valp;
3710                 changed = ca0132_cvoice_switch_set(codec);
3711                 goto exit;
3712         }
3713
3714         /* out and in effects */
3715         if (((nid >= OUT_EFFECT_START_NID) && (nid < OUT_EFFECT_END_NID)) ||
3716             ((nid >= IN_EFFECT_START_NID) && (nid < IN_EFFECT_END_NID))) {
3717                 spec->effects_switch[nid - EFFECT_START_NID] = *valp;
3718                 changed = ca0132_effects_set(codec, nid, *valp);
3719                 goto exit;
3720         }
3721
3722         /* mic boost */
3723         if (nid == spec->input_pins[0]) {
3724                 spec->cur_mic_boost = *valp;
3725
3726                 /* Mic boost does not apply to Digital Mic */
3727                 if (spec->cur_mic_type != DIGITAL_MIC)
3728                         changed = ca0132_mic_boost_set(codec, *valp);
3729                 goto exit;
3730         }
3731
3732 exit:
3733         snd_hda_power_down(codec);
3734         return changed;
3735 }
3736
3737 /*
3738  * Volume related
3739  */
3740 static int ca0132_volume_info(struct snd_kcontrol *kcontrol,
3741                               struct snd_ctl_elem_info *uinfo)
3742 {
3743         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3744         struct ca0132_spec *spec = codec->spec;
3745         hda_nid_t nid = get_amp_nid(kcontrol);
3746         int ch = get_amp_channels(kcontrol);
3747         int dir = get_amp_direction(kcontrol);
3748         unsigned long pval;
3749         int err;
3750
3751         switch (nid) {
3752         case VNID_SPK:
3753                 /* follow shared_out info */
3754                 nid = spec->shared_out_nid;
3755                 mutex_lock(&codec->control_mutex);
3756                 pval = kcontrol->private_value;
3757                 kcontrol->private_value = HDA_COMPOSE_AMP_VAL(nid, ch, 0, dir);
3758                 err = snd_hda_mixer_amp_volume_info(kcontrol, uinfo);
3759                 kcontrol->private_value = pval;
3760                 mutex_unlock(&codec->control_mutex);
3761                 break;
3762         case VNID_MIC:
3763                 /* follow shared_mic info */
3764                 nid = spec->shared_mic_nid;
3765                 mutex_lock(&codec->control_mutex);
3766                 pval = kcontrol->private_value;
3767                 kcontrol->private_value = HDA_COMPOSE_AMP_VAL(nid, ch, 0, dir);
3768                 err = snd_hda_mixer_amp_volume_info(kcontrol, uinfo);
3769                 kcontrol->private_value = pval;
3770                 mutex_unlock(&codec->control_mutex);
3771                 break;
3772         default:
3773                 err = snd_hda_mixer_amp_volume_info(kcontrol, uinfo);
3774         }
3775         return err;
3776 }
3777
3778 static int ca0132_volume_get(struct snd_kcontrol *kcontrol,
3779                                 struct snd_ctl_elem_value *ucontrol)
3780 {
3781         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3782         struct ca0132_spec *spec = codec->spec;
3783         hda_nid_t nid = get_amp_nid(kcontrol);
3784         int ch = get_amp_channels(kcontrol);
3785         long *valp = ucontrol->value.integer.value;
3786
3787         /* store the left and right volume */
3788         if (ch & 1) {
3789                 *valp = spec->vnode_lvol[nid - VNODE_START_NID];
3790                 valp++;
3791         }
3792         if (ch & 2) {
3793                 *valp = spec->vnode_rvol[nid - VNODE_START_NID];
3794                 valp++;
3795         }
3796         return 0;
3797 }
3798
3799 static int ca0132_volume_put(struct snd_kcontrol *kcontrol,
3800                                 struct snd_ctl_elem_value *ucontrol)
3801 {
3802         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3803         struct ca0132_spec *spec = codec->spec;
3804         hda_nid_t nid = get_amp_nid(kcontrol);
3805         int ch = get_amp_channels(kcontrol);
3806         long *valp = ucontrol->value.integer.value;
3807         hda_nid_t shared_nid = 0;
3808         bool effective;
3809         int changed = 1;
3810
3811         /* store the left and right volume */
3812         if (ch & 1) {
3813                 spec->vnode_lvol[nid - VNODE_START_NID] = *valp;
3814                 valp++;
3815         }
3816         if (ch & 2) {
3817                 spec->vnode_rvol[nid - VNODE_START_NID] = *valp;
3818                 valp++;
3819         }
3820
3821         /* if effective conditions, then update hw immediately. */
3822         effective = ca0132_is_vnode_effective(codec, nid, &shared_nid);
3823         if (effective) {
3824                 int dir = get_amp_direction(kcontrol);
3825                 unsigned long pval;
3826
3827                 snd_hda_power_up(codec);
3828                 mutex_lock(&codec->control_mutex);
3829                 pval = kcontrol->private_value;
3830                 kcontrol->private_value = HDA_COMPOSE_AMP_VAL(shared_nid, ch,
3831                                                                 0, dir);
3832                 changed = snd_hda_mixer_amp_volume_put(kcontrol, ucontrol);
3833                 kcontrol->private_value = pval;
3834                 mutex_unlock(&codec->control_mutex);
3835                 snd_hda_power_down(codec);
3836         }
3837
3838         return changed;
3839 }
3840
3841 static int ca0132_volume_tlv(struct snd_kcontrol *kcontrol, int op_flag,
3842                              unsigned int size, unsigned int __user *tlv)
3843 {
3844         struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
3845         struct ca0132_spec *spec = codec->spec;
3846         hda_nid_t nid = get_amp_nid(kcontrol);
3847         int ch = get_amp_channels(kcontrol);
3848         int dir = get_amp_direction(kcontrol);
3849         unsigned long pval;
3850         int err;
3851
3852         switch (nid) {
3853         case VNID_SPK:
3854                 /* follow shared_out tlv */
3855                 nid = spec->shared_out_nid;
3856                 mutex_lock(&codec->control_mutex);
3857                 pval = kcontrol->private_value;
3858                 kcontrol->private_value = HDA_COMPOSE_AMP_VAL(nid, ch, 0, dir);
3859                 err = snd_hda_mixer_amp_tlv(kcontrol, op_flag, size, tlv);
3860                 kcontrol->private_value = pval;
3861                 mutex_unlock(&codec->control_mutex);
3862                 break;
3863         case VNID_MIC:
3864                 /* follow shared_mic tlv */
3865                 nid = spec->shared_mic_nid;
3866                 mutex_lock(&codec->control_mutex);
3867                 pval = kcontrol->private_value;
3868                 kcontrol->private_value = HDA_COMPOSE_AMP_VAL(nid, ch, 0, dir);
3869                 err = snd_hda_mixer_amp_tlv(kcontrol, op_flag, size, tlv);
3870                 kcontrol->private_value = pval;
3871                 mutex_unlock(&codec->control_mutex);
3872                 break;
3873         default:
3874                 err = snd_hda_mixer_amp_tlv(kcontrol, op_flag, size, tlv);
3875         }
3876         return err;
3877 }
3878
3879 static int add_fx_switch(struct hda_codec *codec, hda_nid_t nid,
3880                          const char *pfx, int dir)
3881 {
3882         char namestr[SNDRV_CTL_ELEM_ID_NAME_MAXLEN];
3883         int type = dir ? HDA_INPUT : HDA_OUTPUT;
3884         struct snd_kcontrol_new knew =
3885                 CA0132_CODEC_MUTE_MONO(namestr, nid, 1, type);
3886         sprintf(namestr, "%s %s Switch", pfx, dirstr[dir]);
3887         return snd_hda_ctl_add(codec, nid, snd_ctl_new1(&knew, codec));
3888 }
3889
3890 static int add_voicefx(struct hda_codec *codec)
3891 {
3892         struct snd_kcontrol_new knew =
3893                 HDA_CODEC_MUTE_MONO(ca0132_voicefx.name,
3894                                     VOICEFX, 1, 0, HDA_INPUT);
3895         knew.info = ca0132_voicefx_info;
3896         knew.get = ca0132_voicefx_get;
3897         knew.put = ca0132_voicefx_put;
3898         return snd_hda_ctl_add(codec, VOICEFX, snd_ctl_new1(&knew, codec));
3899 }
3900
3901 /*
3902  * When changing Node IDs for Mixer Controls below, make sure to update
3903  * Node IDs in ca0132_config() as well.
3904  */
3905 static struct snd_kcontrol_new ca0132_mixer[] = {
3906         CA0132_CODEC_VOL("Master Playback Volume", VNID_SPK, HDA_OUTPUT),
3907         CA0132_CODEC_MUTE("Master Playback Switch", VNID_SPK, HDA_OUTPUT),
3908         CA0132_CODEC_VOL("Capture Volume", VNID_MIC, HDA_INPUT),
3909         CA0132_CODEC_MUTE("Capture Switch", VNID_MIC, HDA_INPUT),
3910         HDA_CODEC_VOLUME("Analog-Mic2 Capture Volume", 0x08, 0, HDA_INPUT),
3911         HDA_CODEC_MUTE("Analog-Mic2 Capture Switch", 0x08, 0, HDA_INPUT),
3912         HDA_CODEC_VOLUME("What U Hear Capture Volume", 0x0a, 0, HDA_INPUT),
3913         HDA_CODEC_MUTE("What U Hear Capture Switch", 0x0a, 0, HDA_INPUT),
3914         CA0132_CODEC_MUTE_MONO("Mic1-Boost (30dB) Capture Switch",
3915                                0x12, 1, HDA_INPUT),
3916         CA0132_CODEC_MUTE_MONO("HP/Speaker Playback Switch",
3917                                VNID_HP_SEL, 1, HDA_OUTPUT),
3918         CA0132_CODEC_MUTE_MONO("AMic1/DMic Capture Switch",
3919                                VNID_AMIC1_SEL, 1, HDA_INPUT),
3920         CA0132_CODEC_MUTE_MONO("HP/Speaker Auto Detect Playback Switch",
3921                                VNID_HP_ASEL, 1, HDA_OUTPUT),
3922         CA0132_CODEC_MUTE_MONO("AMic1/DMic Auto Detect Capture Switch",
3923                                VNID_AMIC1_ASEL, 1, HDA_INPUT),
3924         { } /* end */
3925 };
3926
3927 static int ca0132_build_controls(struct hda_codec *codec)
3928 {
3929         struct ca0132_spec *spec = codec->spec;
3930         int i, num_fx;
3931         int err = 0;
3932
3933         /* Add Mixer controls */
3934         for (i = 0; i < spec->num_mixers; i++) {
3935                 err = snd_hda_add_new_ctls(codec, spec->mixers[i]);
3936                 if (err < 0)
3937                         return err;
3938         }
3939
3940         /* Add in and out effects controls.
3941          * VoiceFX, PE and CrystalVoice are added separately.
3942          */
3943         num_fx = OUT_EFFECTS_COUNT + IN_EFFECTS_COUNT;
3944         for (i = 0; i < num_fx; i++) {
3945                 err = add_fx_switch(codec, ca0132_effects[i].nid,
3946                                     ca0132_effects[i].name,
3947                                     ca0132_effects[i].direct);
3948                 if (err < 0)
3949                         return err;
3950         }
3951
3952         err = add_fx_switch(codec, PLAY_ENHANCEMENT, "PlayEnhancement", 0);
3953         if (err < 0)
3954                 return err;
3955
3956         err = add_fx_switch(codec, CRYSTAL_VOICE, "CrystalVoice", 1);
3957         if (err < 0)
3958                 return err;
3959
3960         add_voicefx(codec);
3961
3962 #ifdef ENABLE_TUNING_CONTROLS
3963         add_tuning_ctls(codec);
3964 #endif
3965
3966         err = snd_hda_jack_add_kctls(codec, &spec->autocfg);
3967         if (err < 0)
3968                 return err;
3969
3970         if (spec->dig_out) {
3971                 err = snd_hda_create_spdif_out_ctls(codec, spec->dig_out,
3972                                                     spec->dig_out);
3973                 if (err < 0)
3974                         return err;
3975                 err = snd_hda_create_spdif_share_sw(codec, &spec->multiout);
3976                 if (err < 0)
3977                         return err;
3978                 /* spec->multiout.share_spdif = 1; */
3979         }
3980
3981         if (spec->dig_in) {
3982                 err = snd_hda_create_spdif_in_ctls(codec, spec->dig_in);
3983                 if (err < 0)
3984                         return err;
3985         }
3986         return 0;
3987 }
3988
3989 /*
3990  * PCM
3991  */
3992 static struct hda_pcm_stream ca0132_pcm_analog_playback = {
3993         .substreams = 1,
3994         .channels_min = 2,
3995         .channels_max = 6,
3996         .ops = {
3997                 .prepare = ca0132_playback_pcm_prepare,
3998                 .cleanup = ca0132_playback_pcm_cleanup,
3999                 .get_delay = ca0132_playback_pcm_delay,
4000         },
4001 };
4002
4003 static struct hda_pcm_stream ca0132_pcm_analog_capture = {
4004         .substreams = 1,
4005         .channels_min = 2,
4006         .channels_max = 2,
4007         .ops = {
4008                 .prepare = ca0132_capture_pcm_prepare,
4009                 .cleanup = ca0132_capture_pcm_cleanup,
4010                 .get_delay = ca0132_capture_pcm_delay,
4011         },
4012 };
4013
4014 static struct hda_pcm_stream ca0132_pcm_digital_playback = {
4015         .substreams = 1,
4016         .channels_min = 2,
4017         .channels_max = 2,
4018         .ops = {
4019                 .open = ca0132_dig_playback_pcm_open,
4020                 .close = ca0132_dig_playback_pcm_close,
4021                 .prepare = ca0132_dig_playback_pcm_prepare,
4022                 .cleanup = ca0132_dig_playback_pcm_cleanup
4023         },
4024 };
4025
4026 static struct hda_pcm_stream ca0132_pcm_digital_capture = {
4027         .substreams = 1,
4028         .channels_min = 2,
4029         .channels_max = 2,
4030 };
4031
4032 static int ca0132_build_pcms(struct hda_codec *codec)
4033 {
4034         struct ca0132_spec *spec = codec->spec;
4035         struct hda_pcm *info;
4036
4037         info = snd_hda_codec_pcm_new(codec, "CA0132 Analog");
4038         if (!info)
4039                 return -ENOMEM;
4040         info->stream[SNDRV_PCM_STREAM_PLAYBACK] = ca0132_pcm_analog_playback;
4041         info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid = spec->dacs[0];
4042         info->stream[SNDRV_PCM_STREAM_PLAYBACK].channels_max =
4043                 spec->multiout.max_channels;
4044         info->stream[SNDRV_PCM_STREAM_CAPTURE] = ca0132_pcm_analog_capture;
4045         info->stream[SNDRV_PCM_STREAM_CAPTURE].substreams = 1;
4046         info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->adcs[0];
4047
4048         info = snd_hda_codec_pcm_new(codec, "CA0132 Analog Mic-In2");
4049         if (!info)
4050                 return -ENOMEM;
4051         info->stream[SNDRV_PCM_STREAM_CAPTURE] = ca0132_pcm_analog_capture;
4052         info->stream[SNDRV_PCM_STREAM_CAPTURE].substreams = 1;
4053         info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->adcs[1];
4054
4055         info = snd_hda_codec_pcm_new(codec, "CA0132 What U Hear");
4056         if (!info)
4057                 return -ENOMEM;
4058         info->stream[SNDRV_PCM_STREAM_CAPTURE] = ca0132_pcm_analog_capture;
4059         info->stream[SNDRV_PCM_STREAM_CAPTURE].substreams = 1;
4060         info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->adcs[2];
4061
4062         if (!spec->dig_out && !spec->dig_in)
4063                 return 0;
4064
4065         info = snd_hda_codec_pcm_new(codec, "CA0132 Digital");
4066         if (!info)
4067                 return -ENOMEM;
4068         info->pcm_type = HDA_PCM_TYPE_SPDIF;
4069         if (spec->dig_out) {
4070                 info->stream[SNDRV_PCM_STREAM_PLAYBACK] =
4071                         ca0132_pcm_digital_playback;
4072                 info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid = spec->dig_out;
4073         }
4074         if (spec->dig_in) {
4075                 info->stream[SNDRV_PCM_STREAM_CAPTURE] =
4076                         ca0132_pcm_digital_capture;
4077                 info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->dig_in;
4078         }
4079
4080         return 0;
4081 }
4082
4083 static void init_output(struct hda_codec *codec, hda_nid_t pin, hda_nid_t dac)
4084 {
4085         if (pin) {
4086                 snd_hda_set_pin_ctl(codec, pin, PIN_HP);
4087                 if (get_wcaps(codec, pin) & AC_WCAP_OUT_AMP)
4088                         snd_hda_codec_write(codec, pin, 0,
4089                                             AC_VERB_SET_AMP_GAIN_MUTE,
4090                                             AMP_OUT_UNMUTE);
4091         }
4092         if (dac && (get_wcaps(codec, dac) & AC_WCAP_OUT_AMP))
4093                 snd_hda_codec_write(codec, dac, 0,
4094                                     AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO);
4095 }
4096
4097 static void init_input(struct hda_codec *codec, hda_nid_t pin, hda_nid_t adc)
4098 {
4099         if (pin) {
4100                 snd_hda_set_pin_ctl(codec, pin, PIN_VREF80);
4101                 if (get_wcaps(codec, pin) & AC_WCAP_IN_AMP)
4102                         snd_hda_codec_write(codec, pin, 0,
4103                                             AC_VERB_SET_AMP_GAIN_MUTE,
4104                                             AMP_IN_UNMUTE(0));
4105         }
4106         if (adc && (get_wcaps(codec, adc) & AC_WCAP_IN_AMP)) {
4107                 snd_hda_codec_write(codec, adc, 0, AC_VERB_SET_AMP_GAIN_MUTE,
4108                                     AMP_IN_UNMUTE(0));
4109
4110                 /* init to 0 dB and unmute. */
4111                 snd_hda_codec_amp_stereo(codec, adc, HDA_INPUT, 0,
4112                                          HDA_AMP_VOLMASK, 0x5a);
4113                 snd_hda_codec_amp_stereo(codec, adc, HDA_INPUT, 0,
4114                                          HDA_AMP_MUTE, 0);
4115         }
4116 }
4117
4118 static void refresh_amp_caps(struct hda_codec *codec, hda_nid_t nid, int dir)
4119 {
4120         unsigned int caps;
4121
4122         caps = snd_hda_param_read(codec, nid, dir == HDA_OUTPUT ?
4123                                   AC_PAR_AMP_OUT_CAP : AC_PAR_AMP_IN_CAP);
4124         snd_hda_override_amp_caps(codec, nid, dir, caps);
4125 }
4126
4127 /*
4128  * Switch between Digital built-in mic and analog mic.
4129  */
4130 static void ca0132_set_dmic(struct hda_codec *codec, int enable)
4131 {
4132         struct ca0132_spec *spec = codec->spec;
4133         unsigned int tmp;
4134         u8 val;
4135         unsigned int oldval;
4136
4137         codec_dbg(codec, "ca0132_set_dmic: enable=%d\n", enable);
4138
4139         oldval = stop_mic1(codec);
4140         ca0132_set_vipsource(codec, 0);
4141         if (enable) {
4142                 /* set DMic input as 2-ch */
4143                 tmp = FLOAT_TWO;
4144                 dspio_set_uint_param(codec, 0x80, 0x00, tmp);
4145
4146                 val = spec->dmic_ctl;
4147                 val |= 0x80;
4148                 snd_hda_codec_write(codec, spec->input_pins[0], 0,
4149                                     VENDOR_CHIPIO_DMIC_CTL_SET, val);
4150
4151                 if (!(spec->dmic_ctl & 0x20))
4152                         chipio_set_control_flag(codec, CONTROL_FLAG_DMIC, 1);
4153         } else {
4154                 /* set AMic input as mono */
4155                 tmp = FLOAT_ONE;
4156                 dspio_set_uint_param(codec, 0x80, 0x00, tmp);
4157
4158                 val = spec->dmic_ctl;
4159                 /* clear bit7 and bit5 to disable dmic */
4160                 val &= 0x5f;
4161                 snd_hda_codec_write(codec, spec->input_pins[0], 0,
4162                                     VENDOR_CHIPIO_DMIC_CTL_SET, val);
4163
4164                 if (!(spec->dmic_ctl & 0x20))
4165                         chipio_set_control_flag(codec, CONTROL_FLAG_DMIC, 0);
4166         }
4167         ca0132_set_vipsource(codec, 1);
4168         resume_mic1(codec, oldval);
4169 }
4170
4171 /*
4172  * Initialization for Digital Mic.
4173  */
4174 static void ca0132_init_dmic(struct hda_codec *codec)
4175 {
4176         struct ca0132_spec *spec = codec->spec;
4177         u8 val;
4178
4179         /* Setup Digital Mic here, but don't enable.
4180          * Enable based on jack detect.
4181          */
4182
4183         /* MCLK uses MPIO1, set to enable.
4184          * Bit 2-0: MPIO select
4185          * Bit   3: set to disable
4186          * Bit 7-4: reserved
4187          */
4188         val = 0x01;
4189         snd_hda_codec_write(codec, spec->input_pins[0], 0,
4190                             VENDOR_CHIPIO_DMIC_MCLK_SET, val);
4191
4192         /* Data1 uses MPIO3. Data2 not use
4193          * Bit 2-0: Data1 MPIO select
4194          * Bit   3: set disable Data1
4195          * Bit 6-4: Data2 MPIO select
4196          * Bit   7: set disable Data2
4197          */
4198         val = 0x83;
4199         snd_hda_codec_write(codec, spec->input_pins[0], 0,
4200                             VENDOR_CHIPIO_DMIC_PIN_SET, val);
4201
4202         /* Use Ch-0 and Ch-1. Rate is 48K, mode 1. Disable DMic first.
4203          * Bit 3-0: Channel mask
4204          * Bit   4: set for 48KHz, clear for 32KHz
4205          * Bit   5: mode
4206          * Bit   6: set to select Data2, clear for Data1
4207          * Bit   7: set to enable DMic, clear for AMic
4208          */
4209         val = 0x23;
4210         /* keep a copy of dmic ctl val for enable/disable dmic purpuse */
4211         spec->dmic_ctl = val;
4212         snd_hda_codec_write(codec, spec->input_pins[0], 0,
4213                             VENDOR_CHIPIO_DMIC_CTL_SET, val);
4214 }
4215
4216 /*
4217  * Initialization for Analog Mic 2
4218  */
4219 static void ca0132_init_analog_mic2(struct hda_codec *codec)
4220 {
4221         struct ca0132_spec *spec = codec->spec;
4222
4223         mutex_lock(&spec->chipio_mutex);
4224         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
4225                             VENDOR_CHIPIO_8051_ADDRESS_LOW, 0x20);
4226         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
4227                             VENDOR_CHIPIO_8051_ADDRESS_HIGH, 0x19);
4228         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
4229                             VENDOR_CHIPIO_8051_DATA_WRITE, 0x00);
4230         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
4231                             VENDOR_CHIPIO_8051_ADDRESS_LOW, 0x2D);
4232         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
4233                             VENDOR_CHIPIO_8051_ADDRESS_HIGH, 0x19);
4234         snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
4235                             VENDOR_CHIPIO_8051_DATA_WRITE, 0x00);
4236         mutex_unlock(&spec->chipio_mutex);
4237 }
4238
4239 static void ca0132_refresh_widget_caps(struct hda_codec *codec)
4240 {
4241         struct ca0132_spec *spec = codec->spec;
4242         int i;
4243
4244         codec_dbg(codec, "ca0132_refresh_widget_caps.\n");
4245         snd_hda_codec_update_widgets(codec);
4246
4247         for (i = 0; i < spec->multiout.num_dacs; i++)
4248                 refresh_amp_caps(codec, spec->dacs[i], HDA_OUTPUT);
4249
4250         for (i = 0; i < spec->num_outputs; i++)
4251                 refresh_amp_caps(codec, spec->out_pins[i], HDA_OUTPUT);
4252
4253         for (i = 0; i < spec->num_inputs; i++) {
4254                 refresh_amp_caps(codec, spec->adcs[i], HDA_INPUT);
4255                 refresh_amp_caps(codec, spec->input_pins[i], HDA_INPUT);
4256         }
4257 }
4258
4259 /*
4260  * Setup default parameters for DSP
4261  */
4262 static void ca0132_setup_defaults(struct hda_codec *codec)
4263 {
4264         struct ca0132_spec *spec = codec->spec;
4265         unsigned int tmp;
4266         int num_fx;
4267         int idx, i;
4268
4269         if (spec->dsp_state != DSP_DOWNLOADED)
4270                 return;
4271
4272         /* out, in effects + voicefx */
4273         num_fx = OUT_EFFECTS_COUNT + IN_EFFECTS_COUNT + 1;
4274         for (idx = 0; idx < num_fx; idx++) {
4275                 for (i = 0; i <= ca0132_effects[idx].params; i++) {
4276                         dspio_set_uint_param(codec, ca0132_effects[idx].mid,
4277                                              ca0132_effects[idx].reqs[i],
4278                                              ca0132_effects[idx].def_vals[i]);
4279                 }
4280         }
4281
4282         /*remove DSP headroom*/
4283         tmp = FLOAT_ZERO;
4284         dspio_set_uint_param(codec, 0x96, 0x3C, tmp);
4285
4286         /*set speaker EQ bypass attenuation*/
4287         dspio_set_uint_param(codec, 0x8f, 0x01, tmp);
4288
4289         /* set AMic1 and AMic2 as mono mic */
4290         tmp = FLOAT_ONE;
4291         dspio_set_uint_param(codec, 0x80, 0x00, tmp);
4292         dspio_set_uint_param(codec, 0x80, 0x01, tmp);
4293
4294         /* set AMic1 as CrystalVoice input */
4295         tmp = FLOAT_ONE;
4296         dspio_set_uint_param(codec, 0x80, 0x05, tmp);
4297
4298         /* set WUH source */
4299         tmp = FLOAT_TWO;
4300         dspio_set_uint_param(codec, 0x31, 0x00, tmp);
4301 }
4302
4303 /*
4304  * Initialization of flags in chip
4305  */
4306 static void ca0132_init_flags(struct hda_codec *codec)
4307 {
4308         chipio_set_control_flag(codec, CONTROL_FLAG_IDLE_ENABLE, 0);
4309         chipio_set_control_flag(codec, CONTROL_FLAG_PORT_A_COMMON_MODE, 0);
4310         chipio_set_control_flag(codec, CONTROL_FLAG_PORT_D_COMMON_MODE, 0);
4311         chipio_set_control_flag(codec, CONTROL_FLAG_PORT_A_10KOHM_LOAD, 0);
4312         chipio_set_control_flag(codec, CONTROL_FLAG_PORT_D_10KOHM_LOAD, 0);
4313         chipio_set_control_flag(codec, CONTROL_FLAG_ADC_C_HIGH_PASS, 1);
4314 }
4315
4316 /*
4317  * Initialization of parameters in chip
4318  */
4319 static void ca0132_init_params(struct hda_codec *codec)
4320 {
4321         chipio_set_control_param(codec, CONTROL_PARAM_PORTA_160OHM_GAIN, 6);
4322         chipio_set_control_param(codec, CONTROL_PARAM_PORTD_160OHM_GAIN, 6);
4323 }
4324
4325 static void ca0132_set_dsp_msr(struct hda_codec *codec, bool is96k)
4326 {
4327         chipio_set_control_flag(codec, CONTROL_FLAG_DSP_96KHZ, is96k);
4328         chipio_set_control_flag(codec, CONTROL_FLAG_DAC_96KHZ, is96k);
4329         chipio_set_control_flag(codec, CONTROL_FLAG_SRC_RATE_96KHZ, is96k);
4330         chipio_set_control_flag(codec, CONTROL_FLAG_SRC_CLOCK_196MHZ, is96k);
4331         chipio_set_control_flag(codec, CONTROL_FLAG_ADC_B_96KHZ, is96k);
4332         chipio_set_control_flag(codec, CONTROL_FLAG_ADC_C_96KHZ, is96k);
4333
4334         chipio_set_conn_rate(codec, MEM_CONNID_MICIN1, SR_96_000);
4335         chipio_set_conn_rate(codec, MEM_CONNID_MICOUT1, SR_96_000);
4336         chipio_set_conn_rate(codec, MEM_CONNID_WUH, SR_48_000);
4337 }
4338
4339 static bool ca0132_download_dsp_images(struct hda_codec *codec)
4340 {
4341         bool dsp_loaded = false;
4342         const struct dsp_image_seg *dsp_os_image;
4343         const struct firmware *fw_entry;
4344
4345         if (request_firmware(&fw_entry, EFX_FILE, codec->card->dev) != 0)
4346                 return false;
4347
4348         dsp_os_image = (struct dsp_image_seg *)(fw_entry->data);
4349         if (dspload_image(codec, dsp_os_image, 0, 0, true, 0)) {
4350                 pr_err("ca0132 dspload_image failed.\n");
4351                 goto exit_download;
4352         }
4353
4354         dsp_loaded = dspload_wait_loaded(codec);
4355
4356 exit_download:
4357         release_firmware(fw_entry);
4358
4359         return dsp_loaded;
4360 }
4361
4362 static void ca0132_download_dsp(struct hda_codec *codec)
4363 {
4364         struct ca0132_spec *spec = codec->spec;
4365
4366 #ifndef CONFIG_SND_HDA_CODEC_CA0132_DSP
4367         return; /* NOP */
4368 #endif
4369
4370         if (spec->dsp_state == DSP_DOWNLOAD_FAILED)
4371                 return; /* don't retry failures */
4372
4373         chipio_enable_clocks(codec);
4374         spec->dsp_state = DSP_DOWNLOADING;
4375         if (!ca0132_download_dsp_images(codec))
4376                 spec->dsp_state = DSP_DOWNLOAD_FAILED;
4377         else
4378                 spec->dsp_state = DSP_DOWNLOADED;
4379
4380         if (spec->dsp_state == DSP_DOWNLOADED)
4381                 ca0132_set_dsp_msr(codec, true);
4382 }
4383
4384 static void ca0132_process_dsp_response(struct hda_codec *codec,
4385                                         struct hda_jack_callback *callback)
4386 {
4387         struct ca0132_spec *spec = codec->spec;
4388
4389         codec_dbg(codec, "ca0132_process_dsp_response\n");
4390         if (spec->wait_scp) {
4391                 if (dspio_get_response_data(codec) >= 0)
4392                         spec->wait_scp = 0;
4393         }
4394
4395         dspio_clear_response_queue(codec);
4396 }
4397
4398 static void hp_callback(struct hda_codec *codec, struct hda_jack_callback *cb)
4399 {
4400         struct ca0132_spec *spec = codec->spec;
4401
4402         /* Delay enabling the HP amp, to let the mic-detection
4403          * state machine run.
4404          */
4405         cancel_delayed_work_sync(&spec->unsol_hp_work);
4406         schedule_delayed_work(&spec->unsol_hp_work, msecs_to_jiffies(500));
4407         cb->tbl->block_report = 1;
4408 }
4409
4410 static void amic_callback(struct hda_codec *codec, struct hda_jack_callback *cb)
4411 {
4412         ca0132_select_mic(codec);
4413 }
4414
4415 static void ca0132_init_unsol(struct hda_codec *codec)
4416 {
4417         snd_hda_jack_detect_enable_callback(codec, UNSOL_TAG_HP, hp_callback);
4418         snd_hda_jack_detect_enable_callback(codec, UNSOL_TAG_AMIC1,
4419                                             amic_callback);
4420         snd_hda_jack_detect_enable_callback(codec, UNSOL_TAG_DSP,
4421                                             ca0132_process_dsp_response);
4422 }
4423
4424 /*
4425  * Verbs tables.
4426  */
4427
4428 /* Sends before DSP download. */
4429 static struct hda_verb ca0132_base_init_verbs[] = {
4430         /*enable ct extension*/
4431         {0x15, VENDOR_CHIPIO_CT_EXTENSIONS_ENABLE, 0x1},
4432         {}
4433 };
4434
4435 /* Send at exit. */
4436 static struct hda_verb ca0132_base_exit_verbs[] = {
4437         /*set afg to D3*/
4438         {0x01, AC_VERB_SET_POWER_STATE, 0x03},
4439         /*disable ct extension*/
4440         {0x15, VENDOR_CHIPIO_CT_EXTENSIONS_ENABLE, 0},
4441         {}
4442 };
4443
4444 /* Other verbs tables.  Sends after DSP download. */
4445 static struct hda_verb ca0132_init_verbs0[] = {
4446         /* chip init verbs */
4447         {0x15, 0x70D, 0xF0},
4448         {0x15, 0x70E, 0xFE},
4449         {0x15, 0x707, 0x75},
4450         {0x15, 0x707, 0xD3},
4451         {0x15, 0x707, 0x09},
4452         {0x15, 0x707, 0x53},
4453         {0x15, 0x707, 0xD4},
4454         {0x15, 0x707, 0xEF},
4455         {0x15, 0x707, 0x75},
4456         {0x15, 0x707, 0xD3},
4457         {0x15, 0x707, 0x09},
4458         {0x15, 0x707, 0x02},
4459         {0x15, 0x707, 0x37},
4460         {0x15, 0x707, 0x78},
4461         {0x15, 0x53C, 0xCE},
4462         {0x15, 0x575, 0xC9},
4463         {0x15, 0x53D, 0xCE},
4464         {0x15, 0x5B7, 0xC9},
4465         {0x15, 0x70D, 0xE8},
4466         {0x15, 0x70E, 0xFE},
4467         {0x15, 0x707, 0x02},
4468         {0x15, 0x707, 0x68},
4469         {0x15, 0x707, 0x62},
4470         {0x15, 0x53A, 0xCE},
4471         {0x15, 0x546, 0xC9},
4472         {0x15, 0x53B, 0xCE},
4473         {0x15, 0x5E8, 0xC9},
4474         {0x15, 0x717, 0x0D},
4475         {0x15, 0x718, 0x20},
4476         {}
4477 };
4478
4479 static struct hda_verb ca0132_init_verbs1[] = {
4480         {0x10, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | UNSOL_TAG_HP},
4481         {0x12, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | UNSOL_TAG_AMIC1},
4482         /* config EAPD */
4483         {0x0b, 0x78D, 0x00},
4484         /*{0x0b, AC_VERB_SET_EAPD_BTLENABLE, 0x02},*/
4485         /*{0x10, 0x78D, 0x02},*/
4486         /*{0x10, AC_VERB_SET_EAPD_BTLENABLE, 0x02},*/
4487         {}
4488 };
4489
4490 static void ca0132_init_chip(struct hda_codec *codec)
4491 {
4492         struct ca0132_spec *spec = codec->spec;
4493         int num_fx;
4494         int i;
4495         unsigned int on;
4496
4497         mutex_init(&spec->chipio_mutex);
4498
4499         spec->cur_out_type = SPEAKER_OUT;
4500         spec->cur_mic_type = DIGITAL_MIC;
4501         spec->cur_mic_boost = 0;
4502
4503         for (i = 0; i < VNODES_COUNT; i++) {
4504                 spec->vnode_lvol[i] = 0x5a;
4505                 spec->vnode_rvol[i] = 0x5a;
4506                 spec->vnode_lswitch[i] = 0;
4507                 spec->vnode_rswitch[i] = 0;
4508         }
4509
4510         /*
4511          * Default states for effects are in ca0132_effects[].
4512          */
4513         num_fx = OUT_EFFECTS_COUNT + IN_EFFECTS_COUNT;
4514         for (i = 0; i < num_fx; i++) {
4515                 on = (unsigned int)ca0132_effects[i].reqs[0];
4516                 spec->effects_switch[i] = on ? 1 : 0;
4517         }
4518
4519         spec->voicefx_val = 0;
4520         spec->effects_switch[PLAY_ENHANCEMENT - EFFECT_START_NID] = 1;
4521         spec->effects_switch[CRYSTAL_VOICE - EFFECT_START_NID] = 0;
4522
4523 #ifdef ENABLE_TUNING_CONTROLS
4524         ca0132_init_tuning_defaults(codec);
4525 #endif
4526 }
4527
4528 static void ca0132_exit_chip(struct hda_codec *codec)
4529 {
4530         /* put any chip cleanup stuffs here. */
4531
4532         if (dspload_is_loaded(codec))
4533                 dsp_reset(codec);
4534 }
4535
4536 static int ca0132_init(struct hda_codec *codec)
4537 {
4538         struct ca0132_spec *spec = codec->spec;
4539         struct auto_pin_cfg *cfg = &spec->autocfg;
4540         int i;
4541
4542         if (spec->dsp_state != DSP_DOWNLOAD_FAILED)
4543                 spec->dsp_state = DSP_DOWNLOAD_INIT;
4544         spec->curr_chip_addx = INVALID_CHIP_ADDRESS;
4545
4546         snd_hda_power_up_pm(codec);
4547
4548         ca0132_init_unsol(codec);
4549
4550         ca0132_init_params(codec);
4551         ca0132_init_flags(codec);
4552         snd_hda_sequence_write(codec, spec->base_init_verbs);
4553         ca0132_download_dsp(codec);
4554         ca0132_refresh_widget_caps(codec);
4555         ca0132_setup_defaults(codec);
4556         ca0132_init_analog_mic2(codec);
4557         ca0132_init_dmic(codec);
4558
4559         for (i = 0; i < spec->num_outputs; i++)
4560                 init_output(codec, spec->out_pins[i], spec->dacs[0]);
4561
4562         init_output(codec, cfg->dig_out_pins[0], spec->dig_out);
4563
4564         for (i = 0; i < spec->num_inputs; i++)
4565                 init_input(codec, spec->input_pins[i], spec->adcs[i]);
4566
4567         init_input(codec, cfg->dig_in_pin, spec->dig_in);
4568
4569         for (i = 0; i < spec->num_init_verbs; i++)
4570                 snd_hda_sequence_write(codec, spec->init_verbs[i]);
4571
4572         ca0132_select_out(codec);
4573         ca0132_select_mic(codec);
4574
4575         snd_hda_jack_report_sync(codec);
4576
4577         snd_hda_power_down_pm(codec);
4578
4579         return 0;
4580 }
4581
4582 static void ca0132_free(struct hda_codec *codec)
4583 {
4584         struct ca0132_spec *spec = codec->spec;
4585
4586         cancel_delayed_work_sync(&spec->unsol_hp_work);
4587         snd_hda_power_up(codec);
4588         snd_hda_sequence_write(codec, spec->base_exit_verbs);
4589         ca0132_exit_chip(codec);
4590         snd_hda_power_down(codec);
4591         kfree(codec->spec);
4592 }
4593
4594 static struct hda_codec_ops ca0132_patch_ops = {
4595         .build_controls = ca0132_build_controls,
4596         .build_pcms = ca0132_build_pcms,
4597         .init = ca0132_init,
4598         .free = ca0132_free,
4599         .unsol_event = snd_hda_jack_unsol_event,
4600 };
4601
4602 static void ca0132_config(struct hda_codec *codec)
4603 {
4604         struct ca0132_spec *spec = codec->spec;
4605         struct auto_pin_cfg *cfg = &spec->autocfg;
4606
4607         spec->dacs[0] = 0x2;
4608         spec->dacs[1] = 0x3;
4609         spec->dacs[2] = 0x4;
4610
4611         spec->multiout.dac_nids = spec->dacs;
4612         spec->multiout.num_dacs = 3;
4613         spec->multiout.max_channels = 2;
4614
4615         spec->num_outputs = 2;
4616         spec->out_pins[0] = 0x0b; /* speaker out */
4617         spec->out_pins[1] = 0x10; /* headphone out */
4618         spec->shared_out_nid = 0x2;
4619
4620         spec->num_inputs = 3;
4621         spec->adcs[0] = 0x7; /* digital mic / analog mic1 */
4622         spec->adcs[1] = 0x8; /* analog mic2 */
4623         spec->adcs[2] = 0xa; /* what u hear */
4624         spec->shared_mic_nid = 0x7;
4625
4626         spec->input_pins[0] = 0x12;
4627         spec->input_pins[1] = 0x11;
4628         spec->input_pins[2] = 0x13;
4629
4630         /* SPDIF I/O */
4631         spec->dig_out = 0x05;
4632         spec->multiout.dig_out_nid = spec->dig_out;
4633         cfg->dig_out_pins[0] = 0x0c;
4634         cfg->dig_outs = 1;
4635         cfg->dig_out_type[0] = HDA_PCM_TYPE_SPDIF;
4636         spec->dig_in = 0x09;
4637         cfg->dig_in_pin = 0x0e;
4638         cfg->dig_in_type = HDA_PCM_TYPE_SPDIF;
4639 }
4640
4641 static int patch_ca0132(struct hda_codec *codec)
4642 {
4643         struct ca0132_spec *spec;
4644         int err;
4645
4646         codec_dbg(codec, "patch_ca0132\n");
4647
4648         spec = kzalloc(sizeof(*spec), GFP_KERNEL);
4649         if (!spec)
4650                 return -ENOMEM;
4651         codec->spec = spec;
4652         spec->codec = codec;
4653
4654         spec->dsp_state = DSP_DOWNLOAD_INIT;
4655         spec->num_mixers = 1;
4656         spec->mixers[0] = ca0132_mixer;
4657
4658         spec->base_init_verbs = ca0132_base_init_verbs;
4659         spec->base_exit_verbs = ca0132_base_exit_verbs;
4660         spec->init_verbs[0] = ca0132_init_verbs0;
4661         spec->init_verbs[1] = ca0132_init_verbs1;
4662         spec->num_init_verbs = 2;
4663
4664         INIT_DELAYED_WORK(&spec->unsol_hp_work, ca0132_unsol_hp_delayed);
4665
4666         ca0132_init_chip(codec);
4667
4668         ca0132_config(codec);
4669
4670         err = snd_hda_parse_pin_def_config(codec, &spec->autocfg, NULL);
4671         if (err < 0)
4672                 return err;
4673
4674         codec->patch_ops = ca0132_patch_ops;
4675         codec->pcm_format_first = 1;
4676         codec->no_sticky_stream = 1;
4677
4678         return 0;
4679 }
4680
4681 /*
4682  * patch entries
4683  */
4684 static struct hda_codec_preset snd_hda_preset_ca0132[] = {
4685         { .id = 0x11020011, .name = "CA0132",     .patch = patch_ca0132 },
4686         {} /* terminator */
4687 };
4688
4689 MODULE_ALIAS("snd-hda-codec-id:11020011");
4690
4691 MODULE_LICENSE("GPL");
4692 MODULE_DESCRIPTION("Creative Sound Core3D codec");
4693
4694 static struct hda_codec_driver ca0132_driver = {
4695         .preset = snd_hda_preset_ca0132,
4696 };
4697
4698 module_hda_codec_driver(ca0132_driver);