Merge branch 'next-integrity' of git://git.kernel.org/pub/scm/linux/kernel/git/jmorri...
[sfrench/cifs-2.6.git] / drivers / staging / pi433 / pi433_if.c
1 /*
2  * userspace interface for pi433 radio module
3  *
4  * Pi433 is a 433MHz radio module for the Raspberry Pi.
5  * It is based on the HopeRf Module RFM69CW. Therefore inside of this
6  * driver, you'll find an abstraction of the rf69 chip.
7  *
8  * If needed, this driver could be extended, to also support other
9  * devices, basing on HopeRfs rf69.
10  *
11  * The driver can also be extended, to support other modules of
12  * HopeRf with a similar interace - e. g. RFM69HCW, RFM12, RFM95, ...
13  *
14  * Copyright (C) 2016 Wolf-Entwicklungen
15  *      Marcus Wolf <linux@wolf-entwicklungen.de>
16  *
17  * This program is free software; you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation; either version 2 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  */
27
28 #undef DEBUG
29
30 #include <linux/init.h>
31 #include <linux/module.h>
32 #include <linux/idr.h>
33 #include <linux/ioctl.h>
34 #include <linux/uaccess.h>
35 #include <linux/fs.h>
36 #include <linux/device.h>
37 #include <linux/cdev.h>
38 #include <linux/err.h>
39 #include <linux/kfifo.h>
40 #include <linux/errno.h>
41 #include <linux/mutex.h>
42 #include <linux/of.h>
43 #include <linux/of_device.h>
44 #include <linux/interrupt.h>
45 #include <linux/irq.h>
46 #include <linux/gpio/consumer.h>
47 #include <linux/kthread.h>
48 #include <linux/wait.h>
49 #include <linux/spi/spi.h>
50 #ifdef CONFIG_COMPAT
51 #include <asm/compat.h>
52 #endif
53
54 #include "pi433_if.h"
55 #include "rf69.h"
56
57
58 #define N_PI433_MINORS                  (1U << MINORBITS) /*32*/        /* ... up to 256 */
59 #define MAX_MSG_SIZE                    900     /* min: FIFO_SIZE! */
60 #define MSG_FIFO_SIZE                   65536   /* 65536 = 2^16  */
61 #define NUM_DIO                         2
62
63 static dev_t pi433_dev;
64 static DEFINE_IDR(pi433_idr);
65 static DEFINE_MUTEX(minor_lock); /* Protect idr accesses */
66
67 static struct class *pi433_class; /* mainly for udev to create /dev/pi433 */
68
69 /* tx config is instance specific
70  * so with each open a new tx config struct is needed
71  */
72 /* rx config is device specific
73  * so we have just one rx config, ebedded in device struct
74  */
75 struct pi433_device {
76         /* device handling related values */
77         dev_t                   devt;
78         int                     minor;
79         struct device           *dev;
80         struct cdev             *cdev;
81         struct spi_device       *spi;
82         unsigned                users;
83
84         /* irq related values */
85         struct gpio_desc        *gpiod[NUM_DIO];
86         int                     irq_num[NUM_DIO];
87         u8                      irq_state[NUM_DIO];
88
89         /* tx related values */
90         STRUCT_KFIFO_REC_1(MSG_FIFO_SIZE) tx_fifo;
91         struct mutex            tx_fifo_lock; // TODO: check, whether necessary or obsolete
92         struct task_struct      *tx_task_struct;
93         wait_queue_head_t       tx_wait_queue;
94         u8                      free_in_fifo;
95         char                    buffer[MAX_MSG_SIZE];
96
97         /* rx related values */
98         struct pi433_rx_cfg     rx_cfg;
99         u8                      *rx_buffer;
100         unsigned int            rx_buffer_size;
101         u32                     rx_bytes_to_drop;
102         u32                     rx_bytes_dropped;
103         unsigned int            rx_position;
104         struct mutex            rx_lock;
105         wait_queue_head_t       rx_wait_queue;
106
107         /* fifo wait queue */
108         struct task_struct      *fifo_task_struct;
109         wait_queue_head_t       fifo_wait_queue;
110
111         /* flags */
112         bool                    rx_active;
113         bool                    tx_active;
114         bool                    interrupt_rx_allowed;
115 };
116
117 struct pi433_instance {
118         struct pi433_device     *device;
119         struct pi433_tx_cfg     tx_cfg;
120 };
121
122 /*-------------------------------------------------------------------------*/
123
124 /* macro for checked access of registers of radio module */
125 #define SET_CHECKED(retval) \
126         if (retval < 0) \
127                 return retval;
128
129 /*-------------------------------------------------------------------------*/
130
131 /* GPIO interrupt handlers */
132 static irqreturn_t DIO0_irq_handler(int irq, void *dev_id)
133 {
134         struct pi433_device *device = dev_id;
135
136         if      (device->irq_state[DIO0] == DIO_PacketSent)
137         {
138                 device->free_in_fifo = FIFO_SIZE;
139                 printk("DIO0 irq: Packet sent\n"); // TODO: printk() should include KERN_ facility level
140                 wake_up_interruptible(&device->fifo_wait_queue);
141         }
142         else if (device->irq_state[DIO0] == DIO_Rssi_DIO0)
143         {
144                 printk("DIO0 irq: RSSI level over threshold\n");
145                 wake_up_interruptible(&device->rx_wait_queue);
146         }
147         else if (device->irq_state[DIO0] == DIO_PayloadReady)
148         {
149                 printk("DIO0 irq: PayloadReady\n");
150                 device->free_in_fifo = 0;
151                 wake_up_interruptible(&device->fifo_wait_queue);
152         }
153
154         return IRQ_HANDLED;
155 }
156
157 static irqreturn_t DIO1_irq_handler(int irq, void *dev_id)
158 {
159         struct pi433_device *device = dev_id;
160
161         if      (device->irq_state[DIO1] == DIO_FifoNotEmpty_DIO1)
162         {
163                 device->free_in_fifo = FIFO_SIZE;
164         }
165         else if (device->irq_state[DIO1] == DIO_FifoLevel)
166         {
167                 if (device->rx_active)  device->free_in_fifo = FIFO_THRESHOLD - 1;
168                 else                    device->free_in_fifo = FIFO_SIZE - FIFO_THRESHOLD - 1;
169         }
170         printk("DIO1 irq: %d bytes free in fifo\n", device->free_in_fifo); // TODO: printk() should include KERN_ facility level
171         wake_up_interruptible(&device->fifo_wait_queue);
172
173         return IRQ_HANDLED;
174 }
175
176 /*-------------------------------------------------------------------------*/
177
178 static int
179 rf69_set_rx_cfg(struct pi433_device *dev, struct pi433_rx_cfg *rx_cfg)
180 {
181         int ret;
182         int payload_length;
183
184         /* receiver config */
185         SET_CHECKED(rf69_set_frequency  (dev->spi, rx_cfg->frequency));
186         SET_CHECKED(rf69_set_bit_rate   (dev->spi, rx_cfg->bit_rate));
187         SET_CHECKED(rf69_set_modulation (dev->spi, rx_cfg->modulation));
188         SET_CHECKED(rf69_set_antenna_impedance   (dev->spi, rx_cfg->antenna_impedance));
189         SET_CHECKED(rf69_set_rssi_threshold      (dev->spi, rx_cfg->rssi_threshold));
190         SET_CHECKED(rf69_set_ook_threshold_dec   (dev->spi, rx_cfg->thresholdDecrement));
191         SET_CHECKED(rf69_set_bandwidth           (dev->spi, rx_cfg->bw_mantisse, rx_cfg->bw_exponent));
192         SET_CHECKED(rf69_set_bandwidth_during_afc(dev->spi, rx_cfg->bw_mantisse, rx_cfg->bw_exponent));
193         SET_CHECKED(rf69_set_dagc                (dev->spi, rx_cfg->dagc));
194
195         dev->rx_bytes_to_drop = rx_cfg->bytes_to_drop;
196
197         /* packet config */
198         /* enable */
199         SET_CHECKED(rf69_set_sync_enable(dev->spi, rx_cfg->enable_sync));
200         if (rx_cfg->enable_sync == optionOn)
201         {
202                 SET_CHECKED(rf69_set_fifo_fill_condition(dev->spi, afterSyncInterrupt));
203         }
204         else
205         {
206                 SET_CHECKED(rf69_set_fifo_fill_condition(dev->spi, always));
207         }
208         if (rx_cfg->enable_length_byte == optionOn) {
209                 ret = rf69_set_packet_format(dev->spi, packetLengthVar);
210                 if (ret < 0)
211                         return ret;
212         } else {
213                 ret = rf69_set_packet_format(dev->spi, packetLengthFix);
214                 if (ret < 0)
215                         return ret;
216         }
217         SET_CHECKED(rf69_set_adressFiltering(dev->spi, rx_cfg->enable_address_filtering));
218         SET_CHECKED(rf69_set_crc_enable     (dev->spi, rx_cfg->enable_crc));
219
220         /* lengths */
221         SET_CHECKED(rf69_set_sync_size(dev->spi, rx_cfg->sync_length));
222         if (rx_cfg->enable_length_byte == optionOn)
223         {
224                 SET_CHECKED(rf69_set_payload_length(dev->spi, 0xff));
225         }
226         else if (rx_cfg->fixed_message_length != 0)
227         {
228                 payload_length = rx_cfg->fixed_message_length;
229                 if (rx_cfg->enable_length_byte  == optionOn) payload_length++;
230                 if (rx_cfg->enable_address_filtering != filteringOff) payload_length++;
231                 SET_CHECKED(rf69_set_payload_length(dev->spi, payload_length));
232         }
233         else
234         {
235                 SET_CHECKED(rf69_set_payload_length(dev->spi, 0));
236         }
237
238         /* values */
239         if (rx_cfg->enable_sync == optionOn)
240         {
241                 SET_CHECKED(rf69_set_sync_values(dev->spi, rx_cfg->sync_pattern));
242         }
243         if (rx_cfg->enable_address_filtering != filteringOff)
244         {
245                 SET_CHECKED(rf69_set_node_address     (dev->spi, rx_cfg->node_address));
246                 SET_CHECKED(rf69_set_broadcast_address(dev->spi, rx_cfg->broadcast_address));
247         }
248
249         return 0;
250 }
251
252 static int
253 rf69_set_tx_cfg(struct pi433_device *dev, struct pi433_tx_cfg *tx_cfg)
254 {
255         int ret;
256
257         SET_CHECKED(rf69_set_frequency  (dev->spi, tx_cfg->frequency));
258         SET_CHECKED(rf69_set_bit_rate   (dev->spi, tx_cfg->bit_rate));
259         SET_CHECKED(rf69_set_modulation (dev->spi, tx_cfg->modulation));
260         SET_CHECKED(rf69_set_deviation  (dev->spi, tx_cfg->dev_frequency));
261         SET_CHECKED(rf69_set_pa_ramp    (dev->spi, tx_cfg->pa_ramp));
262         SET_CHECKED(rf69_set_modulation_shaping(dev->spi, tx_cfg->modShaping));
263         SET_CHECKED(rf69_set_tx_start_condition(dev->spi, tx_cfg->tx_start_condition));
264
265         /* packet format enable */
266         if (tx_cfg->enable_preamble == optionOn)
267         {
268                 SET_CHECKED(rf69_set_preamble_length(dev->spi, tx_cfg->preamble_length));
269         }
270         else
271         {
272                 SET_CHECKED(rf69_set_preamble_length(dev->spi, 0));
273         }
274         SET_CHECKED(rf69_set_sync_enable  (dev->spi, tx_cfg->enable_sync));
275         if (tx_cfg->enable_length_byte == optionOn) {
276                 ret = rf69_set_packet_format(dev->spi, packetLengthVar);
277                 if (ret < 0)
278                         return ret;
279         } else {
280                 ret = rf69_set_packet_format(dev->spi, packetLengthFix);
281                 if (ret < 0)
282                         return ret;
283         }
284         SET_CHECKED(rf69_set_crc_enable   (dev->spi, tx_cfg->enable_crc));
285
286         /* configure sync, if enabled */
287         if (tx_cfg->enable_sync == optionOn)
288         {
289                 SET_CHECKED(rf69_set_sync_size(dev->spi, tx_cfg->sync_length));
290                 SET_CHECKED(rf69_set_sync_values(dev->spi, tx_cfg->sync_pattern));
291         }
292
293         return 0;
294 }
295
296 /*-------------------------------------------------------------------------*/
297
298 static int
299 pi433_start_rx(struct pi433_device *dev)
300 {
301         int retval;
302
303         /* return without action, if no pending read request */
304         if (!dev->rx_active)
305                 return 0;
306
307         /* setup for receiving */
308         retval = rf69_set_rx_cfg(dev, &dev->rx_cfg);
309         if (retval) return retval;
310
311         /* setup rssi irq */
312         SET_CHECKED(rf69_set_dio_mapping(dev->spi, DIO0, DIO_Rssi_DIO0));
313         dev->irq_state[DIO0] = DIO_Rssi_DIO0;
314         irq_set_irq_type(dev->irq_num[DIO0], IRQ_TYPE_EDGE_RISING);
315
316         /* setup fifo level interrupt */
317         SET_CHECKED(rf69_set_fifo_threshold(dev->spi, FIFO_SIZE - FIFO_THRESHOLD));
318         SET_CHECKED(rf69_set_dio_mapping(dev->spi, DIO1, DIO_FifoLevel));
319         dev->irq_state[DIO1] = DIO_FifoLevel;
320         irq_set_irq_type(dev->irq_num[DIO1], IRQ_TYPE_EDGE_RISING);
321
322         /* set module to receiving mode */
323         SET_CHECKED(rf69_set_mode(dev->spi, receive));
324
325         return 0;
326 }
327
328
329 /*-------------------------------------------------------------------------*/
330
331 static int
332 pi433_receive(void *data)
333 {
334         struct pi433_device *dev = data;
335         struct spi_device *spi = dev->spi; /* needed for SET_CHECKED */
336         int bytes_to_read, bytes_total;
337         int retval;
338
339         dev->interrupt_rx_allowed = false;
340
341         /* wait for any tx to finish */
342         dev_dbg(dev->dev,"rx: going to wait for any tx to finish");
343         retval = wait_event_interruptible(dev->rx_wait_queue, !dev->tx_active);
344         if(retval) /* wait was interrupted */
345         {
346                 dev->interrupt_rx_allowed = true;
347                 wake_up_interruptible(&dev->tx_wait_queue);
348                 return retval;
349         }
350
351         /* prepare status vars */
352         dev->free_in_fifo = FIFO_SIZE;
353         dev->rx_position = 0;
354         dev->rx_bytes_dropped = 0;
355
356         /* setup radio module to listen for something "in the air" */
357         retval = pi433_start_rx(dev);
358         if (retval)
359                 return retval;
360
361         /* now check RSSI, if low wait for getting high (RSSI interrupt) */
362         while ( !rf69_get_flag(dev->spi, rssiExceededThreshold) )
363         {
364                 /* allow tx to interrupt us while waiting for high RSSI */
365                 dev->interrupt_rx_allowed = true;
366                 wake_up_interruptible(&dev->tx_wait_queue);
367
368                 /* wait for RSSI level to become high */
369                 dev_dbg(dev->dev, "rx: going to wait for high RSSI level");
370                 retval = wait_event_interruptible(dev->rx_wait_queue,
371                                                   rf69_get_flag(dev->spi,
372                                                                 rssiExceededThreshold));
373                 if (retval) goto abort; /* wait was interrupted */
374                 dev->interrupt_rx_allowed = false;
375
376                 /* cross check for ongoing tx */
377                 if (!dev->tx_active) break;
378         }
379
380         /* configure payload ready irq */
381         SET_CHECKED(rf69_set_dio_mapping(spi, DIO0, DIO_PayloadReady));
382         dev->irq_state[DIO0] = DIO_PayloadReady;
383         irq_set_irq_type(dev->irq_num[DIO0], IRQ_TYPE_EDGE_RISING);
384
385         /* fixed or unlimited length? */
386         if (dev->rx_cfg.fixed_message_length != 0)
387         {
388                 if (dev->rx_cfg.fixed_message_length > dev->rx_buffer_size)
389                 {
390                         retval = -1;
391                         goto abort;
392                 }
393                 bytes_total = dev->rx_cfg.fixed_message_length;
394                 dev_dbg(dev->dev,"rx: msg len set to %d by fixed length", bytes_total);
395         }
396         else
397         {
398                 bytes_total = dev->rx_buffer_size;
399                 dev_dbg(dev->dev, "rx: msg len set to %d as requested by read", bytes_total);
400         }
401
402         /* length byte enabled? */
403         if (dev->rx_cfg.enable_length_byte == optionOn)
404         {
405                 retval = wait_event_interruptible(dev->fifo_wait_queue,
406                                                   dev->free_in_fifo < FIFO_SIZE);
407                 if (retval) goto abort; /* wait was interrupted */
408
409                 rf69_read_fifo(spi, (u8 *)&bytes_total, 1);
410                 if (bytes_total > dev->rx_buffer_size)
411                 {
412                         retval = -1;
413                         goto abort;
414                 }
415                 dev->free_in_fifo++;
416                 dev_dbg(dev->dev, "rx: msg len reset to %d due to length byte", bytes_total);
417         }
418
419         /* address byte enabled? */
420         if (dev->rx_cfg.enable_address_filtering != filteringOff)
421         {
422                 u8 dummy;
423
424                 bytes_total--;
425
426                 retval = wait_event_interruptible(dev->fifo_wait_queue,
427                                                   dev->free_in_fifo < FIFO_SIZE);
428                 if (retval) goto abort; /* wait was interrupted */
429
430                 rf69_read_fifo(spi, &dummy, 1);
431                 dev->free_in_fifo++;
432                 dev_dbg(dev->dev, "rx: address byte stripped off");
433         }
434
435         /* get payload */
436         while (dev->rx_position < bytes_total)
437         {
438                 if ( !rf69_get_flag(dev->spi, payloadReady) )
439                 {
440                         retval = wait_event_interruptible(dev->fifo_wait_queue,
441                                                           dev->free_in_fifo < FIFO_SIZE);
442                         if (retval) goto abort; /* wait was interrupted */
443                 }
444
445                 /* need to drop bytes or acquire? */
446                 if (dev->rx_bytes_to_drop > dev->rx_bytes_dropped)
447                         bytes_to_read = dev->rx_bytes_to_drop - dev->rx_bytes_dropped;
448                 else
449                         bytes_to_read = bytes_total - dev->rx_position;
450
451
452                 /* access the fifo */
453                 if (bytes_to_read > FIFO_SIZE - dev->free_in_fifo)
454                         bytes_to_read = FIFO_SIZE - dev->free_in_fifo;
455                 retval = rf69_read_fifo(spi,
456                                         &dev->rx_buffer[dev->rx_position],
457                                         bytes_to_read);
458                 if (retval) goto abort; /* read failed */
459                 dev->free_in_fifo += bytes_to_read;
460
461                 /* adjust status vars */
462                 if (dev->rx_bytes_to_drop > dev->rx_bytes_dropped)
463                         dev->rx_bytes_dropped += bytes_to_read;
464                 else
465                         dev->rx_position += bytes_to_read;
466         }
467
468
469         /* rx done, wait was interrupted or error occured */
470 abort:
471         dev->interrupt_rx_allowed = true;
472         SET_CHECKED(rf69_set_mode(dev->spi, standby));
473         wake_up_interruptible(&dev->tx_wait_queue);
474
475         if (retval)
476                 return retval;
477         else
478                 return bytes_total;
479 }
480
481 static int
482 pi433_tx_thread(void *data)
483 {
484         struct pi433_device *device = data;
485         struct spi_device *spi = device->spi; /* needed for SET_CHECKED */
486         struct pi433_tx_cfg tx_cfg;
487         u8     *buffer = device->buffer;
488         size_t size;
489         bool   rx_interrupted = false;
490         int    position, repetitions;
491         int    retval;
492
493         while (1)
494         {
495                 /* wait for fifo to be populated or for request to terminate*/
496                 dev_dbg(device->dev, "thread: going to wait for new messages");
497                 wait_event_interruptible(device->tx_wait_queue,
498                                          ( !kfifo_is_empty(&device->tx_fifo) ||
499                                             kthread_should_stop() ));
500                 if ( kthread_should_stop() )
501                         return 0;
502
503                 /* get data from fifo in the following order:
504                  * - tx_cfg
505                  * - size of message
506                  * - message
507                  */
508                 mutex_lock(&device->tx_fifo_lock);
509
510                 retval = kfifo_out(&device->tx_fifo, &tx_cfg, sizeof(tx_cfg));
511                 if (retval != sizeof(tx_cfg))
512                 {
513                         dev_dbg(device->dev, "reading tx_cfg from fifo failed: got %d byte(s), expected %d", retval, (unsigned int)sizeof(tx_cfg) );
514                         mutex_unlock(&device->tx_fifo_lock);
515                         continue;
516                 }
517
518                 retval = kfifo_out(&device->tx_fifo, &size, sizeof(size_t));
519                 if (retval != sizeof(size_t))
520                 {
521                         dev_dbg(device->dev, "reading msg size from fifo failed: got %d, expected %d", retval, (unsigned int)sizeof(size_t) );
522                         mutex_unlock(&device->tx_fifo_lock);
523                         continue;
524                 }
525
526                 /* use fixed message length, if requested */
527                 if (tx_cfg.fixed_message_length != 0)
528                         size = tx_cfg.fixed_message_length;
529
530                 /* increase size, if len byte is requested */
531                 if (tx_cfg.enable_length_byte == optionOn)
532                         size++;
533
534                 /* increase size, if adr byte is requested */
535                 if (tx_cfg.enable_address_byte == optionOn)
536                         size++;
537
538                 /* prime buffer */
539                 memset(buffer, 0, size);
540                 position = 0;
541
542                 /* add length byte, if requested */
543                 if (tx_cfg.enable_length_byte  == optionOn)
544                         buffer[position++] = size-1; /* according to spec length byte itself must be excluded from the length calculation */
545
546                 /* add adr byte, if requested */
547                 if (tx_cfg.enable_address_byte == optionOn)
548                         buffer[position++] = tx_cfg.address_byte;
549
550                 /* finally get message data from fifo */
551                 retval = kfifo_out(&device->tx_fifo, &buffer[position], sizeof(buffer)-position );
552                 dev_dbg(device->dev, "read %d message byte(s) from fifo queue.", retval);
553                 mutex_unlock(&device->tx_fifo_lock);
554
555                 /* if rx is active, we need to interrupt the waiting for
556                  * incoming telegrams, to be able to send something.
557                  * We are only allowed, if currently no reception takes
558                  * place otherwise we need to  wait for the incoming telegram
559                  * to finish
560                  */
561                 wait_event_interruptible(device->tx_wait_queue,
562                                          !device->rx_active ||
563                                           device->interrupt_rx_allowed == true);
564
565                 /* prevent race conditions
566                  * irq will be reenabled after tx config is set
567                  */
568                 disable_irq(device->irq_num[DIO0]);
569                 device->tx_active = true;
570
571                 if (device->rx_active && rx_interrupted == false)
572                 {
573                         /* rx is currently waiting for a telegram;
574                          * we need to set the radio module to standby
575                          */
576                         SET_CHECKED(rf69_set_mode(device->spi, standby));
577                         rx_interrupted = true;
578                 }
579
580                 /* clear fifo, set fifo threshold, set payload length */
581                 SET_CHECKED(rf69_set_mode(spi, standby)); /* this clears the fifo */
582                 SET_CHECKED(rf69_set_fifo_threshold(spi, FIFO_THRESHOLD));
583                 if (tx_cfg.enable_length_byte == optionOn)
584                 {
585                         SET_CHECKED(rf69_set_payload_length(spi, size * tx_cfg.repetitions));
586                 }
587                 else
588                 {
589                         SET_CHECKED(rf69_set_payload_length(spi, 0));
590                 }
591
592                 /* configure the rf chip */
593                 rf69_set_tx_cfg(device, &tx_cfg);
594
595                 /* enable fifo level interrupt */
596                 SET_CHECKED(rf69_set_dio_mapping(spi, DIO1, DIO_FifoLevel));
597                 device->irq_state[DIO1] = DIO_FifoLevel;
598                 irq_set_irq_type(device->irq_num[DIO1], IRQ_TYPE_EDGE_FALLING);
599
600                 /* enable packet sent interrupt */
601                 SET_CHECKED(rf69_set_dio_mapping(spi, DIO0, DIO_PacketSent));
602                 device->irq_state[DIO0] = DIO_PacketSent;
603                 irq_set_irq_type(device->irq_num[DIO0], IRQ_TYPE_EDGE_RISING);
604                 enable_irq(device->irq_num[DIO0]); /* was disabled by rx active check */
605
606                 /* enable transmission */
607                 SET_CHECKED(rf69_set_mode(spi, transmit));
608
609                 /* transfer this msg (and repetitions) to chip fifo */
610                 device->free_in_fifo = FIFO_SIZE;
611                 position = 0;
612                 repetitions = tx_cfg.repetitions;
613                 while( (repetitions > 0) && (size > position) )
614                 {
615                         if ( (size - position) > device->free_in_fifo)
616                         {       /* msg to big for fifo - take a part */
617                                 int temp = device->free_in_fifo;
618                                 device->free_in_fifo = 0;
619                                 rf69_write_fifo(spi,
620                                                 &buffer[position],
621                                                 temp);
622                                 position +=temp;
623                         }
624                         else
625                         {       /* msg fits into fifo - take all */
626                                 device->free_in_fifo -= size;
627                                 repetitions--;
628                                 rf69_write_fifo(spi,
629                                                 &buffer[position],
630                                                 (size - position) );
631                                 position = 0; /* reset for next repetition */
632                         }
633
634                         retval = wait_event_interruptible(device->fifo_wait_queue,
635                                                           device->free_in_fifo > 0);
636                         if (retval) { printk("ABORT\n"); goto abort; }
637                 }
638
639                 /* we are done. Wait for packet to get sent */
640                 dev_dbg(device->dev, "thread: wait for packet to get sent/fifo to be empty");
641                 wait_event_interruptible(device->fifo_wait_queue,
642                                          device->free_in_fifo == FIFO_SIZE ||
643                                          kthread_should_stop() );
644                 if ( kthread_should_stop() )    printk("ABORT\n");
645
646
647                 /* STOP_TRANSMISSION */
648                 dev_dbg(device->dev, "thread: Packet sent. Set mode to stby.");
649                 SET_CHECKED(rf69_set_mode(spi, standby));
650
651                 /* everything sent? */
652                 if ( kfifo_is_empty(&device->tx_fifo) )
653                 {
654 abort:
655                         if (rx_interrupted)
656                         {
657                                 rx_interrupted = false;
658                                 pi433_start_rx(device);
659                         }
660                         device->tx_active = false;
661                         wake_up_interruptible(&device->rx_wait_queue);
662                 }
663         }
664 }
665
666 /*-------------------------------------------------------------------------*/
667
668 static ssize_t
669 pi433_read(struct file *filp, char __user *buf, size_t size, loff_t *f_pos)
670 {
671         struct pi433_instance   *instance;
672         struct pi433_device     *device;
673         int                     bytes_received;
674         ssize_t                 retval;
675
676         /* check, whether internal buffer is big enough for requested size */
677         if (size > MAX_MSG_SIZE)
678                 return -EMSGSIZE;
679
680         instance = filp->private_data;
681         device = instance->device;
682
683         /* just one read request at a time */
684         mutex_lock(&device->rx_lock);
685         if (device->rx_active)
686         {
687                 mutex_unlock(&device->rx_lock);
688                 return -EAGAIN;
689         }
690         else
691         {
692                 device->rx_active = true;
693                 mutex_unlock(&device->rx_lock);
694         }
695
696         /* start receiving */
697         /* will block until something was received*/
698         device->rx_buffer_size = size;
699         bytes_received = pi433_receive(device);
700
701         /* release rx */
702         mutex_lock(&device->rx_lock);
703         device->rx_active = false;
704         mutex_unlock(&device->rx_lock);
705
706         /* if read was successful copy to user space*/
707         if (bytes_received > 0)
708         {
709                 retval = copy_to_user(buf, device->rx_buffer, bytes_received);
710                 if (retval)
711                         return -EFAULT;
712         }
713
714         return bytes_received;
715 }
716
717
718 static ssize_t
719 pi433_write(struct file *filp, const char __user *buf,
720                 size_t count, loff_t *f_pos)
721 {
722         struct pi433_instance   *instance;
723         struct pi433_device     *device;
724         int                     copied, retval;
725
726         instance = filp->private_data;
727         device = instance->device;
728
729         /* check, whether internal buffer (tx thread) is big enough for requested size */
730         if (count > MAX_MSG_SIZE)
731                 return -EMSGSIZE;
732
733         /* write the following sequence into fifo:
734          * - tx_cfg
735          * - size of message
736          * - message
737          */
738         mutex_lock(&device->tx_fifo_lock);
739         retval = kfifo_in(&device->tx_fifo, &instance->tx_cfg, sizeof(instance->tx_cfg));
740         if ( retval != sizeof(instance->tx_cfg) )
741                 goto abort;
742
743         retval = kfifo_in (&device->tx_fifo, &count, sizeof(size_t));
744         if ( retval != sizeof(size_t) )
745                 goto abort;
746
747         retval = kfifo_from_user(&device->tx_fifo, buf, count, &copied);
748         if (retval || copied != count)
749                 goto abort;
750
751         mutex_unlock(&device->tx_fifo_lock);
752
753         /* start transfer */
754         wake_up_interruptible(&device->tx_wait_queue);
755         dev_dbg(device->dev, "write: generated new msg with %d bytes.", copied);
756
757         return 0;
758
759 abort:
760         dev_dbg(device->dev, "write to fifo failed: 0x%x", retval);
761         kfifo_reset(&device->tx_fifo); // TODO: maybe find a solution, not to discard already stored, valid entries
762         mutex_unlock(&device->tx_fifo_lock);
763         return -EAGAIN;
764 }
765
766
767 static long
768 pi433_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
769 {
770         int                     err = 0;
771         int                     retval = 0;
772         struct pi433_instance   *instance;
773         struct pi433_device     *device;
774         u32                     tmp;
775
776         /* Check type and command number */
777         if (_IOC_TYPE(cmd) != PI433_IOC_MAGIC)
778                 return -ENOTTY;
779
780         /* Check access direction once here; don't repeat below.
781          * IOC_DIR is from the user perspective, while access_ok is
782          * from the kernel perspective; so they look reversed.
783          */
784         if (_IOC_DIR(cmd) & _IOC_READ)
785                 err = !access_ok(VERIFY_WRITE,
786                                  (void __user *)arg,
787                                  _IOC_SIZE(cmd));
788
789         if (err == 0 && _IOC_DIR(cmd) & _IOC_WRITE)
790                 err = !access_ok(VERIFY_READ,
791                                  (void __user *)arg,
792                                  _IOC_SIZE(cmd));
793         if (err)
794                 return -EFAULT;
795
796         /* TODO? guard against device removal before, or while,
797          * we issue this ioctl. --> device_get()
798          */
799         instance = filp->private_data;
800         device = instance->device;
801
802         if (device == NULL)
803                 return -ESHUTDOWN;
804
805         switch (cmd) {
806         case PI433_IOC_RD_TX_CFG:
807                 tmp = _IOC_SIZE(cmd);
808                 if ( (tmp == 0) || ((tmp % sizeof(struct pi433_tx_cfg)) != 0) )
809                 {
810                         retval = -EINVAL;
811                         break;
812                 }
813
814                 if (__copy_to_user((void __user *)arg,
815                                     &instance->tx_cfg,
816                                     tmp))
817                 {
818                         retval = -EFAULT;
819                         break;
820                 }
821
822                 break;
823         case PI433_IOC_WR_TX_CFG:
824                 tmp = _IOC_SIZE(cmd);
825                 if ( (tmp == 0) || ((tmp % sizeof(struct pi433_tx_cfg)) != 0) )
826                 {
827                         retval = -EINVAL;
828                         break;
829                 }
830
831                 if (__copy_from_user(&instance->tx_cfg,
832                                      (void __user *)arg,
833                                      tmp))
834                 {
835                         retval = -EFAULT;
836                         break;
837                 }
838
839                 break;
840
841         case PI433_IOC_RD_RX_CFG:
842                 tmp = _IOC_SIZE(cmd);
843                 if ( (tmp == 0) || ((tmp % sizeof(struct pi433_rx_cfg)) != 0) ) {
844                         retval = -EINVAL;
845                         break;
846                 }
847
848                 if (__copy_to_user((void __user *)arg,
849                                    &device->rx_cfg,
850                                    tmp))
851                 {
852                         retval = -EFAULT;
853                         break;
854                 }
855
856                 break;
857         case PI433_IOC_WR_RX_CFG:
858                 tmp = _IOC_SIZE(cmd);
859                 mutex_lock(&device->rx_lock);
860
861                 /* during pendig read request, change of config not allowed */
862                 if (device->rx_active) {
863                         retval = -EAGAIN;
864                         mutex_unlock(&device->rx_lock);
865                         break;
866                 }
867
868                 if ( (tmp == 0) || ((tmp % sizeof(struct pi433_rx_cfg)) != 0) ) {
869                         retval = -EINVAL;
870                         mutex_unlock(&device->rx_lock);
871                         break;
872                 }
873
874                 if (__copy_from_user(&device->rx_cfg,
875                                      (void __user *)arg,
876                                      tmp))
877                 {
878                         retval = -EFAULT;
879                         mutex_unlock(&device->rx_lock);
880                         break;
881                 }
882
883                 mutex_unlock(&device->rx_lock);
884                 break;
885         default:
886                 retval = -EINVAL;
887         }
888
889         return retval;
890 }
891
892 #ifdef CONFIG_COMPAT
893 static long
894 pi433_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
895 {
896         return pi433_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
897 }
898 #else
899 #define pi433_compat_ioctl NULL
900 #endif /* CONFIG_COMPAT */
901
902 /*-------------------------------------------------------------------------*/
903
904 static int pi433_open(struct inode *inode, struct file *filp)
905 {
906         struct pi433_device     *device;
907         struct pi433_instance   *instance;
908
909         mutex_lock(&minor_lock);
910         device = idr_find(&pi433_idr, iminor(inode));
911         mutex_unlock(&minor_lock);
912         if (!device) {
913                 pr_debug("device: minor %d unknown.\n", iminor(inode));
914                 return -ENODEV;
915         }
916
917         if (!device->rx_buffer) {
918                 device->rx_buffer = kmalloc(MAX_MSG_SIZE, GFP_KERNEL);
919                 if (!device->rx_buffer)
920                 {
921                         dev_dbg(device->dev, "open/ENOMEM\n");
922                         return -ENOMEM;
923                 }
924         }
925
926         device->users++;
927         instance = kzalloc(sizeof(*instance), GFP_KERNEL);
928         if (!instance)
929         {
930                 kfree(device->rx_buffer);
931                 device->rx_buffer = NULL;
932                 return -ENOMEM;
933         }
934
935         /* setup instance data*/
936         instance->device = device;
937         instance->tx_cfg.bit_rate = 4711;
938         // TODO: fill instance->tx_cfg;
939
940         /* instance data as context */
941         filp->private_data = instance;
942         nonseekable_open(inode, filp);
943
944         return 0;
945 }
946
947 static int pi433_release(struct inode *inode, struct file *filp)
948 {
949         struct pi433_instance   *instance;
950         struct pi433_device     *device;
951
952         instance = filp->private_data;
953         device = instance->device;
954         kfree(instance);
955         filp->private_data = NULL;
956
957         /* last close? */
958         device->users--;
959
960         if (!device->users) {
961                 kfree(device->rx_buffer);
962                 device->rx_buffer = NULL;
963                 if (device->spi == NULL)
964                         kfree(device);
965         }
966
967         return 0;
968 }
969
970
971 /*-------------------------------------------------------------------------*/
972
973 static int setup_GPIOs(struct pi433_device *device)
974 {
975         char    name[5];
976         int     retval;
977         int     i;
978         const irq_handler_t DIO_irq_handler[NUM_DIO] = {
979                 DIO0_irq_handler,
980                 DIO1_irq_handler
981         };
982
983         for (i=0; i<NUM_DIO; i++)
984         {
985                 /* "construct" name and get the gpio descriptor */
986                 snprintf(name, sizeof(name), "DIO%d", i);
987                 device->gpiod[i] = gpiod_get(&device->spi->dev, name, 0 /*GPIOD_IN*/);
988
989                 if (device->gpiod[i] == ERR_PTR(-ENOENT))
990                 {
991                         dev_dbg(&device->spi->dev, "Could not find entry for %s. Ignoring.", name);
992                         continue;
993                 }
994
995                 if (device->gpiod[i] == ERR_PTR(-EBUSY))
996                         dev_dbg(&device->spi->dev, "%s is busy.", name);
997
998                 if ( IS_ERR(device->gpiod[i]) )
999                 {
1000                         retval = PTR_ERR(device->gpiod[i]);
1001                         /* release already allocated gpios */
1002                         for (i--; i>=0; i--)
1003                         {
1004                                 free_irq(device->irq_num[i], device);
1005                                 gpiod_put(device->gpiod[i]);
1006                         }
1007                         return retval;
1008                 }
1009
1010
1011                 /* configure the pin */
1012                 gpiod_unexport(device->gpiod[i]);
1013                 retval = gpiod_direction_input(device->gpiod[i]);
1014                 if (retval) return retval;
1015
1016
1017                 /* configure irq */
1018                 device->irq_num[i] = gpiod_to_irq(device->gpiod[i]);
1019                 if (device->irq_num[i] < 0)
1020                 {
1021                         device->gpiod[i] = ERR_PTR(-EINVAL);//(struct gpio_desc *)device->irq_num[i];
1022                         return device->irq_num[i];
1023                 }
1024                 retval = request_irq(device->irq_num[i],
1025                                      DIO_irq_handler[i],
1026                                      0, /* flags */
1027                                      name,
1028                                      device);
1029
1030                 if (retval)
1031                         return retval;
1032
1033                 dev_dbg(&device->spi->dev, "%s succesfully configured", name);
1034         }
1035
1036         return 0;
1037 }
1038
1039 static void free_GPIOs(struct pi433_device *device)
1040 {
1041         int i;
1042
1043         for (i=0; i<NUM_DIO; i++)
1044         {
1045                 /* check if gpiod is valid */
1046                 if ( IS_ERR(device->gpiod[i]) )
1047                         continue;
1048
1049                 free_irq(device->irq_num[i], device);
1050                 gpiod_put(device->gpiod[i]);
1051         }
1052         return;
1053 }
1054
1055 static int pi433_get_minor(struct pi433_device *device)
1056 {
1057         int retval = -ENOMEM;
1058
1059         mutex_lock(&minor_lock);
1060         retval = idr_alloc(&pi433_idr, device, 0, N_PI433_MINORS, GFP_KERNEL);
1061         if (retval >= 0) {
1062                 device->minor = retval;
1063                 retval = 0;
1064         } else if (retval == -ENOSPC) {
1065                 dev_err(device->dev, "too many pi433 devices\n");
1066                 retval = -EINVAL;
1067         }
1068         mutex_unlock(&minor_lock);
1069         return retval;
1070 }
1071
1072 static void pi433_free_minor(struct pi433_device *dev)
1073 {
1074         mutex_lock(&minor_lock);
1075         idr_remove(&pi433_idr, dev->minor);
1076         mutex_unlock(&minor_lock);
1077 }
1078 /*-------------------------------------------------------------------------*/
1079
1080 static const struct file_operations pi433_fops = {
1081         .owner =        THIS_MODULE,
1082         /* REVISIT switch to aio primitives, so that userspace
1083          * gets more complete API coverage.  It'll simplify things
1084          * too, except for the locking.
1085          */
1086         .write =        pi433_write,
1087         .read =         pi433_read,
1088         .unlocked_ioctl = pi433_ioctl,
1089         .compat_ioctl = pi433_compat_ioctl,
1090         .open =         pi433_open,
1091         .release =      pi433_release,
1092         .llseek =       no_llseek,
1093 };
1094
1095 /*-------------------------------------------------------------------------*/
1096
1097 static int pi433_probe(struct spi_device *spi)
1098 {
1099         struct pi433_device     *device;
1100         int                     retval;
1101
1102         /* setup spi parameters */
1103         spi->mode = 0x00;
1104         spi->bits_per_word = 8;
1105         /* spi->max_speed_hz = 10000000;  1MHz already set by device tree overlay */
1106
1107         retval = spi_setup(spi);
1108         if (retval)
1109         {
1110                 dev_dbg(&spi->dev, "configuration of SPI interface failed!\n");
1111                 return retval;
1112         }
1113         else
1114         {
1115                 dev_dbg(&spi->dev,
1116                         "spi interface setup: mode 0x%2x, %d bits per word, %dhz max speed",
1117                         spi->mode, spi->bits_per_word, spi->max_speed_hz);
1118         }
1119
1120         /* Ping the chip by reading the version register */
1121         retval = spi_w8r8(spi, 0x10);
1122         if (retval < 0)
1123                 return retval;
1124
1125         switch (retval) {
1126         case 0x24:
1127                 dev_dbg(&spi->dev, "found pi433 (ver. 0x%x)", retval);
1128                 break;
1129         default:
1130                 dev_dbg(&spi->dev, "unknown chip version: 0x%x", retval);
1131                 return -ENODEV;
1132         }
1133
1134         /* Allocate driver data */
1135         device = kzalloc(sizeof(*device), GFP_KERNEL);
1136         if (!device)
1137                 return -ENOMEM;
1138
1139         /* Initialize the driver data */
1140         device->spi = spi;
1141         device->rx_active = false;
1142         device->tx_active = false;
1143         device->interrupt_rx_allowed = false;
1144
1145         /* init wait queues */
1146         init_waitqueue_head(&device->tx_wait_queue);
1147         init_waitqueue_head(&device->rx_wait_queue);
1148         init_waitqueue_head(&device->fifo_wait_queue);
1149
1150         /* init fifo */
1151         INIT_KFIFO(device->tx_fifo);
1152
1153         /* init mutexes and locks */
1154         mutex_init(&device->tx_fifo_lock);
1155         mutex_init(&device->rx_lock);
1156
1157         /* setup GPIO (including irq_handler) for the different DIOs */
1158         retval = setup_GPIOs(device);
1159         if (retval)
1160         {
1161                 dev_dbg(&spi->dev, "setup of GPIOs failed");
1162                 goto GPIO_failed;
1163         }
1164
1165         /* setup the radio module */
1166         SET_CHECKED(rf69_set_mode               (spi, standby));
1167         SET_CHECKED(rf69_set_data_mode          (spi, packet));
1168         SET_CHECKED(rf69_set_amplifier_0        (spi, optionOn));
1169         SET_CHECKED(rf69_set_amplifier_1        (spi, optionOff));
1170         SET_CHECKED(rf69_set_amplifier_2        (spi, optionOff));
1171         SET_CHECKED(rf69_set_output_power_level (spi, 13));
1172         SET_CHECKED(rf69_set_antenna_impedance  (spi, fiftyOhm));
1173
1174         /* start tx thread */
1175         device->tx_task_struct = kthread_run(pi433_tx_thread,
1176                                              device,
1177                                              "pi433_tx_task");
1178         if (IS_ERR(device->tx_task_struct))
1179         {
1180                 dev_dbg(device->dev, "start of send thread failed");
1181                 goto send_thread_failed;
1182         }
1183
1184         /* determ minor number */
1185         retval = pi433_get_minor(device);
1186         if (retval)
1187         {
1188                 dev_dbg(device->dev, "get of minor number failed");
1189                 goto minor_failed;
1190         }
1191
1192         /* create device */
1193         device->devt = MKDEV(MAJOR(pi433_dev), device->minor);
1194         device->dev = device_create(pi433_class,
1195                                     &spi->dev,
1196                                     device->devt,
1197                                     device,
1198                                     "pi433");
1199         if (IS_ERR(device->dev)) {
1200                 pr_err("pi433: device register failed\n");
1201                 retval = PTR_ERR(device->dev);
1202                 goto device_create_failed;
1203         }
1204         else {
1205                 dev_dbg(device->dev,
1206                         "created device for major %d, minor %d\n",
1207                         MAJOR(pi433_dev),
1208                         device->minor);
1209         }
1210
1211         /* create cdev */
1212         device->cdev = cdev_alloc();
1213         device->cdev->owner = THIS_MODULE;
1214         cdev_init(device->cdev, &pi433_fops);
1215         retval = cdev_add(device->cdev, device->devt, 1);
1216         if (retval)
1217         {
1218                 dev_dbg(device->dev, "register of cdev failed");
1219                 goto cdev_failed;
1220         }
1221
1222         /* spi setup */
1223         spi_set_drvdata(spi, device);
1224
1225         return 0;
1226
1227 cdev_failed:
1228         device_destroy(pi433_class, device->devt);
1229 device_create_failed:
1230         pi433_free_minor(device);
1231 minor_failed:
1232         kthread_stop(device->tx_task_struct);
1233 send_thread_failed:
1234         free_GPIOs(device);
1235 GPIO_failed:
1236         kfree(device);
1237
1238         return retval;
1239 }
1240
1241 static int pi433_remove(struct spi_device *spi)
1242 {
1243         struct pi433_device     *device = spi_get_drvdata(spi);
1244
1245         /* free GPIOs */
1246         free_GPIOs(device);
1247
1248         /* make sure ops on existing fds can abort cleanly */
1249         device->spi = NULL;
1250
1251         kthread_stop(device->tx_task_struct);
1252
1253         device_destroy(pi433_class, device->devt);
1254
1255         cdev_del(device->cdev);
1256
1257         pi433_free_minor(device);
1258
1259         if (device->users == 0)
1260                 kfree(device);
1261
1262         return 0;
1263 }
1264
1265 static const struct of_device_id pi433_dt_ids[] = {
1266         { .compatible = "Smarthome-Wolf,pi433" },
1267         {},
1268 };
1269
1270 MODULE_DEVICE_TABLE(of, pi433_dt_ids);
1271
1272 static struct spi_driver pi433_spi_driver = {
1273         .driver = {
1274                 .name =         "pi433",
1275                 .owner =        THIS_MODULE,
1276                 .of_match_table = of_match_ptr(pi433_dt_ids),
1277         },
1278         .probe =        pi433_probe,
1279         .remove =       pi433_remove,
1280
1281         /* NOTE:  suspend/resume methods are not necessary here.
1282          * We don't do anything except pass the requests to/from
1283          * the underlying controller.  The refrigerator handles
1284          * most issues; the controller driver handles the rest.
1285          */
1286 };
1287
1288 /*-------------------------------------------------------------------------*/
1289
1290 static int __init pi433_init(void)
1291 {
1292         int status;
1293
1294         /* If MAX_MSG_SIZE is smaller then FIFO_SIZE, the driver won't
1295          * work stable - risk of buffer overflow
1296          */
1297         if (MAX_MSG_SIZE < FIFO_SIZE)
1298                 return -EINVAL;
1299
1300         /* Claim device numbers.  Then register a class
1301          * that will key udev/mdev to add/remove /dev nodes.  Last, register
1302          * Last, register the driver which manages those device numbers.
1303          */
1304         status = alloc_chrdev_region(&pi433_dev, 0 /*firstminor*/, N_PI433_MINORS /*count*/, "pi433" /*name*/);
1305         if (status < 0)
1306                 return status;
1307
1308         pi433_class = class_create(THIS_MODULE, "pi433");
1309         if (IS_ERR(pi433_class))
1310         {
1311                 unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1312                 return PTR_ERR(pi433_class);
1313         }
1314
1315         status = spi_register_driver(&pi433_spi_driver);
1316         if (status < 0)
1317         {
1318                 class_destroy(pi433_class);
1319                 unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1320         }
1321
1322         return status;
1323 }
1324
1325 module_init(pi433_init);
1326
1327 static void __exit pi433_exit(void)
1328 {
1329         spi_unregister_driver(&pi433_spi_driver);
1330         class_destroy(pi433_class);
1331         unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1332 }
1333 module_exit(pi433_exit);
1334
1335 MODULE_AUTHOR("Marcus Wolf, <linux@wolf-entwicklungen.de>");
1336 MODULE_DESCRIPTION("Driver for Pi433");
1337 MODULE_LICENSE("GPL");
1338 MODULE_ALIAS("spi:pi433");