hid: release snd_card without causing a deadlock
[linux-3.10.git] / drivers / hid / hid-atv-jarvis.c
1 /*
2  *  HID driver for the Android TV remote
3  *  providing keys and microphone audio functionality
4  *
5  * Copyright (C) 2014 Google, Inc.
6  * Copyright (c) 2015-2016, NVIDIA CORPORATION, All rights reserved.
7  *
8  * This software is licensed under the terms of the GNU General Public
9  * License version 2, as published by the Free Software Foundation, and
10  * may be copied, distributed, and modified under those terms.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  */
17
18 #include <linux/device.h>
19 #include <linux/module.h>
20 #include <linux/hid.h>
21 #include <linux/hiddev.h>
22 #include <linux/hardirq.h>
23 #include <linux/iio/imu/tsfw_icm20628.h>
24 #include <linux/jiffies.h>
25 #include <linux/slab.h>
26 #include <linux/time.h>
27 #include <linux/wait.h>
28 #include <linux/timer.h>
29 #include <linux/spinlock.h>
30 #include <linux/vmalloc.h>
31 #include <linux/switch.h>
32 #include <sound/core.h>
33 #include <sound/control.h>
34 #include <sound/info.h>
35 #include <sound/initval.h>
36 #include <sound/pcm.h>
37
38 #include "hid-ids.h"
39 #include "sbcdec.h"
40
41 MODULE_LICENSE("GPL v2");
42
43 #define snd_atvr_log(...) pr_info("snd_atvr: " __VA_ARGS__)
44
45 #define ADPCM_AUDIO_REPORT_ID 30
46
47 #define MSBC_AUDIO1_REPORT_ID 0xF7
48 #define MSBC_AUDIO2_REPORT_ID 0xFA
49 #define MSBC_AUDIO3_REPORT_ID 0xFB
50
51 #define INPUT_REPORT_ID 2
52 #define INPUT_EVT_INTR_DATA_ID 10
53
54 #define KEYCODE_PRESENT_IN_AUDIO_PACKET_FLAG 0x80
55
56 /* defaults */
57 #define MAX_PCM_DEVICES     1
58 #define MAX_PCM_SUBSTREAMS  4
59 #define MAX_MIDI_DEVICES    0
60
61 /* Define these all in one place so they stay in sync. */
62 #define USE_RATE_MIN          8000
63 #define USE_RATE_MAX          16000
64 #define USE_RATE_MAX_PEPPER   8000
65 #define USE_RATES_ARRAY      {USE_RATE_MIN}
66 #define USE_RATES_MASK       (SNDRV_PCM_RATE_8000|SNDRV_PCM_RATE_16000)
67 #define USE_RATES_MASK_PEPPER    SNDRV_PCM_RATE_8000
68
69 #define MAX_FRAMES_PER_BUFFER  (8192)
70
71 #define USE_CHANNELS_MIN   1
72 #define USE_CHANNELS_MAX   2
73 #define USE_CHANNELS_MAX_PEPPER   1
74 #define USE_PERIODS_MIN    1
75 #define USE_PERIODS_MAX    1024
76
77 #define MAX_PCM_BUFFER_SIZE  (MAX_FRAMES_PER_BUFFER * sizeof(int16_t))
78 #define MIN_PERIOD_SIZE      64
79 #define MAX_PERIOD_SIZE      (MAX_PCM_BUFFER_SIZE / 8)
80 #define USE_FORMATS          (SNDRV_PCM_FMTBIT_S16_LE)
81
82 #define PACKET_TYPE_ADPCM 0
83 #define PACKET_TYPE_MSBC  1
84
85
86 /* Normally SBC has a H2 header but because we want
87  * to embed keycode support while audio is active without
88  * incuring an additional packet in the connection interval,
89  * we only use half the H2 header.  A normal H2 header has
90  * a 12-bit synchronization word and a 2-bit sequence number
91  * (SN0, SN1).  The sequence number is duplicated, so each
92  * pair of bits in the sequence number shall be always 00
93  * or 11 (see 5.7.2 of HFP_SPEC_V16).  We only receive
94  * the second byte of the H2 header that has the latter part
95  * of the sync word and the entire sequence number.
96  *
97  *  0      70      7
98  * b100000000001XXYY - where X is SN0 repeated and Y is SN1 repeated
99  *
100  * So the sequence numbers are:
101  * b1000000000010000 - 0x01 0x08  - only the 0x08 is received
102  * b1000000000011100 - 0x01 0x38  - only the 0x38 is received
103  * b1000000000010011 - 0x01 0xc8  - only the 0xc8 is received
104  * b1000000000011111 - 0x01 0xf8  - only the 0xf8 is received
105  *
106  * Each mSBC frame is split over 3 BLE frames, where each BLE packet has
107  * a 20 byte payload.
108  * The first BLE packet has the format:
109  * byte 0: keycode LSB
110  * byte 1: keycode MSB, with most significant bit 0 for no key
111  *         code active and 1 if keycode is active
112  * byte 2: Second byte of H2
113  * bytes 3-19: then four byte SBC header, then 13 bytes of audio data
114  *
115  * The second and third packet are purely 20 bytes of audio
116  * data.  Second packet arrives on report 0xFA and third packet
117  * arrives on report 0xFB.
118  *
119  * The mSBC decoder works on a mSBC frame, including the four byte SBC header,
120  * so we have to accumulate 3 BLE packets before sending it to the decoder.
121  */
122 #define NUM_SEQUENCES 4
123 const uint8_t msbc_sequence_table[NUM_SEQUENCES] = {0x08, 0x38, 0xc8, 0xf8};
124 #define BLE_PACKETS_PER_MSBC_FRAME 3
125 #define MSBC_PACKET1_BYTES 17
126 #define MSBC_PACKET2_BYTES 20
127 #define MSBC_PACKET3_BYTES 20
128
129 #define BYTES_PER_MSBC_FRAME \
130         (MSBC_PACKET1_BYTES + MSBC_PACKET2_BYTES + MSBC_PACKET3_BYTES)
131
132 const uint8_t msbc_start_offset_in_packet[BLE_PACKETS_PER_MSBC_FRAME] = {
133         1, /* SBC header starts after 1 byte sequence num portion of H2 */
134         0,
135         0
136 };
137 const uint8_t msbc_start_offset_in_buffer[BLE_PACKETS_PER_MSBC_FRAME] = {
138         0,
139         MSBC_PACKET1_BYTES,
140         MSBC_PACKET1_BYTES + MSBC_PACKET2_BYTES
141 };
142 const uint8_t msbc_bytes_in_packet[BLE_PACKETS_PER_MSBC_FRAME] = {
143         /* includes the SBC header but not the sequence num or keycode */
144         MSBC_PACKET1_BYTES,
145         MSBC_PACKET2_BYTES,
146         MSBC_PACKET3_BYTES
147 };
148
149 struct fifo_packet {
150         uint8_t  type;
151         uint8_t  num_bytes;
152         /* Expect no more than 20 bytes. But align struct size to power of 2. */
153         uint8_t  raw_data[1022];
154 };
155
156 #define MAX_SAMPLES_PER_PACKET 128
157 #define MIN_SAMPLES_PER_PACKET_P2  32
158 #define MAX_PACKETS_PER_BUFFER  \
159                 (MAX_FRAMES_PER_BUFFER / MIN_SAMPLES_PER_PACKET_P2)
160 #define MAX_BUFFER_SIZE  \
161                 (MAX_PACKETS_PER_BUFFER * sizeof(struct fifo_packet))
162
163 #define SND_ATVR_RUNNING_TIMEOUT_MSEC    (500)
164
165 #define TIMER_STATE_BEFORE_DECODE    0
166 #define TIMER_STATE_DURING_DECODE    1
167 #define TIMER_STATE_AFTER_DECODE     2
168
169 /* move hid device, sound card into per device data structure */
170 struct shdr_device {
171         struct hid_device       *hdev;
172         struct snd_card *shdr_card;
173         struct tsfw_icm20628_fn_dev *snsr_fns;
174         struct tsfw_icm20628_state *st;
175 };
176 static int num_remotes;
177 static struct mutex snd_cards_lock;
178 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;  /* Index 0-MAX */
179 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;   /* ID for this card */
180 /* enable all cards by default */
181 static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
182 /* remember snd cards already in use */
183 static bool cards_in_use[SNDRV_CARDS] = {false};
184 /* Linux does not like NULL initialization. */
185 static char *model[SNDRV_CARDS]; /* = {[0 ... (SNDRV_CARDS - 1)] = NULL}; */
186 static int pcm_devs[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
187 static int pcm_substreams[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
188
189 module_param_array(index, int, NULL, 0444);
190 MODULE_PARM_DESC(index, "Index value for SHIELD Remote soundcard.");
191 module_param_array(id, charp, NULL, 0444);
192 MODULE_PARM_DESC(id, "ID string for SHIELD Remote soundcard.");
193 module_param_array(enable, bool, NULL, 0444);
194 MODULE_PARM_DESC(enable, "Enable this SHIELD Remote soundcard.");
195 module_param_array(model, charp, NULL, 0444);
196 MODULE_PARM_DESC(model, "Soundcard model.");
197 module_param_array(pcm_devs, int, NULL, 0444);
198 MODULE_PARM_DESC(pcm_devs, "PCM devices # (0-4) for SHIELD Remote driver.");
199 module_param_array(pcm_substreams, int, NULL, 0444);
200 MODULE_PARM_DESC(pcm_substreams,
201         "PCM substreams # (1-128) for SHIELD Remote driver?");
202
203 static struct switch_dev shdr_mic_switch = {
204         .name = "shdr_mic",
205 };
206
207 /* Debug feature to save captured raw and decoded audio into buffers
208  * and make them available for reading from misc devices.
209  * It will record the last session only and only up to the buffer size.
210  * The recording is cleared on read.
211  */
212 #define DEBUG_WITH_MISC_DEVICE 0
213
214 /* Debug feature to trace audio packets being received */
215 #define DEBUG_AUDIO_RECEPTION 1
216
217 /* Debug feature to trace tx audio packets */
218 #define DEBUG_AUDIO_TX 0
219
220 /* Debug feature to trace HID reports we see */
221 #define DEBUG_HID_RAW_INPUT 0
222
223 #if (DEBUG_WITH_MISC_DEVICE == 1)
224 static int16_t large_pcm_buffer[1280*1024];
225 static int large_pcm_index;
226
227 static struct miscdevice pcm_dev_node;
228 static int pcm_dev_open(struct inode *inode, struct file *file)
229 {
230         /* nothing special to do here right now. */
231         return 0;
232 }
233
234 static ssize_t pcm_dev_read(struct file *file, char __user *buffer,
235                             size_t count, loff_t *ppos)
236 {
237         const uint8_t *data = (const uint8_t *)large_pcm_buffer;
238         size_t bytes_left = large_pcm_index * sizeof(int16_t) - *ppos;
239         if (count > bytes_left)
240                 count = bytes_left;
241         if (copy_to_user(buffer, &data[*ppos], count))
242                 return -EFAULT;
243
244         *ppos += count;
245         return count;
246 }
247
248 static const struct file_operations pcm_fops = {
249         .owner = THIS_MODULE,
250         .open = pcm_dev_open,
251         .llseek = no_llseek,
252         .read = pcm_dev_read,
253 };
254
255 static uint8_t raw_adpcm_buffer[640*1024];
256 static int raw_adpcm_index;
257 static struct miscdevice adpcm_dev_node;
258 static int adpcm_dev_open(struct inode *inode, struct file *file)
259 {
260         /* nothing special to do here right now. */
261         return 0;
262 }
263
264 static ssize_t adpcm_dev_read(struct file *file, char __user *buffer,
265                           size_t count, loff_t *ppos)
266 {
267         size_t bytes_left = raw_adpcm_index - *ppos;
268         if (count > bytes_left)
269                 count = bytes_left;
270         if (copy_to_user(buffer, &raw_adpcm_buffer[*ppos], count))
271                 return -EFAULT;
272
273         *ppos += count;
274         return count;
275 }
276
277 static const struct file_operations adpcm_fops = {
278         .owner = THIS_MODULE,
279         .open = adpcm_dev_open,
280         .llseek = no_llseek,
281         .read = adpcm_dev_read,
282 };
283
284 static uint8_t raw_msbc_buffer[640*1024];
285 static int raw_msbc_index;
286 static struct miscdevice msbc_dev_node;
287 static int msbc_dev_open(struct inode *inode, struct file *file)
288 {
289         /* nothing special to do here right now. */
290         return 0;
291 }
292
293 static ssize_t msbc_dev_read(struct file *file, char __user *buffer,
294                           size_t count, loff_t *ppos)
295 {
296         size_t bytes_left = raw_msbc_index - *ppos;
297         if (count > bytes_left)
298                 count = bytes_left;
299         if (copy_to_user(buffer, &raw_msbc_buffer[*ppos], count))
300                 return -EFAULT;
301
302         *ppos += count;
303         return count;
304 }
305
306 static const struct file_operations msbc_fops = {
307         .owner = THIS_MODULE,
308         .open = msbc_dev_open,
309         .llseek = no_llseek,
310         .read = msbc_dev_read,
311 };
312
313 #endif
314
315
316 struct simple_atomic_fifo {
317         /* Read and write cursors are modified by different threads. */
318         uint read_cursor;
319         uint write_cursor;
320         /* Size must be a power of two. */
321         uint size;
322         /* internal mask is 2*size - 1
323          * This allows us to tell the difference between full and empty. */
324         uint internal_mask;
325         uint external_mask;
326 };
327
328 struct snd_atvr {
329         struct snd_card *card;
330         struct snd_pcm *pcm;
331         struct snd_pcm_hardware pcm_hw;
332
333         uint32_t sample_rate;
334
335         uint previous_jiffies; /* Used to detect underflows. */
336         uint timeout_jiffies;
337         struct timer_list decoding_timer;
338         uint timer_state;
339         bool timer_enabled;
340         uint timer_callback_count;
341
342         int16_t peak_level;
343         struct simple_atomic_fifo fifo_controller;
344         struct fifo_packet *fifo_packet_buffer;
345
346         /* IMA/DVI ADPCM Decoder */
347         int pcm_value;
348         int step_index;
349         bool first_packet;
350
351         /* msbc decoder */
352         uint8_t msbc_frame_data[BYTES_PER_MSBC_FRAME];
353         int16_t audio_output[MAX_SAMPLES_PER_PACKET];
354         uint8_t packet_in_frame;
355         uint8_t seq_index;
356
357         /*
358          * Write_index is the circular buffer position.
359          * It is advanced by the BTLE thread after decoding.
360          * It is read by ALSA in snd_atvr_pcm_pointer().
361          * It is not declared volatile because that is not
362          * allowed in the Linux kernel.
363          */
364         uint32_t write_index;
365         uint32_t frames_per_buffer;
366         /* count frames generated so far in this period */
367         uint32_t frames_in_period;
368         int16_t *pcm_buffer;
369
370         /* pointer to hid device */
371         struct hid_device *hdev;
372         struct mutex hdev_lock;
373
374         int card_index; /* sound card index */
375         /* count of packets received from this device */
376         int packet_counter;
377         spinlock_t s_substream_lock;
378         bool pcm_stopped;
379 };
380
381 #define TS_HOSTCMD_REPORT_SIZE 33
382 #define JAR_HOSTCMD_REPORT_SIZE 19
383
384 static int atvr_mic_ctrl(struct hid_device *hdev, bool enable)
385 {
386         unsigned char report[TS_HOSTCMD_REPORT_SIZE] = {
387                 0x04, 0x0e, 0x00, 0x01,
388                 0x00, 0x00, 0x00, 0x00,
389                 0x00, 0x00, 0x00, 0x00,
390                 0x00, 0x00, 0x00, 0x00,
391                 0x00, 0x00, 0x00,
392                 };
393         int ret;
394         int report_size = JAR_HOSTCMD_REPORT_SIZE;
395
396         report[3] = enable ? 0x01 : 0x00;
397         hid_info(hdev, "%s remote mic\n", enable ? "enable" : "disable");
398
399         /* for pepper, send the message to userspace so that
400         ** gattservice can be used to send message to pepper.
401         ** this is to prevent concurrent mic ctrl msgs */
402
403         if (hdev->product == USB_DEVICE_ID_NVIDIA_PEPPER) {
404                 report[0] = 0x03;
405                 report[4] = 0x01;
406                 return hid_report_raw_event(hdev, 0, &report[0],
407                         report_size, 0);
408         }
409
410         if (hdev->product == USB_DEVICE_ID_NVIDIA_THUNDERSTRIKE)
411                 report_size = TS_HOSTCMD_REPORT_SIZE;
412
413         ret =  hdev->hid_output_raw_report(hdev, report, report_size,
414                                         HID_OUTPUT_REPORT);
415         if (ret < 0)
416                 hid_info(hdev, "failed to send mic ctrl report, err=%d\n", ret);
417         else
418                 ret = 0;
419
420         return ret;
421 }
422
423 int atvr_ts_sensor_set(struct hid_device *hdev, bool enable)
424 {
425         u8 report[TS_HOSTCMD_REPORT_SIZE] = { 0x04, 0x5a };
426         u8 sample_rate = 70;
427         int ret;
428
429         hid_info(hdev, "%s enable: %d\n",  __func__, enable);
430
431         if (enable) {
432                 report[3] = 0x01; /* set */
433                 report[4] = 0x01; /* enable */
434                 report[5] = 0x00; /* real data source, 0x01 for dummy */
435                 report[6] = sample_rate;
436                 hid_info(hdev, "enable ts sensor %dHz\n", sample_rate);
437         } else {
438                 report[3] = 0x01; /* set */
439                 hid_info(hdev, "disable ts sensor\n");
440         }
441
442         ret =  hdev->hid_output_raw_report(hdev, report,
443                         TS_HOSTCMD_REPORT_SIZE, HID_OUTPUT_REPORT);
444         if (ret < 0)
445                 hid_info(hdev, "failed to send ts sensor ctrl report, err=%d\n",
446                                 ret);
447         else
448                 ret = 0;
449
450         return ret;
451 }
452 EXPORT_SYMBOL(atvr_ts_sensor_set);
453
454 /***************************************************************************/
455 /************* Atomic FIFO *************************************************/
456 /***************************************************************************/
457 /*
458  * This FIFO is atomic if used by no more than 2 threads.
459  * One thread modifies the read cursor and the other
460  * thread modifies the write_cursor.
461  * Size and mask are not modified while being used.
462  *
463  * The read and write cursors range internally from 0 to (2*size)-1.
464  * This allows us to tell the difference between full and empty.
465  * When we get the cursors for external use we mask with size-1.
466  *
467  * Memory barriers required on SMP platforms.
468  */
469 static int atomic_fifo_init(struct simple_atomic_fifo *fifo_ptr, uint size)
470 {
471         /* Make sure size is a power of 2. */
472         if ((size & (size-1)) != 0) {
473                 pr_err("%s:%d - ERROR FIFO size = %d, not power of 2!\n",
474                         __func__, __LINE__, size);
475                 return -EINVAL;
476         }
477         fifo_ptr->read_cursor = 0;
478         fifo_ptr->write_cursor = 0;
479         fifo_ptr->size = size;
480         fifo_ptr->internal_mask = (size * 2) - 1;
481         fifo_ptr->external_mask = size - 1;
482         smp_wmb();
483         return 0;
484 }
485
486
487 static uint atomic_fifo_available_to_read(struct simple_atomic_fifo *fifo_ptr)
488 {
489         smp_rmb();
490         return (fifo_ptr->write_cursor - fifo_ptr->read_cursor)
491                         & fifo_ptr->internal_mask;
492 }
493
494 static uint atomic_fifo_available_to_write(struct simple_atomic_fifo *fifo_ptr)
495 {
496         smp_rmb();
497         return fifo_ptr->size - atomic_fifo_available_to_read(fifo_ptr);
498 }
499
500 static void atomic_fifo_advance_read(
501                 struct simple_atomic_fifo *fifo_ptr,
502                 uint frames)
503 {
504         smp_rmb();
505         BUG_ON(frames > atomic_fifo_available_to_read(fifo_ptr));
506         fifo_ptr->read_cursor = (fifo_ptr->read_cursor + frames)
507                         & fifo_ptr->internal_mask;
508         smp_wmb();
509 }
510
511 static void atomic_fifo_advance_write(
512                 struct simple_atomic_fifo *fifo_ptr,
513                 uint frames)
514 {
515         smp_rmb();
516         BUG_ON(frames > atomic_fifo_available_to_write(fifo_ptr));
517         fifo_ptr->write_cursor = (fifo_ptr->write_cursor + frames)
518                 & fifo_ptr->internal_mask;
519         smp_wmb();
520 }
521
522 static uint atomic_fifo_get_read_index(struct simple_atomic_fifo *fifo_ptr)
523 {
524         smp_rmb();
525         return fifo_ptr->read_cursor & fifo_ptr->external_mask;
526 }
527
528 static uint atomic_fifo_get_write_index(struct simple_atomic_fifo *fifo_ptr)
529 {
530         smp_rmb();
531         return fifo_ptr->write_cursor & fifo_ptr->external_mask;
532 }
533
534 /****************************************************************************/
535 static void snd_atvr_handle_frame_advance(
536                 struct snd_pcm_substream *substream, uint num_frames)
537 {
538         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
539         atvr_snd->frames_in_period += num_frames;
540         /* Tell ALSA if we have advanced by one or more periods. */
541         if (atvr_snd->frames_in_period >= substream->runtime->period_size) {
542                 snd_pcm_period_elapsed(substream);
543                 atvr_snd->frames_in_period %= substream->runtime->period_size;
544         }
545 }
546
547 static uint32_t snd_atvr_bump_write_index(
548                         struct snd_pcm_substream *substream,
549                         uint32_t num_samples)
550 {
551         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
552         uint32_t pos = atvr_snd->write_index;
553
554         /* Advance write position. */
555         pos += num_samples;
556         /* Wrap around at end of the circular buffer. */
557         pos %= atvr_snd->frames_per_buffer;
558         atvr_snd->write_index = pos;
559
560         snd_atvr_handle_frame_advance(substream, num_samples);
561
562         return pos;
563 }
564
565 /*
566  * Decode an IMA/DVI ADPCM packet and write the PCM data into a circular buffer.
567  * ADPCM is 4:1 16kHz@256kbps -> 16kHz@64kbps.
568  * ADPCM is 4:1 8kHz@128kbps -> 8kHz@32kbps.
569  */
570 static const int ima_index_table[16] = {
571         -1, -1, -1, -1, /* +0 - +3, decrease the step size */
572         2, 4, 6, 8,     /* +4 - +7, increase the step size */
573         -1, -1, -1, -1, /* -0 - -3, decrease the step size */
574         2, 4, 6, 8      /* -4 - -7, increase the step size */
575 };
576 static const int16_t ima_step_table[89] = {
577         7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
578         19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
579         50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
580         130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
581         337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
582         876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
583         2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
584         5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
585         15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
586 };
587
588 static void decode_adpcm_nibble(uint8_t nibble, struct snd_atvr *atvr_snd,
589                                 struct snd_pcm_substream *substream)
590 {
591         int step_index = atvr_snd->step_index;
592         int value = atvr_snd->pcm_value;
593         int step = ima_step_table[step_index];
594         int diff;
595
596         diff = step >> 3;
597         if (nibble & 1)
598                 diff += (step >> 2);
599         if (nibble & 2)
600                 diff += (step >> 1);
601         if (nibble & 4)
602                 diff += step;
603
604         if (nibble & 8) {
605                 value -= diff;
606                 if (value < -32768)
607                         value = -32768;
608         } else {
609                 value += diff;
610                 if (value > 32767)
611                         value = 32767;
612         }
613         atvr_snd->pcm_value = value;
614
615         /* copy to stream */
616         atvr_snd->pcm_buffer[atvr_snd->write_index] = value;
617 #if (DEBUG_WITH_MISC_DEVICE == 1)
618         if (large_pcm_index < ARRAY_SIZE(large_pcm_buffer))
619                 large_pcm_buffer[large_pcm_index++] = value;
620 #endif
621         snd_atvr_bump_write_index(substream, 1);
622         if (value > atvr_snd->peak_level)
623                 atvr_snd->peak_level = value;
624
625         /* update step_index */
626         step_index += ima_index_table[nibble];
627         /* clamp step_index */
628         if (step_index < 0)
629                 step_index = 0;
630         else if (step_index >= ARRAY_SIZE(ima_step_table))
631                 step_index = ARRAY_SIZE(ima_step_table) - 1;
632         atvr_snd->step_index = step_index;
633 }
634
635 static int snd_atvr_decode_adpcm_packet(
636                         struct snd_pcm_substream *substream,
637                         const uint8_t *adpcm_input,
638                         size_t num_bytes
639                         )
640 {
641         uint i;
642         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
643
644         /* Decode IMA ADPCM data to PCM. */
645         if (atvr_snd->first_packet) {
646                 /* the first two bytes of the first packet
647                  * is the unencoded first 16-bit sample, high
648                  * byte first.
649                  */
650                 int value = ((int)adpcm_input[0] << 8) | adpcm_input[1];
651                 pr_info("%s: first packet, initial value is %d (0x%x, 0x%x)\n",
652                         __func__, value, adpcm_input[0], adpcm_input[1]);
653                 atvr_snd->pcm_value = value;
654                 atvr_snd->pcm_buffer[atvr_snd->write_index] = value;
655 #if (DEBUG_WITH_MISC_DEVICE == 1)
656                 if (raw_adpcm_index < ARRAY_SIZE(raw_adpcm_buffer))
657                         raw_adpcm_buffer[raw_adpcm_index++] = adpcm_input[0];
658                 if (raw_adpcm_index < ARRAY_SIZE(raw_adpcm_buffer))
659                         raw_adpcm_buffer[raw_adpcm_index++] = adpcm_input[1];
660                 if (large_pcm_index < ARRAY_SIZE(large_pcm_buffer))
661                         large_pcm_buffer[large_pcm_index++] = value;
662 #endif
663                 snd_atvr_bump_write_index(substream, 1);
664                 atvr_snd->peak_level = value;
665                 atvr_snd->first_packet = false;
666                 i = 2;
667         } else {
668                 i = 0;
669         }
670
671         for (; i < num_bytes; i++) {
672                 uint8_t raw = adpcm_input[i];
673                 uint8_t nibble;
674
675 #if (DEBUG_WITH_MISC_DEVICE == 1)
676                 if (raw_adpcm_index < ARRAY_SIZE(raw_adpcm_buffer))
677                         raw_adpcm_buffer[raw_adpcm_index++] = raw;
678 #endif
679
680                 /* process first nibble */
681                 nibble = (raw >> 4) & 0x0f;
682                 decode_adpcm_nibble(nibble, atvr_snd, substream);
683
684                 /* process second nibble */
685                 nibble = raw & 0x0f;
686                 decode_adpcm_nibble(nibble, atvr_snd, substream);
687         }
688
689         return num_bytes * 2;
690 }
691
692 /*
693  * Decode an mSBC packet and write the PCM data into a circular buffer.
694  */
695 #define BLOCKS_PER_PACKET 15
696 #define NUM_BITS 26
697
698 static int snd_atvr_decode_msbc_packet(
699                         struct snd_pcm_substream *substream,
700                         const uint8_t *sbc_input,
701                         size_t num_bytes
702                         )
703 {
704         uint num_samples = 0;
705         uint remaining;
706         uint i;
707         uint32_t pos;
708         uint read_index;
709         uint write_index;
710         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
711         if (num_bytes < BYTES_PER_MSBC_FRAME) {
712                 /* assume we have a BLE frame that needs to be reconstructed */
713                 if (atvr_snd->packet_in_frame == 0) {
714                         if (sbc_input[0] !=
715                                 msbc_sequence_table[atvr_snd->seq_index]) {
716
717                                 snd_atvr_log(
718                                 "sequence_num err, 0x%02x != 0x%02x\n",
719                                 sbc_input[0],
720                                 msbc_sequence_table[atvr_snd->seq_index]);
721
722                                 return 0;
723                         }
724                         atvr_snd->seq_index++;
725                         if (atvr_snd->seq_index == NUM_SEQUENCES)
726                                 atvr_snd->seq_index = 0;
727
728                         /* subtract the sequence number */
729                         num_bytes--;
730                 }
731                 if (num_bytes !=
732                         msbc_bytes_in_packet[atvr_snd->packet_in_frame]) {
733
734                         pr_err(
735                           "%s: received %zd audio bytes but expected %d bytes\n",
736                           __func__, num_bytes,
737                           msbc_bytes_in_packet[atvr_snd->packet_in_frame]);
738
739                         return 0;
740                 }
741                 write_index =
742                         msbc_start_offset_in_buffer[atvr_snd->packet_in_frame];
743                 read_index =
744                         msbc_start_offset_in_packet[atvr_snd->packet_in_frame];
745                 memcpy(&atvr_snd->msbc_frame_data[write_index],
746                            &sbc_input[read_index],
747                            msbc_bytes_in_packet[atvr_snd->packet_in_frame]);
748                 atvr_snd->packet_in_frame++;
749                 if (atvr_snd->packet_in_frame < BLE_PACKETS_PER_MSBC_FRAME) {
750                         /* we don't have a complete mSBC frame yet,
751                          * just return */
752                         return 0;
753                 }
754                 /* reset for next mSBC frame */
755                 atvr_snd->packet_in_frame = 0;
756                 /* we have a complete mSBC frame, send it to the decoder */
757                 num_samples = sbc_decode(BLOCKS_PER_PACKET, NUM_BITS,
758                                          atvr_snd->msbc_frame_data,
759                                          BYTES_PER_MSBC_FRAME,
760                                          &atvr_snd->audio_output[0]);
761         } else {
762                 /* we have a complete mSBC frame, send it to the decoder */
763                 num_samples = sbc_decode(BLOCKS_PER_PACKET, NUM_BITS,
764                                          sbc_input,
765                                          BYTES_PER_MSBC_FRAME,
766                                          &atvr_snd->audio_output[0]);
767         }
768         /* Write PCM data to the buffer. */
769         pos = atvr_snd->write_index;
770         read_index = 0;
771         if ((pos + num_samples) > atvr_snd->frames_per_buffer) {
772                 for (i = pos; i < atvr_snd->frames_per_buffer; i++) {
773                         int16_t sample = atvr_snd->audio_output[read_index++];
774                         if (sample > atvr_snd->peak_level)
775                                 atvr_snd->peak_level = sample;
776                         atvr_snd->pcm_buffer[i] = sample;
777                 }
778
779                 remaining = (pos + num_samples) - atvr_snd->frames_per_buffer;
780                 for (i = 0; i < remaining; i++) {
781                         int16_t sample = atvr_snd->audio_output[read_index++];
782                         if (sample > atvr_snd->peak_level)
783                                 atvr_snd->peak_level = sample;
784                         atvr_snd->pcm_buffer[i] = sample;
785                 }
786
787         } else {
788                 for (i = 0; i < num_samples; i++) {
789                         int16_t sample = atvr_snd->audio_output[read_index++];
790                         if (sample > atvr_snd->peak_level)
791                                 atvr_snd->peak_level = sample;
792                         atvr_snd->pcm_buffer[i + pos] = sample;
793                 }
794         }
795
796         snd_atvr_bump_write_index(substream, num_samples);
797
798         return num_samples;
799 }
800
801 static int snd_atvr_alloc_audio_buffs(struct snd_atvr *atvr_snd)
802 {
803         int ret;
804
805         ret = atomic_fifo_init(&atvr_snd->fifo_controller,
806                                    MAX_PACKETS_PER_BUFFER);
807         if (ret)
808                 return ret;
809
810         /*
811          * Allocate the maximum buffer now and then just use part of it when
812          * the substream starts. We don't need DMA because it will just
813          * get written to by the BTLE code.
814          */
815
816         if (atvr_snd->pcm_buffer == NULL)
817                 atvr_snd->pcm_buffer = vmalloc(MAX_PCM_BUFFER_SIZE);
818         if (atvr_snd->pcm_buffer == NULL) {
819                 pr_err("%s:%d - ERROR PCM buffer allocation failed\n",
820                         __func__, __LINE__);
821                 return -ENOMEM;
822         }
823
824         if (atvr_snd->fifo_packet_buffer == NULL)
825                 atvr_snd->fifo_packet_buffer = vmalloc(MAX_BUFFER_SIZE);
826         if (atvr_snd->fifo_packet_buffer == NULL) {
827                 pr_err("%s:%d - ERROR buffer allocation failed\n",
828                         __func__, __LINE__);
829                 vfree(atvr_snd->pcm_buffer);
830                 atvr_snd->pcm_buffer = NULL;
831                 return -ENOMEM;
832         }
833
834         return 0;
835 }
836
837 static void snd_atvr_dealloc_audio_buffs(struct snd_atvr *atvr_snd)
838 {
839         vfree(atvr_snd->pcm_buffer);
840         vfree(atvr_snd->fifo_packet_buffer);
841 }
842
843 /**
844  * This is called by the event filter when it gets an audio packet
845  * from the AndroidTV remote.  It writes the packet into a FIFO
846  * which is then read and decoded by the timer task.
847  * @param input pointer to data to be decoded
848  * @param num_bytes how many bytes in raw_input
849  * @return number of samples decoded or negative error.
850  */
851 static void audio_dec(struct hid_device *hdev, const uint8_t *raw_input,
852                                                 int type, size_t num_bytes)
853 {
854         bool dropped_packet = false;
855         struct snd_pcm_substream *substream;
856         struct shdr_device *shdr_dev = hid_get_drvdata(hdev);
857         struct snd_card *shdr_card;
858         struct snd_atvr *atvr_snd;
859         int ret;
860
861         if (shdr_dev == NULL)
862                 return;
863         shdr_card = shdr_dev->shdr_card;
864
865         if (shdr_card == NULL)
866                 return;
867
868         atvr_snd = shdr_card->private_data;
869
870         if (atvr_snd != NULL && atvr_snd->pcm_stopped == false) {
871                 spin_lock(&atvr_snd->s_substream_lock);
872
873                 /* Write data to a FIFO for decoding by the timer task. */
874                 uint writable = atomic_fifo_available_to_write(
875                         &atvr_snd->fifo_controller);
876                 if (writable > 0) {
877                         uint fifo_index = atomic_fifo_get_write_index(
878                                 &atvr_snd->fifo_controller);
879                         struct fifo_packet *packet =
880                                 &atvr_snd->fifo_packet_buffer[fifo_index];
881                         packet->type = type;
882                         packet->num_bytes = (uint8_t)num_bytes;
883                         memcpy(packet->raw_data, raw_input, num_bytes);
884                         atomic_fifo_advance_write(
885                                 &atvr_snd->fifo_controller, 1);
886                 } else {
887                         dropped_packet = true;
888                         atvr_snd->pcm_stopped = true;
889                 }
890                 atvr_snd->packet_counter++;
891                 spin_unlock(&atvr_snd->s_substream_lock);
892         }
893
894         if (dropped_packet)
895                 snd_atvr_log("WARNING, raw audio packet dropped, FIFO full\n");
896 }
897
898 /*
899  * Note that smp_rmb() is called by snd_atvr_timer_callback()
900  * before calling this function.
901  *
902  * Reads:
903  *    jiffies
904  *    atvr_snd->previous_jiffies
905  * Writes:
906  *    atvr_snd->previous_jiffies
907  * Returns:
908  *    num_frames needed to catch up to the current time
909  */
910 static uint snd_atvr_calc_frame_advance(struct snd_atvr *atvr_snd)
911 {
912         /* Determine how much time passed. */
913         uint now_jiffies = jiffies;
914         uint elapsed_jiffies = now_jiffies - atvr_snd->previous_jiffies;
915         /* Convert jiffies to frames. */
916         uint frames_by_time = jiffies_to_msecs(elapsed_jiffies)
917                 * atvr_snd->sample_rate / 1000;
918         atvr_snd->previous_jiffies = now_jiffies;
919
920         /* Don't write more than one buffer full. */
921         if (frames_by_time > (atvr_snd->frames_per_buffer - 4))
922                 frames_by_time  = atvr_snd->frames_per_buffer - 4;
923
924         return frames_by_time;
925 }
926
927 /* Write zeros into the PCM buffer. */
928 static uint32_t snd_atvr_write_silence(struct snd_atvr *atvr_snd,
929                         uint32_t pos,
930                         int frames_to_advance)
931 {
932         /* Does it wrap? */
933         if ((pos + frames_to_advance) > atvr_snd->frames_per_buffer) {
934                 /* Write to end of buffer. */
935                 int16_t *destination = &atvr_snd->pcm_buffer[pos];
936                 size_t num_frames = atvr_snd->frames_per_buffer - pos;
937                 size_t num_bytes = num_frames * sizeof(int16_t);
938                 memset(destination, 0, num_bytes);
939                 /* Write from start of buffer to new pos. */
940                 destination = &atvr_snd->pcm_buffer[0];
941                 num_frames = frames_to_advance - num_frames;
942                 num_bytes = num_frames * sizeof(int16_t);
943                 memset(destination, 0, num_bytes);
944         } else {
945                 /* Write within the buffer. */
946                 int16_t *destination = &atvr_snd->pcm_buffer[pos];
947                 size_t num_bytes = frames_to_advance * sizeof(int16_t);
948                 memset(destination, 0, num_bytes);
949         }
950         /* Advance and wrap write_index */
951         pos += frames_to_advance;
952         pos %= atvr_snd->frames_per_buffer;
953         return pos;
954 }
955
956 /*
957  * Called by timer task to decode raw audio data from the FIFO into the PCM
958  * buffer.  Returns the number of packets decoded.
959  */
960 static uint snd_atvr_decode_from_fifo(struct snd_pcm_substream *substream)
961 {
962         uint i;
963         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
964         uint readable = atomic_fifo_available_to_read(
965                 &atvr_snd->fifo_controller);
966         for (i = 0; i < readable; i++) {
967                 uint fifo_index = atomic_fifo_get_read_index(
968                         &atvr_snd->fifo_controller);
969                 struct fifo_packet *packet =
970                         &atvr_snd->fifo_packet_buffer[fifo_index];
971                 if (packet->type == PACKET_TYPE_ADPCM) {
972                         snd_atvr_decode_adpcm_packet(substream,
973                                                      packet->raw_data,
974                                                      packet->num_bytes);
975                 } else if (packet->type == PACKET_TYPE_MSBC) {
976                         snd_atvr_decode_msbc_packet(substream,
977                                                          packet->raw_data,
978                                                          packet->num_bytes);
979                 } else {
980                         pr_err("Unknown packet type %d\n", packet->type);
981                 }
982
983                 atomic_fifo_advance_read(&atvr_snd->fifo_controller, 1);
984         }
985
986         return readable;
987 }
988
989 static int snd_atvr_schedule_timer(struct snd_pcm_substream *substream)
990 {
991         int ret;
992         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
993         uint msec_to_sleep = (substream->runtime->period_size * 1000)
994                         / atvr_snd->sample_rate;
995         uint jiffies_to_sleep = msecs_to_jiffies(msec_to_sleep);
996         if (jiffies_to_sleep < 2)
997                 jiffies_to_sleep = 2;
998         ret = mod_timer(&atvr_snd->decoding_timer, jiffies + jiffies_to_sleep);
999         if (ret < 0)
1000                 pr_err("%s:%d - ERROR in mod_timer, ret = %d\n",
1001                            __func__, __LINE__, ret);
1002         return ret;
1003 }
1004
1005 static void snd_atvr_timer_callback(unsigned long data)
1006 {
1007         uint readable;
1008         uint packets_read;
1009         bool need_silence = false;
1010         struct snd_pcm_substream *substream = (struct snd_pcm_substream *)data;
1011         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1012
1013         /* timer_enabled will be false when stopping a stream. */
1014         smp_rmb();
1015         if (!atvr_snd->timer_enabled)
1016                 return;
1017
1018         if (!spin_trylock(&atvr_snd->s_substream_lock)) {
1019                 pr_info("%s: trylock fail\n", __func__);
1020                 goto lock_err;
1021         }
1022
1023         atvr_snd->timer_callback_count++;
1024
1025         switch (atvr_snd->timer_state) {
1026         case TIMER_STATE_BEFORE_DECODE:
1027                 readable = atomic_fifo_available_to_read(
1028                                 &atvr_snd->fifo_controller);
1029                 if (readable > 0) {
1030                         atvr_snd->timer_state = TIMER_STATE_DURING_DECODE;
1031                         /* Fall through into next state. */
1032                 } else {
1033                         need_silence = true;
1034                         break;
1035                 }
1036
1037         case TIMER_STATE_DURING_DECODE:
1038                 packets_read = snd_atvr_decode_from_fifo(substream);
1039                 if (packets_read > 0) {
1040                         /* Defer timeout */
1041                         atvr_snd->previous_jiffies = jiffies;
1042                         break;
1043                 }
1044                 if (atvr_snd->pcm_stopped) {
1045                         atvr_snd->timer_state = TIMER_STATE_AFTER_DECODE;
1046                         /* Decoder died. Overflowed?
1047                          * Fall through into next state. */
1048                 } else if ((jiffies - atvr_snd->previous_jiffies) >
1049                            atvr_snd->timeout_jiffies) {
1050                         pr_debug("%s: audio UNDERFLOW detected\n", __func__);
1051                         /*  Not fatal.  Reset timeout. */
1052                         atvr_snd->previous_jiffies = jiffies;
1053                         break;
1054                 } else
1055                         break;
1056
1057         case TIMER_STATE_AFTER_DECODE:
1058                 need_silence = true;
1059                 break;
1060         }
1061
1062         /* Write silence before and after decoding. */
1063         if (need_silence) {
1064                 uint frames_to_silence = snd_atvr_calc_frame_advance(atvr_snd);
1065                 atvr_snd->write_index = snd_atvr_write_silence(
1066                                 atvr_snd,
1067                                 atvr_snd->write_index,
1068                                 frames_to_silence);
1069                 spin_unlock(&atvr_snd->s_substream_lock);
1070                 /* This can cause snd_atvr_pcm_trigger() to be called, which
1071                  * may try to stop the timer. */
1072                 snd_atvr_handle_frame_advance(substream, frames_to_silence);
1073         } else
1074                 spin_unlock(&atvr_snd->s_substream_lock);
1075
1076 lock_err:
1077         smp_rmb();
1078         if (atvr_snd->timer_enabled)
1079                 snd_atvr_schedule_timer(substream);
1080 }
1081
1082 static void snd_atvr_timer_start(struct snd_pcm_substream *substream)
1083 {
1084         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1085         atvr_snd->timer_enabled = true;
1086         atvr_snd->previous_jiffies = jiffies;
1087         atvr_snd->timeout_jiffies =
1088                 msecs_to_jiffies(SND_ATVR_RUNNING_TIMEOUT_MSEC);
1089         atvr_snd->timer_callback_count = 0;
1090         smp_wmb();
1091         setup_timer(&atvr_snd->decoding_timer,
1092                 snd_atvr_timer_callback,
1093                 (unsigned long)substream);
1094
1095         snd_atvr_schedule_timer(substream);
1096 }
1097
1098 static void snd_atvr_timer_stop(struct snd_pcm_substream *substream)
1099 {
1100         int ret;
1101         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1102
1103         /* Tell timer function not to reschedule itself if it runs. */
1104         atvr_snd->timer_enabled = false;
1105         smp_wmb();
1106         if (!in_interrupt()) {
1107                 /*
1108                  * The timer callback could call snd_pcm_period_elapsed()
1109                  * which need snd_pcm_stream_lock_irqsave() on the substream,
1110                  * while a snd_pcm_suspend() who already holds the same lock
1111                  * eventually comes here and wait the timer to finish, forming
1112                  * a deadlock.
1113                  *
1114                  * We could temporarily give up the lock and relock later.
1115                  * However, that could break the original purpose of the lock.
1116                  * Thus we just try delete the timer but do not block.
1117                  * Instead, we check if previous timer is finished in
1118                  * snd_atvr_timer_start() where timing has less stress.
1119                  * In the rare case it is still not finished, we return EAGAIN
1120                  * and let userspace try again later.
1121                  */
1122                 ret = try_to_del_timer_sync(&atvr_snd->decoding_timer);
1123                 if (ret < 0)
1124                         pr_err("%s:%d - ERROR del_timer_sync failed, %d\n",
1125                                 __func__, __LINE__, ret);
1126         }
1127         /*
1128          * Else if we are in an interrupt then we are being called from the
1129          * middle of the snd_atvr_timer_callback(). The timer will not get
1130          * rescheduled because atvr_snd->timer_enabled will be false
1131          * at the end of snd_atvr_timer_callback().
1132          * We do not need to "delete" the timer.
1133          * The del_timer functions just cancel pending timers.
1134          * There are no resources that need to be cleaned up.
1135          */
1136 }
1137
1138 /* ===================================================================== */
1139 /*
1140  * PCM interface
1141  */
1142
1143 static int snd_atvr_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
1144 {
1145         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1146         switch (cmd) {
1147         case SNDRV_PCM_TRIGGER_START:
1148         case SNDRV_PCM_TRIGGER_RESUME:
1149 #if (DEBUG_AUDIO_TX == 1)
1150                 snd_atvr_log("%s starting audio\n", __func__);
1151 #endif
1152
1153 #if (DEBUG_WITH_MISC_DEVICE == 1)
1154                 large_pcm_index = 0;
1155                 raw_adpcm_index = 0;
1156                 raw_msbc_index = 0;
1157 #endif
1158                 atvr_snd->packet_counter = 0;
1159                 atvr_snd->peak_level = -32768;
1160                 atvr_snd->previous_jiffies = jiffies;
1161                 atvr_snd->timer_state = TIMER_STATE_BEFORE_DECODE;
1162
1163                 /* ADPCM decoder state */
1164                 atvr_snd->step_index = 0;
1165                 atvr_snd->pcm_value = 0;
1166                 atvr_snd->first_packet = true;
1167
1168                 /* msbc decoder */
1169                 atvr_snd->packet_in_frame = 0;
1170                 atvr_snd->seq_index = 0;
1171
1172                 atvr_snd->pcm_stopped = false;
1173                 snd_atvr_timer_start(substream);
1174                 smp_wmb(); /* so other thread will see s_substream_for_btle */
1175                 return 0;
1176
1177         case SNDRV_PCM_TRIGGER_STOP:
1178         case SNDRV_PCM_TRIGGER_SUSPEND:
1179 #if (DEBUG_AUDIO_TX == 1)
1180                 snd_atvr_log("%s stopping audio, peak = %d, # packets = %d\n",
1181                         __func__, atvr_snd->peak_level,
1182                         atvr_snd->packet_counter);
1183 #endif
1184                 atvr_snd->pcm_stopped = true;
1185                 smp_wmb(); /* so other thread will see s_substream_for_btle */
1186                 snd_atvr_timer_stop(substream);
1187                 return 0;
1188         }
1189         return -EINVAL;
1190 }
1191
1192 static int snd_atvr_pcm_prepare(struct snd_pcm_substream *substream)
1193 {
1194         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1195         struct snd_pcm_runtime *runtime = substream->runtime;
1196 #if (DEBUG_AUDIO_TX == 1)
1197         snd_atvr_log("%s, rate = %d, period_size = %d, buffer_size = %d\n",
1198                 __func__, (int) runtime->rate,
1199                 (int) runtime->period_size,
1200                 (int) runtime->buffer_size);
1201 #endif
1202         if (runtime->buffer_size > MAX_FRAMES_PER_BUFFER)
1203                 return -EINVAL;
1204
1205         atvr_snd->sample_rate = runtime->rate;
1206         atvr_snd->frames_per_buffer = runtime->buffer_size;
1207
1208         return 0; /* TODO - review */
1209 }
1210
1211 static struct snd_pcm_hardware atvr_pcm_hardware = {
1212         .info =                 (SNDRV_PCM_INFO_MMAP |
1213                                  SNDRV_PCM_INFO_INTERLEAVED |
1214                                  SNDRV_PCM_INFO_RESUME |
1215                                  SNDRV_PCM_INFO_MMAP_VALID),
1216         .formats =              USE_FORMATS,
1217         .rates =                USE_RATES_MASK,
1218         .rate_min =             USE_RATE_MIN,
1219         .rate_max =             USE_RATE_MAX,
1220         .channels_min =         USE_CHANNELS_MIN,
1221         .channels_max =         USE_CHANNELS_MAX,
1222         .buffer_bytes_max =     MAX_PCM_BUFFER_SIZE,
1223         .period_bytes_min =     MIN_PERIOD_SIZE,
1224         .period_bytes_max =     MAX_PERIOD_SIZE,
1225         .periods_min =          USE_PERIODS_MIN,
1226         .periods_max =          USE_PERIODS_MAX,
1227         .fifo_size =            0,
1228 };
1229
1230 static struct snd_pcm_hardware atvr_pcm_hardware_pepper = {
1231         .info =                 (SNDRV_PCM_INFO_MMAP |
1232                                  SNDRV_PCM_INFO_INTERLEAVED |
1233                                  SNDRV_PCM_INFO_RESUME |
1234                                  SNDRV_PCM_INFO_MMAP_VALID),
1235         .formats =              USE_FORMATS,
1236         .rates =                USE_RATES_MASK_PEPPER,
1237         .rate_min =             USE_RATE_MIN,
1238         .rate_max =             USE_RATE_MAX_PEPPER,
1239         .channels_min =         USE_CHANNELS_MIN,
1240         .channels_max =         USE_CHANNELS_MAX_PEPPER,
1241         .buffer_bytes_max =     MAX_PCM_BUFFER_SIZE,
1242         .period_bytes_min =     MIN_PERIOD_SIZE,
1243         .period_bytes_max =     MAX_PERIOD_SIZE,
1244         .periods_min =          USE_PERIODS_MIN,
1245         .periods_max =          USE_PERIODS_MAX,
1246         .fifo_size =            0,
1247 };
1248
1249 static int snd_atvr_pcm_hw_params(struct snd_pcm_substream *substream,
1250                                         struct snd_pcm_hw_params *hw_params)
1251 {
1252         int ret = 0;
1253         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1254
1255         atvr_snd->write_index = 0;
1256         smp_wmb();
1257
1258         return ret;
1259 }
1260
1261 static int snd_atvr_pcm_hw_free(struct snd_pcm_substream *substream)
1262 {
1263         return 0;
1264 }
1265
1266 static int snd_atvr_pcm_open(struct snd_pcm_substream *substream)
1267 {
1268         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1269         struct snd_pcm_runtime *runtime = substream->runtime;
1270         int ret;
1271
1272         mutex_lock(&atvr_snd->hdev_lock);
1273         if (atvr_snd->hdev == NULL) {
1274                 pr_warn("%s: remote is not ready\n", __func__);
1275                 mutex_unlock(&atvr_snd->hdev_lock);
1276                 return -EAGAIN;
1277         }
1278
1279         ret = atvr_mic_ctrl(atvr_snd->hdev, true);
1280         mutex_unlock(&atvr_snd->hdev_lock);
1281
1282         if (ret)
1283                 return ret;
1284
1285         runtime->hw = atvr_snd->pcm_hw;
1286         if (substream->pcm->device & 1) {
1287                 runtime->hw.info &= ~SNDRV_PCM_INFO_INTERLEAVED;
1288                 runtime->hw.info |= SNDRV_PCM_INFO_NONINTERLEAVED;
1289         }
1290         if (substream->pcm->device & 2)
1291                 runtime->hw.info &= ~(SNDRV_PCM_INFO_MMAP
1292                         | SNDRV_PCM_INFO_MMAP_VALID);
1293
1294         snd_atvr_log("%s, built %s %s\n", __func__, __DATE__, __TIME__);
1295
1296         return ret;
1297 }
1298
1299 static int snd_atvr_pcm_close(struct snd_pcm_substream *substream)
1300 {
1301         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1302         int ret;
1303
1304         /* Make sure the timer is not running */
1305         if (atvr_snd->timer_enabled)
1306                 snd_atvr_timer_stop(substream);
1307
1308         if (atvr_snd->timer_callback_count > 0)
1309                 snd_atvr_log("processed %d packets in %d timer callbacks\n",
1310                         atvr_snd->packet_counter,
1311                         atvr_snd->timer_callback_count);
1312
1313         ret = atomic_fifo_init(&atvr_snd->fifo_controller,
1314                                    MAX_PACKETS_PER_BUFFER);
1315         if (ret)
1316                 return ret;
1317
1318         mutex_lock(&atvr_snd->hdev_lock);
1319         if (atvr_snd->hdev)
1320                 atvr_mic_ctrl(atvr_snd->hdev, false);
1321         else
1322                 pr_warn("%s: unexpected remote connection lost\n", __func__);
1323         mutex_unlock(&atvr_snd->hdev_lock);
1324
1325         return 0;
1326 }
1327
1328 static snd_pcm_uframes_t snd_atvr_pcm_pointer(
1329                 struct snd_pcm_substream *substream)
1330 {
1331         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1332         /* write_index is written by another driver thread */
1333         smp_rmb();
1334         return atvr_snd->write_index;
1335 }
1336
1337 static int snd_atvr_pcm_copy(struct snd_pcm_substream *substream,
1338                           int channel, snd_pcm_uframes_t pos,
1339                           void __user *dst, snd_pcm_uframes_t count)
1340 {
1341         struct snd_atvr *atvr_snd = snd_pcm_substream_chip(substream);
1342
1343         /* TODO Needs to be modified if we support more than 1 channel. */
1344         /*
1345          * Copy from PCM buffer to user memory.
1346          * Are we reading past the end of the buffer?
1347          */
1348         if ((pos + count) > atvr_snd->frames_per_buffer) {
1349                 const int16_t *source = &atvr_snd->pcm_buffer[pos];
1350                 int16_t __user *destination = dst;
1351                 size_t num_frames = atvr_snd->frames_per_buffer - pos;
1352                 size_t num_bytes = num_frames * sizeof(int16_t);
1353                 copy_to_user(destination, source, num_bytes);
1354
1355                 source = &atvr_snd->pcm_buffer[0];
1356                 destination += num_frames;
1357                 num_frames = count - num_frames;
1358                 num_bytes = num_frames * sizeof(int16_t);
1359                 copy_to_user(destination, source, num_bytes);
1360         } else {
1361                 const int16_t *source = &atvr_snd->pcm_buffer[pos];
1362                 int16_t __user *destination = dst;
1363                 size_t num_bytes = count * sizeof(int16_t);
1364                 copy_to_user(destination, source, num_bytes);
1365         }
1366
1367         return 0;
1368 }
1369
1370 static int snd_atvr_pcm_silence(struct snd_pcm_substream *substream,
1371                                 int channel, snd_pcm_uframes_t pos,
1372                                 snd_pcm_uframes_t count)
1373 {
1374         return 0; /* Do nothing. Only used by output? */
1375 }
1376
1377 static struct snd_pcm_ops snd_atvr_pcm_ops_no_buf = {
1378         .open =         snd_atvr_pcm_open,
1379         .close =        snd_atvr_pcm_close,
1380         .ioctl =        snd_pcm_lib_ioctl,
1381         .hw_params =    snd_atvr_pcm_hw_params,
1382         .hw_free =      snd_atvr_pcm_hw_free,
1383         .prepare =      snd_atvr_pcm_prepare,
1384         .trigger =      snd_atvr_pcm_trigger,
1385         .pointer =      snd_atvr_pcm_pointer,
1386         .copy =         snd_atvr_pcm_copy,
1387         .silence =      snd_atvr_pcm_silence,
1388 };
1389
1390 static int snd_card_atvr_pcm(struct snd_atvr *atvr_snd,
1391                              int device,
1392                              int substreams)
1393 {
1394         struct snd_pcm *pcm;
1395         struct snd_pcm_ops *ops;
1396         int err;
1397
1398         err = snd_pcm_new(atvr_snd->card, "SHDR PCM", device,
1399                           0, /* no playback substreams */
1400                           1, /* 1 capture substream */
1401                           &pcm);
1402         if (err < 0)
1403                 return err;
1404         atvr_snd->pcm = pcm;
1405         ops = &snd_atvr_pcm_ops_no_buf;
1406         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, ops);
1407         pcm->private_data = atvr_snd;
1408         pcm->info_flags = 0;
1409         strcpy(pcm->name, "SHDR PCM");
1410
1411         return 0;
1412 }
1413
1414 static int atvr_snd_initialize(struct hid_device *hdev,
1415                         struct snd_card **p_shdr_card)
1416 {
1417         struct snd_atvr *atvr_snd;
1418         struct snd_card *shdr_card;
1419         int err;
1420         int i;
1421         int dev = 0;
1422         struct hid_input *hidinput = list_first_entry(&hdev->inputs,
1423                         struct hid_input, list);
1424         struct input_dev *shdr_input_dev = hidinput->input;
1425
1426         while (dev < SNDRV_CARDS && cards_in_use[dev])
1427                 dev++;
1428
1429         if (dev >= SNDRV_CARDS)
1430                 return -ENODEV;
1431         if (!enable[dev]) {
1432                 return -ENOENT;
1433         }
1434         cards_in_use[dev] = true;
1435
1436         err = snd_card_create(index[dev], id[dev], THIS_MODULE,
1437                               sizeof(struct snd_atvr), &shdr_card);
1438         if (err < 0) {
1439                 pr_err("%s: snd_card_create() returned err %d\n",
1440                        __func__, err);
1441                 cards_in_use[dev] = false;
1442                 return err;
1443         }
1444         *p_shdr_card = shdr_card;
1445         atvr_snd = shdr_card->private_data;
1446         atvr_snd->card = shdr_card;
1447         atvr_snd->card_index = dev;
1448         mutex_init(&atvr_snd->hdev_lock);
1449         spin_lock_init(&atvr_snd->s_substream_lock);
1450         /* dummy initialization */
1451         setup_timer(&atvr_snd->decoding_timer,
1452                 snd_atvr_timer_callback, 0);
1453
1454         for (i = 0; i < MAX_PCM_DEVICES && i < pcm_devs[dev]; i++) {
1455                 if (pcm_substreams[dev] < 1)
1456                         pcm_substreams[dev] = 1;
1457                 if (pcm_substreams[dev] > MAX_PCM_SUBSTREAMS)
1458                         pcm_substreams[dev] = MAX_PCM_SUBSTREAMS;
1459                 err = snd_card_atvr_pcm(atvr_snd, i, pcm_substreams[dev]);
1460                 if (err < 0) {
1461                         pr_err("%s: snd_card_atvr_pcm() returned err %d\n",
1462                                __func__, err);
1463                         goto __nodev;
1464                 }
1465         }
1466
1467         if (hdev->product == USB_DEVICE_ID_NVIDIA_PEPPER)
1468                 atvr_snd->pcm_hw = atvr_pcm_hardware_pepper;
1469         else
1470                 atvr_snd->pcm_hw = atvr_pcm_hardware;
1471
1472         /* Alloc pcm buffers */
1473         err = snd_atvr_alloc_audio_buffs(atvr_snd);
1474         if (err)
1475                 goto __nodev;
1476
1477         strcpy(shdr_card->driver, "SHIELD Remote Audio");
1478         strcpy(shdr_card->shortname, "SHDRAudio");
1479         sprintf(shdr_card->longname, "SHIELD Remote %i audio", dev + 1);
1480
1481         err = snd_card_register(shdr_card);
1482
1483         if (err)
1484                 goto __nodev;
1485
1486         err = sysfs_create_link(&(hdev->dev.kobj), &(shdr_card->card_dev->kobj),
1487                         "sound");
1488
1489         if (err < 0)
1490                 dev_warn(&hdev->dev, "Can't create sound sysfs link\n");
1491
1492         err = sysfs_create_link(&(hdev->dev.kobj), &(shdr_input_dev->dev.kobj),
1493                         "input");
1494
1495         if (err < 0)
1496                 dev_warn(&hdev->dev, "Can't create input sysfs link\n");
1497         return 0;
1498
1499 __nodev:
1500         snd_card_free(shdr_card);
1501         *p_shdr_card = NULL;
1502         cards_in_use[dev] = false;
1503         return err;
1504 }
1505
1506 #define JAR_BUTTON_REPORT_ID    0x01
1507 #define JAR_BUTTON_REPORT_SIZE  3
1508
1509 #define JAR_AUDIO_REPORT_ID     0xFD
1510 #define JAR_AUDIO_REPORT_SIZE   233
1511 #define JAR_AUDIO_FRAME_SIZE    0x3A
1512
1513 #define TS_BUTTON_REPORT_SIZE 19
1514
1515 static int atvr_jarvis_break_events(struct hid_device *hdev,
1516                                     struct hid_report *report,
1517                                     u8 *data, int size)
1518 {
1519         unsigned int button_report_id = JAR_BUTTON_REPORT_ID;
1520         unsigned int button_report_size = JAR_BUTTON_REPORT_SIZE;
1521         unsigned int audio_report_id = JAR_AUDIO_REPORT_ID;
1522         unsigned int audio_report_size = JAR_AUDIO_REPORT_SIZE;
1523
1524         /* breaks events apart if they are not proper */
1525         pr_debug("%s: packet 0x%02x#%i\n", __func__, data[0], size);
1526
1527         /*
1528          * break the ts events also similarly,
1529          * just account for size differences
1530          */
1531         if (hdev->product == USB_DEVICE_ID_NVIDIA_THUNDERSTRIKE)
1532                 button_report_size = TS_HOSTCMD_REPORT_SIZE;
1533
1534         if (!((report->id == button_report_id &&
1535                size >= button_report_size) ||
1536               (report->id == audio_report_id &&
1537                size >= audio_report_size)))
1538                 return 0;
1539
1540         /*
1541          * This is a WAR for a CSR issue at the moment
1542          * (packets get put together)
1543          */
1544         while (size > 0) {
1545                 int amount = 0;
1546                 if ((data[0] == button_report_id) &&
1547                     (size >= button_report_size)) {
1548                         amount = button_report_size;
1549                         hid_report_raw_event(hdev, 0, data,
1550                                              amount, 0);
1551                 } else if ((data[0] == audio_report_id) &&
1552                            (size >= audio_report_size)) {
1553                         u8 *frame = &data[1];
1554                         amount = audio_report_size;
1555                         while (frame < &data[JAR_AUDIO_REPORT_SIZE]) {
1556                                 audio_dec(hdev, &frame[0], PACKET_TYPE_MSBC,
1557                                           JAR_AUDIO_FRAME_SIZE);
1558                                 frame = &frame[JAR_AUDIO_FRAME_SIZE];
1559                         }
1560                 } else {
1561                         pr_info("%s: unknown id or broken packet 0x%02x#%i\n",
1562                                 __func__, data[0], size);
1563                         break;
1564                 }
1565                 /* skip over the HID_DATP indicator */
1566                 if (size > amount)
1567                         amount++;
1568                 data += amount;
1569                 size -= amount;
1570         }
1571         return 1;
1572 }
1573
1574 static int atvr_raw_event(struct hid_device *hdev, struct hid_report *report,
1575         u8 *data, int size)
1576 {
1577         struct shdr_device *shdr_dev = hid_get_drvdata(hdev);
1578         struct snd_card *shdr_card = shdr_dev->shdr_card;
1579         struct snd_atvr *atvr_snd;
1580         void *debug_info;
1581
1582         if (shdr_card == NULL)
1583                 return 0;
1584
1585         atvr_snd = shdr_card->private_data;
1586
1587 #if (DEBUG_HID_RAW_INPUT == 1)
1588         pr_info("%s: report->id = 0x%x, size = %d\n",
1589                 __func__, report->id, size);
1590         if (size <= 22) {
1591                 u32 i;
1592                 for (i = 0; i < size; i++)
1593                         pr_info("data[%d] = 0x%02x\n", i, data[i]);
1594         }
1595 #endif
1596
1597         /* WAR for CSR issue */
1598         if (atvr_jarvis_break_events(hdev, report, data, size))
1599                 return 1;
1600
1601         if (report->id == ADPCM_AUDIO_REPORT_ID) {
1602                 /* send the data, minus the report-id in data[0], to the
1603                  * alsa audio decoder driver for ADPCM
1604                  */
1605 #if (DEBUG_AUDIO_RECEPTION == 1)
1606                 if (atvr_snd->packet_counter == 0)
1607                         snd_atvr_log("first ADPCM packet received\n");
1608 #endif
1609                 audio_dec(hdev, &data[1], PACKET_TYPE_ADPCM, size - 1);
1610                 /* we've handled the event */
1611                 return 1;
1612         } else if (report->id == MSBC_AUDIO1_REPORT_ID) {
1613                 /* first do special case check if there is any
1614                  * keyCode active in this report.  if so, we
1615                  * generate the same keyCode but on report 2, which
1616                  * is where normal keys are reported.  the keycode
1617                  * is being sent in the audio packet to save packets
1618                  * and over the air bandwidth.
1619                  */
1620                 if (data[2] & KEYCODE_PRESENT_IN_AUDIO_PACKET_FLAG) {
1621                         u8 key_data[3];
1622                         key_data[0] = INPUT_REPORT_ID;
1623                         key_data[1] = data[1]; /* low byte */
1624                         key_data[2] = data[2]; /* high byte */
1625                         key_data[2] &= ~KEYCODE_PRESENT_IN_AUDIO_PACKET_FLAG;
1626                         hid_report_raw_event(hdev, 0, key_data,
1627                                              sizeof(key_data), 0);
1628                         pr_info("%s: generated hid keycode 0x%02x%02x\n",
1629                                 __func__, key_data[2], key_data[1]);
1630                 }
1631
1632                 /* send the audio part to the alsa audio decoder for mSBC */
1633 #if (DEBUG_AUDIO_RECEPTION == 1)
1634                 if (atvr_snd->packet_counter == 0)
1635                         snd_atvr_log("first MSBC packet received\n");
1636 #endif
1637                 /* strip the one byte report id and two byte keycode field */
1638                 audio_dec(hdev, &data[1 + 2], PACKET_TYPE_MSBC, size - 1 - 2);
1639                 /* we've handled the event */
1640                 return 1;
1641         } else if ((report->id == MSBC_AUDIO2_REPORT_ID) ||
1642                    (report->id == MSBC_AUDIO3_REPORT_ID)) {
1643                 /* strip the one byte report id */
1644                 audio_dec(hdev, &data[1], PACKET_TYPE_MSBC, size - 1);
1645                 /* we've handled the event */
1646                 return 1;
1647         } else if (report->id == INPUT_EVT_INTR_DATA_ID) {
1648                 /*Debug infor sent by device*/
1649                 debug_info = kmalloc(sizeof(u8) * size + 1, GFP_ATOMIC);
1650                 if (!debug_info) {
1651                         pr_err("%s, Kmalloc failed!", __func__);
1652                         return -ENOMEM;
1653                 }
1654                 *((char *)(debug_info + size)) = '\0';
1655                 memcpy(debug_info, data, size);
1656                 pr_info("Report ID 10: PID: %d, report %s", hdev->product,
1657                         (char *)debug_info);
1658                 kfree(debug_info);
1659         } else if (hdev->product == USB_DEVICE_ID_NVIDIA_THUNDERSTRIKE &&
1660                         (report->id == SENSOR_REPORT_ID ||
1661                         report->id == SENSOR_REPORT_ID_SYN ||
1662                         report->id == SENSOR_REPORT_ID_COMBINED) &&
1663                         shdr_dev->snsr_fns && shdr_dev->snsr_fns->recv) {
1664                 shdr_dev->snsr_fns->recv(shdr_dev->st, data, size);
1665                 /* TODO: ret check */
1666                 if (report->id == SENSOR_REPORT_ID_COMBINED)
1667                         hid_report_raw_event(hdev, 0, data,
1668                                              TS_BUTTON_REPORT_SIZE, 0);
1669                 /* we've handled the event */
1670                 return 1;
1671         }
1672         /* let the event through for regular input processing */
1673         return 0;
1674 }
1675
1676 static int atvr_probe(struct hid_device *hdev, const struct hid_device_id *id)
1677 {
1678         struct snd_atvr *atvr_snd;
1679         int ret;
1680         struct shdr_device *shdr_dev;
1681         struct snd_card *shdr_card;
1682         struct tsfw_icm20628_state *st = NULL;
1683
1684         shdr_dev = kzalloc(sizeof(*shdr_dev), GFP_KERNEL);
1685         if (shdr_dev == NULL) {
1686                 hid_err(hdev, "can't alloc descriptor\n");
1687                 return -ENOMEM;
1688         }
1689         /* since vendor/product id filter doesn't work yet, because
1690          * Bluedroid is unable to get the vendor/product id, we
1691          * have to filter on name
1692          */
1693         pr_info("%s: name = %s, vendor_id = %d, product_id = %d, num %d\n",
1694                 __func__, hdev->name, hdev->vendor, hdev->product, num_remotes);
1695
1696         pr_info("%s: Found target remote %s\n", __func__, hdev->name);
1697
1698         ret = hid_parse(hdev);
1699         if (ret) {
1700                 hid_err(hdev, "hid parse failed\n");
1701                 goto err_parse;
1702         }
1703
1704         ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
1705         if (ret) {
1706                 hid_err(hdev, "hw start failed\n");
1707                 goto err_start;
1708         }
1709
1710         /*
1711          * Lazy-creation of the soundcard, and enable the wired headset
1712          * only then to avoid race conditions on subsequent connections.
1713          * AudioService.java delays enabling the output
1714          */
1715         mutex_lock(&snd_cards_lock);
1716         ret = atvr_snd_initialize(hdev, &shdr_card);
1717         if (ret)
1718                 goto err_stop;
1719
1720         /*
1721          * hdev pointer is not guaranteed to be the same thus following
1722          * stuff has to be updated every time.
1723          */
1724         shdr_dev->shdr_card = shdr_card;
1725         hid_set_drvdata(hdev, shdr_dev);
1726         atvr_snd = shdr_card->private_data;
1727         atvr_snd->hdev = hdev;
1728         snd_card_set_dev(shdr_card, &hdev->dev);
1729
1730         switch_set_state(&shdr_mic_switch, true);
1731
1732         pr_info("%s: remotes count %d->%d\n", __func__,
1733                 num_remotes, num_remotes+1);
1734         num_remotes++;
1735
1736         mutex_unlock(&snd_cards_lock);
1737
1738         if (hdev->product == USB_DEVICE_ID_NVIDIA_THUNDERSTRIKE)
1739                 shdr_dev->snsr_fns = tsfw_icm20628_fns();
1740         if (shdr_dev->snsr_fns && shdr_dev->snsr_fns->probe)
1741                 shdr_dev->snsr_fns->probe(hdev, &st);
1742         /* TODO: ret check */
1743         shdr_dev->st = st;
1744
1745         return 0;
1746 err_stop:
1747         hid_hw_stop(hdev);
1748         mutex_unlock(&snd_cards_lock);
1749 err_start:
1750 err_parse:
1751         kfree(shdr_dev);
1752         return ret;
1753 }
1754
1755 static void atvr_remove(struct hid_device *hdev)
1756 {
1757         unsigned long flags;
1758         struct shdr_device *shdr_dev = hid_get_drvdata(hdev);
1759         struct snd_card *shdr_card = shdr_dev->shdr_card;
1760         struct snd_atvr *atvr_snd;
1761
1762         if (shdr_card == NULL)
1763                 return -EIO;
1764
1765         if (shdr_dev->snsr_fns && shdr_dev->snsr_fns->remove)
1766                 shdr_dev->snsr_fns->remove(shdr_dev->st);
1767         /* TODO: ret check */
1768
1769         mutex_lock(&snd_cards_lock);
1770         atvr_snd = shdr_card->private_data;
1771         mutex_lock(&atvr_snd->hdev_lock);
1772         atvr_snd->hdev = NULL;
1773         mutex_unlock(&atvr_snd->hdev_lock);
1774
1775         hid_set_drvdata(hdev, NULL);
1776         hid_hw_stop(hdev);
1777         pr_info("%s: hdev->name = %s removed, num %d->%d\n",
1778                 __func__, hdev->name, num_remotes, num_remotes - 1);
1779         num_remotes--;
1780
1781         if (num_remotes == 0)
1782                 switch_set_state(&shdr_mic_switch, false);
1783
1784         cards_in_use[atvr_snd->card_index] = false;
1785         snd_atvr_dealloc_audio_buffs(atvr_snd);
1786         mutex_destroy(&atvr_snd->hdev_lock);
1787         snd_card_disconnect(shdr_card);
1788         snd_card_free_when_closed(shdr_card);
1789         kfree(shdr_dev);
1790         mutex_unlock(&snd_cards_lock);
1791 }
1792
1793 static const struct hid_device_id atvr_devices[] = {
1794         {HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NVIDIA,
1795                               USB_DEVICE_ID_NVIDIA_JARVIS)},
1796         {HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NVIDIA,
1797                               USB_DEVICE_ID_NVIDIA_PEPPER)},
1798         {HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NVIDIA,
1799                               USB_DEVICE_ID_NVIDIA_THUNDERSTRIKE)},
1800         {HID_USB_DEVICE(USB_VENDOR_ID_NVIDIA,
1801                               USB_DEVICE_ID_NVIDIA_THUNDERSTRIKE)},
1802         { }
1803 };
1804 MODULE_DEVICE_TABLE(hid, atvr_devices);
1805
1806 static struct hid_driver atvr_driver = {
1807         .name = "Jarvis",
1808         .id_table = atvr_devices,
1809         .raw_event = atvr_raw_event,
1810         .probe = atvr_probe,
1811         .remove = atvr_remove,
1812 };
1813
1814 static int atvr_init(void)
1815 {
1816         int ret;
1817
1818         mutex_init(&snd_cards_lock);
1819         ret = switch_dev_register(&shdr_mic_switch);
1820         if (ret)
1821                 pr_err("%s: failed to create shdr_mic_switch\n", __func__);
1822
1823         ret = hid_register_driver(&atvr_driver);
1824         if (ret)
1825                 pr_err("%s: can't register SHIELD Remote driver\n",
1826                         __func__);
1827
1828 #if (DEBUG_WITH_MISC_DEVICE == 1)
1829         pcm_dev_node.minor = MISC_DYNAMIC_MINOR;
1830         pcm_dev_node.name = "snd_atvr_pcm";
1831         pcm_dev_node.fops = &pcm_fops;
1832         ret = misc_register(&pcm_dev_node);
1833         if (ret)
1834                 pr_err("%s: failed to create pcm misc device %d\n",
1835                        __func__, ret);
1836         else
1837                 pr_info("%s: succeeded creating misc device %s\n",
1838                         __func__, pcm_dev_node.name);
1839
1840         adpcm_dev_node.minor = MISC_DYNAMIC_MINOR;
1841         adpcm_dev_node.name = "snd_atvr_adpcm";
1842         adpcm_dev_node.fops = &adpcm_fops;
1843         ret = misc_register(&adpcm_dev_node);
1844         if (ret)
1845                 pr_err("%s: failed to create adpcm misc device %d\n",
1846                        __func__, ret);
1847         else
1848                 pr_info("%s: succeeded creating misc device %s\n",
1849                         __func__, adpcm_dev_node.name);
1850
1851         msbc_dev_node.minor = MISC_DYNAMIC_MINOR;
1852         msbc_dev_node.name = "snd_atvr_msbc";
1853         msbc_dev_node.fops = &msbc_fops;
1854         ret = misc_register(&msbc_dev_node);
1855         if (ret)
1856                 pr_err("%s: failed to create mSBC misc device %d\n",
1857                        __func__, ret);
1858         else
1859                 pr_info("%s: succeeded creating misc device %s\n",
1860                         __func__, msbc_dev_node.name);
1861 #endif
1862
1863         return ret;
1864 }
1865
1866 static void atvr_exit(void)
1867 {
1868 #if (DEBUG_WITH_MISC_DEVICE == 1)
1869         misc_deregister(&msbc_dev_node);
1870         misc_deregister(&adpcm_dev_node);
1871         misc_deregister(&pcm_dev_node);
1872 #endif
1873
1874         hid_unregister_driver(&atvr_driver);
1875         mutex_destroy(&snd_cards_lock);
1876 }
1877
1878 module_init(atvr_init);
1879 module_exit(atvr_exit);
1880 MODULE_LICENSE("GPL");