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