Merge tag 'v5.15.57' into rpi-5.15.y
[platform/kernel/linux-rpi.git] / sound / soc / bcm / pisound.c
1 /*
2  * Pisound Linux kernel module.
3  * Copyright (C) 2016-2020  Vilniaus Blokas UAB, https://blokas.io/pisound
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; version 2 of the
8  * License.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18  * MA  02110-1301, USA.
19  */
20
21 #include <linux/init.h>
22 #include <linux/module.h>
23 #include <linux/platform_device.h>
24 #include <linux/gpio.h>
25 #include <linux/kobject.h>
26 #include <linux/sysfs.h>
27 #include <linux/delay.h>
28 #include <linux/spi/spi.h>
29 #include <linux/interrupt.h>
30 #include <linux/kfifo.h>
31 #include <linux/jiffies.h>
32
33 #include <sound/core.h>
34 #include <sound/pcm.h>
35 #include <sound/pcm_params.h>
36 #include <sound/soc.h>
37 #include <sound/jack.h>
38 #include <sound/rawmidi.h>
39 #include <sound/asequencer.h>
40 #include <sound/control.h>
41
42 static int pisnd_spi_init(struct device *dev);
43 static void pisnd_spi_uninit(void);
44
45 static void pisnd_spi_flush(void);
46 static void pisnd_spi_start(void);
47 static uint8_t pisnd_spi_recv(uint8_t *buffer, uint8_t length);
48
49 typedef void (*pisnd_spi_recv_cb)(void *data);
50 static void pisnd_spi_set_callback(pisnd_spi_recv_cb cb, void *data);
51
52 static const char *pisnd_spi_get_serial(void);
53 static const char *pisnd_spi_get_id(void);
54 static const char *pisnd_spi_get_fw_version(void);
55 static const char *pisnd_spi_get_hw_version(void);
56
57 static int pisnd_midi_init(struct snd_card *card);
58 static void pisnd_midi_uninit(void);
59
60 enum task_e {
61         TASK_PROCESS = 0,
62 };
63
64 static void pisnd_schedule_process(enum task_e task);
65
66 #define PISOUND_LOG_PREFIX "pisound: "
67
68 #ifdef PISOUND_DEBUG
69 #       define printd(...) pr_alert(PISOUND_LOG_PREFIX __VA_ARGS__)
70 #else
71 #       define printd(...) do {} while (0)
72 #endif
73
74 #define printe(...) pr_err(PISOUND_LOG_PREFIX __VA_ARGS__)
75 #define printi(...) pr_info(PISOUND_LOG_PREFIX __VA_ARGS__)
76
77 static struct snd_rawmidi *g_rmidi;
78 static struct snd_rawmidi_substream *g_midi_output_substream;
79
80 static int pisnd_output_open(struct snd_rawmidi_substream *substream)
81 {
82         g_midi_output_substream = substream;
83         return 0;
84 }
85
86 static int pisnd_output_close(struct snd_rawmidi_substream *substream)
87 {
88         g_midi_output_substream = NULL;
89         return 0;
90 }
91
92 static void pisnd_output_trigger(
93         struct snd_rawmidi_substream *substream,
94         int up
95         )
96 {
97         if (substream != g_midi_output_substream) {
98                 printe("MIDI output trigger called for an unexpected stream!");
99                 return;
100         }
101
102         if (!up)
103                 return;
104
105         pisnd_spi_start();
106 }
107
108 static void pisnd_output_drain(struct snd_rawmidi_substream *substream)
109 {
110         pisnd_spi_flush();
111 }
112
113 static int pisnd_input_open(struct snd_rawmidi_substream *substream)
114 {
115         return 0;
116 }
117
118 static int pisnd_input_close(struct snd_rawmidi_substream *substream)
119 {
120         return 0;
121 }
122
123 static void pisnd_midi_recv_callback(void *substream)
124 {
125         uint8_t data[128];
126         uint8_t n = 0;
127
128         while ((n = pisnd_spi_recv(data, sizeof(data)))) {
129                 int res = snd_rawmidi_receive(substream, data, n);
130                 (void)res;
131                 printd("midi recv %u bytes, res = %d\n", n, res);
132         }
133 }
134
135 static void pisnd_input_trigger(struct snd_rawmidi_substream *substream, int up)
136 {
137         if (up) {
138                 pisnd_spi_set_callback(pisnd_midi_recv_callback, substream);
139                 pisnd_schedule_process(TASK_PROCESS);
140         } else {
141                 pisnd_spi_set_callback(NULL, NULL);
142         }
143 }
144
145 static struct snd_rawmidi_ops pisnd_output_ops = {
146         .open = pisnd_output_open,
147         .close = pisnd_output_close,
148         .trigger = pisnd_output_trigger,
149         .drain = pisnd_output_drain,
150 };
151
152 static struct snd_rawmidi_ops pisnd_input_ops = {
153         .open = pisnd_input_open,
154         .close = pisnd_input_close,
155         .trigger = pisnd_input_trigger,
156 };
157
158 static void pisnd_get_port_info(
159         struct snd_rawmidi *rmidi,
160         int number,
161         struct snd_seq_port_info *seq_port_info
162         )
163 {
164         seq_port_info->type =
165                 SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC |
166                 SNDRV_SEQ_PORT_TYPE_HARDWARE |
167                 SNDRV_SEQ_PORT_TYPE_PORT;
168         seq_port_info->midi_voices = 0;
169 }
170
171 static struct snd_rawmidi_global_ops pisnd_global_ops = {
172         .get_port_info = pisnd_get_port_info,
173 };
174
175 static int pisnd_midi_init(struct snd_card *card)
176 {
177         int err;
178
179         g_midi_output_substream = NULL;
180
181         err = snd_rawmidi_new(card, "pisound MIDI", 0, 1, 1, &g_rmidi);
182
183         if (err < 0) {
184                 printe("snd_rawmidi_new failed: %d\n", err);
185                 return err;
186         }
187
188         strcpy(g_rmidi->name, "pisound MIDI ");
189         strcat(g_rmidi->name, pisnd_spi_get_serial());
190
191         g_rmidi->info_flags =
192                 SNDRV_RAWMIDI_INFO_OUTPUT |
193                 SNDRV_RAWMIDI_INFO_INPUT |
194                 SNDRV_RAWMIDI_INFO_DUPLEX;
195
196         g_rmidi->ops = &pisnd_global_ops;
197
198         g_rmidi->private_data = (void *)0;
199
200         snd_rawmidi_set_ops(
201                 g_rmidi,
202                 SNDRV_RAWMIDI_STREAM_OUTPUT,
203                 &pisnd_output_ops
204                 );
205
206         snd_rawmidi_set_ops(
207                 g_rmidi,
208                 SNDRV_RAWMIDI_STREAM_INPUT,
209                 &pisnd_input_ops
210                 );
211
212         return 0;
213 }
214
215 static void pisnd_midi_uninit(void)
216 {
217 }
218
219 static void *g_recvData;
220 static pisnd_spi_recv_cb g_recvCallback;
221
222 #define FIFO_SIZE 4096
223
224 static char g_serial_num[11];
225 static char g_id[25];
226 enum { MAX_VERSION_STR_LEN = 6 };
227 static char g_fw_version[MAX_VERSION_STR_LEN];
228 static char g_hw_version[MAX_VERSION_STR_LEN];
229
230 static uint8_t g_ledFlashDuration;
231 static bool    g_ledFlashDurationChanged;
232
233 DEFINE_KFIFO(spi_fifo_in,  uint8_t, FIFO_SIZE);
234 DEFINE_KFIFO(spi_fifo_out, uint8_t, FIFO_SIZE);
235
236 static struct gpio_desc *data_available;
237 static struct gpio_desc *spi_reset;
238
239 static struct spi_device *pisnd_spi_device;
240
241 static struct workqueue_struct *pisnd_workqueue;
242 static struct work_struct pisnd_work_process;
243
244 static void pisnd_work_handler(struct work_struct *work);
245
246 static void spi_transfer(const uint8_t *txbuf, uint8_t *rxbuf, int len);
247 static uint16_t spi_transfer16(uint16_t val);
248
249 static int pisnd_init_workqueues(void)
250 {
251         pisnd_workqueue = create_singlethread_workqueue("pisnd_workqueue");
252         INIT_WORK(&pisnd_work_process, pisnd_work_handler);
253
254         return 0;
255 }
256
257 static void pisnd_uninit_workqueues(void)
258 {
259         flush_workqueue(pisnd_workqueue);
260         destroy_workqueue(pisnd_workqueue);
261
262         pisnd_workqueue = NULL;
263 }
264
265 static bool pisnd_spi_has_more(void)
266 {
267         return gpiod_get_value(data_available);
268 }
269
270 static void pisnd_schedule_process(enum task_e task)
271 {
272         if (pisnd_spi_device != NULL &&
273                 pisnd_workqueue != NULL &&
274                 !work_pending(&pisnd_work_process)
275                 ) {
276                 printd("schedule: has more = %d\n", pisnd_spi_has_more());
277                 if (task == TASK_PROCESS)
278                         queue_work(pisnd_workqueue, &pisnd_work_process);
279         }
280 }
281
282 static irqreturn_t data_available_interrupt_handler(int irq, void *dev_id)
283 {
284         if (irq == gpiod_to_irq(data_available) && pisnd_spi_has_more()) {
285                 printd("schedule from irq\n");
286                 pisnd_schedule_process(TASK_PROCESS);
287         }
288
289         return IRQ_HANDLED;
290 }
291
292 static uint16_t spi_transfer16(uint16_t val)
293 {
294         uint8_t txbuf[2];
295         uint8_t rxbuf[2];
296
297         if (!pisnd_spi_device) {
298                 printe("pisnd_spi_device null, returning\n");
299                 return 0;
300         }
301
302         txbuf[0] = val >> 8;
303         txbuf[1] = val & 0xff;
304
305         spi_transfer(txbuf, rxbuf, sizeof(txbuf));
306
307         printd("received: %02x%02x\n", rxbuf[0], rxbuf[1]);
308
309         return (rxbuf[0] << 8) | rxbuf[1];
310 }
311
312 static void spi_transfer(const uint8_t *txbuf, uint8_t *rxbuf, int len)
313 {
314         int err;
315         struct spi_transfer transfer;
316         struct spi_message msg;
317
318         memset(rxbuf, 0, len);
319
320         if (!pisnd_spi_device) {
321                 printe("pisnd_spi_device null, returning\n");
322                 return;
323         }
324
325         spi_message_init(&msg);
326
327         memset(&transfer, 0, sizeof(transfer));
328
329         transfer.tx_buf = txbuf;
330         transfer.rx_buf = rxbuf;
331         transfer.len = len;
332         transfer.speed_hz = 150000;
333         transfer.delay.value = 10;
334         transfer.delay.unit = SPI_DELAY_UNIT_USECS;
335
336         spi_message_add_tail(&transfer, &msg);
337
338         err = spi_sync(pisnd_spi_device, &msg);
339
340         if (err < 0) {
341                 printe("spi_sync error %d\n", err);
342                 return;
343         }
344
345         printd("hasMore %d\n", pisnd_spi_has_more());
346 }
347
348 static int spi_read_bytes(char *dst, size_t length, uint8_t *bytesRead)
349 {
350         uint16_t rx;
351         uint8_t size;
352         uint8_t i;
353
354         memset(dst, 0, length);
355         *bytesRead = 0;
356
357         rx = spi_transfer16(0);
358         if (!(rx >> 8))
359                 return -EINVAL;
360
361         size = rx & 0xff;
362
363         if (size > length)
364                 return -EINVAL;
365
366         for (i = 0; i < size; ++i) {
367                 rx = spi_transfer16(0);
368                 if (!(rx >> 8))
369                         return -EINVAL;
370
371                 dst[i] = rx & 0xff;
372         }
373
374         *bytesRead = i;
375
376         return 0;
377 }
378
379 static int spi_device_match(struct device *dev, const void *data)
380 {
381         struct spi_device *spi = container_of(dev, struct spi_device, dev);
382
383         printd("      %s %s %dkHz %d bits mode=0x%02X\n",
384                 spi->modalias, dev_name(dev), spi->max_speed_hz/1000,
385                 spi->bits_per_word, spi->mode);
386
387         if (strcmp("pisound-spi", spi->modalias) == 0) {
388                 printi("\tFound!\n");
389                 return 1;
390         }
391
392         printe("\tNot found!\n");
393         return 0;
394 }
395
396 static struct spi_device *pisnd_spi_find_device(void)
397 {
398         struct device *dev;
399
400         printi("Searching for spi device...\n");
401         dev = bus_find_device(&spi_bus_type, NULL, NULL, spi_device_match);
402         if (dev != NULL)
403                 return container_of(dev, struct spi_device, dev);
404         else
405                 return NULL;
406 }
407
408 static void pisnd_work_handler(struct work_struct *work)
409 {
410         enum { TRANSFER_SIZE = 4 };
411         enum { PISOUND_OUTPUT_BUFFER_SIZE_MILLIBYTES = 127 * 1000 };
412         enum { MIDI_MILLIBYTES_PER_JIFFIE = (3125 * 1000) / HZ };
413         int out_buffer_used_millibytes = 0;
414         unsigned long now;
415         uint8_t val;
416         uint8_t txbuf[TRANSFER_SIZE];
417         uint8_t rxbuf[TRANSFER_SIZE];
418         uint8_t midibuf[TRANSFER_SIZE];
419         int i, n;
420         bool had_data;
421
422         unsigned long last_transfer_at = jiffies;
423
424         if (work == &pisnd_work_process) {
425                 if (pisnd_spi_device == NULL)
426                         return;
427
428                 do {
429                         if (g_midi_output_substream &&
430                                 kfifo_avail(&spi_fifo_out) >= sizeof(midibuf)) {
431
432                                 n = snd_rawmidi_transmit_peek(
433                                         g_midi_output_substream,
434                                         midibuf, sizeof(midibuf)
435                                 );
436
437                                 if (n > 0) {
438                                         for (i = 0; i < n; ++i)
439                                                 kfifo_put(
440                                                         &spi_fifo_out,
441                                                         midibuf[i]
442                                                         );
443                                         snd_rawmidi_transmit_ack(
444                                                 g_midi_output_substream,
445                                                 i
446                                                 );
447                                 }
448                         }
449
450                         had_data = false;
451                         memset(txbuf, 0, sizeof(txbuf));
452                         for (i = 0; i < sizeof(txbuf) &&
453                                 ((out_buffer_used_millibytes+1000 <
454                                 PISOUND_OUTPUT_BUFFER_SIZE_MILLIBYTES) ||
455                                 g_ledFlashDurationChanged);
456                                 i += 2) {
457
458                                 val = 0;
459
460                                 if (g_ledFlashDurationChanged) {
461                                         txbuf[i+0] = 0xf0;
462                                         txbuf[i+1] = g_ledFlashDuration;
463                                         g_ledFlashDuration = 0;
464                                         g_ledFlashDurationChanged = false;
465                                 } else if (kfifo_get(&spi_fifo_out, &val)) {
466                                         txbuf[i+0] = 0x0f;
467                                         txbuf[i+1] = val;
468                                         out_buffer_used_millibytes += 1000;
469                                 }
470                         }
471
472                         spi_transfer(txbuf, rxbuf, sizeof(txbuf));
473                         /* Estimate the Pisound's MIDI output buffer usage, so
474                          * that we don't overflow it. Space in the buffer should
475                          * be becoming available at the UART MIDI byte transfer
476                          * rate.
477                          */
478                         now = jiffies;
479                         if (now != last_transfer_at) {
480                                 out_buffer_used_millibytes -=
481                                         (now - last_transfer_at) *
482                                         MIDI_MILLIBYTES_PER_JIFFIE;
483                                 if (out_buffer_used_millibytes < 0)
484                                         out_buffer_used_millibytes = 0;
485                                 last_transfer_at = now;
486                         }
487
488                         for (i = 0; i < sizeof(rxbuf); i += 2) {
489                                 if (rxbuf[i]) {
490                                         kfifo_put(&spi_fifo_in, rxbuf[i+1]);
491                                         if (kfifo_len(&spi_fifo_in) > 16 &&
492                                                 g_recvCallback)
493                                                 g_recvCallback(g_recvData);
494                                         had_data = true;
495                                 }
496                         }
497                 } while (had_data
498                         || !kfifo_is_empty(&spi_fifo_out)
499                         || pisnd_spi_has_more()
500                         || g_ledFlashDurationChanged
501                         || out_buffer_used_millibytes != 0
502                         );
503
504                 if (!kfifo_is_empty(&spi_fifo_in) && g_recvCallback)
505                         g_recvCallback(g_recvData);
506         }
507 }
508
509 static int pisnd_spi_gpio_init(struct device *dev)
510 {
511         spi_reset = gpiod_get_index(dev, "reset", 1, GPIOD_ASIS);
512         data_available = gpiod_get_index(dev, "data_available", 0, GPIOD_ASIS);
513
514         gpiod_direction_output(spi_reset, 1);
515         gpiod_direction_input(data_available);
516
517         /* Reset the slave. */
518         gpiod_set_value(spi_reset, false);
519         mdelay(1);
520         gpiod_set_value(spi_reset, true);
521
522         /* Give time for spi slave to start. */
523         mdelay(64);
524
525         return 0;
526 }
527
528 static void pisnd_spi_gpio_uninit(void)
529 {
530         gpiod_set_value(spi_reset, false);
531         gpiod_put(spi_reset);
532         spi_reset = NULL;
533
534         gpiod_put(data_available);
535         data_available = NULL;
536 }
537
538 static int pisnd_spi_gpio_irq_init(struct device *dev)
539 {
540         return request_threaded_irq(
541                 gpiod_to_irq(data_available), NULL,
542                 data_available_interrupt_handler,
543                 IRQF_TIMER | IRQF_TRIGGER_RISING | IRQF_ONESHOT,
544                 "data_available_int",
545                 NULL
546                 );
547 }
548
549 static void pisnd_spi_gpio_irq_uninit(void)
550 {
551         free_irq(gpiod_to_irq(data_available), NULL);
552 }
553
554 static int spi_read_info(void)
555 {
556         uint16_t tmp;
557         uint8_t count;
558         uint8_t n;
559         uint8_t i;
560         uint8_t j;
561         char buffer[257];
562         int ret;
563         char *p;
564
565         memset(g_serial_num, 0, sizeof(g_serial_num));
566         memset(g_fw_version, 0, sizeof(g_fw_version));
567         strcpy(g_hw_version, "1.0"); // Assume 1.0 hw version.
568         memset(g_id, 0, sizeof(g_id));
569
570         tmp = spi_transfer16(0);
571
572         if (!(tmp >> 8))
573                 return -EINVAL;
574
575         count = tmp & 0xff;
576
577         for (i = 0; i < count; ++i) {
578                 memset(buffer, 0, sizeof(buffer));
579                 ret = spi_read_bytes(buffer, sizeof(buffer)-1, &n);
580
581                 if (ret < 0)
582                         return ret;
583
584                 switch (i) {
585                 case 0:
586                         if (n != 2)
587                                 return -EINVAL;
588
589                         snprintf(
590                                 g_fw_version,
591                                 MAX_VERSION_STR_LEN,
592                                 "%x.%02x",
593                                 buffer[0],
594                                 buffer[1]
595                                 );
596
597                         g_fw_version[MAX_VERSION_STR_LEN-1] = '\0';
598                         break;
599                 case 3:
600                         if (n != 2)
601                                 return -EINVAL;
602
603                         snprintf(
604                                 g_hw_version,
605                                 MAX_VERSION_STR_LEN,
606                                 "%x.%x",
607                                 buffer[0],
608                                 buffer[1]
609                         );
610
611                         g_hw_version[MAX_VERSION_STR_LEN-1] = '\0';
612                         break;
613                 case 1:
614                         if (n >= sizeof(g_serial_num))
615                                 return -EINVAL;
616
617                         memcpy(g_serial_num, buffer, sizeof(g_serial_num));
618                         break;
619                 case 2:
620                         {
621                                 if (n*2 >= sizeof(g_id))
622                                         return -EINVAL;
623
624                                 p = g_id;
625                                 for (j = 0; j < n; ++j)
626                                         p += sprintf(p, "%02x", buffer[j]);
627
628                                 *p = '\0';
629                         }
630                         break;
631                 default:
632                         break;
633                 }
634         }
635
636         return 0;
637 }
638
639 static int pisnd_spi_init(struct device *dev)
640 {
641         int ret;
642         struct spi_device *spi;
643
644         memset(g_serial_num, 0, sizeof(g_serial_num));
645         memset(g_id, 0, sizeof(g_id));
646         memset(g_fw_version, 0, sizeof(g_fw_version));
647         memset(g_hw_version, 0, sizeof(g_hw_version));
648
649         spi = pisnd_spi_find_device();
650
651         if (spi != NULL) {
652                 printd("initializing spi!\n");
653                 pisnd_spi_device = spi;
654                 ret = spi_setup(pisnd_spi_device);
655         } else {
656                 printe("SPI device not found, deferring!\n");
657                 return -EPROBE_DEFER;
658         }
659
660         ret = pisnd_spi_gpio_init(dev);
661
662         if (ret < 0) {
663                 printe("SPI GPIO init failed: %d\n", ret);
664                 spi_dev_put(pisnd_spi_device);
665                 pisnd_spi_device = NULL;
666                 pisnd_spi_gpio_uninit();
667                 return ret;
668         }
669
670         ret = spi_read_info();
671
672         if (ret < 0) {
673                 printe("Reading card info failed: %d\n", ret);
674                 spi_dev_put(pisnd_spi_device);
675                 pisnd_spi_device = NULL;
676                 pisnd_spi_gpio_uninit();
677                 return ret;
678         }
679
680         /* Flash the LEDs. */
681         spi_transfer16(0xf008);
682
683         ret = pisnd_spi_gpio_irq_init(dev);
684         if (ret < 0) {
685                 printe("SPI irq request failed: %d\n", ret);
686                 spi_dev_put(pisnd_spi_device);
687                 pisnd_spi_device = NULL;
688                 pisnd_spi_gpio_irq_uninit();
689                 pisnd_spi_gpio_uninit();
690         }
691
692         ret = pisnd_init_workqueues();
693         if (ret != 0) {
694                 printe("Workqueue initialization failed: %d\n", ret);
695                 spi_dev_put(pisnd_spi_device);
696                 pisnd_spi_device = NULL;
697                 pisnd_spi_gpio_irq_uninit();
698                 pisnd_spi_gpio_uninit();
699                 pisnd_uninit_workqueues();
700                 return ret;
701         }
702
703         if (pisnd_spi_has_more()) {
704                 printd("data is available, scheduling from init\n");
705                 pisnd_schedule_process(TASK_PROCESS);
706         }
707
708         return 0;
709 }
710
711 static void pisnd_spi_uninit(void)
712 {
713         pisnd_uninit_workqueues();
714
715         spi_dev_put(pisnd_spi_device);
716         pisnd_spi_device = NULL;
717
718         pisnd_spi_gpio_irq_uninit();
719         pisnd_spi_gpio_uninit();
720 }
721
722 static void pisnd_spi_flash_leds(uint8_t duration)
723 {
724         g_ledFlashDuration = duration;
725         g_ledFlashDurationChanged = true;
726         printd("schedule from spi_flash_leds\n");
727         pisnd_schedule_process(TASK_PROCESS);
728 }
729
730 static void pisnd_spi_flush(void)
731 {
732         while (!kfifo_is_empty(&spi_fifo_out)) {
733                 pisnd_spi_start();
734                 flush_workqueue(pisnd_workqueue);
735         }
736 }
737
738 static void pisnd_spi_start(void)
739 {
740         printd("schedule from spi_start\n");
741         pisnd_schedule_process(TASK_PROCESS);
742 }
743
744 static uint8_t pisnd_spi_recv(uint8_t *buffer, uint8_t length)
745 {
746         return kfifo_out(&spi_fifo_in, buffer, length);
747 }
748
749 static void pisnd_spi_set_callback(pisnd_spi_recv_cb cb, void *data)
750 {
751         g_recvData = data;
752         g_recvCallback = cb;
753 }
754
755 static const char *pisnd_spi_get_serial(void)
756 {
757         return g_serial_num;
758 }
759
760 static const char *pisnd_spi_get_id(void)
761 {
762         return g_id;
763 }
764
765 static const char *pisnd_spi_get_fw_version(void)
766 {
767         return g_fw_version;
768 }
769
770 static const char *pisnd_spi_get_hw_version(void)
771 {
772         return g_hw_version;
773 }
774
775 static const struct of_device_id pisound_of_match[] = {
776         { .compatible = "blokaslabs,pisound", },
777         { .compatible = "blokaslabs,pisound-spi", },
778         {},
779 };
780
781 enum {
782         SWITCH = 0,
783         VOLUME = 1,
784 };
785
786 static int pisnd_ctl_info(struct snd_kcontrol *kcontrol,
787         struct snd_ctl_elem_info *uinfo)
788 {
789         if (kcontrol->private_value == SWITCH) {
790                 uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
791                 uinfo->count = 1;
792                 uinfo->value.integer.min = 0;
793                 uinfo->value.integer.max = 1;
794                 return 0;
795         } else if (kcontrol->private_value == VOLUME) {
796                 uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
797                 uinfo->count = 1;
798                 uinfo->value.integer.min = 0;
799                 uinfo->value.integer.max = 100;
800                 return 0;
801         }
802         return -EINVAL;
803 }
804
805 static int pisnd_ctl_get(struct snd_kcontrol *kcontrol,
806         struct snd_ctl_elem_value *ucontrol)
807 {
808         if (kcontrol->private_value == SWITCH) {
809                 ucontrol->value.integer.value[0] = 1;
810                 return 0;
811         } else if (kcontrol->private_value == VOLUME) {
812                 ucontrol->value.integer.value[0] = 100;
813                 return 0;
814         }
815
816         return -EINVAL;
817 }
818
819 static struct snd_kcontrol_new pisnd_ctl[] = {
820         {
821                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
822                 .name = "PCM Playback Switch",
823                 .index = 0,
824                 .private_value = SWITCH,
825                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
826                 .info = pisnd_ctl_info,
827                 .get = pisnd_ctl_get,
828         },
829         {
830                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
831                 .name = "PCM Playback Volume",
832                 .index = 0,
833                 .private_value = VOLUME,
834                 .access = SNDRV_CTL_ELEM_ACCESS_READ,
835                 .info = pisnd_ctl_info,
836                 .get = pisnd_ctl_get,
837         },
838 };
839
840 static int pisnd_ctl_init(struct snd_card *card)
841 {
842         int err, i;
843
844         for (i = 0; i < ARRAY_SIZE(pisnd_ctl); ++i) {
845                 err = snd_ctl_add(card, snd_ctl_new1(&pisnd_ctl[i], NULL));
846                 if (err < 0)
847                         return err;
848         }
849
850         return 0;
851 }
852
853 static int pisnd_ctl_uninit(void)
854 {
855         return 0;
856 }
857
858 static struct gpio_desc *osr0, *osr1, *osr2;
859 static struct gpio_desc *reset;
860 static struct gpio_desc *button;
861
862 static int pisnd_hw_params(
863         struct snd_pcm_substream *substream,
864         struct snd_pcm_hw_params *params
865         )
866 {
867         struct snd_soc_pcm_runtime *rtd = substream->private_data;
868         struct snd_soc_dai *cpu_dai = asoc_rtd_to_cpu(rtd, 0);
869
870         /* Pisound runs on fixed 32 clock counts per channel,
871          * as generated by the master ADC.
872          */
873         snd_soc_dai_set_bclk_ratio(cpu_dai, 32*2);
874
875         printd("rate   = %d\n", params_rate(params));
876         printd("ch     = %d\n", params_channels(params));
877         printd("bits   = %u\n",
878                 snd_pcm_format_physical_width(params_format(params)));
879         printd("format = %d\n", params_format(params));
880
881         gpiod_set_value(reset, false);
882
883         switch (params_rate(params)) {
884         case 48000:
885                 gpiod_set_value(osr0, true);
886                 gpiod_set_value(osr1, false);
887                 gpiod_set_value(osr2, false);
888                 break;
889         case 96000:
890                 gpiod_set_value(osr0, true);
891                 gpiod_set_value(osr1, false);
892                 gpiod_set_value(osr2, true);
893                 break;
894         case 192000:
895                 gpiod_set_value(osr0, true);
896                 gpiod_set_value(osr1, true);
897                 gpiod_set_value(osr2, true);
898                 break;
899         default:
900                 printe("Unsupported rate %u!\n", params_rate(params));
901                 return -EINVAL;
902         }
903
904         gpiod_set_value(reset, true);
905
906         return 0;
907 }
908
909 static unsigned int rates[3] = {
910         48000, 96000, 192000
911 };
912
913 static struct snd_pcm_hw_constraint_list constraints_rates = {
914         .count = ARRAY_SIZE(rates),
915         .list = rates,
916         .mask = 0,
917 };
918
919 static int pisnd_startup(struct snd_pcm_substream *substream)
920 {
921         int err = snd_pcm_hw_constraint_list(
922                 substream->runtime,
923                 0,
924                 SNDRV_PCM_HW_PARAM_RATE,
925                 &constraints_rates
926                 );
927
928         if (err < 0)
929                 return err;
930
931         err = snd_pcm_hw_constraint_single(
932                 substream->runtime,
933                 SNDRV_PCM_HW_PARAM_CHANNELS,
934                 2
935                 );
936
937         if (err < 0)
938                 return err;
939
940         err = snd_pcm_hw_constraint_mask64(
941                 substream->runtime,
942                 SNDRV_PCM_HW_PARAM_FORMAT,
943                 SNDRV_PCM_FMTBIT_S16_LE |
944                 SNDRV_PCM_FMTBIT_S24_LE |
945                 SNDRV_PCM_FMTBIT_S32_LE
946                 );
947
948         if (err < 0)
949                 return err;
950
951         return 0;
952 }
953
954 static struct snd_soc_ops pisnd_ops = {
955         .startup = pisnd_startup,
956         .hw_params = pisnd_hw_params,
957 };
958
959 SND_SOC_DAILINK_DEFS(pisnd,
960         DAILINK_COMP_ARRAY(COMP_CPU("bcm2708-i2s.0")),
961         DAILINK_COMP_ARRAY(COMP_DUMMY()),
962         DAILINK_COMP_ARRAY(COMP_PLATFORM("bcm2708-i2s.0")));
963
964 static struct snd_soc_dai_link pisnd_dai[] = {
965         {
966                 .name           = "pisound",
967                 .stream_name    = "pisound",
968                 .dai_fmt        =
969                         SND_SOC_DAIFMT_I2S |
970                         SND_SOC_DAIFMT_NB_NF |
971                         SND_SOC_DAIFMT_CBM_CFM,
972                 .ops            = &pisnd_ops,
973                 SND_SOC_DAILINK_REG(pisnd),
974         },
975 };
976
977 static int pisnd_card_probe(struct snd_soc_card *card)
978 {
979         int err = pisnd_midi_init(card->snd_card);
980
981         if (err < 0) {
982                 printe("pisnd_midi_init failed: %d\n", err);
983                 return err;
984         }
985
986         err = pisnd_ctl_init(card->snd_card);
987         if (err < 0) {
988                 printe("pisnd_ctl_init failed: %d\n", err);
989                 return err;
990         }
991
992         return 0;
993 }
994
995 static int pisnd_card_remove(struct snd_soc_card *card)
996 {
997         pisnd_ctl_uninit();
998         pisnd_midi_uninit();
999         return 0;
1000 }
1001
1002 static struct snd_soc_card pisnd_card = {
1003         .name         = "pisound",
1004         .owner        = THIS_MODULE,
1005         .dai_link     = pisnd_dai,
1006         .num_links    = ARRAY_SIZE(pisnd_dai),
1007         .probe        = pisnd_card_probe,
1008         .remove       = pisnd_card_remove,
1009 };
1010
1011 static int pisnd_init_gpio(struct device *dev)
1012 {
1013         osr0 = gpiod_get_index(dev, "osr", 0, GPIOD_ASIS);
1014         osr1 = gpiod_get_index(dev, "osr", 1, GPIOD_ASIS);
1015         osr2 = gpiod_get_index(dev, "osr", 2, GPIOD_ASIS);
1016
1017         reset = gpiod_get_index(dev, "reset", 0, GPIOD_ASIS);
1018
1019         button = gpiod_get_index(dev, "button", 0, GPIOD_ASIS);
1020
1021         gpiod_direction_output(osr0,  1);
1022         gpiod_direction_output(osr1,  1);
1023         gpiod_direction_output(osr2,  1);
1024         gpiod_direction_output(reset, 1);
1025
1026         gpiod_set_value(reset, false);
1027         gpiod_set_value(osr0,   true);
1028         gpiod_set_value(osr1,  false);
1029         gpiod_set_value(osr2,  false);
1030         gpiod_set_value(reset,  true);
1031
1032         gpiod_export(button, false);
1033
1034         return 0;
1035 }
1036
1037 static int pisnd_uninit_gpio(void)
1038 {
1039         int i;
1040
1041         struct gpio_desc **gpios[] = {
1042                 &osr0, &osr1, &osr2, &reset, &button,
1043         };
1044
1045         gpiod_unexport(button);
1046
1047         for (i = 0; i < ARRAY_SIZE(gpios); ++i) {
1048                 if (*gpios[i] == NULL) {
1049                         printd("weird, GPIO[%d] is NULL already\n", i);
1050                         continue;
1051                 }
1052
1053                 gpiod_put(*gpios[i]);
1054                 *gpios[i] = NULL;
1055         }
1056
1057         return 0;
1058 }
1059
1060 static struct kobject *pisnd_kobj;
1061
1062 static ssize_t pisnd_serial_show(
1063         struct kobject *kobj,
1064         struct kobj_attribute *attr,
1065         char *buf
1066         )
1067 {
1068         return sprintf(buf, "%s\n", pisnd_spi_get_serial());
1069 }
1070
1071 static ssize_t pisnd_id_show(
1072         struct kobject *kobj,
1073         struct kobj_attribute *attr,
1074         char *buf
1075         )
1076 {
1077         return sprintf(buf, "%s\n", pisnd_spi_get_id());
1078 }
1079
1080 static ssize_t pisnd_fw_version_show(
1081         struct kobject *kobj,
1082         struct kobj_attribute *attr,
1083         char *buf
1084         )
1085 {
1086         return sprintf(buf, "%s\n", pisnd_spi_get_fw_version());
1087 }
1088
1089 static ssize_t pisnd_hw_version_show(
1090         struct kobject *kobj,
1091         struct kobj_attribute *attr,
1092         char *buf
1093 )
1094 {
1095         return sprintf(buf, "%s\n", pisnd_spi_get_hw_version());
1096 }
1097
1098 static ssize_t pisnd_led_store(
1099         struct kobject *kobj,
1100         struct kobj_attribute *attr,
1101         const char *buf,
1102         size_t length
1103         )
1104 {
1105         uint32_t timeout;
1106         int err;
1107
1108         err = kstrtou32(buf, 10, &timeout);
1109
1110         if (err == 0 && timeout <= 255)
1111                 pisnd_spi_flash_leds(timeout);
1112
1113         return length;
1114 }
1115
1116 static struct kobj_attribute pisnd_serial_attribute =
1117         __ATTR(serial, 0444, pisnd_serial_show, NULL);
1118 static struct kobj_attribute pisnd_id_attribute =
1119         __ATTR(id, 0444, pisnd_id_show, NULL);
1120 static struct kobj_attribute pisnd_fw_version_attribute =
1121         __ATTR(version, 0444, pisnd_fw_version_show, NULL);
1122 static struct kobj_attribute pisnd_hw_version_attribute =
1123 __ATTR(hw_version, 0444, pisnd_hw_version_show, NULL);
1124 static struct kobj_attribute pisnd_led_attribute =
1125         __ATTR(led, 0644, NULL, pisnd_led_store);
1126
1127 static struct attribute *attrs[] = {
1128         &pisnd_serial_attribute.attr,
1129         &pisnd_id_attribute.attr,
1130         &pisnd_fw_version_attribute.attr,
1131         &pisnd_hw_version_attribute.attr,
1132         &pisnd_led_attribute.attr,
1133         NULL
1134 };
1135
1136 static struct attribute_group attr_group = { .attrs = attrs };
1137
1138 static int pisnd_probe(struct platform_device *pdev)
1139 {
1140         int ret = 0;
1141         int i;
1142
1143         ret = pisnd_spi_init(&pdev->dev);
1144         if (ret < 0) {
1145                 printe("pisnd_spi_init failed: %d\n", ret);
1146                 return ret;
1147         }
1148
1149         printi("Detected Pisound card:\n");
1150         printi("\tSerial:           %s\n", pisnd_spi_get_serial());
1151         printi("\tFirmware Version: %s\n", pisnd_spi_get_fw_version());
1152         printi("\tHardware Version: %s\n", pisnd_spi_get_hw_version());
1153         printi("\tId:               %s\n", pisnd_spi_get_id());
1154
1155         pisnd_kobj = kobject_create_and_add("pisound", kernel_kobj);
1156         if (!pisnd_kobj) {
1157                 pisnd_spi_uninit();
1158                 return -ENOMEM;
1159         }
1160
1161         ret = sysfs_create_group(pisnd_kobj, &attr_group);
1162         if (ret < 0) {
1163                 pisnd_spi_uninit();
1164                 kobject_put(pisnd_kobj);
1165                 return -ENOMEM;
1166         }
1167
1168         pisnd_init_gpio(&pdev->dev);
1169         pisnd_card.dev = &pdev->dev;
1170
1171         if (pdev->dev.of_node) {
1172                 struct device_node *i2s_node;
1173
1174                 i2s_node = of_parse_phandle(
1175                         pdev->dev.of_node,
1176                         "i2s-controller",
1177                         0
1178                         );
1179
1180                 for (i = 0; i < pisnd_card.num_links; ++i) {
1181                         struct snd_soc_dai_link *dai = &pisnd_dai[i];
1182
1183                         if (i2s_node) {
1184                                 dai->cpus->dai_name = NULL;
1185                                 dai->cpus->of_node = i2s_node;
1186                                 dai->platforms->name = NULL;
1187                                 dai->platforms->of_node = i2s_node;
1188                                 dai->stream_name = pisnd_spi_get_serial();
1189                         }
1190                 }
1191         }
1192
1193         ret = snd_soc_register_card(&pisnd_card);
1194
1195         if (ret < 0) {
1196                 if (ret != -EPROBE_DEFER)
1197                         printe("snd_soc_register_card() failed: %d\n", ret);
1198                 pisnd_uninit_gpio();
1199                 kobject_put(pisnd_kobj);
1200                 pisnd_spi_uninit();
1201         }
1202
1203         return ret;
1204 }
1205
1206 static int pisnd_remove(struct platform_device *pdev)
1207 {
1208         printi("Unloading.\n");
1209
1210         if (pisnd_kobj) {
1211                 kobject_put(pisnd_kobj);
1212                 pisnd_kobj = NULL;
1213         }
1214
1215         pisnd_spi_uninit();
1216
1217         /* Turn off */
1218         gpiod_set_value(reset, false);
1219         pisnd_uninit_gpio();
1220
1221         return snd_soc_unregister_card(&pisnd_card);
1222 }
1223
1224 MODULE_DEVICE_TABLE(of, pisound_of_match);
1225
1226 static struct platform_driver pisnd_driver = {
1227         .driver = {
1228                 .name           = "snd-rpi-pisound",
1229                 .owner          = THIS_MODULE,
1230                 .of_match_table = pisound_of_match,
1231         },
1232         .probe              = pisnd_probe,
1233         .remove             = pisnd_remove,
1234 };
1235
1236 module_platform_driver(pisnd_driver);
1237
1238 MODULE_AUTHOR("Giedrius Trainavicius <giedrius@blokas.io>");
1239 MODULE_DESCRIPTION("ASoC Driver for Pisound, https://blokas.io/pisound");
1240 MODULE_LICENSE("GPL v2");