OSDN Git Service

5631bce04793e9f36a33379491feecfcdec353f3
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / sound / soc / codecs / tfa98xx / tfa_dsp.c
1 /*
2  *Copyright 2015 NXP Semiconductors
3  *
4  *Licensed under the Apache License, Version 2.0 (the "License");
5  *you may not use this file except in compliance with the License.
6  *You may obtain a copy of the License at
7  *
8  *http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *Unless required by applicable law or agreed to in writing, software
11  *distributed under the License is distributed on an "AS IS" BASIS,
12  *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *See the License for the specific language governing permissions and
14  *limitations under the License.
15  */
16
17 #include "config.h"
18
19 #include "tfa98xx_tfafieldnames.h"
20 #include "tfa_internal.h"
21 #include "tfa.h"
22 #include "tfa_service.h"
23 #include "tfa_container.h"
24 #include "tfa_dsp_fw.h"
25 /* TODO: remove genregs usage? */
26 #include "tfa98xx_genregs_N1C.h"
27
28 /* handle macro for bitfield */
29 #define TFA_MK_BF(reg, pos, len) ((reg<<8)|(pos<<4)|(len-1))
30
31 /* abstract family for register */
32 #define FAM_TFA98XX_CF_CONTROLS (TFA_FAM(handle, RST) >> 8)
33 #define FAM_TFA98XX_CF_MEM      (TFA_FAM(handle, MEMA) >> 8)
34 #define FAM_TFA98XX_MTP0        (TFA_FAM(handle, MTPOTC) >> 8)
35 #define FAM_TFA98xx_INT_EN      (TFA_FAM(handle, INTENVDDS) >> 8)
36
37 #define CF_STATUS_I2C_CMD_ACK 0x01
38
39 #if (defined(TFA9888) || defined(TFA98XX_FULL))
40 void tfa9888_ops(struct tfa_device_ops *ops);
41 #endif
42 #if (defined(TFA9891) || defined(TFA98XX_FULL))
43 void tfa9891_ops(struct tfa_device_ops *ops);
44 #endif
45 #if (defined(TFA9897) || defined(TFA98XX_FULL))
46 void tfa9897_ops(struct tfa_device_ops *ops);
47 #endif
48 #if (defined(TFA9890) || defined(TFA98XX_FULL))
49 void tfa9890_ops(struct tfa_device_ops *ops);
50 #endif
51 #if (defined(TFA9887B) || defined(TFA98XX_FULL))
52 int tfa9887B_is87(Tfa98xx_handle_t handle);
53 void tfa9887B_ops(struct tfa_device_ops *ops);
54 #endif
55 #if (defined(TFA9887) || defined(TFA98XX_FULL))
56 void tfa9887_ops(struct tfa_device_ops *ops);
57 #endif
58
59 #ifndef MIN
60 #define MIN(A, B) (A < B ? A : B)
61 #endif
62
63 /* retry values */
64 #define CFSTABLE_TRIES   10
65 #define PWDNWAIT_TRIES   50
66 #define AMPOFFWAIT_TRIES 50
67 #define MTPBWAIT_TRIES   50
68 #define MTPEX_WAIT_NTRIES 25
69
70 static int tfa98xx_runtime_verbose;
71 static int tfa98xx_trace_level;
72
73 extern struct tfa98xx *getHandle(int dev);
74 extern void tfa98xx_dump_register(struct tfa98xx *tfa98xx, int level, char *msg);
75
76 /* 4 possible I2C addresses
77  */
78 #define MAX_HANDLES 4
79 TFA_INTERNAL struct Tfa98xx_handle_private handles_local[MAX_HANDLES];
80
81 /*
82  * static functions
83  */
84
85 TFA_INTERNAL int tfa98xx_handle_is_open(Tfa98xx_handle_t h)
86 {
87         int retval = 0;
88
89         if ((h >= 0) && (h < MAX_HANDLES))
90                 retval = handles_local[h].in_use != 0;
91
92         return retval;
93 }
94
95 int print_calibration(Tfa98xx_handle_t handle, char *str, size_t size)
96 {
97         return snprintf(str, size, " Prim:%d mOhms, Sec:%d mOhms\n",
98                                 handles_local[handle].mohm[0],
99                                 handles_local[handle].mohm[1]);
100 }
101
102 int tfa_get_calibration_info(Tfa98xx_handle_t handle, int channel)
103 {
104         return handles_local[handle].mohm[channel];
105 }
106 /*
107  * open
108  */
109
110 /*
111  *  set device info and register device ops
112  */
113 static void tfa_set_query_info(int dev_idx)
114 {
115         if (dev_idx > MAX_HANDLES) {
116                 _ASSERT(dev_idx >= MAX_HANDLES);
117                 return;
118         }
119
120         /* invalidate  device struct cached values */
121         handles_local[dev_idx].hw_feature_bits = -1;
122         handles_local[dev_idx].sw_feature_bits[0] = -1;
123         handles_local[dev_idx].sw_feature_bits[1] = -1;
124         handles_local[dev_idx].profile = -1;
125         handles_local[dev_idx].vstep[0] = -1;
126         handles_local[dev_idx].vstep[1] = -1;
127         /* defaults */
128         handles_local[dev_idx].tfa_family = 1;
129         handles_local[dev_idx].daimap = Tfa98xx_DAI_I2S;                /* all others */
130         handles_local[dev_idx].spkr_count = 1;
131         handles_local[dev_idx].spkr_select = 0;
132         handles_local[dev_idx].support_tcoef = supportYes;
133         handles_local[dev_idx].supportDrc = supportNotSet;
134         handles_local[dev_idx].support_saam = supportNotSet;
135
136         /* TODO use the getfeatures() for retrieving the features [artf103523]
137         handles_local[dev_idx].supportDrc = supportNotSet;*/
138
139         switch (handles_local[dev_idx].rev & 0xff) {
140         case 0x88:
141                 /* tfa9888 */
142                 handles_local[dev_idx].tfa_family = 2;
143                 handles_local[dev_idx].spkr_count = 2;
144                 handles_local[dev_idx].daimap = Tfa98xx_DAI_TDM;
145                 tfa9888_ops(&handles_local[dev_idx].dev_ops); /* register device operations */
146                 break;
147         case 0x97:
148                 /* tfa9897 */
149                 handles_local[dev_idx].supportDrc = supportNo;
150                 handles_local[dev_idx].spkr_count = 1;
151                 handles_local[dev_idx].daimap = Tfa98xx_DAI_TDM;
152                 tfa9897_ops(&handles_local[dev_idx].dev_ops); /* register device operations */
153                 break;
154         case 0x92:
155                 /* tfa9891 */
156                 handles_local[dev_idx].spkr_count = 1;
157                 handles_local[dev_idx].daimap = (Tfa98xx_DAI_PDM | Tfa98xx_DAI_I2S);
158                 tfa9891_ops(&handles_local[dev_idx].dev_ops); /* register device operations */
159                 break;
160         case 0x91:
161                 /* tfa9890B */
162                 handles_local[dev_idx].spkr_count = 1;
163                 handles_local[dev_idx].daimap = (Tfa98xx_DAI_PDM | Tfa98xx_DAI_I2S);
164                 break;
165         case 0x80:
166         case 0x81:
167                 /* tfa9890 */
168                 handles_local[dev_idx].spkr_count = 1;
169                 handles_local[dev_idx].daimap = Tfa98xx_DAI_I2S;
170                 handles_local[dev_idx].supportDrc = supportNo;
171                 handles_local[dev_idx].supportFramework = supportNo;
172                 tfa9890_ops(&handles_local[dev_idx].dev_ops); /* register device operations */
173                 break;
174         case 0x12:
175                 /* tfa9887 / tfa9887B / tfa9895 */
176                 handles_local[dev_idx].spkr_count = 1;
177                 handles_local[dev_idx].daimap = Tfa98xx_DAI_I2S;
178                 if (tfa9887B_is87(dev_idx)) {
179                         handles_local[dev_idx].support_tcoef = supportNo;
180                         tfa9887_ops(&handles_local[dev_idx].dev_ops); /* register device operations */
181                 } else
182                         tfa9887B_ops(&handles_local[dev_idx].dev_ops); /* register device operations */
183                 break;
184         default:
185                 pr_err("unknown device type : 0x%02x\n", handles_local[dev_idx].rev);
186                 _ASSERT(0);
187                 break;
188         }
189 }
190
191 /*
192  * lookup the device type and return the family type
193  */
194 int tfa98xx_dev2family(int dev_type)
195 {
196         /* only look at the die ID part (lsb byte) */
197         switch (dev_type & 0xff) {
198         case 0x12:
199         case 0x80:
200         case 0x81:
201         case 0x91:
202         case 0x92:
203         case 0x97:
204                 return 1;
205         case 0x88:
206                 return 2;
207         case 0x50:
208                 return 3;
209         default:
210                 return 0;
211         }
212 }
213
214 int tfa98xx_dev_family(Tfa98xx_handle_t dev_idx)
215 {
216         return handles_local[dev_idx].tfa_family;
217 }
218
219 unsigned short tfa98xx_dev_revision(Tfa98xx_handle_t dev_idx)
220 {
221         return handles_local[dev_idx].rev;
222 }
223
224 void tfa98xx_set_spkr_select(Tfa98xx_handle_t dev_idx, char *configuration)
225 {
226          char firstLetter;
227
228         /* 4=Left, 2=Right, 1=none, 0=default */
229         if (configuration == NULL)
230                 handles_local[dev_idx].spkr_select = 0;
231         else {
232                 firstLetter = (char)tolower((unsigned char)configuration[0]);
233                 switch (firstLetter) {
234                 case 'b': /* SC / both -> apply primary also to secondary */
235                         handles_local[dev_idx].spkr_select = 8;
236                         handles_local[dev_idx].spkr_count = 2;
237                         break;
238                 case 'l':
239                 case 'p': /* DS / left -> only use primary channel */
240                         handles_local[dev_idx].spkr_select = 4;
241                         handles_local[dev_idx].spkr_count = 1;
242                         break;
243                 case 'r':
244                 case 's': /* DP / right -> only use secondary channel */
245                         handles_local[dev_idx].spkr_select = 2;
246                         handles_local[dev_idx].spkr_count = 1;
247                         break;
248                 case 'd': /* DC / disable -> skip applying configuration for both */
249                         handles_local[dev_idx].spkr_select = 1;
250                         handles_local[dev_idx].spkr_count = 2;
251                         break;
252                 default:
253                         handles_local[dev_idx].spkr_select = 0;
254                         handles_local[dev_idx].spkr_count = 2;
255                         break;
256                 }
257         }
258 }
259
260 void tfa_mock_probe(int dev_idx, unsigned short revid, int slave_address)
261 {
262         handles_local[dev_idx].slave_address = (unsigned char)slave_address*2;
263         handles_local[dev_idx].rev = revid;
264         tfa_set_query_info(dev_idx);
265 }
266
267 enum Tfa98xx_Error tfa_soft_probe(int dev_idx, int revid)
268 {
269         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
270
271         error = tfaContGetSlave(dev_idx, &handles_local[dev_idx].slave_address);
272         handles_local[dev_idx].slave_address *= 2;
273         if (error)
274                 return error;
275
276         handles_local[dev_idx].rev = (unsigned short)revid;
277         tfa_set_query_info(dev_idx);
278
279         return error;
280 }
281
282 /*
283  * TODO The slave/cnt check in tfa98xx_register_dsp() should be done here in tfa_probe()
284  */
285 enum Tfa98xx_Error tfa_probe(unsigned char slave_address,
286                                                                 Tfa98xx_handle_t *pHandle)
287 {
288         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
289         int rev;
290         int idx;
291
292         _ASSERT(pHandle != NULL);
293         *pHandle = -1;
294
295         /* when available select index used in container file */
296         idx = tfa98xx_cnt_slave2idx(slave_address>>1);
297         if (idx < 0)
298                 idx = 0; /* when no container file, use first instance */
299
300         if (handles_local[idx].in_use == 1)
301                 return Tfa98xx_Error_InUse;
302
303         handles_local[idx].in_use = 1;
304
305         switch (slave_address) {
306         case TFA98XX_GENERIC_SLAVE_ADDRESS:     /* same as (0x0E<<1) test adr */
307         case 0x68:
308         case 0x6A:
309         case 0x6C:
310         case 0x6E:
311         case (0x1a<<1): /* TODO properly implement foreign i2c addressing like uda1355 */
312                 handles_local[idx].buffer_size =  NXP_I2C_BufferSize();
313                 handles_local[idx].slave_address = slave_address;
314 /* TODO: how do we deal with old bugs? */
315 #if (defined(TFA9887)  || defined (TFA9887B) || defined(TFA98XX_FULL))
316                 /* do a dummy read in order to generate
317                  * i2c clocks when accessing the device
318                  * for the first time
319                  */
320                 rev = TFA_READ_REG(idx, REV);
321 #endif
322                 /* this can be the very first read, so check error here */
323                 rev = TFA_READ_REG(idx, REV);
324                 if (rev < 0) /* returns negative if error */
325                         error = -rev;
326                 if (Tfa98xx_Error_Ok != error) {
327                         handles_local[idx].in_use = 0;
328                         pr_debug("\nError: Unable to read revid from slave:0x%02x\n", slave_address / 2);
329                         return error;
330                 }
331                 handles_local[idx].rev = (unsigned short) rev;
332                 *pHandle = idx;
333                 error = Tfa98xx_Error_Ok;
334 #ifdef __KERNEL__ /* don't spam userspace with information */
335                 tfa98xx_trace_printk("slave:0x%02x revid:0x%04x\n", slave_address, rev);
336                 pr_debug("slave:0x%02x revid:0x%04x\n", slave_address, rev);
337 #endif
338                 break;
339         default:
340                 pr_info("Unknown slave adress! \n");
341                 /* wrong slave address */
342                 error = Tfa98xx_Error_Bad_Parameter;
343         }
344
345         tfa_set_query_info(idx);
346
347         handles_local[idx].in_use = 0;
348
349         return error;
350 }
351
352 enum Tfa98xx_Error
353 tfa98xx_open(Tfa98xx_handle_t handle)
354 {
355         if (tfa98xx_handle_is_open(handle)) {
356                 return Tfa98xx_Error_InUse;
357         } else {
358                 handles_local[handle].in_use = 1;
359                 return Tfa98xx_Error_Ok;
360         }
361 }
362
363 /*
364  * close
365  */
366 enum Tfa98xx_Error tfa98xx_close(Tfa98xx_handle_t handle)
367 {
368         if (tfa98xx_handle_is_open(handle)) {
369                 handles_local[handle].in_use = 0;
370                 return Tfa98xx_Error_Ok;
371         } else {
372                 return Tfa98xx_Error_NotOpen;
373         }
374 }
375
376 /*
377  *      return the target address for the filter on this device
378
379   filter_index:
380         [0..9] reserved for EQ (not deployed, calc. is available)
381         [10..12] anti-alias filter
382         [13]  integrator filter
383
384  */
385 enum Tfa98xx_DMEM tfa98xx_filter_mem(Tfa98xx_handle_t dev, int filter_index, unsigned short *address, int channel)
386 {
387         enum Tfa98xx_DMEM  dmem = -1;
388         int idx;
389         unsigned short bq_table[7][4] = {
390         /* index: 10, 11, 12, 13 */
391                 {346, 351, 356, 288}, /* 87 BRA_MAX_MRA4-2_7.00 */
392                 {346, 351, 356, 288}, /* 90 BRA_MAX_MRA6_9.02 */
393                 {467, 472, 477, 409}, /* 95 BRA_MAX_MRA7_10.02 */
394                 {406, 411, 416, 348}, /* 97 BRA_MAX_MRA9_12.01 */
395                 {467, 472, 477, 409}, /* 91 BRA_MAX_MRAA_13.02 */
396                 {8832, 8837, 8842, 8847}, /* 88 part1 */
397                 {8853, 8858, 8863, 8868}  /* 88 part2 */
398                 /* Since the 88 is stereo we have 2 parts.
399                  * Every index has 5 values except index 13 this one has 6 values
400                  */
401         };
402
403         if ((filter_index >= 10) && (filter_index <= 13)) {
404                 dmem = Tfa98xx_DMEM_YMEM; /* for all devices */
405                 idx = filter_index-10;
406
407                 switch (handles_local[dev].rev & 0xff) { /* only compare lower byte */
408                 case 0x12:
409                         if (tfa9887B_is87(dev))
410                                 *address = bq_table[0][idx];
411                         else
412                                 *address = bq_table[2][idx];
413                         break;
414                 case 0x97:
415                         *address = bq_table[3][idx];
416                         break;
417                 case 0x80:
418                 case 0x81:  /* for the RAM version */
419                 case 0x91:
420                         *address = bq_table[1][idx];
421                         break;
422                 case 0x92:
423                         *address = bq_table[4][idx];
424                         break;
425                 case 0x88:
426                         /* Channel 1 = primary, 2 = secondary */
427                         if (channel == 1)
428                                 *address = bq_table[5][idx];
429                         else
430                                 *address = bq_table[6][idx];
431                         break;
432                 default:
433                         /* unsupported case, possibly intermediate version */
434                         return -EPERM;
435                         _ASSERT(0);
436                 }
437         }
438         return dmem;
439 }
440
441 /************************ query functions *****************/
442 /* no device involved */
443 /**
444  * return revision
445  */
446 void tfa98xx_rev(int *major, int *minor, int *revision)
447 {
448         *major = TFA98XX_API_REV_MAJOR;
449         *minor = TFA98XX_API_REV_MINOR;
450         *revision = TFA98XX_API_REV_REVISION;
451 }
452
453 /**
454  * Return the maximum nr of devices (SC39786)
455  */
456 int tfa98xx_max_devices(void) /* TODO get from cnt (now only called from contOpen) */
457 {
458         return MAX_HANDLES;
459 }
460
461 /* return the device revision id
462  */
463 unsigned short tfa98xx_get_device_revision(Tfa98xx_handle_t handle)
464 {
465         /* local function. Caller must make sure handle is valid */
466         return handles_local[handle].rev;
467 }
468
469 /**
470  * return the device digital audio interface (DAI) type bitmap
471  */
472 enum Tfa98xx_DAI tfa98xx_get_device_dai(Tfa98xx_handle_t handle)
473 {
474         /* local function. Caller must make sure handle is valid */
475         return handles_local[handle].daimap;
476 }
477
478 /**
479  * get the feature bits from the DSP
480  *  - the older tfa9887 does not support this getfeature and
481  *    also no tcoef support so we use this as the info for returning
482  *    this feature
483  */
484 enum Tfa98xx_Error tfa98xx_dsp_support_tcoef(Tfa98xx_handle_t dev_idx,
485                 int *pb_support_tCoef)
486 {
487         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
488
489         /* if already set return that state , always assume supported */
490         if (handles_local[dev_idx].support_tcoef != supportNotSet)
491                 *pb_support_tCoef = (handles_local[dev_idx].support_tcoef == supportYes);
492
493         handles_local[dev_idx].support_tcoef = *pb_support_tCoef ? supportYes : supportNo;
494
495         return error;
496 }
497
498 /**
499  * tfa98xx_supported_speakers
500  *  returns the number of the supported speaker count
501  */
502 enum Tfa98xx_Error tfa98xx_supported_speakers(Tfa98xx_handle_t handle, int *spkr_count)
503 {
504         if (tfa98xx_handle_is_open(handle)) {
505                 *spkr_count = handles_local[handle].spkr_count;
506         } else
507                 return Tfa98xx_Error_NotOpen;
508
509         return Tfa98xx_Error_Ok;
510 }
511
512 /**
513  * tfa98xx_supported_dai
514  *  returns the bitmap of the supported Digital Audio Interfaces
515  */
516 enum Tfa98xx_Error tfa98xx_supported_dai(Tfa98xx_handle_t handle, enum Tfa98xx_DAI *daimap)
517 {
518         if (tfa98xx_handle_is_open(handle)) {
519                 *daimap = handles_local[handle].daimap;
520         } else
521                 return Tfa98xx_Error_NotOpen;
522
523         return Tfa98xx_Error_Ok;
524 }
525
526 /*
527  * tfa98xx_supported_saam
528  *  returns the supportedspeaker as microphone feature
529  */
530 enum Tfa98xx_Error tfa98xx_supported_saam(Tfa98xx_handle_t handle, enum Tfa98xx_saam *saam)
531 {
532         int features;
533         enum Tfa98xx_Error error;
534
535         if (handles_local[handle].support_saam == supportNotSet) {
536                 error = tfa98xx_dsp_get_hw_feature_bits(handle, &features);
537                 if (error != Tfa98xx_Error_Ok)
538                         return error;
539                 handles_local[handle].support_saam =
540                                 (features & 0x8000) ? supportYes : supportNo; /* SAAM is bit15 */
541         }
542         *saam = handles_local[handle].support_saam == supportYes ? Tfa98xx_saam : Tfa98xx_saam_none ;
543
544         return Tfa98xx_Error_Ok;
545 }
546
547 /*
548  * tfa98xx_compare_features
549  *  Obtains features_from_MTP and features_from_cnt
550  */
551 enum Tfa98xx_Error tfa98xx_compare_features(Tfa98xx_handle_t handle, int features_from_MTP[3], int features_from_cnt[3])
552 {
553         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
554         uint32_t value;
555         uint16_t mtpbf;
556         unsigned char bytes[3 * 2];
557
558         /* int sw_feature_bits[2]; *//* cached feature bits data */
559         /* int hw_feature_bits; *//* cached feature bits data */
560
561         /* Nothing to test without clock: */
562         int status;
563
564         tfa98xx_dsp_system_stable(handle, &status);
565         if (!status)
566                 return Tfa98xx_Error_NoClock; /* Only test when we have a clock. */
567
568         /* Set proper MTP location per device: */
569         if (tfa98xx_dev_family(handle) == 1)
570                 mtpbf = 0x850f;  /* MTP5 for tfa1,16 bits */
571         else
572                 mtpbf = 0xf907;  /* MTP9 for tfa2, 8 bits */
573
574         /* Read HW features from MTP: */
575         value = tfa_read_reg(handle, mtpbf) & 0xffff;
576         features_from_MTP[0] = handles_local[handle].hw_feature_bits = value;
577
578         /* Read SW features: */
579         error = tfa_dsp_cmd_id_write_read(handle, MODULE_FRAMEWORK,
580                         FW_PAR_ID_GET_FEATURE_INFO, sizeof(bytes), bytes);
581         if (error != Tfa98xx_Error_Ok)
582                 return error; /* old ROM code may respond with Tfa98xx_Error_RpcParamId */
583         tfa98xx_convert_bytes2data(sizeof(bytes), bytes, &features_from_MTP[1]);
584
585         /* check if feature bits from MTP match feature bits from cnt file: */
586         get_hw_features_from_cnt(handle, &features_from_cnt[0]);
587         get_sw_features_from_cnt(handle, &features_from_cnt[1]);
588
589         return error;
590 }
591
592 /********************************* device specific ops ************************************************/
593 /* the wrapper for DspReset, in case of full */
594 enum Tfa98xx_Error tfa98xx_dsp_reset(Tfa98xx_handle_t dev_idx, int state)
595 {
596         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
597
598         if (tfa98xx_handle_is_open(dev_idx)) {
599                 if (handles_local[dev_idx].dev_ops.tfa_dsp_reset)
600                         error = (*handles_local[dev_idx].dev_ops.tfa_dsp_reset)(dev_idx, state);
601                 else
602                         /* generic function */
603                         TFA_SET_BF_VOLATILE(dev_idx, RST, (uint16_t)state);
604         }
605         return error;
606 }
607
608 /* tfa98xx_dsp_system_stable
609  *  return: *ready = 1 when clocks are stable to allow DSP subsystem access
610  */
611
612 /* This is the clean, default static
613  */
614 static enum Tfa98xx_Error _tfa98xx_dsp_system_stable(Tfa98xx_handle_t handle,
615                                                 int *ready)
616 {
617         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
618         unsigned short status;
619         int value;
620
621         /* check the contents of the STATUS register */
622         value = TFA_READ_REG(handle, AREFS);
623         if (value < 0) {
624                 error = -value;
625                 *ready = 0;
626                 _ASSERT(error);         /* an error here can be fatal */
627                 return error;
628         }
629         status = (unsigned short)value;
630
631         /* check AREFS and CLKS and MTPB: not ready if either is clear */
632         *ready = !((TFA_GET_BF_VALUE(handle, AREFS, status) == 0)
633                                 || (TFA_GET_BF_VALUE(handle, CLKS, status) == 0)
634                                 || (TFA_GET_BF_VALUE(handle, MTPB, status) == 1));
635
636         return error;
637 }
638
639 /* deferred calibration */
640 void tfa98xx_apply_deferred_calibration(Tfa98xx_handle_t handle)
641 {
642         struct tfa98xx_controls *controls = &(handles_local[handle].dev_ops.controls);
643         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
644         unsigned short value;
645
646         if (controls->otc.deferrable && controls->otc.triggered) {
647                 pr_debug("Deferred writing otc = %d\n", controls->otc.wr_value);
648                 err = tfa98xx_set_mtp(handle,
649                         (uint16_t)controls->otc.wr_value << TFA98XX_KEY2_PROTECTED_MTP0_MTPOTC_POS,
650                         1 << TFA98XX_KEY2_PROTECTED_MTP0_MTPOTC_POS);
651                 if (err != Tfa98xx_Error_Ok) {
652                         pr_err("Unable to apply deferred MTP OTC write. Error=%d\n",
653                                                                         err);
654                 } else {
655                         controls->otc.triggered = false;
656                         controls->otc.rd_valid = true;
657                         err = tfa98xx_get_mtp(handle, &value);
658                         if (err == Tfa98xx_Error_Ok)
659                                 controls->otc.rd_value =
660                                         (value & TFA98XX_KEY2_PROTECTED_MTP0_MTPOTC_MSK)
661                                         >> TFA98XX_KEY2_PROTECTED_MTP0_MTPOTC_POS;
662                         else
663                                 controls->otc.rd_value = controls->otc.wr_value;
664                 }
665         }
666
667         if (controls->mtpex.deferrable && controls->mtpex.triggered) {
668                 pr_debug("Deferred writing mtpex = %d\n", controls->mtpex.wr_value);
669                 err = tfa98xx_set_mtp(handle,
670                         (uint16_t)controls->mtpex.wr_value << TFA98XX_KEY2_PROTECTED_MTP0_MTPEX_POS,
671                         1 << TFA98XX_KEY2_PROTECTED_MTP0_MTPEX_POS);
672                 if (err != Tfa98xx_Error_Ok) {
673                         pr_err("Unable to apply deferred MTPEX write. Rrror=%d\n",
674                                                                         err);
675                 } else {
676                         controls->mtpex.triggered = false;
677                         controls->mtpex.rd_valid = true;
678                         err = tfa98xx_get_mtp(handle, &value);
679                         if (err == Tfa98xx_Error_Ok)
680                                 controls->mtpex.rd_value =
681                                         (value & TFA98XX_KEY2_PROTECTED_MTP0_MTPEX_MSK)
682                                         >> TFA98XX_KEY2_PROTECTED_MTP0_MTPEX_POS;
683                         else
684                                 controls->mtpex.rd_value = controls->mtpex.wr_value;
685                 }
686         }
687
688         if (controls->calib.triggered) {
689                 err = tfa_calibrate(handle);
690                 if (err) {
691                         pr_info("Deferred calibration failed: %d\n", err);
692                 } else {
693                         pr_debug("Deferred calibration ok\n");
694                         controls->calib.triggered = false;
695                 }
696         }
697 }
698
699 /* the ops wrapper for tfa98xx_dsp_SystemStable */
700 enum Tfa98xx_Error tfa98xx_dsp_system_stable(Tfa98xx_handle_t dev_idx, int *ready)
701 {
702         enum Tfa98xx_Error error;
703
704         if (!tfa98xx_handle_is_open(dev_idx))
705                 return Tfa98xx_Error_NotOpen;
706
707         if (handles_local[dev_idx].dev_ops.tfa_dsp_system_stable)
708                 error = (*handles_local[dev_idx].dev_ops.tfa_dsp_system_stable)(dev_idx, ready);
709         else
710                 /* generic function */
711                 error = _tfa98xx_dsp_system_stable(dev_idx, ready);
712         return error;
713 }
714
715 /* the ops wrapper for tfa98xx_dsp_SystemStable */
716 int tfa98xx_cf_enabled(Tfa98xx_handle_t dev_idx)
717 {
718         if (!tfa98xx_handle_is_open(dev_idx))
719                 return Tfa98xx_Error_NotOpen;
720
721         return TFA_GET_BF(dev_idx, CFE);
722 }
723
724
725 /*
726  * bring the device into a state similar to reset
727  */
728 enum Tfa98xx_Error tfa98xx_init(Tfa98xx_handle_t handle)
729 {
730         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
731         uint16_t value = 0;
732
733         if (!tfa98xx_handle_is_open(handle))
734                 return Tfa98xx_Error_NotOpen;
735
736         /* reset all i2C registers to default
737          *  Write the register directly to avoid the read in the bitfield function.
738          *  The I2CR bit may overwrite the full register because it is reset anyway.
739          *  This will save a reg read transaction.
740          */
741         TFA_SET_BF_VALUE(handle, I2CR, 1, &value);
742         TFA_WRITE_REG(handle, I2CR, value);
743
744         if (tfa98xx_dev_family(handle) == 2) {
745                 /* restore MANSCONF and MANCOLD to POR state */
746                 TFA_SET_BF_VOLATILE(handle, MANSCONF, 0);
747                 TFA_SET_BF_VOLATILE(handle, MANCOLD, 1);
748         } else {
749                 /* Mark TFA1 family chips OTC and MTPEX calibration accesses
750                  * as deferrable, since these registers cannot be accesed
751                  * while the I2S link is not up and running
752                  */
753                 handles_local[handle].dev_ops.controls.otc.deferrable = true;
754                 handles_local[handle].dev_ops.controls.mtpex.deferrable = true;
755         }
756         switch (TFA_GET_BF(handle, REV) & 0xff) {
757         case 0x80:
758                 pr_debug("tfa98xx_init Dev ID %x\n", (TFA_GET_BF(handle, REV) & 0xff));
759                 break;
760         default:
761                 tfa98xx_dsp_reset(handle, 1); /* in pair of tfaRunStartDSP() */
762         }
763
764         /* some other registers must be set for optimal amplifier behaviour
765          * This is implemented in a file specific for the type number
766          */
767
768         if (handles_local[handle].dev_ops.tfa_init)
769                 error = (*handles_local[handle].dev_ops.tfa_init)(handle);
770
771         return error;
772 }
773
774 enum Tfa98xx_Error tfa98xx_dsp_write_tables(Tfa98xx_handle_t handle, int sample_rate)
775 {
776         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
777
778         if (!tfa98xx_handle_is_open(handle))
779                 return Tfa98xx_Error_NotOpen;
780
781         if (handles_local[handle].dev_ops.tfa_dsp_write_tables)
782                 error = (*handles_local[handle].dev_ops.tfa_dsp_write_tables)(handle, sample_rate);
783
784         return error;
785 }
786
787 /********************* new tfa2 *********************************************************************/
788 /* newly added messaging for tfa2 tfa1? */
789 enum Tfa98xx_Error tfa98xx_dsp_get_memory(Tfa98xx_handle_t handle, int memoryType,
790                 int offset, int length, unsigned char bytes[])
791 {
792         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
793         char msg[12];
794
795         msg[0] = 8;
796         msg[1] = MODULE_FRAMEWORK + 128;
797         msg[2] = FW_PAR_ID_GET_MEMORY;
798
799         msg[3] = 0;
800         msg[4] = 0;
801         msg[5] = (char)memoryType;
802
803         msg[6] = 0;
804         msg[7] = (offset>>8) & 0xff;
805         msg[8] = offset & 0xff;
806
807         msg[9] = 0;
808         msg[10] = (length>>8) & 0xff;
809         msg[11] = length & 0xff;
810
811         /* send msg */
812         error = tfa_dsp_msg(handle, sizeof(msg), (char *)msg);
813
814         if (error != Tfa98xx_Error_Ok)
815                 return error;
816
817         /* read the data from the device (length * 3 = words) */
818         error = tfa_dsp_msg_read(handle, length * 3, bytes);
819
820         return error;
821 }
822
823 enum Tfa98xx_Error tfa98xx_dsp_set_memory(Tfa98xx_handle_t handle, int memoryType,
824                 int offset, int length, int value)
825 {
826         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
827         char msg[15];
828
829         msg[0] = 8;
830         msg[1] = MODULE_FRAMEWORK + 128;
831         msg[2] = FW_PAR_ID_SET_MEMORY;
832
833         msg[3] = 0;
834         msg[4] = 0;
835         msg[5] = (char)memoryType;
836
837         msg[6] = 0;
838         msg[7] = (offset>>8) & 0xff;
839         msg[8] = offset & 0xff;
840
841         msg[9] = 0;
842         msg[10] = (length>>8) & 0xff;
843         msg[11] = length & 0xff;
844
845         msg[12] = (value>>16) & 0xff;
846         msg[13] = (value>>8) & 0xff;
847         msg[14] = value & 0xff;
848
849         /* send msg */
850         error = tfa_dsp_msg(handle, sizeof(msg), (char *)msg);
851
852         return error;
853 }
854 /****************************** calibration support **************************/
855 /*
856  * get/set the mtp with user controllable values
857  *
858  *  check if the relevant clocks are available
859  */
860 enum Tfa98xx_Error tfa98xx_get_mtp(Tfa98xx_handle_t handle, uint16_t *value)
861 {
862         int status;
863         int result;
864
865         /* not possible if PLL in powerdown */
866         if (TFA_GET_BF(handle, PWDN)) {
867                 pr_debug("PLL in powerdown\n");
868                 return Tfa98xx_Error_NoClock;
869         }
870
871         /* tfa1 needs audio PLL */
872         if (tfa98xx_dev_family(handle) == 1) {
873                 tfa98xx_dsp_system_stable(handle, &status);
874                 if (status == 0) {
875                         pr_debug("PLL not running\n");
876                         return Tfa98xx_Error_NoClock;
877                 }
878         }
879
880         result = TFA_READ_REG(handle, MTP0);
881         if (result <  0) {
882                 return -result;
883         }
884         *value = (uint16_t)result;
885
886         return Tfa98xx_Error_Ok;
887 }
888
889 /*
890  * lock or unlock KEY2
891  *  lock = 1 will lock
892  *  lock = 0 will unlock
893  *
894  *  note that on return all the hidden key will be off
895  */
896 void tfa98xx_key2(Tfa98xx_handle_t handle, int lock)
897 {
898
899         /* unhide lock registers */
900         tfa98xx_write_register16(handle,
901                                 (tfa98xx_dev_family(handle) == 1) ? 0x40 : 0x0F, 0x5A6B);
902         /* lock/unlock key2 MTPK */
903         TFA_WRITE_REG(handle, MTPKEY2, lock ? 0 : 0x5A);
904         /* unhide lock registers */
905         tfa98xx_write_register16(handle,
906                                 (tfa98xx_dev_family(handle) == 1) ? 0x40 : 0x0F, 0);
907
908
909 }
910
911 enum Tfa98xx_Error tfa98xx_set_mtp(Tfa98xx_handle_t handle,
912                                                                         uint16_t value,
913                                                                         uint16_t mask)
914 {
915         unsigned short mtp_old, mtp_new;
916         int loop, status;
917         enum Tfa98xx_Error error;
918
919         error = tfa98xx_get_mtp(handle, &mtp_old);
920
921         if (error != Tfa98xx_Error_Ok)
922                 return error;
923
924         mtp_new = (value & mask) | (mtp_old & ~mask);
925
926         if (mtp_old == mtp_new) /* no change */
927                 return Tfa98xx_Error_Ok;
928
929         /* assure that the clock is up, else we can't write MTP */
930         error = tfa98xx_dsp_system_stable(handle, &status);
931         if (error)
932                 return error;
933         if (status == 0)
934                 return Tfa98xx_Error_NoClock;
935
936         tfa98xx_key2(handle , 0); /* unlock */
937         TFA_WRITE_REG(handle, MTP0, mtp_new);   /* write to i2c shadow reg */
938         /* CIMTP=1 start copying all the data from i2c regs_mtp to mtp*/
939         TFA_SET_BF(handle, CIMTP, 1);
940         /* no check for MTPBUSY here, i2c delay assumed to be enough */
941         tfa98xx_key2(handle , 1); /* lock */
942
943         /* wait until MTP write is done
944          */
945         for (loop = 0; loop < 100; loop++) {
946                 msleep_interruptible(10);                       /* wait 10ms to avoid busload */
947                 if (TFA_GET_BF(handle, MTPB) == 0)
948                         return Tfa98xx_Error_Ok;
949         }
950
951         return Tfa98xx_Error_StateTimedOut;
952 }
953 /*
954  * clear mtpex
955  * set ACS
956  * start tfa
957  */
958 int tfa_calibrate(Tfa98xx_handle_t handle)
959 {
960         enum Tfa98xx_Error error;
961
962         /* clear mtpex */
963         error = tfa98xx_set_mtp(handle, 0, 0x2);
964         if (error)
965                 return error ;
966
967         /* set ACS/coldboot state */
968         error = tfaRunColdboot(handle, 1);
969
970         /* start tfa by playing */
971         return error;
972 }
973
974 static short twos(short x)
975 {
976         return (x < 0) ? x+512 : x;
977 }
978 void tfa98xx_set_exttemp(Tfa98xx_handle_t handle, short ext_temp)
979 {
980         if ((-256 <= ext_temp) && (ext_temp <= 255)) {
981                 /* make twos complement */
982                 pr_debug("Using ext temp %d C\n", twos(ext_temp));
983                 TFA_SET_BF(handle, TROS, 1);
984                 TFA_SET_BF(handle, EXTTS, twos(ext_temp));
985         } else {
986                 pr_debug("Clearing ext temp settings\n");
987                 TFA_SET_BF(handle, TROS, 0);
988         }
989 }
990 short tfa98xx_get_exttemp(Tfa98xx_handle_t handle)
991 {
992         short ext_temp = (short)TFA_GET_BF(handle, EXTTS);
993         return twos(ext_temp);
994 }
995
996 /************************** tfa simple bitfield interfacing ************************/
997 /* convenience functions */
998 enum Tfa98xx_Error tfa98xx_set_volume_level(Tfa98xx_handle_t handle, unsigned short vol)
999 {
1000         if (!tfa98xx_handle_is_open(handle))
1001                 return Tfa98xx_Error_NotOpen;
1002
1003         if (vol > 255)  /* restricted to 8 bits */
1004                 vol = 255;
1005
1006         /* 0x00 -> 0.0 dB
1007          * 0x01 -> -0.5 dB
1008          * ...
1009          * 0xFE -> -127dB
1010          * 0xFF -> muted
1011          */
1012
1013         /* volume value is in the top 8 bits of the register */
1014         return -TFA_SET_BF(handle, VOL, (uint16_t)vol);
1015 }
1016
1017 static enum Tfa98xx_Error
1018 tfa98xx_set_mute_tfa2(Tfa98xx_handle_t handle, enum Tfa98xx_Mute mute)
1019 {
1020         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1021
1022         switch (mute) {
1023         case Tfa98xx_Mute_Off:
1024                 TFA_SET_BF(handle, CFSMR, 0);
1025                 TFA_SET_BF(handle, CFSML, 0);
1026                 break;
1027         case Tfa98xx_Mute_Amplifier:
1028         case Tfa98xx_Mute_Digital:
1029                 TFA_SET_BF(handle, CFSMR, 1);
1030                 TFA_SET_BF(handle, CFSML, 1);
1031                 break;
1032         default:
1033                 return Tfa98xx_Error_Bad_Parameter;
1034         }
1035
1036         return error;
1037 }
1038
1039 static enum Tfa98xx_Error
1040 tfa98xx_set_mute_tfa1(Tfa98xx_handle_t handle, enum Tfa98xx_Mute mute)
1041 {
1042         enum Tfa98xx_Error error;
1043         unsigned short audioctrl_value;
1044         unsigned short sysctrl_value;
1045         int value;
1046
1047         value = TFA_READ_REG(handle, CFSM); /* audio control register */
1048         if (value < 0)
1049                 return -value;
1050         audioctrl_value = (unsigned short)value;
1051         value = TFA_READ_REG(handle, AMPE); /* system control register */
1052         if (value < 0)
1053                 return -value;
1054         sysctrl_value = (unsigned short)value;
1055
1056         switch (mute) {
1057         case Tfa98xx_Mute_Off:
1058                 /* previous state can be digital or amplifier mute,
1059                  * clear the cf_mute and set the enbl_amplifier bits
1060                  *
1061                  * To reduce PLOP at power on it is needed to switch the
1062                  * amplifier on with the DCDC in follower mode
1063                  * (enbl_boost = 0 ?).
1064                  * This workaround is also needed when toggling the
1065                  * powerdown bit!
1066                  */
1067                 TFA_SET_BF_VALUE(handle, CFSM, 0, &audioctrl_value);
1068                 TFA_SET_BF_VALUE(handle, AMPE, 1, &sysctrl_value);
1069                 TFA_SET_BF_VALUE(handle, DCA, 1, &sysctrl_value);
1070                 break;
1071         case Tfa98xx_Mute_Digital:
1072                 /* expect the amplifier to run */
1073                 /* set the cf_mute bit */
1074                 TFA_SET_BF_VALUE(handle, CFSM, 1, &audioctrl_value);
1075                 /* set the enbl_amplifier bit */
1076                 TFA_SET_BF_VALUE(handle, AMPE, 1, &sysctrl_value);
1077                 /* clear active mode */
1078                 TFA_SET_BF_VALUE(handle, DCA, 0, &sysctrl_value);
1079                 break;
1080         case Tfa98xx_Mute_Amplifier:
1081                 /* clear the cf_mute bit */
1082                 TFA_SET_BF_VALUE(handle, CFSM, 0, &audioctrl_value);
1083                 /* clear the enbl_amplifier bit and active mode */
1084                 TFA_SET_BF_VALUE(handle, AMPE, 0, &sysctrl_value);
1085                 TFA_SET_BF_VALUE(handle, DCA, 0, &sysctrl_value);
1086                 break;
1087         default:
1088                 return Tfa98xx_Error_Bad_Parameter;
1089         }
1090
1091         error = -TFA_WRITE_REG(handle, CFSM, audioctrl_value);
1092         if (error)
1093                 return error;
1094         error = -TFA_WRITE_REG(handle, AMPE, sysctrl_value);
1095         return error;
1096 }
1097
1098 enum Tfa98xx_Error
1099 tfa98xx_set_mute(Tfa98xx_handle_t handle, enum Tfa98xx_Mute mute)
1100 {
1101         if (!tfa98xx_handle_is_open(handle)) {
1102                 pr_err("device not opened\n");
1103                 return Tfa98xx_Error_NotOpen;
1104         }
1105
1106         if (tfa98xx_dev_family(handle) == 1)
1107                 return tfa98xx_set_mute_tfa1(handle, mute);
1108         else
1109                 return tfa98xx_set_mute_tfa2(handle, mute);
1110 }
1111
1112 /****************** patching **********************************************************/
1113 static enum Tfa98xx_Error
1114 tfa98xx_process_patch_file(Tfa98xx_handle_t handle, int length,
1115                  const unsigned char *bytes)
1116 {
1117         unsigned short size;
1118         int index = 0;
1119         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1120
1121         while (index < length) {
1122                 size = bytes[index] + bytes[index + 1] * 256;
1123                 index += 2;
1124                 if ((index + size) > length) {
1125                         /* outside the buffer, error in the input data */
1126                         return Tfa98xx_Error_Bad_Parameter;
1127                 }
1128
1129                 if (size > handles_local[handle].buffer_size) {
1130                         /* too big, must fit buffer */
1131                         return Tfa98xx_Error_Bad_Parameter;
1132                 }
1133
1134                 error = tfa98xx_write_raw(handle, size, &bytes[index]);
1135                 if (error != Tfa98xx_Error_Ok)
1136                         break;
1137                 index += size;
1138         }
1139         return  error;
1140 }
1141
1142
1143
1144 /* the patch contains a header with the following
1145  * IC revision register: 1 byte, 0xFF means don't care
1146  * XMEM address to check: 2 bytes, big endian, 0xFFFF means don't care
1147  * XMEM value to expect: 3 bytes, big endian
1148  */
1149 static enum Tfa98xx_Error
1150 tfa98xx_check_ic_rom_version(Tfa98xx_handle_t handle, const unsigned char patchheader[])
1151 {
1152         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1153         unsigned short checkrev, revid;
1154         unsigned char lsb_revid;
1155         unsigned short checkaddress;
1156         int checkvalue;
1157         int value = 0;
1158         int status;
1159         checkrev = patchheader[0];
1160         lsb_revid = handles_local[handle].rev & 0xff; /* only compare lower byte */
1161
1162         if ((checkrev != 0xFF) && (checkrev != lsb_revid))
1163                 return Tfa98xx_Error_Not_Supported;
1164
1165         checkaddress = (patchheader[1] << 8) + patchheader[2];
1166         checkvalue =
1167             (patchheader[3] << 16) + (patchheader[4] << 8) + patchheader[5];
1168         if (checkaddress != 0xFFFF) {
1169                 /* before reading XMEM, check if we can access the DSP */
1170                 error = tfa98xx_dsp_system_stable(handle, &status);
1171                 if (error == Tfa98xx_Error_Ok) {
1172                         if (!status) {
1173                                 /* DSP subsys not running */
1174                                 error = Tfa98xx_Error_DSP_not_running;
1175                         }
1176                 }
1177                 /* read register to check the correct ROM version */
1178                 if (error == Tfa98xx_Error_Ok) {
1179                         error =
1180                         tfa98xx_dsp_read_mem(handle, checkaddress, 1, &value);
1181                 }
1182                 if (error == Tfa98xx_Error_Ok) {
1183                         if (value != checkvalue) {
1184                                 pr_err("patch file romid type check failed [0x%04x]: expected 0x%02x, actual 0x%02x\n",
1185                                                 checkaddress, value, checkvalue);
1186                                 error = Tfa98xx_Error_Not_Supported;
1187                         }
1188                 }
1189         } else { /* == 0xffff */
1190                 /* check if the revid subtype is in there */
1191                 if (checkvalue != 0xFFFFFF && checkvalue != 0) {
1192                         revid = patchheader[5]<<8 | patchheader[0]; /* full revid */
1193                         if (revid != handles_local[handle].rev) {
1194                                 pr_err("patch file device type check failed: expected 0x%02x, actual 0x%02x\n",
1195                                                 handles_local[handle].rev, revid);
1196                                 return Tfa98xx_Error_Not_Supported;
1197                         }
1198                 }
1199         }
1200
1201         return error;
1202 }
1203
1204
1205 #define PATCH_HEADER_LENGTH 6
1206 enum Tfa98xx_Error
1207 tfa_dsp_patch(Tfa98xx_handle_t handle, int patchLength,
1208                  const unsigned char *patchBytes)
1209 {
1210         enum Tfa98xx_Error error;
1211         if (!tfa98xx_handle_is_open(handle))
1212                 return Tfa98xx_Error_NotOpen;
1213         if (patchLength < PATCH_HEADER_LENGTH)
1214                 return Tfa98xx_Error_Bad_Parameter;
1215         error = tfa98xx_check_ic_rom_version(handle, patchBytes);
1216         if (Tfa98xx_Error_Ok != error) {
1217                 return error;
1218         }
1219         error =
1220             tfa98xx_process_patch_file(handle, patchLength - PATCH_HEADER_LENGTH,
1221                              patchBytes + PATCH_HEADER_LENGTH);
1222         return error;
1223 }
1224
1225 /******************  end patching **************************/
1226
1227 TFA_INTERNAL enum Tfa98xx_Error
1228 tfa98xx_wait_result(Tfa98xx_handle_t handle, int wait_retry_count)
1229 {
1230         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1231         int cf_status; /* the contents of the CF_STATUS register */
1232         int tries = 0;
1233         do {
1234                 cf_status = TFA_GET_BF(handle, ACK);
1235                 if (cf_status < 0)
1236                         error = -cf_status;
1237                 tries++;
1238         /* i2c_cmd_ack */
1239         /* don't wait forever, DSP is pretty quick to respond (< 1ms) */
1240         } while ((error == Tfa98xx_Error_Ok) &&
1241                         ((cf_status & CF_STATUS_I2C_CMD_ACK) == 0) &&
1242                         (tries < wait_retry_count));
1243
1244         if (tries >= wait_retry_count) {
1245                 /* something wrong with communication with DSP */
1246                 error = Tfa98xx_Error_DSP_not_running;
1247         }
1248         return error;
1249 }
1250
1251 /*
1252  * *  support functions for data conversion
1253  */
1254 /**
1255  * convert memory bytes to signed 24 bit integers
1256  * input:  bytes contains "num_bytes" byte elements
1257  * output: data contains "num_bytes/3" int24 elements
1258 */
1259 void tfa98xx_convert_bytes2data(int num_bytes,
1260                                 const unsigned char bytes[],
1261                                 int data[])
1262 {
1263         int i;                  /* index for data */
1264         int k;                  /* index for bytes */
1265         int d;
1266         int num_data = num_bytes / 3;
1267         _ASSERT((num_bytes % 3) == 0);
1268         for (i = 0, k = 0; i < num_data; ++i, k += 3) {
1269                 d = (bytes[k] << 16) | (bytes[k + 1] << 8) | (bytes[k + 2]);
1270                 _ASSERT(d >= 0);
1271                 _ASSERT(d < (1 << 24)); /* max 24 bits in use */
1272                 if (bytes[k] & 0x80)    /* sign bit was set */
1273                         d = -((1 << 24) - d);
1274
1275                 data[i] = d;
1276         }
1277 }
1278
1279 /**
1280  convert signed 24 bit integers to 32bit aligned bytes
1281    input:   data contains "num_bytes/3" int24 elements
1282    output:  bytes contains "num_bytes" byte elements
1283 */
1284 void tfa98xx_convert_data2bytes(int num_data, const int data[],
1285                                 unsigned char bytes[])
1286 {
1287         int i;                  /* index for data */
1288         int k;                  /* index for bytes */
1289         int d;
1290         /* note: cannot just take the lowest 3 bytes from the 32 bit
1291          * integer, because also need to take care of clipping any
1292          * value > 2&23 */
1293         for (i = 0, k = 0; i < num_data; ++i, k += 3) {
1294                 if (data[i] >= 0)
1295                         d = MIN(data[i], (1 << 23) - 1);
1296                 else {
1297                         /* 2's complement */
1298                         d = (1 << 24) - MIN(-data[i], 1 << 23);
1299                 }
1300                 _ASSERT(d >= 0);
1301                 _ASSERT(d < (1 << 24)); /* max 24 bits in use */
1302                 bytes[k] = (d >> 16) & 0xFF;    /* MSB */
1303                 bytes[k + 1] = (d >> 8) & 0xFF;
1304                 bytes[k + 2] = (d) & 0xFF;      /* LSB */
1305         }
1306 }
1307
1308 /*
1309  *  DSP RPC message support functions
1310  *   depending on framework to be up and running
1311  *   need base i2c of memaccess (tfa1=0x70/tfa2=0x90)
1312  */
1313
1314
1315 /* write dsp messages in function tfa_dsp_msg() */
1316 /*  note the 'old' write_parameter() was more efficient because all i2c was in one burst transaction */
1317
1318 /*TODO properly handle bitfields: state should be restored! (now it will change eg dmesg field to xmem)*/
1319 enum Tfa98xx_Error tfa_dsp_msg_write(Tfa98xx_handle_t handle, int length, const char *buffer)
1320 {
1321         int offset = 0;
1322         int chunk_size = ROUND_DOWN(handles_local[handle].buffer_size, 3);  /* XMEM word size */
1323         int remaining_bytes = length;
1324         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1325         uint16_t cfctl;
1326         int value;
1327
1328         value = TFA_READ_REG(handle, DMEM);
1329         if (value < 0) {
1330                 error = -value;
1331                 return error;
1332         }
1333         cfctl = (uint16_t)value;
1334         /* assume no I2C errors from here */
1335
1336         TFA_SET_BF_VALUE(handle, DMEM, (uint16_t)Tfa98xx_DMEM_XMEM, &cfctl); /* set cf ctl to DMEM  */
1337         TFA_SET_BF_VALUE(handle, AIF, 0, &cfctl); /* set to autoincrement */
1338         TFA_WRITE_REG(handle, DMEM, cfctl);
1339
1340         /* xmem[1] is start of message
1341          *  direct write to register to save cycles avoiding read-modify-write
1342          */
1343         TFA_WRITE_REG(handle, MADD, 1);
1344
1345         /* due to autoincrement in cf_ctrl, next write will happen at
1346          * the next address */
1347         while ((error == Tfa98xx_Error_Ok) && (remaining_bytes > 0)) {
1348                 if (remaining_bytes < chunk_size)
1349                         chunk_size = remaining_bytes;
1350                 /* else chunk_size remains at initialize value above */
1351                 error = tfa98xx_write_data(handle, FAM_TFA98XX_CF_MEM,
1352                                         chunk_size, (const unsigned char *)buffer + offset);
1353                 remaining_bytes -= chunk_size;
1354                 offset += chunk_size;
1355         }
1356
1357         /* notify the DSP */
1358         if (error == Tfa98xx_Error_Ok) {
1359                 /* cf_int=0, cf_aif=0, cf_dmem=XMEM=01, cf_rst_dsp=0 */
1360                 /* set the cf_req1 and cf_int bit */
1361                 TFA_SET_BF_VALUE(handle, REQCMD, 0x01, &cfctl); /* bit 0 */
1362                 TFA_SET_BF_VALUE(handle, CFINT, 1, &cfctl);
1363                 error = -TFA_WRITE_REG(handle, CFINT, cfctl);
1364         }
1365
1366         return error;
1367 }
1368
1369 enum Tfa98xx_Error tfa_dsp_msg_write_id(Tfa98xx_handle_t handle, int length, const char *buffer, uint8_t cmdid[3])
1370 {
1371         int offset = 0;
1372         int chunk_size = ROUND_DOWN(handles_local[handle].buffer_size, 3);  /* XMEM word size */
1373         int remaining_bytes = length;
1374         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1375         uint16_t cfctl;
1376         int value;
1377
1378         value = TFA_READ_REG(handle, DMEM);
1379         if (value < 0) {
1380                 error = -value;
1381                 return error;
1382         }
1383         cfctl = (uint16_t)value;
1384         /* assume no I2C errors from here */
1385
1386         TFA_SET_BF_VALUE(handle, DMEM, (uint16_t)Tfa98xx_DMEM_XMEM, &cfctl); /* set cf ctl to DMEM  */
1387         TFA_SET_BF_VALUE(handle, AIF, 0, &cfctl); /* set to autoincrement */
1388         TFA_WRITE_REG(handle, DMEM, cfctl);
1389
1390         /* xmem[1] is start of message
1391          *  direct write to register to save cycles avoiding read-modify-write
1392          */
1393         TFA_WRITE_REG(handle, MADD, 1);
1394
1395         /* write cmd-id */
1396         error = tfa98xx_write_data(handle, FAM_TFA98XX_CF_MEM, 3, (const unsigned char *)cmdid);
1397
1398         /* due to autoincrement in cf_ctrl, next write will happen at
1399          * the next address */
1400         while ((error == Tfa98xx_Error_Ok) && (remaining_bytes > 0)) {
1401                 if (remaining_bytes < chunk_size)
1402                         chunk_size = remaining_bytes;
1403                 /* else chunk_size remains at initialize value above */
1404                 error = tfa98xx_write_data(handle, FAM_TFA98XX_CF_MEM,
1405                                       chunk_size, (const unsigned char *)buffer + offset);
1406                 remaining_bytes -= chunk_size;
1407                 offset += chunk_size;
1408         }
1409
1410         /* notify the DSP */
1411         if (error == Tfa98xx_Error_Ok) {
1412                 /* cf_int=0, cf_aif=0, cf_dmem=XMEM=01, cf_rst_dsp=0 */
1413                 /* set the cf_req1 and cf_int bit */
1414                 TFA_SET_BF_VALUE(handle, REQCMD, 0x01, &cfctl); /* bit 0 */
1415                 TFA_SET_BF_VALUE(handle, CFINT, 1, &cfctl);
1416                 error = -TFA_WRITE_REG(handle, CFINT, cfctl);
1417         }
1418
1419         return error;
1420 }
1421
1422 /*
1423 * status function used by tfa_dsp_msg() to retrieve command/msg status:
1424 * return a <0 status of the DSP did not ACK.
1425 */
1426 enum Tfa98xx_Error tfa_dsp_msg_status(Tfa98xx_handle_t handle, int *pRpcStatus)
1427 {
1428         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1429
1430         error = tfa98xx_wait_result(handle, 2); /* 2 is only one try */
1431         if (error == Tfa98xx_Error_DSP_not_running) {
1432                 *pRpcStatus = -1;
1433                 return Tfa98xx_Error_Ok;
1434         } else if (error != Tfa98xx_Error_Ok)
1435                 return error;
1436
1437         error = tfa98xx_check_rpc_status(handle, pRpcStatus);
1438
1439         return error;
1440 }
1441
1442 const char *tfa98xx_get_i2c_status_id_string(int status)
1443 {
1444         const char *p_id_str;
1445
1446         switch (status) {
1447         case Tfa98xx_DSP_Not_Running:
1448                 p_id_str = "No response from DSP";
1449                 break;
1450         case Tfa98xx_I2C_Req_Done:
1451                 p_id_str = "Ok";
1452                 break;
1453         case Tfa98xx_I2C_Req_Busy:
1454                 p_id_str = "Request is being processed";
1455                 break;
1456         case Tfa98xx_I2C_Req_Invalid_M_ID:
1457                 p_id_str = "Provided M-ID does not fit in valid rang [0..2]";
1458                 break;
1459         case Tfa98xx_I2C_Req_Invalid_P_ID:
1460                 p_id_str = "Provided P-ID is not valid in the given M-ID context";
1461                 break;
1462         case Tfa98xx_I2C_Req_Invalid_CC:
1463                 p_id_str = "Invalid channel configuration bits (SC|DS|DP|DC) combination";
1464                 break;
1465         case Tfa98xx_I2C_Req_Invalid_Seq:
1466                 p_id_str = "Invalid sequence of commands, in case the DSP expects some commands in a specific order";
1467                 break;
1468         case Tfa98xx_I2C_Req_Invalid_Param:
1469                 p_id_str = "Generic error";
1470                 break;
1471         case Tfa98xx_I2C_Req_Buffer_Overflow:
1472                 p_id_str = "I2C buffer has overflowed: host has sent too many parameters, memory integrity is not guaranteed";
1473                 break;
1474         default:
1475                 p_id_str = "Unspecified error";
1476         }
1477
1478         return p_id_str;
1479 }
1480
1481 enum Tfa98xx_Error tfa_dsp_msg_read(Tfa98xx_handle_t handle, int length, unsigned char *bytes)
1482 {
1483         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1484         int burst_size; /* number of words per burst size */
1485         int bytes_per_word = 3;
1486         int num_bytes;
1487         int offset = 0;
1488         unsigned short start_offset = 2; /* msg starts @xmem[2] ,[1]=cmd */
1489
1490         if (length > TFA2_MAX_PARAM_SIZE)
1491                 return Tfa98xx_Error_Bad_Parameter;
1492
1493         TFA_SET_BF(handle, DMEM, (uint16_t)Tfa98xx_DMEM_XMEM);
1494         error = -TFA_WRITE_REG(handle, MADD, start_offset);
1495         if (error != Tfa98xx_Error_Ok)
1496                 return error;
1497
1498         num_bytes = length; /* input param */
1499         while (num_bytes > 0) {
1500                 burst_size = ROUND_DOWN(handles_local[handle].buffer_size, bytes_per_word);
1501                 if (num_bytes < burst_size)
1502                         burst_size = num_bytes;
1503                 error = tfa98xx_read_data(handle, FAM_TFA98XX_CF_MEM, burst_size, bytes + offset);
1504                 if (error != Tfa98xx_Error_Ok)
1505                         return error;
1506
1507                 num_bytes -= burst_size;
1508                 offset += burst_size;
1509         }
1510
1511         return Tfa98xx_Error_Ok;
1512 }
1513
1514 /*
1515  *  write/read raw msg functions :
1516  *  the buffer is provided in little endian format, each word occupying 3 bytes, length is in bytes.
1517  *  The functions will return immediately and do not not wait for DSP reponse.
1518  */
1519 #define MAX_WORDS (300)
1520 enum Tfa98xx_Error tfa_dsp_msg(Tfa98xx_handle_t handle, int length, const char *buf)
1521 {
1522         enum Tfa98xx_Error error;
1523         int tries, rpc_status = Tfa98xx_I2C_Req_Done;
1524
1525         /* write the message and notify the DSP */
1526         error = tfa_dsp_msg_write(handle, length, buf);
1527         if (error != Tfa98xx_Error_Ok)
1528                 return error;
1529
1530         /* get the result from the DSP (polling) */
1531         for (tries = TFA98XX_WAITRESULT_NTRIES; tries > 0; tries--) {
1532                 error = tfa_dsp_msg_status(handle, &rpc_status);
1533                 if (error == Tfa98xx_Error_Ok && rpc_status == Tfa98xx_I2C_Req_Done)
1534                         break;
1535                 /* If the rpc status is a specific error we want to know it.
1536                  * If it is busy or not running it should retry
1537                  */
1538                 if (rpc_status != Tfa98xx_I2C_Req_Busy && rpc_status != Tfa98xx_DSP_Not_Running)
1539                         break;
1540         }
1541
1542         /* if (tfa98xx_runtime_verbose)
1543                 PRINT("Number of tries: %d \n", TFA98XX_WAITRESULT_NTRIES-tries); */
1544
1545         if (rpc_status != Tfa98xx_I2C_Req_Done) {
1546                 /* DSP RPC call returned an error */
1547                 error = (enum Tfa98xx_Error) (rpc_status + Tfa98xx_Error_RpcBase);
1548                 pr_debug("DSP msg status: %d (%s)\n",
1549                                         rpc_status, tfa98xx_get_i2c_status_id_string(rpc_status));
1550         }
1551
1552         return error;
1553 }
1554
1555 /**
1556  *  write/read raw msg functions:
1557  *  the buffer is provided in little endian format, each word occupying 3 bytes, length is in bytes.
1558  *  The functions will return immediately and do not not wait for DSP reponse.
1559  *  An ID is added to modify the command-ID
1560  */
1561 enum Tfa98xx_Error tfa_dsp_msg_id(Tfa98xx_handle_t handle,
1562                                                                 int length,
1563                                                                 const char *buf,
1564                                                                 uint8_t cmdid[3])
1565 {
1566         enum Tfa98xx_Error error;
1567         int tries, rpc_status = Tfa98xx_I2C_Req_Done;
1568
1569         /* write the message and notify the DSP */
1570         error = tfa_dsp_msg_write_id(handle, length, buf, cmdid);
1571         if (error != Tfa98xx_Error_Ok)
1572                 return error;
1573
1574         /* get the result from the DSP (polling) */
1575         for (tries = TFA98XX_WAITRESULT_NTRIES; tries > 0; tries--) {
1576                 error = tfa_dsp_msg_status(handle, &rpc_status);
1577                 if (error == Tfa98xx_Error_Ok && rpc_status == Tfa98xx_I2C_Req_Done)
1578                         break;
1579         }
1580
1581         /* if (tfa98xx_runtime_verbose)
1582                 PRINT("Number of tries: %d \n", TFA98XX_WAITRESULT_NTRIES-tries);
1583         */
1584
1585         if (rpc_status != Tfa98xx_I2C_Req_Done) {
1586                 /* DSP RPC call returned an error */
1587                 error = (enum Tfa98xx_Error) (rpc_status + Tfa98xx_Error_RpcBase);
1588                 pr_debug("DSP msg status: %d (%s)\n",
1589                                         rpc_status, tfa98xx_get_i2c_status_id_string(rpc_status));
1590         }
1591
1592         return error;
1593 }
1594
1595 /* read the return code for the RPC call */
1596 TFA_INTERNAL enum Tfa98xx_Error
1597 tfa98xx_check_rpc_status(Tfa98xx_handle_t handle, int *pRpcStatus)
1598 {
1599         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1600         /* the value to sent to the * CF_CONTROLS register: cf_req=00000000,
1601          * cf_int=0, cf_aif=0, cf_dmem=XMEM=01, cf_rst_dsp=0 */
1602         unsigned short cf_ctrl = 0x0002;
1603         /* memory address to be accessed (0: Status, 1: ID, 2: parameters) */
1604         unsigned short cf_mad = 0x0000;
1605
1606         if (!tfa98xx_handle_is_open(handle))
1607                 return Tfa98xx_Error_NotOpen;
1608         if (pRpcStatus == 0)
1609                 return Tfa98xx_Error_Bad_Parameter;
1610
1611         /* 1) write DMEM=XMEM to the DSP XMEM */
1612         {
1613                 /* minimize the number of I2C transactions by making use of the autoincrement in I2C */
1614                 unsigned char buffer[4];
1615                 /* first the data for CF_CONTROLS */
1616                 buffer[0] = (unsigned char)((cf_ctrl >> 8) & 0xFF);
1617                 buffer[1] = (unsigned char)(cf_ctrl & 0xFF);
1618                 /* write the contents of CF_MAD which is the subaddress following CF_CONTROLS */
1619                 buffer[2] = (unsigned char)((cf_mad >> 8) & 0xFF);
1620                 buffer[3] = (unsigned char)(cf_mad & 0xFF);
1621                 error = tfa98xx_write_data(handle, FAM_TFA98XX_CF_CONTROLS, sizeof(buffer), buffer);
1622         }
1623         if (error == Tfa98xx_Error_Ok) {
1624                 /* read 1 word (24 bit) from XMEM */
1625                 error = tfa98xx_dsp_read_mem(handle, 0, 1, pRpcStatus);
1626         }
1627
1628         return error;
1629 }
1630
1631 /***************************** xmem only **********************************/
1632 enum Tfa98xx_Error
1633 tfa98xx_dsp_read_mem(Tfa98xx_handle_t handle,
1634                 unsigned int start_offset, int num_words, int *pValues)
1635 {
1636         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1637         unsigned char *bytes;
1638         int burst_size;         /* number of words per burst size */
1639         const int bytes_per_word = 3;
1640         int dmem;
1641         int num_bytes;
1642         int *p;
1643
1644         bytes = (unsigned char *)kmalloc(num_words*bytes_per_word, GFP_KERNEL);
1645         if (bytes == NULL)
1646                 return Tfa98xx_Error_Fail;
1647
1648         /* If no offset is given, assume XMEM! */
1649         if (((start_offset>>16) & 0xf) > 0)
1650                 dmem = (start_offset>>16) & 0xf;
1651         else
1652                 dmem = Tfa98xx_DMEM_XMEM;
1653
1654         /* Remove offset from adress */
1655         start_offset = start_offset & 0xffff;
1656         num_bytes = num_words * bytes_per_word;
1657         p = pValues;
1658
1659         TFA_SET_BF(handle, DMEM, (uint16_t)dmem);
1660         error = -TFA_WRITE_REG(handle, MADD, (unsigned short)start_offset);
1661         if (error != Tfa98xx_Error_Ok)
1662                 goto tfa98xx_dsp_read_mem_exit;
1663
1664         for (; num_bytes > 0;) {
1665                 burst_size = ROUND_DOWN(handles_local[handle].buffer_size, bytes_per_word);
1666                 if (num_bytes < burst_size)
1667                         burst_size = num_bytes;
1668
1669                 _ASSERT(burst_size <= sizeof(bytes));
1670                 error = tfa98xx_read_data(handle, FAM_TFA98XX_CF_MEM, burst_size, bytes);
1671                 if (error != Tfa98xx_Error_Ok)
1672                         goto tfa98xx_dsp_read_mem_exit;
1673
1674                 tfa98xx_convert_bytes2data(burst_size, bytes, p);
1675
1676                 num_bytes -= burst_size;
1677                 p += burst_size / bytes_per_word;
1678         }
1679
1680 tfa98xx_dsp_read_mem_exit:
1681         kfree(bytes);
1682         return error;
1683 }
1684
1685 enum Tfa98xx_Error
1686 tfa98xx_dsp_write_mem_word(Tfa98xx_handle_t handle, unsigned short address, int value, int memtype)
1687 {
1688         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1689         unsigned char bytes[3];
1690
1691         TFA_SET_BF(handle, DMEM, (uint16_t)memtype);
1692
1693         error = -TFA_WRITE_REG(handle, MADD, address);
1694         if (error != Tfa98xx_Error_Ok)
1695                 return error;
1696
1697         tfa98xx_convert_data2bytes(1, &value, bytes);
1698         error = tfa98xx_write_data(handle, FAM_TFA98XX_CF_MEM, 3, bytes);
1699
1700         return error;
1701 }
1702
1703 enum Tfa98xx_Error tfa_cont_write_filterbank(int device, nxpTfaFilter_t *filter)
1704 {
1705         unsigned char biquad_index;
1706         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1707
1708         for (biquad_index = 0; biquad_index < 10; biquad_index++) {
1709                 if (filter[biquad_index].enabled) {
1710                         error = tfa_dsp_cmd_id_write(device, MODULE_BIQUADFILTERBANK,
1711                                         biquad_index+1,
1712                                         sizeof(filter[biquad_index].biquad.bytes),
1713                                                 filter[biquad_index].biquad.bytes);
1714                 } else {
1715                         error = Tfa98xx_DspBiquad_Disable(device, biquad_index+1);
1716                 }
1717                 if (error)
1718                         return error;
1719
1720         }
1721         return error;
1722 }
1723
1724 enum Tfa98xx_Error
1725 Tfa98xx_DspBiquad_Disable(Tfa98xx_handle_t handle, int biquad_index)
1726 {
1727         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1728         int coeff_buffer[BIQUAD_COEFF_SIZE];
1729         unsigned char bytes[3 + BIQUAD_COEFF_SIZE * 3];
1730
1731         if (biquad_index > TFA98XX_BIQUAD_NUM)
1732                 return Tfa98xx_Error_Bad_Parameter;
1733         if (biquad_index < 1)
1734                 return Tfa98xx_Error_Bad_Parameter;
1735
1736         /* make opcode */
1737
1738         /* set in correct order and format for the DSP */
1739         coeff_buffer[0] = (int) -8388608;       /* -1.0f */
1740         coeff_buffer[1] = 0;
1741         coeff_buffer[2] = 0;
1742         coeff_buffer[3] = 0;
1743         coeff_buffer[4] = 0;
1744         coeff_buffer[5] = 0;
1745         /* convert to packed 24 bits data */
1746         tfa98xx_convert_data2bytes(BIQUAD_COEFF_SIZE, coeff_buffer, &bytes[3]);
1747
1748         bytes[0] = 0;
1749         bytes[1] = MODULE_BIQUADFILTERBANK+128;
1750         bytes[2] = (unsigned char)biquad_index;
1751
1752         error = tfa_dsp_msg(handle, 3 + BIQUAD_COEFF_SIZE * 3, (char *)bytes);
1753
1754         return error;
1755 }
1756
1757 /* wrapper for dsp_msg that adds opcode */
1758 enum Tfa98xx_Error tfa_dsp_cmd_id_write(Tfa98xx_handle_t handle,
1759                                         unsigned char module_id,
1760                                         unsigned char param_id, int num_bytes,
1761                                         const unsigned char data[])
1762 {
1763         enum Tfa98xx_Error error;
1764         unsigned char *buffer;
1765
1766         if (!tfa98xx_handle_is_open(handle))
1767                 return Tfa98xx_Error_NotOpen;
1768
1769         buffer = kmalloc(3 + num_bytes, GFP_KERNEL);
1770         if (buffer == NULL)
1771                 return Tfa98xx_Error_Fail;
1772
1773         buffer[0] = handles_local[handle].spkr_select;
1774         buffer[1] = module_id + 128;
1775         buffer[2] = param_id;
1776
1777         memcpy(&buffer[3], data, num_bytes);
1778
1779         error = tfa_dsp_msg(handle, 3 + num_bytes, (char *)buffer);
1780
1781         kfree(buffer);
1782
1783         return error;
1784 }
1785
1786 /* wrapper for dsp_msg that adds opcode */
1787 /* this is as the former tfa98xx_dsp_get_param() */
1788 enum Tfa98xx_Error tfa_dsp_cmd_id_write_read(Tfa98xx_handle_t handle,
1789                                                 unsigned char module_id,
1790                                                 unsigned char param_id, int num_bytes,
1791                                                 unsigned char data[])
1792 {
1793         enum Tfa98xx_Error error;
1794         unsigned char buffer[3];
1795
1796         if (!tfa98xx_handle_is_open(handle))
1797                 return Tfa98xx_Error_NotOpen;
1798
1799         buffer[0] = handles_local[handle].spkr_select;
1800         buffer[1] = module_id + 128;
1801         buffer[2] = param_id;
1802
1803         error = tfa_dsp_msg(handle, sizeof(unsigned char[3]), (char *)buffer);
1804         if (error != Tfa98xx_Error_Ok)
1805                 return error;
1806     /* read the data from the dsp */
1807         error = tfa_dsp_msg_read(handle, num_bytes, data);
1808
1809         return error;
1810 }
1811
1812 /* wrapper for dsp_msg that adds opcode and 3 bytes required for coefs */
1813 enum Tfa98xx_Error tfa_dsp_cmd_id_coefs(Tfa98xx_handle_t handle,
1814                         unsigned char module_id,
1815                         unsigned char param_id, int num_bytes,
1816                         unsigned char data[])
1817 {
1818         enum Tfa98xx_Error error;
1819         unsigned char buffer[6];
1820
1821         if (!tfa98xx_handle_is_open(handle))
1822                 return Tfa98xx_Error_NotOpen;
1823
1824         buffer[0] = handles_local[handle].spkr_select;
1825         buffer[1] = module_id + 128;
1826         buffer[2] = param_id;
1827         buffer[3] = 0;
1828         buffer[4] = 0;
1829         buffer[5] = 0;
1830
1831         error = tfa_dsp_msg(handle, sizeof(unsigned char[6]), (char *)buffer);
1832         if (error != Tfa98xx_Error_Ok)
1833                 return error;
1834
1835         /* read the data from the dsp */
1836         error = tfa_dsp_msg_read(handle, num_bytes, data);
1837
1838         return error;
1839 }
1840
1841 /* wrapper for dsp_msg that adds opcode and 3 bytes required for MBDrcDynamics */
1842 enum Tfa98xx_Error tfa_dsp_cmd_id_MBDrc_dynamics(Tfa98xx_handle_t handle,
1843                         unsigned char module_id,
1844                         unsigned char param_id, int index_subband,
1845                         int num_bytes, unsigned char data[])
1846 {
1847         enum Tfa98xx_Error error;
1848         unsigned char buffer[6];
1849
1850         if (!tfa98xx_handle_is_open(handle))
1851                 return Tfa98xx_Error_NotOpen;
1852
1853         buffer[0] = handles_local[handle].spkr_select;
1854         buffer[1] = module_id + 128;
1855         buffer[2] = param_id;
1856         buffer[3] = 0;
1857         buffer[4] = 0;
1858         buffer[5] = (unsigned char)index_subband;
1859
1860         error = tfa_dsp_msg(handle, sizeof(unsigned char[6]), (char *)buffer);
1861         if (error != Tfa98xx_Error_Ok)
1862                 return error;
1863
1864         /* read the data from the dsp */
1865         error = tfa_dsp_msg_read(handle, num_bytes, data);
1866
1867         return error;
1868 }
1869
1870 enum Tfa98xx_Error
1871 tfa98xx_dsp_write_preset(Tfa98xx_handle_t handle, int length,
1872                         const unsigned char *p_preset_bytes)
1873 {
1874         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1875         if (p_preset_bytes != 0) {
1876                 /* by design: keep the data opaque and no
1877                  * interpreting/calculation */
1878                 error = tfa_dsp_cmd_id_write(handle, MODULE_SPEAKERBOOST,
1879                                         SB_PARAM_SET_PRESET, length,
1880                                         p_preset_bytes);
1881         } else {
1882                 error = Tfa98xx_Error_Bad_Parameter;
1883         }
1884         return error;
1885 }
1886
1887 /*
1888  * get features from MTP
1889  */
1890 enum Tfa98xx_Error
1891 tfa98xx_dsp_get_hw_feature_bits(Tfa98xx_handle_t handle, int *features)
1892 {
1893         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1894         uint32_t value;
1895         uint16_t mtpbf;
1896
1897         /* return the cache data if it's valid */
1898         if (handles_local[handle].hw_feature_bits != -1) {
1899                 *features = handles_local[handle].hw_feature_bits;
1900         } else {
1901                 /* for tfa1 check if we have clock */
1902                 if (tfa98xx_dev_family(handle) == 1) {
1903                         int status;
1904                         tfa98xx_dsp_system_stable(handle, &status);
1905                         if (!status) {
1906                                 get_hw_features_from_cnt(handle, features);
1907                                 /* skip reading MTP: */
1908                                 return (*features == -1) ? Tfa98xx_Error_Fail : Tfa98xx_Error_Ok;
1909                         }
1910                         mtpbf = 0x850f;  /* MTP5 for tfa1,16 bits */
1911                 } else
1912                         mtpbf = 0xf907;  /* MTP9 for tfa2, 8 bits */
1913
1914                 value = tfa_read_reg(handle, mtpbf) & 0xffff;
1915                 *features = handles_local[handle].hw_feature_bits = value;
1916         }
1917
1918         return error;
1919 }
1920
1921 enum Tfa98xx_Error
1922 tfa98xx_dsp_get_sw_feature_bits(Tfa98xx_handle_t handle, int features[2])
1923 {
1924         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1925         unsigned char bytes[3 * 2];
1926
1927         /* return the cache data if it's valid */
1928         if (handles_local[handle].sw_feature_bits[0] != -1) {
1929                 features[0] = handles_local[handle].sw_feature_bits[0];
1930                 features[1] = handles_local[handle].sw_feature_bits[1];
1931         } else {
1932                 /* for tfa1 check if we have clock */
1933                 if (tfa98xx_dev_family(handle) == 1) {
1934                         int status;
1935
1936                         tfa98xx_dsp_system_stable(handle, &status);
1937                         if (!status) {
1938                                 get_sw_features_from_cnt(handle, features);
1939                                 /* skip reading MTP: */
1940                                 return (features[0] == -1) ? Tfa98xx_Error_Fail : Tfa98xx_Error_Ok;
1941                         }
1942                 }
1943                 error = tfa_dsp_cmd_id_write_read(handle, MODULE_FRAMEWORK,
1944                                 FW_PAR_ID_GET_FEATURE_INFO, sizeof(bytes), bytes);
1945
1946                 if (error != Tfa98xx_Error_Ok) {
1947                         /* old ROM code may respond with Tfa98xx_Error_RpcParamId */
1948                         return error;
1949                 }
1950                 tfa98xx_convert_bytes2data(sizeof(bytes), bytes, features);
1951         }
1952         return error;
1953 }
1954
1955 enum Tfa98xx_Error tfa98xx_dsp_get_state_info(Tfa98xx_handle_t handle, unsigned char bytes[], unsigned int *statesize)
1956 {
1957         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
1958         int bSupportFramework = 0;
1959         unsigned int stateSize = 9;
1960
1961         err = tfa98xx_dsp_support_framework(handle, &bSupportFramework);
1962         if (err == Tfa98xx_Error_Ok) {
1963                 if (bSupportFramework) {
1964                         err = tfa_dsp_cmd_id_write_read(handle, MODULE_FRAMEWORK,
1965                                 FW_PARAM_GET_STATE, 3 * stateSize, bytes);
1966                 } else {
1967                         /* old ROM code, ask SpeakerBoost and only do first portion */
1968                         stateSize = 8;
1969                         err = tfa_dsp_cmd_id_write_read(handle, MODULE_SPEAKERBOOST,
1970                                 SB_PARAM_GET_STATE, 3 * stateSize, bytes);
1971                 }
1972         }
1973
1974         *statesize = stateSize;
1975
1976         return err;
1977 }
1978
1979 enum Tfa98xx_Error tfa98xx_dsp_support_drc(Tfa98xx_handle_t handle, int *pbSupportDrc)
1980 {
1981         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
1982
1983         *pbSupportDrc = 0;
1984
1985         if (!tfa98xx_handle_is_open(handle))
1986                 return Tfa98xx_Error_NotOpen;
1987         if (handles_local[handle].supportDrc != supportNotSet) {
1988                 *pbSupportDrc = (handles_local[handle].supportDrc == supportYes);
1989         } else {
1990                 int featureBits[2];
1991
1992                 error = tfa98xx_dsp_get_sw_feature_bits(handle, featureBits);
1993                 if (error == Tfa98xx_Error_Ok) {
1994                         /* easy case: new API available */
1995                         /* bit=0 means DRC enabled */
1996                         *pbSupportDrc = (featureBits[0] & FEATURE1_DRC) == 0;
1997                 } else if (error == Tfa98xx_Error_RpcParamId) {
1998                         /* older ROM code, doesn't support it */
1999                         *pbSupportDrc = 0;
2000                         error = Tfa98xx_Error_Ok;
2001                 }
2002                 /* else some other error, return transparently */
2003                 /* pbSupportDrc only changed when error == Tfa98xx_Error_Ok */
2004
2005                 if (error == Tfa98xx_Error_Ok) {
2006                         handles_local[handle].supportDrc = *pbSupportDrc ? supportYes : supportNo;
2007                 }
2008         }
2009         return error;
2010 }
2011
2012 enum Tfa98xx_Error
2013 tfa98xx_dsp_support_framework(Tfa98xx_handle_t handle, int *pbSupportFramework)
2014 {
2015         int featureBits[2] = {0, 0};
2016         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
2017
2018         _ASSERT(pbSupportFramework != 0);
2019
2020         if (!tfa98xx_handle_is_open(handle))
2021                 return Tfa98xx_Error_NotOpen;
2022
2023         if (handles_local[handle].supportFramework != supportNotSet) {
2024                 if (handles_local[handle].supportFramework == supportNo)
2025                         *pbSupportFramework = 0;
2026                 else
2027                         *pbSupportFramework = 1;
2028         } else {
2029                 error = tfa98xx_dsp_get_sw_feature_bits(handle, featureBits);
2030                 if (error == Tfa98xx_Error_Ok) {
2031                         *pbSupportFramework = 1;
2032                         handles_local[handle].supportFramework = supportYes;
2033                 } else {
2034                         *pbSupportFramework = 0;
2035                         handles_local[handle].supportFramework = supportNo;
2036                         error = Tfa98xx_Error_Ok;
2037                 }
2038         }
2039
2040         /* *pbSupportFramework only changed when error == Tfa98xx_Error_Ok */
2041         return error;
2042 }
2043
2044 enum Tfa98xx_Error
2045 tfa98xx_dsp_write_speaker_parameters(Tfa98xx_handle_t handle,
2046                                                                         int length,
2047                                                                         const unsigned char *p_speaker_bytes)
2048 {
2049         enum Tfa98xx_Error error;
2050         if (p_speaker_bytes != 0) {
2051                 /* by design: keep the data opaque and no
2052                  * interpreting/calculation */
2053                 /* Use long WaitResult retry count */
2054                 error = tfa_dsp_cmd_id_write(
2055                                         handle,
2056                                         MODULE_SPEAKERBOOST,
2057                                         SB_PARAM_SET_LSMODEL, length,
2058                                         p_speaker_bytes);
2059         } else {
2060                 error = Tfa98xx_Error_Bad_Parameter;
2061         }
2062
2063 #if (defined(TFA9887B) || defined(TFA98XX_FULL))
2064         {
2065                 int bSupportDrc;
2066
2067                 if (error != Tfa98xx_Error_Ok)
2068                         return error;
2069
2070                 error = tfa98xx_dsp_support_drc(handle, &bSupportDrc);
2071                 if (error != Tfa98xx_Error_Ok)
2072                         return error;
2073
2074                 if (bSupportDrc) {
2075                 /* Need to set AgcGainInsert back to PRE,
2076                 * as the SetConfig forces it to POST */
2077                         uint8_t bytes[3] = {0, 0, 0};
2078
2079                         error = tfa_dsp_cmd_id_write(handle,
2080                                                         MODULE_SPEAKERBOOST,
2081                                                         SB_PARAM_SET_AGCINS,
2082                                                         sizeof(bytes),
2083                                                         bytes);
2084                 }
2085         }
2086 #endif
2087
2088         return error;
2089 }
2090
2091 enum Tfa98xx_Error
2092 tfa98xx_dsp_write_config(Tfa98xx_handle_t handle, int length,
2093                                                         const unsigned char *p_config_bytes)
2094 {
2095         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
2096
2097         error = tfa_dsp_cmd_id_write(handle,
2098                                                                 MODULE_SPEAKERBOOST,
2099                                                                 SB_PARAM_SET_CONFIG, length,
2100                                                                 p_config_bytes);
2101
2102 #if (defined(TFA9887B) || defined(TFA98XX_FULL))
2103         {
2104                 int bSupportDrc;
2105
2106                 if (error != Tfa98xx_Error_Ok)
2107                         return error;
2108
2109                 error = tfa98xx_dsp_support_drc(handle, &bSupportDrc);
2110                 if (error != Tfa98xx_Error_Ok)
2111                         return error;
2112
2113                 if (bSupportDrc) {
2114                         /* Need to set AgcGainInsert back to PRE,
2115                         * as the SetConfig forces it to POST */
2116                         uint8_t bytes[3] = {0, 0, 0};
2117
2118                         error = tfa_dsp_cmd_id_write(handle,
2119                                                         MODULE_SPEAKERBOOST,
2120                                                         SB_PARAM_SET_AGCINS,
2121                                                         sizeof(bytes),
2122                                                         bytes);
2123                 }
2124         }
2125 #endif
2126
2127         return error;
2128 }
2129
2130 #if (defined(TFA9887B) || defined(TFA98XX_FULL))
2131 /* load all the parameters for the DRC settings from a file */
2132 enum Tfa98xx_Error tfa98xx_dsp_write_drc(Tfa98xx_handle_t handle,
2133                                         int length,
2134                                         const unsigned char *p_drc_bytes)
2135 {
2136         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
2137         if (p_drc_bytes != 0) {
2138         error = tfa_dsp_cmd_id_write(handle,
2139                                         MODULE_SPEAKERBOOST,
2140                                         SB_PARAM_SET_DRC, length,
2141                                         p_drc_bytes);
2142
2143         } else {
2144                 error = Tfa98xx_Error_Bad_Parameter;
2145         }
2146         return error;
2147 }
2148 #endif
2149
2150 enum Tfa98xx_Error tfa98xx_powerdown(Tfa98xx_handle_t handle, int powerdown)
2151 {
2152         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
2153         if (!tfa98xx_handle_is_open(handle))
2154                 return Tfa98xx_Error_NotOpen;
2155
2156         TFA_SET_BF(handle, PWDN, (uint16_t)powerdown);
2157         return error;
2158 }
2159
2160 enum Tfa98xx_Error
2161 tfa98xx_select_mode(Tfa98xx_handle_t handle, enum Tfa98xx_Mode mode)
2162 {
2163         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
2164
2165         if (!tfa98xx_handle_is_open(handle))
2166                 return Tfa98xx_Error_NotOpen;
2167
2168         if (error == Tfa98xx_Error_Ok) {
2169                 switch (mode) {
2170
2171                 default:
2172                         error = Tfa98xx_Error_Bad_Parameter;
2173                 }
2174         }
2175
2176         return error;
2177 }
2178
2179 int tfa_set_bf(Tfa98xx_handle_t dev_idx, const uint16_t bf, const uint16_t value)
2180 {
2181         enum Tfa98xx_Error err;
2182         uint16_t regvalue, msk, oldvalue;
2183
2184         /*
2185          * bitfield enum:
2186          * - 0..3  : len
2187          * - 4..7  : pos
2188          * - 8..15 : address
2189          */
2190         uint8_t len = bf & 0x0f;
2191         uint8_t pos = (bf >> 4) & 0x0f;
2192         uint8_t address = (bf >> 8) & 0xff;
2193
2194         err = tfa98xx_read_register16(dev_idx, address, &regvalue);
2195         if (err) {
2196                 pr_err("Error getting bf :%d \n", -err);
2197                 return -err;
2198         }
2199
2200         oldvalue = regvalue;
2201         msk = ((1<<(len+1))-1)<<pos;
2202         regvalue &= ~msk;
2203         regvalue |= value<<pos;
2204
2205         /* Only write when the current register value is not the same as the new value */
2206         if (oldvalue != regvalue) {
2207                 err = tfa98xx_write_register16(dev_idx, address, regvalue);
2208                 if (err) {
2209                         pr_err("Error setting bf :%d \n", -err);
2210                         return -err;
2211                 }
2212         }
2213
2214         return 0;
2215 }
2216
2217 int tfa_set_bf_volatile(Tfa98xx_handle_t dev_idx, const uint16_t bf, const uint16_t value)
2218 {
2219         enum Tfa98xx_Error err;
2220         uint16_t regvalue, msk;
2221
2222         /*
2223          * bitfield enum:
2224          * - 0..3  : len
2225          * - 4..7  : pos
2226          * - 8..15 : address
2227          */
2228         uint8_t len = bf & 0x0f;
2229         uint8_t pos = (bf >> 4) & 0x0f;
2230         uint8_t address = (bf >> 8) & 0xff;
2231
2232         err = tfa98xx_read_register16(dev_idx, address, &regvalue);
2233         if (err) {
2234                 pr_err("Error getting bf :%d \n", -err);
2235                 return -err;
2236         }
2237
2238         msk = ((1<<(len+1))-1)<<pos;
2239         regvalue &= ~msk;
2240         regvalue |= value<<pos;
2241
2242         err = tfa98xx_write_register16(dev_idx, address, regvalue);
2243         if (err) {
2244                 pr_err("Error setting bf :%d \n", -err);
2245                 return -err;
2246         }
2247
2248         return 0;
2249 }
2250
2251 int tfa_get_bf(Tfa98xx_handle_t dev_idx, const uint16_t bf)
2252 {
2253         enum Tfa98xx_Error err;
2254         uint16_t regvalue, msk;
2255         uint16_t value;
2256
2257         /*
2258          * bitfield enum:
2259          * - 0..3  : len
2260          * - 4..7  : pos
2261          * - 8..15 : address
2262          */
2263         uint8_t len = bf & 0x0f;
2264         uint8_t pos = (bf >> 4) & 0x0f;
2265         uint8_t address = (bf >> 8) & 0xff;
2266
2267         err = tfa98xx_read_register16(dev_idx, address, &regvalue);
2268         if (err) {
2269                 pr_err("Error getting bf :%d \n", -err);
2270                 return -err;
2271         }
2272
2273         msk = ((1<<(len+1))-1)<<pos;
2274         regvalue &= msk;
2275         value = regvalue>>pos;
2276
2277         return value;
2278 }
2279
2280 int tfa_set_bf_value(const uint16_t bf, const uint16_t bf_value, uint16_t *p_reg_value)
2281 {
2282         uint16_t regvalue, msk;
2283
2284         /*
2285          * bitfield enum:
2286          * - 0..3  : len
2287          * - 4..7  : pos
2288          * - 8..15 : address
2289          */
2290         uint8_t len = bf & 0x0f;
2291         uint8_t pos = (bf >> 4) & 0x0f;
2292
2293         regvalue = *p_reg_value;
2294
2295         msk = ((1<<(len+1))-1)<<pos;
2296         regvalue &= ~msk;
2297         regvalue |= bf_value<<pos;
2298
2299         *p_reg_value = regvalue;
2300
2301         return 0;
2302 }
2303
2304 uint16_t tfa_get_bf_value(const uint16_t bf, const uint16_t reg_value)
2305 {
2306         uint16_t msk, value;
2307
2308         /*
2309          * bitfield enum:
2310          * - 0..3  : len
2311          * - 4..7  : pos
2312          * - 8..15 : address
2313          */
2314         uint8_t len = bf & 0x0f;
2315         uint8_t pos = (bf >> 4) & 0x0f;
2316
2317         msk = ((1<<(len+1))-1)<<pos;
2318         value = (reg_value & msk) >> pos;
2319
2320         return value;
2321 }
2322
2323
2324 int tfa_write_reg(Tfa98xx_handle_t dev_idx, const uint16_t bf, const uint16_t reg_value)
2325 {
2326         enum Tfa98xx_Error err;
2327
2328         /* bitfield enum - 8..15 : address */
2329         uint8_t address = (bf >> 8) & 0xff;
2330
2331         err = tfa98xx_write_register16(dev_idx, address, reg_value);
2332         if (err)
2333                 return -err;
2334
2335         return 0;
2336 }
2337
2338 int tfa_read_reg(Tfa98xx_handle_t dev_idx, const uint16_t bf)
2339 {
2340         enum Tfa98xx_Error err;
2341         uint16_t regvalue;
2342
2343         /* bitfield enum - 8..15 : address */
2344         uint8_t address = (bf >> 8) & 0xff;
2345
2346         err = tfa98xx_read_register16(dev_idx, address, &regvalue);
2347         if (err)
2348                 return -err;
2349
2350         return regvalue;
2351 }
2352
2353 /*
2354  * powerup the coolflux subsystem and wait for it
2355  */
2356 enum Tfa98xx_Error tfa_cf_powerup(Tfa98xx_handle_t handle)
2357 {
2358         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2359         int tries, status;
2360
2361         /* power on the sub system */
2362         TFA_SET_BF_VOLATILE(handle, PWDN, 0);
2363
2364         /* wait until everything is stable, in case clock has been off */
2365         if (tfa98xx_runtime_verbose)
2366                 pr_info("Waiting for DSP system stable...\n");
2367         for (tries = CFSTABLE_TRIES; tries > 0; tries--) {
2368                 err = tfa98xx_dsp_system_stable(handle, &status);
2369                 _ASSERT(err == Tfa98xx_Error_Ok);
2370                 if (status)
2371                         break;
2372                 else
2373                         udelay(2000); /* wait 2ms to avoid busload */
2374         }
2375         if (tries == 0) { /* timedout */
2376                 pr_err("DSP subsystem start timed out\n");
2377                 return Tfa98xx_Error_StateTimedOut;
2378         }
2379
2380         return err;
2381 }
2382
2383 /*
2384  * Enable/Disable the I2S output for TFA1 devices
2385  * without TDM interface
2386  */
2387 static enum Tfa98xx_Error tfa98xx_aec_output(Tfa98xx_handle_t handle, int enable)
2388 {
2389         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2390
2391         if ((tfa98xx_get_device_dai(handle) & Tfa98xx_DAI_TDM) == Tfa98xx_DAI_TDM)
2392                 return err;
2393
2394         if (tfa98xx_dev_family(handle) == 1)
2395                 err = -tfa_set_bf(handle, TFA1_BF_I2SDOE, (enable != 0));
2396         else {
2397                 pr_err("I2SDOE on unsupported family\n");
2398                 err = Tfa98xx_Error_Not_Supported;
2399         }
2400
2401         return err;
2402 }
2403
2404 /*
2405  * Print the current state of the hardware manager
2406  * Device manager status information, man_state from TFA9888_N1B_I2C_regmap_V12
2407  */
2408 enum Tfa98xx_Error show_current_state(Tfa98xx_handle_t handle)
2409 {
2410         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2411         int manstate = -1;
2412
2413         if (tfa98xx_dev_family(handle) == 2) {
2414                 manstate = TFA_GET_BF(handle, MANSTATE);
2415                 if (manstate < 0)
2416                         return -manstate;
2417         }
2418
2419         pr_info("Current HW manager state: ");
2420
2421         switch (manstate) {
2422         case 0:
2423                 pr_info("power_down_state\n");
2424                 break;
2425         case 1:
2426                 pr_info("wait_for_source_settings_state\n");
2427                 break;
2428         case 2:
2429                 pr_info("connnect_pll_input_state\n");
2430                 break;
2431         case 3:
2432                 pr_info("disconnect_pll_input_state\n");
2433                 break;
2434         case 4:
2435                 pr_info("enable_pll_state\n");
2436                 break;
2437         case 5:
2438                 pr_info("enable_cgu_state\n");
2439                 break;
2440         case 6:
2441                 pr_info("init_cf_state\n");
2442                 break;
2443         case 7:
2444                 pr_info("enable_amplifier_state\n");
2445                 break;
2446         case 8:
2447                 pr_info("alarm_state\n");
2448                 break;
2449         case 9:
2450                 pr_info("operating_state\n");
2451                 break;
2452         case 10:
2453                 pr_info("mute_audio_state\n");
2454                 break;
2455         case 11:
2456                 pr_info("disable_cgu_pll_state\n");
2457                 break;
2458         default:
2459                 pr_info("Unable to find current state\n");
2460                 break;
2461         }
2462
2463         return err;
2464 }
2465
2466 /*
2467  *  start the speakerboost algorithm
2468  *  this implies a full system startup when the system was not already started
2469  *
2470  */
2471 enum Tfa98xx_Error tfaRunSpeakerBoost(Tfa98xx_handle_t handle, int force, int profile)
2472 {
2473         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2474         int value;
2475         int istap_prof = 0;
2476
2477         tfa98xx_dump_register(getHandle(handle), 2, "[dump]  tfaRunSpeakerBoost()   begin");
2478         if (force) {
2479                 err = tfaRunColdStartup(handle, profile);
2480                 if (err)
2481                         return err;
2482                 /* DSP is running now */
2483         }
2484
2485         value = TFA_GET_BF(handle, ACS);
2486         pr_debug("%s: ACS = %d\n", __func__, value);
2487
2488 #ifdef __KERNEL__ /* TODO try to combine this with the pr_debug below */
2489         tfa98xx_trace_printk("%s %sstart\n",
2490                                                 tfaContDeviceName(handle),
2491                                                 value ? "cold" : "warm");
2492 #endif
2493         /* Check if next profile is a tap profile */
2494         istap_prof = tfaContIsTapProfile(handle, profile);
2495
2496         if ((value == 1) && (!istap_prof)) {
2497                 /* SL: If cold start, make sure partial update is disabled */
2498                 tfa_set_partial_update(0);
2499
2500                 /* Run startup and write all files */
2501                 err = tfaRunSpeakerStartup(handle, force, profile);
2502                 if (err)
2503                         return err;
2504
2505                 /* Save the current profile and set the vstep to 0 */
2506                 /* This needs to be overwriten even in CF bypass */
2507                 tfa_set_swprof(handle, (unsigned short)profile);
2508                 tfa_set_swvstep(handle, 0);
2509
2510                 /* Startup with CF in bypass then return here */
2511                 if (TFA_GET_BF(handle, CFE) == 0) {
2512                         return err;
2513                 }
2514
2515 #ifdef __KERNEL__ /* TODO check if this can move to the tfa98xx.c */
2516                         /* Necessary here for early calibrate (MTPEX + ACS) */
2517                         tfa98xx_apply_deferred_calibration(handle);
2518 #endif
2519                 /* calibrate */
2520                 err = tfaRunSpeakerCalibration(handle, profile);
2521
2522                 switch (TFA_GET_BF(handle, REV) & 0xff) {
2523                 case 0x96:
2524                 case 0x97:
2525                         err = tfa98xx_dsp_reset(handle, 1);
2526                         err = tfa98xx_dsp_reset(handle, 0);
2527                         pr_info("Reset 97 at first cold start up\n");
2528                         break;
2529                 default:
2530                         break;
2531                 }
2532
2533         } else if (istap_prof)  {
2534                 /* Save the current profile and set the vstep to 0 */
2535                 /* This needs to be overwriten even in CF bypass and tap*/
2536                 tfa_set_swprof(handle, (unsigned short)profile);
2537                 tfa_set_swvstep(handle, 0);
2538         }
2539 #ifdef __KERNEL__ /* For kernel, DSP is turned off during cold start in tfa_probe */
2540         else {
2541                 if ((tfa98xx_dev_family(handle) == 2) && !(TFA_GET_BF(handle, CFE)))
2542                         TFA_SET_BF_VOLATILE(handle, CFE, 1);
2543         }
2544 #endif
2545
2546         return err;
2547 }
2548
2549 enum Tfa98xx_Error tfaRunSpeakerStartup(Tfa98xx_handle_t handle, int force, int profile)
2550 {
2551         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2552         pr_debug("coldstart%s :", force ? " (forced)" : "");
2553
2554         if (!force) { /* in case of force CF already runnning */
2555                 err = tfaRunStartup(handle, profile);
2556                 PRINT_ASSERT(err);
2557                 if (err)
2558                         return err;
2559                 /* Startup with CF in bypass then return here */
2560                 if (TFA_GET_BF(handle, CFE) == 0)
2561                         return err;
2562
2563                 err = tfaRunStartDSP(handle);
2564                 if (err)
2565                         return err;
2566         }
2567         /* DSP is running now
2568         * NOTE that ACS may be active
2569         *  no DSP reset/sample rate may be done until configured (SBSL)
2570         * For the first configuration the DSP expects at least
2571         * the speaker, config and a preset.
2572         * Therefore all files from the device list as well as the file
2573         * from the default profile are loaded before SBSL is set.
2574         * Note that the register settings were already done before loading the patch
2575         * write all the files from the device list (speaker, vstep and all messages)
2576         */
2577         err = tfaContWriteFiles(handle);
2578         if (err)
2579                 return err;
2580
2581         /* write all the files from the profile list (typically preset) */
2582         err = tfaContWriteFilesProf(handle, profile, 0); /* use volumestep 0 */
2583         if (err)
2584                 return err;
2585
2586         return err;
2587 }
2588
2589 /*
2590  * Run calibration
2591  */
2592 enum Tfa98xx_Error tfaRunSpeakerCalibration(Tfa98xx_handle_t handle, int profile)
2593 {
2594         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2595         int calibrateDone, spkr_count = 0;
2596         /* Avoid warning in user-space */
2597         profile = profile;
2598
2599 #ifdef __KERNEL__ /* Necessary otherwise we are thrown out of operating mode in kernel (because of internal clock) */
2600         /* SL: In kernel, there's no clock available during cold start, therefore power down chip */
2601         if (tfa98xx_dev_family(handle) == 2) {
2602                 TFA_SET_BF_VOLATILE(handle, PWDN, 1);
2603                 TFA_SET_BF_VOLATILE(handle, SBSL, 1);
2604                 TFA_SET_BF_VOLATILE(handle, CFE, 0);
2605                 return Tfa98xx_Error_NoClock;
2606         } else if (tfa98xx_dev_family(handle) != 2)
2607 #endif
2608                 TFA_SET_BF_VOLATILE(handle, SBSL, 1);
2609
2610         /* return if there is no audio running */
2611         if (TFA_GET_BF(handle, NOCLK) && tfa98xx_dev_family(handle) == 2)
2612                 return Tfa98xx_Error_NoClock;
2613
2614         /* When MTPOTC is set (cal=once) unlock key2 */
2615         if (TFA_GET_BF(handle, MTPOTC) == 1) {
2616                 tfa98xx_key2(handle, 0);
2617         }
2618
2619         /* await calibration, this should return ok */
2620         err = tfaRunWaitCalibration(handle, &calibrateDone);
2621         if (err == Tfa98xx_Error_Ok) {
2622                 err = tfa_dsp_get_calibration_impedance(handle);
2623                 PRINT_ASSERT(err);
2624         }
2625
2626         /* Give reason why calibration failed! */
2627         if (err != Tfa98xx_Error_Ok) {
2628                 if ((tfa98xx_dev_family(handle) == 2 && TFA_GET_BF(handle, REFCKSEL) == 1)) {
2629                         pr_err("Unable to calibrate the device with the internal clock! \n");
2630                 }
2631         }
2632
2633         if (err == Tfa98xx_Error_Ok) {
2634                 err = tfa98xx_supported_speakers(handle, &spkr_count);
2635
2636                 if (spkr_count == 1) {
2637                         pr_debug(" %d mOhms \n", handles_local[handle].mohm[0]);
2638                 } else {
2639                         pr_debug(" Prim:%d mOhms, Sec:%d mOhms\n",
2640                                                 handles_local[handle].mohm[0],
2641                                                 handles_local[handle].mohm[1]);
2642                 }
2643         }
2644
2645         /* When MTPOTC is set (cal=once) re-lock key2 */
2646         if (TFA_GET_BF(handle, MTPOTC) == 1) {
2647                 tfa98xx_key2(handle, 1);
2648         }
2649
2650         return err;
2651 }
2652
2653 /*
2654  * Set the debug option
2655  */
2656 void tfa_verbose(int level)
2657 {
2658         tfa98xx_trace_level = level;
2659         tfa98xx_runtime_verbose = level != 0; /* any non-zero */
2660         tfa_cnt_verbose(level);
2661 }
2662
2663 enum Tfa98xx_Error tfaRunColdboot(Tfa98xx_handle_t handle, int state)
2664 {
2665 #define CF_CONTROL 0x8100
2666         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2667         int tries = 10;
2668
2669         /* repeat set ACS bit until set as requested */
2670         while (state != TFA_GET_BF(handle, ACS)) {
2671                 /* set colstarted in CF_CONTROL to force ACS */
2672                 err = tfa98xx_dsp_write_mem_word(handle, CF_CONTROL, state, Tfa98xx_DMEM_IOMEM);
2673                 PRINT_ASSERT(err);
2674
2675                 if (tries-- == 0) {
2676                         pr_info("coldboot (ACS) did not %s\n", state ? "set":"clear");
2677                         return Tfa98xx_Error_Other;
2678                 }
2679         }
2680
2681         return err;
2682 }
2683
2684
2685
2686 /*
2687  * load the patch if any
2688  *   else tell no loaded
2689  */
2690 static enum Tfa98xx_Error tfa_run_load_patch(Tfa98xx_handle_t handle)
2691 {
2692         return tfaContWritePatch(handle);
2693 }
2694
2695 /*
2696  *  this will load the patch witch will implicitly start the DSP
2697  *   if no patch is available the DPS is started immediately
2698  */
2699 enum Tfa98xx_Error tfaRunStartDSP(Tfa98xx_handle_t handle)
2700 {
2701         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2702
2703         err = tfa_run_load_patch(handle);
2704         if (err) { /* patch load is fatal so return immediately*/
2705                 return err;
2706         }
2707
2708         /* Clear count_boot, should be reset to 0 before the DSP reset is released */
2709         err = tfa98xx_dsp_write_mem_word(handle, 512, 0, Tfa98xx_DMEM_XMEM);
2710         PRINT_ASSERT(err);
2711
2712         /* Reset DSP once for sure after initializing */
2713         if (err == Tfa98xx_Error_Ok) {
2714                 err = tfa98xx_dsp_reset(handle, 0); /* in pair of tfa98xx_init() - tfaRunStartup() */
2715                 PRINT_ASSERT(err);
2716         }
2717
2718         /* Sample rate is needed to set the correct tables */
2719         err = tfa98xx_dsp_write_tables(handle, TFA_GET_BF(handle, AUDFS));
2720         PRINT_ASSERT(err);
2721
2722         return err;
2723 }
2724
2725 /*
2726  * start the clocks and wait until the AMP is switching
2727  *  on return the DSP sub system will be ready for loading
2728  */
2729 enum Tfa98xx_Error tfaRunStartup(Tfa98xx_handle_t handle, int profile)
2730 {
2731         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2732         nxpTfaDeviceList_t *dev = tfaContDevice(handle);
2733         int tries, status, i, noinit = 0;
2734
2735         if (dev == NULL)
2736                 return Tfa98xx_Error_Fail;
2737
2738         /* process the device list to see if the user implemented the noinit */
2739         for (i = 0; i < dev->length; i++) {
2740                 if (dev->list[i].type == dscNoInit) {
2741                         noinit = 1;
2742                         break;
2743                 }
2744         }
2745
2746         if (!noinit) {
2747                 /* load the optimal TFA98XX in HW settings */
2748                 err = tfa98xx_init(handle);
2749                 PRINT_ASSERT(err);
2750         } else {
2751                 pr_debug("\nWarning: No init keyword found in the cnt file. Init is skipped! \n");
2752         }
2753
2754         /* I2S settings to define the audio input properties
2755          *  these must be set before the subsys is up */
2756         /* this will run the list until a non-register item is encountered */
2757         err = tfaContWriteRegsDev(handle); /* write device register settings */
2758         PRINT_ASSERT(err);
2759         /* also write register the settings from the default profile
2760            NOTE we may still have ACS=1 so we can switch sample rate here */
2761         err = tfaContWriteRegsProf(handle, profile);
2762         PRINT_ASSERT(err);
2763
2764         if (tfa98xx_dev_family(handle) == 2) {
2765                 /* Factory trimming for the Boost converter */
2766                 tfa_factory_trimmer(handle);
2767         }
2768
2769         /* leave power off state */
2770         err = tfa98xx_powerdown(handle, 0);
2771         PRINT_ASSERT(err);
2772
2773         if (tfa98xx_dev_family(handle) == 2) {
2774         /* signal that the clock settings are done
2775          *  - PLL can start */
2776                 TFA_SET_BF_VOLATILE(handle, MANSCONF, 1);
2777         }
2778
2779         switch (TFA_GET_BF(handle, REV) & 0xff) {
2780         case 0x80:
2781                 err = tfa98xx_dsp_reset(handle, 1);
2782                 pr_debug("tfaRunStartup Reset DSP after power on\n");
2783                 break;
2784         default:
2785                 break;
2786         }
2787
2788         /*  wait until the PLL is ready
2789          *    note that the DSP CPU is not running (RST=1) */
2790         if (tfa98xx_runtime_verbose) {
2791                 if (TFA_GET_BF(handle, NOCLK) && (tfa98xx_dev_family(handle) == 2))
2792                         pr_debug("Using internal clock\n");
2793                 pr_debug("Waiting for DSP system stable...\n");
2794         }
2795         for (tries = 1; tries < CFSTABLE_TRIES; tries++) {
2796                 err = tfa98xx_dsp_system_stable(handle, &status);
2797                 _ASSERT(err == Tfa98xx_Error_Ok);
2798                 if (status)
2799                         break;
2800                 else
2801                         msleep_interruptible(10); /* wait 10ms to avoid busload */
2802         }
2803         if (tries == CFSTABLE_TRIES) {
2804                 if (tfa98xx_runtime_verbose)
2805                         pr_debug("Timed out\n");
2806                 return Tfa98xx_Error_StateTimedOut;
2807         }  else
2808                 if (tfa98xx_runtime_verbose)
2809                         pr_debug(" OK (tries=%d)\n", tries);
2810
2811         if (tfa98xx_runtime_verbose && tfa98xx_dev_family(handle) == 2)
2812                 err = show_current_state(handle);
2813
2814         return err;
2815 }
2816
2817 /*
2818  * run the startup/init sequence and set ACS bit
2819  */
2820 enum Tfa98xx_Error tfaRunColdStartup(Tfa98xx_handle_t handle, int profile)
2821 {
2822         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2823
2824         err = tfaRunStartup(handle, profile);
2825         PRINT_ASSERT(err);
2826         if (err)
2827                 return err;
2828
2829         /* force cold boot */
2830         err = tfaRunColdboot(handle, 1);
2831         PRINT_ASSERT(err);
2832         if (err)
2833                 return err;
2834
2835         /* start */
2836         err = tfaRunStartDSP(handle);
2837         PRINT_ASSERT(err);
2838
2839         return err;
2840 }
2841
2842 /*
2843  *
2844  */
2845 enum Tfa98xx_Error tfaRunMute(Tfa98xx_handle_t handle)
2846 {
2847         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2848         int status;
2849         int tries = 0;
2850
2851         /* signal the TFA98XX to mute  */
2852         if (tfa98xx_dev_family(handle) == 1) {
2853                 err = tfa98xx_set_mute(handle, Tfa98xx_Mute_Amplifier);
2854
2855                 if (err == Tfa98xx_Error_Ok) {
2856                         /* now wait for the amplifier to turn off */
2857                         do {
2858                                 status = TFA_GET_BF(handle, SWS);
2859                                 if (status != 0)
2860                                         msleep_interruptible(10); /* wait 10ms to avoid busload */
2861                                 else
2862                                         break;
2863                                 tries++;
2864                         }  while (tries < AMPOFFWAIT_TRIES);
2865
2866
2867                         /* if (tfa98xx_runtime_verbose) */
2868                                 pr_info("-------------------- muted --------------------\n");
2869
2870                         /*The amplifier is always switching*/
2871                         if (tries == AMPOFFWAIT_TRIES)
2872                                 return Tfa98xx_Error_Other;
2873                 }
2874         }
2875
2876         return err;
2877 }
2878 /*
2879  *
2880  */
2881 enum Tfa98xx_Error tfaRunUnmute(Tfa98xx_handle_t handle)
2882 {
2883         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2884         int retry = 0;
2885
2886         if (tfa98xx_runtime_verbose)
2887                 pr_debug("Entering unmute\n");
2888
2889         /* signal the TFA98XX to mute  */
2890         err = tfa98xx_set_mute(handle, Tfa98xx_Mute_Off);
2891         if (err)
2892                 pr_err("Unmute failed\n");
2893
2894         if (tfa98xx_dev_family(handle) == 2) {
2895                 int manstate = TFA_GET_BF(handle, MANSTATE);
2896                 show_current_state(handle);
2897
2898                 if ((TFA_GET_BF(handle, CFE) != 0) && (9 == manstate)) {
2899                         /* handset mode */
2900                         TFA_SET_BF_VOLATILE(handle, AMPE, 1);
2901                         return err;
2902                 } else {
2903                         if ((TFA_GET_BF(handle, REFCKSEL) == 1) && (TFA_GET_BF(handle, MANSTATE) == 6)) {
2904                                 pr_info("tfaUnmute() MANSCONF and MANCOLD will be switching to external clock\n");
2905                                 TFA_SET_BF_VOLATILE(handle, MANSCONF, 0);
2906                                 TFA_SET_BF_VOLATILE(handle, RST, 1);
2907                                 TFA_SET_BF_VOLATILE(handle, MANCOLD, 1);
2908                                 /* set ACS=0 to avoid DSP think it's real cold start */
2909                                 err = tfaRunColdboot(handle, 0);
2910                                 TFA_SET_BF_VOLATILE(handle, SBSL, 1);
2911                                 pr_info("tfaUnmute()  SBSL=1  switching to external clock\n");
2912                                 TFA_SET_BF_VOLATILE(handle, REFCKSEL, 0);
2913                                 TFA_SET_BF_VOLATILE(handle, RST, 0);
2914                                 TFA_SET_BF_VOLATILE(handle, SBSL, 0);
2915                                 pr_info("tfaUnmute() REFCKSEL=0  SBSL=0 switched to external clock\n");
2916                         }
2917                 }
2918
2919                 do {
2920                         manstate = TFA_GET_BF(handle, MANSTATE);
2921                         if (manstate <= 1) {
2922                                 TFA_SET_BF_VOLATILE(handle, MANSCONF, 1);
2923                                 break;
2924                         }
2925                         retry++;
2926                         pr_info("tfaUnmute() MANSTATE %d, retry times %d\n", manstate, retry);
2927                         udelay(300);
2928                 } while (retry < 10);
2929
2930                 udelay(5000);
2931                 /* SL: Enable everything,
2932                  * there will be sound after clock and sound
2933                  * applied
2934                  */
2935                 TFA_SET_BF_VOLATILE(handle, SBSL, 1);
2936                 TFA_SET_BF_VOLATILE(handle, AMPE, 1);
2937                 show_current_state(handle);
2938                 /* SL: when device is warm, enable partial update for next profile switching */
2939                 tfa_set_partial_update(1);
2940         }
2941
2942         /* if (tfa98xx_runtime_verbose) */
2943                 pr_info("-------------------unmuted ------------------\n");
2944
2945         return err;
2946 }
2947
2948
2949 /*
2950  * wait for calibrateDone
2951  */
2952 enum Tfa98xx_Error tfaRunWaitCalibration(Tfa98xx_handle_t handle, int *calibrateDone)
2953 {
2954         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
2955         int tries = 0, mtp_busy = 1, tries_mtp_busy = 0;
2956
2957         *calibrateDone = 0;
2958
2959         /* in case of calibrate once wait for MTPEX */
2960         if (TFA_GET_BF(handle, MTPOTC)) {
2961                 /* Check if MTP_busy is clear! */
2962                 while (tries_mtp_busy < MTPBWAIT_TRIES) {
2963                         mtp_busy = TFA_GET_BF(handle, MTPB);
2964                         if (mtp_busy == 1)
2965                                 msleep_interruptible(10); /* wait 10ms to avoid busload */
2966                         else
2967                                 break;
2968                         tries_mtp_busy++;
2969                 }
2970
2971                 if (tries_mtp_busy < MTPBWAIT_TRIES) {
2972                         /* Because of the msleep TFA98XX_API_WAITRESULT_NTRIES is way to long!
2973                                 * Setting this to 25 will take it atleast 25*50ms = 1.25 sec
2974                                 */
2975                         while ((*calibrateDone == 0) && (tries < MTPEX_WAIT_NTRIES)) {
2976                                 *calibrateDone = TFA_GET_BF(handle, MTPEX);
2977                                 if (*calibrateDone == 1)
2978                                         break;
2979                                 msleep_interruptible(50); /* wait 50ms to avoid busload */
2980                                 tries++;
2981                         }
2982
2983                         if (tries >= MTPEX_WAIT_NTRIES) {
2984                                 tries = TFA98XX_API_WAITRESULT_NTRIES;
2985                         }
2986                 } else {
2987                         pr_err("MTP bussy after %d tries\n", MTPBWAIT_TRIES);
2988                 }
2989         }
2990
2991         /* poll xmem for calibrate always
2992                 * calibrateDone = 0 means "calibrating",
2993                 * calibrateDone = -1 (or 0xFFFFFF) means "fails"
2994                 * calibrateDone = 1 means calibration done
2995                 */
2996         while ((*calibrateDone != 1) && (tries < TFA98XX_API_WAITRESULT_NTRIES)) {
2997                 err = tfa98xx_dsp_read_mem(handle, TFA_FW_XMEM_CALIBRATION_DONE, 1, calibrateDone);
2998                 tries++;
2999         }
3000
3001         if (*calibrateDone != 1) {
3002                 pr_err("Calibration failed! \n");
3003                 err = Tfa98xx_Error_Bad_Parameter;
3004         } else if (tries == TFA98XX_API_WAITRESULT_NTRIES) {
3005                 pr_debug("Calibration has timedout! \n");
3006                 err = Tfa98xx_Error_StateTimedOut;
3007         } else if (tries_mtp_busy == 1000) {
3008                 pr_err("Calibrate Failed: MTP_busy stays high! \n");
3009                 err = Tfa98xx_Error_StateTimedOut;
3010         }
3011
3012         /* Check which speaker calibration failed. Only for 88C */
3013         if ((err != Tfa98xx_Error_Ok) && ((handles_local[handle].rev & 0x0FFF) == 0xc88)) {
3014                 individual_calibration_results(handle);
3015         }
3016
3017 #ifdef CONFIG_DEBUG_FS
3018         tfa98xx_deferred_calibration_status(handle, *calibrateDone);
3019 #endif
3020         return err;
3021 }
3022
3023 enum tfa_error tfa_start(int next_profile, int *vstep)
3024 {
3025         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
3026         int dev, devcount = tfa98xx_cnt_max_device();
3027         int cal_profile = -1, istap_prof = 0, active_profile = -1;
3028
3029         if (devcount < 1) {
3030                 pr_err("No or wrong container file loaded\n");
3031                 return  tfa_error_bad_param;
3032         }
3033
3034         for (dev = 0; dev < devcount; dev++) {
3035                 pr_info("tfa_start()    dev=%d    will perform tfaContOpen()\n", dev);
3036                 err = tfaContOpen(dev);
3037                 if (err != Tfa98xx_Error_Ok) {
3038                         pr_err("tfa_start()        tfaContOpen error(%d)\n", err);
3039                         goto error_exit;
3040                 }
3041
3042                 /* Get currentprofile */
3043                 active_profile = tfa_get_swprof(dev);
3044                 pr_info("tfa_start()       tfa_get_swprof active_profile(%d)\n", active_profile);
3045                 if (active_profile == 0xff)
3046                         active_profile = -1;
3047
3048                 /* Search if there is a calibration profile
3049                  * Only if the user did not give a specific profile and coldstart
3050                  */
3051                 if (active_profile == -1 && next_profile < 1) {
3052                         pr_info("tfa_start()    will perform tfaContGetCalProfile()\n");
3053                         cal_profile = tfaContGetCalProfile(dev);
3054                         if (cal_profile >= 0)
3055                                 next_profile = cal_profile;
3056                 }
3057                 /* Check if next profile is a tap profile */
3058                 istap_prof = tfaContIsTapProfile(dev, next_profile);
3059
3060                 /* tfaRun_SpeakerBoost implies un-mute */
3061                 if (tfa98xx_runtime_verbose) {
3062                         pr_debug("active_profile:%s, next_profile:%s\n",
3063                                         tfaContProfileName(dev, active_profile),
3064                                         tfaContProfileName(dev, next_profile));
3065                         pr_debug("Starting device [%s]\n", tfaContDeviceName(dev));
3066
3067                         if (tfa98xx_dev_family(dev) == 2) {
3068                                 err = show_current_state(dev);
3069                         }
3070                 }
3071
3072                 /* enable I2S output on TFA1 devices without TDM */
3073                 pr_info("tfa_start()    will perform tfa98xx_aec_output()\n");
3074                 err = tfa98xx_aec_output(dev, 1);
3075                 if (err != Tfa98xx_Error_Ok) {
3076                         pr_err("tfa_start()        tfa98xx_aec_output error(%d)\n", err);
3077                         goto error_exit;
3078                 }
3079                 tfa98xx_dump_register(getHandle(dev), 2, "tfa_start after tfa98xx_aec_output");
3080
3081                 /* Check if we need coldstart or ACS is set */
3082                 pr_info("tfa_start()    will perform tfaRunSpeakerBoost()\n");
3083                 err = tfaRunSpeakerBoost(dev, 0, next_profile);
3084                 show_current_state(dev);
3085                 if (err != Tfa98xx_Error_Ok) {
3086                         pr_err("tfa_start()        tfaRunSpeakerBoost error(%d)\n", err);
3087                         goto error_exit;
3088                 }
3089                 active_profile = tfa_get_swprof(dev);
3090                 tfa98xx_dump_register(getHandle(dev), 2, "tfa_start after tfaRunSpeakerBoost");
3091
3092                 /* After loading calibration profile we need to load acoustic shock profile */
3093                 if (cal_profile >= 0) {
3094                         next_profile = 0;
3095                         pr_debug("Loading %s profile! \n", tfaContProfileName(dev, next_profile));
3096                 }
3097         }
3098
3099         for (dev = 0; dev < devcount; dev++) {
3100                 /* check if the profile and steps are the one we want */
3101                 /* was it not done already */
3102                 if ((next_profile != active_profile && active_profile != -1)
3103                        || (istap_prof == 1)) {
3104                         tfa98xx_dump_register(getHandle(dev), 2, "tfa_start before tfaContWriteProfile");
3105                         pr_info("tfa_start()    will perform tfaContWriteProfile()\n");
3106                         err = tfaContWriteProfile(dev, next_profile, vstep[dev]);
3107                         if (err != Tfa98xx_Error_Ok) {
3108                                 pr_err("tfa_start()        tfaContWriteProfile error(%d)\n", err);
3109                                 goto error_exit;
3110                         }
3111                 }
3112
3113                 pr_info("tfa_start()    after performed tfaContWriteProfile()\n");
3114                 /* If the profile contains the .standby suffix go to powerdown
3115                  * else we should be in operating state
3116                  */
3117                 if (strnstr(tfaContProfileName(dev, next_profile), ".standby", strlen(tfaContProfileName(dev, next_profile))) != NULL) {
3118                         /* SL: standby profile is called and goes to return immediately */
3119                         tfa_set_swprof(dev, (unsigned short)next_profile);
3120                         tfa_set_swvstep(dev, (unsigned short)tfaContGetCurrentVstep(dev));
3121                         goto error_exit;
3122                 } else if (TFA_GET_BF(dev, PWDN) != 0) {
3123                         err = tfa_cf_powerup(dev);
3124                 }
3125
3126                 if ((TFA_GET_BF(dev, CFE) != 0)
3127                          && (vstep[dev] != tfaContGetCurrentVstep(dev) && vstep[dev] != -1)) {
3128
3129                         err = tfaContWriteFilesVstep(dev, next_profile, vstep[dev]);
3130                         if (err != Tfa98xx_Error_Ok)
3131                                 goto error_exit;
3132                         /* Always search and apply filters after a new vstep is applied */
3133                         err = tfa_set_filters(dev, next_profile);
3134                         if (err != Tfa98xx_Error_Ok)
3135                                 goto error_exit;
3136                 }
3137                 if (err != Tfa98xx_Error_Ok)
3138                         goto error_exit;
3139
3140                 if (tfa98xx_runtime_verbose && tfa98xx_dev_family(dev) == 2)
3141                         err = show_current_state(dev);
3142
3143                 tfa_set_swprof(dev, (unsigned short)next_profile);
3144                 tfa_set_swvstep(dev, (unsigned short)tfaContGetCurrentVstep(dev));
3145
3146                 tfaRunUnmute(dev);      /* unmute at final stage */
3147         }
3148
3149 error_exit:
3150         for (dev = 0; dev < devcount; dev++) {
3151                 if (tfa98xx_runtime_verbose && tfa98xx_dev_family(dev) == 2)
3152                         show_current_state(dev);
3153                 tfaContClose(dev); /* close all of them */
3154         }
3155         return err;
3156 }
3157
3158 enum tfa_error tfa_stop(void)
3159 {
3160         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
3161         int dev, devcount = tfa98xx_cnt_max_device();
3162
3163         if (devcount == 0) {
3164                 pr_err("No or wrong container file loaded\n");
3165                 return  tfa_error_bad_param;
3166         }
3167
3168         for (dev = 0; dev < devcount; dev++) {
3169                 err = tfaContOpen(dev);
3170                 if (err != Tfa98xx_Error_Ok)
3171                         goto error_exit;
3172                 if (tfa98xx_runtime_verbose)
3173                         pr_debug("Stopping device [%s]\n", tfaContDeviceName(dev));
3174
3175                 if (tfa98xx_dev_family(dev) == 2) {/* Max2 */
3176                         int stop_profile = 0;
3177                         int vstep[2] = {0};
3178
3179                         do {
3180                                 if (strnstr(tfaContProfileName(dev, stop_profile), ".standby", strlen(tfaContProfileName(dev, stop_profile))) != NULL) {
3181                                         /*SL: Found the stop profile*/
3182                                         break;
3183                                 }
3184                                 stop_profile++;
3185                         } while (stop_profile <= tfaContMaxProfile(dev));
3186
3187                         vstep[dev] = tfaContGetCurrentVstep(dev);
3188                         if (stop_profile != tfaContMaxProfile(dev)) {
3189                                 /*SL: Switch to powerdown profile */
3190                                 err = tfaContWriteProfile(dev, stop_profile, vstep[dev]);
3191                                 /* SL: standby profile is called and goes to return immediately */
3192                                 tfa_set_swprof(dev, (unsigned short)stop_profile);
3193                                 tfa_set_swvstep(dev, (unsigned short)tfaContGetCurrentVstep(dev));
3194                         }
3195                         if (err != Tfa98xx_Error_Ok)
3196                                 goto error_exit;
3197                 } else {/* Max1 */
3198                         /* mute */
3199                         tfaRunMute(dev);
3200                         /* powerdown CF */
3201                         err = tfa98xx_powerdown(dev, 1);
3202                         if (err != Tfa98xx_Error_Ok)
3203                                 goto error_exit;
3204
3205                         /* disable I2S output on TFA1 devices without TDM */
3206                         err = tfa98xx_aec_output(dev, 0);
3207                         if (err != Tfa98xx_Error_Ok)
3208                                 goto error_exit;
3209                 }
3210         }
3211
3212 error_exit:
3213         for (dev = 0; dev < devcount; dev++)
3214                 tfaContClose(dev); /* close all of them */
3215         return err;
3216 }
3217
3218 /*
3219  *  int registers and coldboot dsp
3220  */
3221 int tfa98xx_reset(Tfa98xx_handle_t handle)
3222 {
3223         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
3224
3225         /* TFA_SET_BF_VOLATILE(handle, I2CR, 1); */
3226     if (tfa98xx_dev_family(handle) == 2) {
3227                 /* restore MANSCONF and MANCOLD to POR state */
3228                 TFA_SET_BF_VOLATILE(handle, MANSCONF, 0);
3229                 TFA_SET_BF_VOLATILE(handle, MANCOLD, 1);
3230     }
3231
3232         /* for clock */
3233         err = tfa_cf_powerup(handle);
3234         PRINT_ASSERT(err);
3235
3236         /* force cold boot */
3237         err = tfaRunColdboot(handle, 1);
3238         PRINT_ASSERT(err);
3239
3240         /* reset all i2C registers to default */
3241         err = -TFA_SET_BF(handle, I2CR, 1);
3242         PRINT_ASSERT(err);
3243
3244         return err;
3245 }
3246
3247 enum tfa_error tfa_reset(void)
3248 {
3249         enum Tfa98xx_Error err = Tfa98xx_Error_Ok;
3250         int dev, devcount = tfa98xx_cnt_max_device();
3251
3252         for (dev = 0; dev < devcount; dev++) {
3253                 err = tfaContOpen(dev);
3254                 if (err != Tfa98xx_Error_Ok)
3255                         break;
3256                 if (tfa98xx_runtime_verbose)
3257                         pr_debug("resetting device [%s]\n", tfaContDeviceName(dev));
3258                 err = tfa98xx_reset(dev);
3259                 if (err != Tfa98xx_Error_Ok)
3260                         break;
3261         }
3262
3263         for (dev = 0; dev < devcount; dev++) {
3264                 tfaContClose(dev);
3265         }
3266
3267         return err;
3268 }
3269
3270 /*
3271  * Write all the bytes specified by num_bytes and data
3272  */
3273 enum Tfa98xx_Error
3274 tfa98xx_write_data(Tfa98xx_handle_t handle,
3275                   unsigned char subaddress, int num_bytes,
3276                   const unsigned char data[])
3277 {
3278         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
3279         /* subaddress followed by data */
3280         const int bytes2write = num_bytes + 1;
3281         unsigned char *write_data;
3282
3283         if (num_bytes > TFA2_MAX_PARAM_SIZE)
3284                 return Tfa98xx_Error_Bad_Parameter;
3285
3286         write_data = (unsigned char *)kmalloc(bytes2write, GFP_KERNEL);
3287         if (write_data == NULL)
3288                 return Tfa98xx_Error_Fail;
3289
3290         write_data[0] = subaddress;
3291         memcpy(&write_data[1], data, num_bytes);
3292
3293         error = tfa98xx_write_raw(handle, bytes2write, write_data);
3294
3295         kfree (write_data);
3296         return error;
3297 }
3298
3299 /*
3300  * fill the calibration value as milli ohms in the struct
3301  *
3302  *  assume that the device has been calibrated
3303  */
3304 enum Tfa98xx_Error tfa_dsp_get_calibration_impedance(Tfa98xx_handle_t handle)
3305 {
3306         enum Tfa98xx_Error error = Tfa98xx_Error_Ok;
3307         int spkr_count, nr_bytes, i;
3308         unsigned char bytes[6] = {0};
3309         int data[2];
3310
3311         error = tfa98xx_supported_speakers(handle, &spkr_count);
3312         if (error == Tfa98xx_Error_Ok) {
3313                 /* If calibrate=once then get values from MTP */
3314                 if (TFA_GET_BF(handle, MTPOTC) && ((handles_local[handle].rev & 0xff) == 0x88)) {
3315                         if (tfa98xx_runtime_verbose)
3316                                 pr_debug("Getting calibration values from MTP\n");
3317
3318                         for (i = 0; i < spkr_count; i++) {
3319                                 handles_local[handle].mohm[i] = tfa_read_reg(handle, (uint16_t)TFA_MK_BF((0xF4 + i), 0, 16));
3320                         }
3321                 } else {
3322                         /* Get values from speakerboost */
3323                         if (tfa98xx_runtime_verbose)
3324                                 pr_debug("Getting calibration values from Speakerboost\n");
3325                         nr_bytes = spkr_count * 3;
3326                         error = tfa_dsp_cmd_id_write_read(handle, MODULE_SPEAKERBOOST, SB_PARAM_GET_RE0, nr_bytes, bytes);
3327                         if (error == Tfa98xx_Error_Ok) {
3328                                 tfa98xx_convert_bytes2data(nr_bytes, bytes, data);
3329                                 for (i = 0; i < spkr_count; i++) {
3330                                         handles_local[handle].mohm[i] = (data[i]*1000)/TFA_FW_ReZ_SCALE;
3331                                 }
3332                         } else {
3333                                 for (i = 0; i < spkr_count; i++)
3334                                         handles_local[handle].mohm[i] = -1;
3335                         }
3336                 }
3337         }
3338
3339         return error;
3340 }
3341
3342 /* start count from 1, 0 is invalid */
3343 int tfa_get_swprof(Tfa98xx_handle_t handle)
3344 {
3345         /* get from register if not set yet */
3346         if (handles_local[handle].profile < 0)
3347                 /* get current profile, consider invalid if 0 */
3348                 handles_local[handle].profile = TFA_GET_BF(handle, SWPROFIL)-1;
3349
3350         return handles_local[handle].profile;
3351 }
3352
3353 int tfa_set_swprof(Tfa98xx_handle_t handle, unsigned short new_value)
3354 {
3355         int mtpk, active_value = tfa_get_swprof(handle);
3356
3357         handles_local[handle].profile = new_value;
3358
3359         if (handles_local[handle].tfa_family > 1) {
3360                 TFA_SET_BF_VOLATILE(handle, SWPROFIL, new_value+1);
3361         } else {
3362                 /* it's in MTP shadow, so unlock if not done already */
3363                 mtpk = TFA_GET_BF(handle, MTPK); /* get current key */
3364                 TFA_SET_BF_VOLATILE(handle, MTPK, 0x5a);
3365                 TFA_SET_BF_VOLATILE(handle, SWPROFIL, new_value+1); /* set current profile */
3366                 TFA_SET_BF_VOLATILE(handle, MTPK, (uint16_t)mtpk); /* restore key */
3367         }
3368
3369         return active_value;
3370 }
3371
3372 /*   same value for all channels
3373  * start count from 1, 0 is invalid */
3374 int tfa_get_swvstep(Tfa98xx_handle_t handle)
3375 {
3376         int value;
3377
3378         if (handles_local[handle].vstep[0] > 0)
3379                 return handles_local[handle].vstep[0] - 1;
3380
3381         value = TFA_GET_BF(handle, SWVSTEP); /* get current vstep[0] */
3382
3383         handles_local[handle].vstep[0] = value;
3384         handles_local[handle].vstep[1] = value;
3385         return value-1; /* invalid if 0 */
3386 }
3387 int tfa_set_swvstep(Tfa98xx_handle_t handle, unsigned short new_value)
3388 {
3389         int mtpk, active_value = tfa_get_swvstep(handle);
3390
3391         handles_local[handle].vstep[0] = new_value;
3392         handles_local[handle].vstep[1] = new_value;
3393
3394         if (handles_local[handle].tfa_family > 1) {
3395                 TFA_SET_BF_VOLATILE(handle, SWVSTEP, new_value+1);
3396         } else {
3397                 /* it's in MTP shadow, so unlock if not done already */
3398                 mtpk = TFA_GET_BF(handle, MTPK); /* get current key */
3399                 TFA_SET_BF_VOLATILE(handle, MTPK, 0x5a);
3400                 TFA_SET_BF_VOLATILE(handle, SWVSTEP, new_value+1); /* set current vstep[0] */
3401                 TFA_SET_BF_VOLATILE(handle, MTPK, (uint16_t)mtpk); /* restore key */
3402         }
3403
3404         return active_value;
3405 }