2 * userspace interface for pi433 radio module
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.
8 * If needed, this driver could be extended, to also support other
9 * devices, basing on HopeRfs rf69.
11 * The driver can also be extended, to support other modules of
12 * HopeRf with a similar interace - e. g. RFM69HCW, RFM12, RFM95, ...
14 * Copyright (C) 2016 Wolf-Entwicklungen
15 * Marcus Wolf <linux@wolf-entwicklungen.de>
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.
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.
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>
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>
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>
51 #include <asm/compat.h>
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 */
63 static dev_t pi433_dev;
64 static DEFINE_IDR(pi433_idr);
65 static DEFINE_MUTEX(minor_lock); /* Protect idr accesses */
67 static struct class *pi433_class; /* mainly for udev to create /dev/pi433 */
69 /* tx config is instance specific
70 * so with each open a new tx config struct is needed
72 /* rx config is device specific
73 * so we have just one rx config, ebedded in device struct
76 /* device handling related values */
81 struct spi_device *spi;
84 /* irq related values */
85 struct gpio_desc *gpiod[NUM_DIO];
87 u8 irq_state[NUM_DIO];
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;
95 char buffer[MAX_MSG_SIZE];
97 /* rx related values */
98 struct pi433_rx_cfg rx_cfg;
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;
107 /* fifo wait queue */
108 struct task_struct *fifo_task_struct;
109 wait_queue_head_t fifo_wait_queue;
114 bool interrupt_rx_allowed;
117 struct pi433_instance {
118 struct pi433_device *device;
119 struct pi433_tx_cfg tx_cfg;
122 /*-------------------------------------------------------------------------*/
124 /* macro for checked access of registers of radio module */
125 #define SET_CHECKED(retval) \
129 /*-------------------------------------------------------------------------*/
131 /* GPIO interrupt handlers */
132 static irqreturn_t DIO0_irq_handler(int irq, void *dev_id)
134 struct pi433_device *device = dev_id;
136 if (device->irq_state[DIO0] == DIO_PacketSent)
138 device->free_in_fifo = FIFO_SIZE;
139 dev_dbg(device->dev, "DIO0 irq: Packet sent\n");
140 wake_up_interruptible(&device->fifo_wait_queue);
142 else if (device->irq_state[DIO0] == DIO_Rssi_DIO0)
144 dev_dbg(device->dev, "DIO0 irq: RSSI level over threshold\n");
145 wake_up_interruptible(&device->rx_wait_queue);
147 else if (device->irq_state[DIO0] == DIO_PayloadReady)
149 dev_dbg(device->dev, "DIO0 irq: PayloadReady\n");
150 device->free_in_fifo = 0;
151 wake_up_interruptible(&device->fifo_wait_queue);
157 static irqreturn_t DIO1_irq_handler(int irq, void *dev_id)
159 struct pi433_device *device = dev_id;
161 if (device->irq_state[DIO1] == DIO_FifoNotEmpty_DIO1)
163 device->free_in_fifo = FIFO_SIZE;
165 else if (device->irq_state[DIO1] == DIO_FifoLevel)
167 if (device->rx_active) device->free_in_fifo = FIFO_THRESHOLD - 1;
168 else device->free_in_fifo = FIFO_SIZE - FIFO_THRESHOLD - 1;
171 "DIO1 irq: %d bytes free in fifo\n", device->free_in_fifo);
172 wake_up_interruptible(&device->fifo_wait_queue);
177 /*-------------------------------------------------------------------------*/
180 rf69_set_rx_cfg(struct pi433_device *dev, struct pi433_rx_cfg *rx_cfg)
185 /* receiver config */
186 SET_CHECKED(rf69_set_frequency (dev->spi, rx_cfg->frequency));
187 SET_CHECKED(rf69_set_bit_rate (dev->spi, rx_cfg->bit_rate));
188 SET_CHECKED(rf69_set_modulation (dev->spi, rx_cfg->modulation));
189 SET_CHECKED(rf69_set_antenna_impedance (dev->spi, rx_cfg->antenna_impedance));
190 SET_CHECKED(rf69_set_rssi_threshold (dev->spi, rx_cfg->rssi_threshold));
191 SET_CHECKED(rf69_set_ook_threshold_dec (dev->spi, rx_cfg->thresholdDecrement));
192 SET_CHECKED(rf69_set_bandwidth (dev->spi, rx_cfg->bw_mantisse, rx_cfg->bw_exponent));
193 SET_CHECKED(rf69_set_bandwidth_during_afc(dev->spi, rx_cfg->bw_mantisse, rx_cfg->bw_exponent));
194 SET_CHECKED(rf69_set_dagc (dev->spi, rx_cfg->dagc));
196 dev->rx_bytes_to_drop = rx_cfg->bytes_to_drop;
200 SET_CHECKED(rf69_set_sync_enable(dev->spi, rx_cfg->enable_sync));
201 if (rx_cfg->enable_sync == optionOn)
203 SET_CHECKED(rf69_set_fifo_fill_condition(dev->spi, afterSyncInterrupt));
207 SET_CHECKED(rf69_set_fifo_fill_condition(dev->spi, always));
209 if (rx_cfg->enable_length_byte == optionOn) {
210 ret = rf69_set_packet_format(dev->spi, packetLengthVar);
214 ret = rf69_set_packet_format(dev->spi, packetLengthFix);
218 SET_CHECKED(rf69_set_adressFiltering(dev->spi, rx_cfg->enable_address_filtering));
219 SET_CHECKED(rf69_set_crc_enable (dev->spi, rx_cfg->enable_crc));
222 SET_CHECKED(rf69_set_sync_size(dev->spi, rx_cfg->sync_length));
223 if (rx_cfg->enable_length_byte == optionOn)
225 SET_CHECKED(rf69_set_payload_length(dev->spi, 0xff));
227 else if (rx_cfg->fixed_message_length != 0)
229 payload_length = rx_cfg->fixed_message_length;
230 if (rx_cfg->enable_length_byte == optionOn) payload_length++;
231 if (rx_cfg->enable_address_filtering != filteringOff) payload_length++;
232 SET_CHECKED(rf69_set_payload_length(dev->spi, payload_length));
236 SET_CHECKED(rf69_set_payload_length(dev->spi, 0));
240 if (rx_cfg->enable_sync == optionOn)
242 SET_CHECKED(rf69_set_sync_values(dev->spi, rx_cfg->sync_pattern));
244 if (rx_cfg->enable_address_filtering != filteringOff)
246 SET_CHECKED(rf69_set_node_address (dev->spi, rx_cfg->node_address));
247 SET_CHECKED(rf69_set_broadcast_address(dev->spi, rx_cfg->broadcast_address));
254 rf69_set_tx_cfg(struct pi433_device *dev, struct pi433_tx_cfg *tx_cfg)
258 SET_CHECKED(rf69_set_frequency (dev->spi, tx_cfg->frequency));
259 SET_CHECKED(rf69_set_bit_rate (dev->spi, tx_cfg->bit_rate));
260 SET_CHECKED(rf69_set_modulation (dev->spi, tx_cfg->modulation));
261 SET_CHECKED(rf69_set_deviation (dev->spi, tx_cfg->dev_frequency));
262 SET_CHECKED(rf69_set_pa_ramp (dev->spi, tx_cfg->pa_ramp));
263 SET_CHECKED(rf69_set_modulation_shaping(dev->spi, tx_cfg->modShaping));
264 SET_CHECKED(rf69_set_tx_start_condition(dev->spi, tx_cfg->tx_start_condition));
266 /* packet format enable */
267 if (tx_cfg->enable_preamble == optionOn)
269 SET_CHECKED(rf69_set_preamble_length(dev->spi, tx_cfg->preamble_length));
273 SET_CHECKED(rf69_set_preamble_length(dev->spi, 0));
275 SET_CHECKED(rf69_set_sync_enable (dev->spi, tx_cfg->enable_sync));
276 if (tx_cfg->enable_length_byte == optionOn) {
277 ret = rf69_set_packet_format(dev->spi, packetLengthVar);
281 ret = rf69_set_packet_format(dev->spi, packetLengthFix);
285 SET_CHECKED(rf69_set_crc_enable (dev->spi, tx_cfg->enable_crc));
287 /* configure sync, if enabled */
288 if (tx_cfg->enable_sync == optionOn) {
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));
296 /*-------------------------------------------------------------------------*/
299 pi433_start_rx(struct pi433_device *dev)
303 /* return without action, if no pending read request */
307 /* setup for receiving */
308 retval = rf69_set_rx_cfg(dev, &dev->rx_cfg);
309 if (retval) return retval;
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);
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);
322 /* set module to receiving mode */
323 SET_CHECKED(rf69_set_mode(dev->spi, receive));
329 /*-------------------------------------------------------------------------*/
332 pi433_receive(void *data)
334 struct pi433_device *dev = data;
335 struct spi_device *spi = dev->spi; /* needed for SET_CHECKED */
336 int bytes_to_read, bytes_total;
339 dev->interrupt_rx_allowed = false;
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 */
346 dev->interrupt_rx_allowed = true;
347 wake_up_interruptible(&dev->tx_wait_queue);
351 /* prepare status vars */
352 dev->free_in_fifo = FIFO_SIZE;
353 dev->rx_position = 0;
354 dev->rx_bytes_dropped = 0;
356 /* setup radio module to listen for something "in the air" */
357 retval = pi433_start_rx(dev);
361 /* now check RSSI, if low wait for getting high (RSSI interrupt) */
362 while ( !rf69_get_flag(dev->spi, rssiExceededThreshold) )
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);
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;
376 /* cross check for ongoing tx */
377 if (!dev->tx_active) break;
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);
385 /* fixed or unlimited length? */
386 if (dev->rx_cfg.fixed_message_length != 0)
388 if (dev->rx_cfg.fixed_message_length > dev->rx_buffer_size)
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);
398 bytes_total = dev->rx_buffer_size;
399 dev_dbg(dev->dev, "rx: msg len set to %d as requested by read", bytes_total);
402 /* length byte enabled? */
403 if (dev->rx_cfg.enable_length_byte == optionOn)
405 retval = wait_event_interruptible(dev->fifo_wait_queue,
406 dev->free_in_fifo < FIFO_SIZE);
407 if (retval) goto abort; /* wait was interrupted */
409 rf69_read_fifo(spi, (u8 *)&bytes_total, 1);
410 if (bytes_total > dev->rx_buffer_size) {
415 dev_dbg(dev->dev, "rx: msg len reset to %d due to length byte", bytes_total);
418 /* address byte enabled? */
419 if (dev->rx_cfg.enable_address_filtering != filteringOff)
425 retval = wait_event_interruptible(dev->fifo_wait_queue,
426 dev->free_in_fifo < FIFO_SIZE);
427 if (retval) goto abort; /* wait was interrupted */
429 rf69_read_fifo(spi, &dummy, 1);
431 dev_dbg(dev->dev, "rx: address byte stripped off");
435 while (dev->rx_position < bytes_total)
437 if ( !rf69_get_flag(dev->spi, payloadReady) )
439 retval = wait_event_interruptible(dev->fifo_wait_queue,
440 dev->free_in_fifo < FIFO_SIZE);
441 if (retval) goto abort; /* wait was interrupted */
444 /* need to drop bytes or acquire? */
445 if (dev->rx_bytes_to_drop > dev->rx_bytes_dropped)
446 bytes_to_read = dev->rx_bytes_to_drop - dev->rx_bytes_dropped;
448 bytes_to_read = bytes_total - dev->rx_position;
451 /* access the fifo */
452 if (bytes_to_read > FIFO_SIZE - dev->free_in_fifo)
453 bytes_to_read = FIFO_SIZE - dev->free_in_fifo;
454 retval = rf69_read_fifo(spi,
455 &dev->rx_buffer[dev->rx_position],
457 if (retval) goto abort; /* read failed */
458 dev->free_in_fifo += bytes_to_read;
460 /* adjust status vars */
461 if (dev->rx_bytes_to_drop > dev->rx_bytes_dropped)
462 dev->rx_bytes_dropped += bytes_to_read;
464 dev->rx_position += bytes_to_read;
468 /* rx done, wait was interrupted or error occurred */
470 dev->interrupt_rx_allowed = true;
471 SET_CHECKED(rf69_set_mode(dev->spi, standby));
472 wake_up_interruptible(&dev->tx_wait_queue);
481 pi433_tx_thread(void *data)
483 struct pi433_device *device = data;
484 struct spi_device *spi = device->spi; /* needed for SET_CHECKED */
485 struct pi433_tx_cfg tx_cfg;
486 u8 *buffer = device->buffer;
488 bool rx_interrupted = false;
489 int position, repetitions;
494 /* wait for fifo to be populated or for request to terminate*/
495 dev_dbg(device->dev, "thread: going to wait for new messages");
496 wait_event_interruptible(device->tx_wait_queue,
497 ( !kfifo_is_empty(&device->tx_fifo) ||
498 kthread_should_stop() ));
499 if ( kthread_should_stop() )
502 /* get data from fifo in the following order:
507 mutex_lock(&device->tx_fifo_lock);
509 retval = kfifo_out(&device->tx_fifo, &tx_cfg, sizeof(tx_cfg));
510 if (retval != sizeof(tx_cfg)) {
511 dev_dbg(device->dev, "reading tx_cfg from fifo failed: got %d byte(s), expected %d", retval, (unsigned int)sizeof(tx_cfg) );
512 mutex_unlock(&device->tx_fifo_lock);
516 retval = kfifo_out(&device->tx_fifo, &size, sizeof(size_t));
517 if (retval != sizeof(size_t)) {
518 dev_dbg(device->dev, "reading msg size from fifo failed: got %d, expected %d", retval, (unsigned int)sizeof(size_t) );
519 mutex_unlock(&device->tx_fifo_lock);
523 /* use fixed message length, if requested */
524 if (tx_cfg.fixed_message_length != 0)
525 size = tx_cfg.fixed_message_length;
527 /* increase size, if len byte is requested */
528 if (tx_cfg.enable_length_byte == optionOn)
531 /* increase size, if adr byte is requested */
532 if (tx_cfg.enable_address_byte == optionOn)
536 memset(buffer, 0, size);
539 /* add length byte, if requested */
540 if (tx_cfg.enable_length_byte == optionOn)
541 buffer[position++] = size-1; /* according to spec length byte itself must be excluded from the length calculation */
543 /* add adr byte, if requested */
544 if (tx_cfg.enable_address_byte == optionOn)
545 buffer[position++] = tx_cfg.address_byte;
547 /* finally get message data from fifo */
548 retval = kfifo_out(&device->tx_fifo, &buffer[position], sizeof(buffer)-position );
549 dev_dbg(device->dev, "read %d message byte(s) from fifo queue.", retval);
550 mutex_unlock(&device->tx_fifo_lock);
552 /* if rx is active, we need to interrupt the waiting for
553 * incoming telegrams, to be able to send something.
554 * We are only allowed, if currently no reception takes
555 * place otherwise we need to wait for the incoming telegram
558 wait_event_interruptible(device->tx_wait_queue,
559 !device->rx_active ||
560 device->interrupt_rx_allowed == true);
562 /* prevent race conditions
563 * irq will be reenabled after tx config is set
565 disable_irq(device->irq_num[DIO0]);
566 device->tx_active = true;
568 if (device->rx_active && rx_interrupted == false)
570 /* rx is currently waiting for a telegram;
571 * we need to set the radio module to standby
573 SET_CHECKED(rf69_set_mode(device->spi, standby));
574 rx_interrupted = true;
577 /* clear fifo, set fifo threshold, set payload length */
578 SET_CHECKED(rf69_set_mode(spi, standby)); /* this clears the fifo */
579 SET_CHECKED(rf69_set_fifo_threshold(spi, FIFO_THRESHOLD));
580 if (tx_cfg.enable_length_byte == optionOn)
582 SET_CHECKED(rf69_set_payload_length(spi, size * tx_cfg.repetitions));
586 SET_CHECKED(rf69_set_payload_length(spi, 0));
589 /* configure the rf chip */
590 rf69_set_tx_cfg(device, &tx_cfg);
592 /* enable fifo level interrupt */
593 SET_CHECKED(rf69_set_dio_mapping(spi, DIO1, DIO_FifoLevel));
594 device->irq_state[DIO1] = DIO_FifoLevel;
595 irq_set_irq_type(device->irq_num[DIO1], IRQ_TYPE_EDGE_FALLING);
597 /* enable packet sent interrupt */
598 SET_CHECKED(rf69_set_dio_mapping(spi, DIO0, DIO_PacketSent));
599 device->irq_state[DIO0] = DIO_PacketSent;
600 irq_set_irq_type(device->irq_num[DIO0], IRQ_TYPE_EDGE_RISING);
601 enable_irq(device->irq_num[DIO0]); /* was disabled by rx active check */
603 /* enable transmission */
604 SET_CHECKED(rf69_set_mode(spi, transmit));
606 /* transfer this msg (and repetitions) to chip fifo */
607 device->free_in_fifo = FIFO_SIZE;
609 repetitions = tx_cfg.repetitions;
610 while( (repetitions > 0) && (size > position) )
612 if ( (size - position) > device->free_in_fifo)
613 { /* msg to big for fifo - take a part */
614 int temp = device->free_in_fifo;
615 device->free_in_fifo = 0;
622 { /* msg fits into fifo - take all */
623 device->free_in_fifo -= size;
628 position = 0; /* reset for next repetition */
631 retval = wait_event_interruptible(device->fifo_wait_queue,
632 device->free_in_fifo > 0);
633 if (retval) { printk("ABORT\n"); goto abort; }
636 /* we are done. Wait for packet to get sent */
637 dev_dbg(device->dev, "thread: wait for packet to get sent/fifo to be empty");
638 wait_event_interruptible(device->fifo_wait_queue,
639 device->free_in_fifo == FIFO_SIZE ||
640 kthread_should_stop() );
641 if ( kthread_should_stop() ) printk("ABORT\n");
644 /* STOP_TRANSMISSION */
645 dev_dbg(device->dev, "thread: Packet sent. Set mode to stby.");
646 SET_CHECKED(rf69_set_mode(spi, standby));
648 /* everything sent? */
649 if (kfifo_is_empty(&device->tx_fifo)) {
653 rx_interrupted = false;
654 pi433_start_rx(device);
656 device->tx_active = false;
657 wake_up_interruptible(&device->rx_wait_queue);
662 /*-------------------------------------------------------------------------*/
665 pi433_read(struct file *filp, char __user *buf, size_t size, loff_t *f_pos)
667 struct pi433_instance *instance;
668 struct pi433_device *device;
672 /* check, whether internal buffer is big enough for requested size */
673 if (size > MAX_MSG_SIZE)
676 instance = filp->private_data;
677 device = instance->device;
679 /* just one read request at a time */
680 mutex_lock(&device->rx_lock);
681 if (device->rx_active)
683 mutex_unlock(&device->rx_lock);
688 device->rx_active = true;
689 mutex_unlock(&device->rx_lock);
692 /* start receiving */
693 /* will block until something was received*/
694 device->rx_buffer_size = size;
695 bytes_received = pi433_receive(device);
698 mutex_lock(&device->rx_lock);
699 device->rx_active = false;
700 mutex_unlock(&device->rx_lock);
702 /* if read was successful copy to user space*/
703 if (bytes_received > 0) {
704 retval = copy_to_user(buf, device->rx_buffer, bytes_received);
709 return bytes_received;
714 pi433_write(struct file *filp, const char __user *buf,
715 size_t count, loff_t *f_pos)
717 struct pi433_instance *instance;
718 struct pi433_device *device;
721 instance = filp->private_data;
722 device = instance->device;
724 /* check, whether internal buffer (tx thread) is big enough for requested size */
725 if (count > MAX_MSG_SIZE)
728 /* write the following sequence into fifo:
733 mutex_lock(&device->tx_fifo_lock);
734 retval = kfifo_in(&device->tx_fifo, &instance->tx_cfg, sizeof(instance->tx_cfg));
735 if ( retval != sizeof(instance->tx_cfg) )
738 retval = kfifo_in (&device->tx_fifo, &count, sizeof(size_t));
739 if ( retval != sizeof(size_t) )
742 retval = kfifo_from_user(&device->tx_fifo, buf, count, &copied);
743 if (retval || copied != count)
746 mutex_unlock(&device->tx_fifo_lock);
749 wake_up_interruptible(&device->tx_wait_queue);
750 dev_dbg(device->dev, "write: generated new msg with %d bytes.", copied);
755 dev_dbg(device->dev, "write to fifo failed: 0x%x", retval);
756 kfifo_reset(&device->tx_fifo); // TODO: maybe find a solution, not to discard already stored, valid entries
757 mutex_unlock(&device->tx_fifo_lock);
763 pi433_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
766 struct pi433_instance *instance;
767 struct pi433_device *device;
768 void __user *argp = (void __user *)arg;
770 /* Check type and command number */
771 if (_IOC_TYPE(cmd) != PI433_IOC_MAGIC)
774 /* TODO? guard against device removal before, or while,
775 * we issue this ioctl. --> device_get()
777 instance = filp->private_data;
778 device = instance->device;
784 case PI433_IOC_RD_TX_CFG:
785 if (copy_to_user(argp, &instance->tx_cfg,
786 sizeof(struct pi433_tx_cfg)))
789 case PI433_IOC_WR_TX_CFG:
790 if (copy_from_user(&instance->tx_cfg, argp,
791 sizeof(struct pi433_tx_cfg)))
794 case PI433_IOC_RD_RX_CFG:
795 if (copy_to_user(argp, &device->rx_cfg,
796 sizeof(struct pi433_rx_cfg)))
799 case PI433_IOC_WR_RX_CFG:
800 mutex_lock(&device->rx_lock);
802 /* during pendig read request, change of config not allowed */
803 if (device->rx_active) {
804 mutex_unlock(&device->rx_lock);
808 if (copy_from_user(&device->rx_cfg, argp,
809 sizeof(struct pi433_rx_cfg))) {
810 mutex_unlock(&device->rx_lock);
814 mutex_unlock(&device->rx_lock);
825 pi433_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
827 return pi433_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
830 #define pi433_compat_ioctl NULL
831 #endif /* CONFIG_COMPAT */
833 /*-------------------------------------------------------------------------*/
835 static int pi433_open(struct inode *inode, struct file *filp)
837 struct pi433_device *device;
838 struct pi433_instance *instance;
840 mutex_lock(&minor_lock);
841 device = idr_find(&pi433_idr, iminor(inode));
842 mutex_unlock(&minor_lock);
844 pr_debug("device: minor %d unknown.\n", iminor(inode));
848 if (!device->rx_buffer) {
849 device->rx_buffer = kmalloc(MAX_MSG_SIZE, GFP_KERNEL);
850 if (!device->rx_buffer) {
851 dev_dbg(device->dev, "open/ENOMEM\n");
857 instance = kzalloc(sizeof(*instance), GFP_KERNEL);
859 kfree(device->rx_buffer);
860 device->rx_buffer = NULL;
864 /* setup instance data*/
865 instance->device = device;
866 instance->tx_cfg.bit_rate = 4711;
867 // TODO: fill instance->tx_cfg;
869 /* instance data as context */
870 filp->private_data = instance;
871 nonseekable_open(inode, filp);
876 static int pi433_release(struct inode *inode, struct file *filp)
878 struct pi433_instance *instance;
879 struct pi433_device *device;
881 instance = filp->private_data;
882 device = instance->device;
884 filp->private_data = NULL;
889 if (!device->users) {
890 kfree(device->rx_buffer);
891 device->rx_buffer = NULL;
892 if (device->spi == NULL)
900 /*-------------------------------------------------------------------------*/
902 static int setup_GPIOs(struct pi433_device *device)
907 const irq_handler_t DIO_irq_handler[NUM_DIO] = {
912 for (i=0; i<NUM_DIO; i++)
914 /* "construct" name and get the gpio descriptor */
915 snprintf(name, sizeof(name), "DIO%d", i);
916 device->gpiod[i] = gpiod_get(&device->spi->dev, name, 0 /*GPIOD_IN*/);
918 if (device->gpiod[i] == ERR_PTR(-ENOENT)) {
919 dev_dbg(&device->spi->dev, "Could not find entry for %s. Ignoring.", name);
923 if (device->gpiod[i] == ERR_PTR(-EBUSY))
924 dev_dbg(&device->spi->dev, "%s is busy.", name);
926 if ( IS_ERR(device->gpiod[i]) )
928 retval = PTR_ERR(device->gpiod[i]);
929 /* release already allocated gpios */
932 free_irq(device->irq_num[i], device);
933 gpiod_put(device->gpiod[i]);
939 /* configure the pin */
940 gpiod_unexport(device->gpiod[i]);
941 retval = gpiod_direction_input(device->gpiod[i]);
942 if (retval) return retval;
946 device->irq_num[i] = gpiod_to_irq(device->gpiod[i]);
947 if (device->irq_num[i] < 0) {
948 device->gpiod[i] = ERR_PTR(-EINVAL);//(struct gpio_desc *)device->irq_num[i];
949 return device->irq_num[i];
951 retval = request_irq(device->irq_num[i],
960 dev_dbg(&device->spi->dev, "%s successfully configured", name);
966 static void free_GPIOs(struct pi433_device *device)
970 for (i=0; i<NUM_DIO; i++)
972 /* check if gpiod is valid */
973 if ( IS_ERR(device->gpiod[i]) )
976 free_irq(device->irq_num[i], device);
977 gpiod_put(device->gpiod[i]);
982 static int pi433_get_minor(struct pi433_device *device)
984 int retval = -ENOMEM;
986 mutex_lock(&minor_lock);
987 retval = idr_alloc(&pi433_idr, device, 0, N_PI433_MINORS, GFP_KERNEL);
989 device->minor = retval;
991 } else if (retval == -ENOSPC) {
992 dev_err(device->dev, "too many pi433 devices\n");
995 mutex_unlock(&minor_lock);
999 static void pi433_free_minor(struct pi433_device *dev)
1001 mutex_lock(&minor_lock);
1002 idr_remove(&pi433_idr, dev->minor);
1003 mutex_unlock(&minor_lock);
1005 /*-------------------------------------------------------------------------*/
1007 static const struct file_operations pi433_fops = {
1008 .owner = THIS_MODULE,
1009 /* REVISIT switch to aio primitives, so that userspace
1010 * gets more complete API coverage. It'll simplify things
1011 * too, except for the locking.
1013 .write = pi433_write,
1015 .unlocked_ioctl = pi433_ioctl,
1016 .compat_ioctl = pi433_compat_ioctl,
1018 .release = pi433_release,
1019 .llseek = no_llseek,
1022 /*-------------------------------------------------------------------------*/
1024 static int pi433_probe(struct spi_device *spi)
1026 struct pi433_device *device;
1029 /* setup spi parameters */
1031 spi->bits_per_word = 8;
1032 /* spi->max_speed_hz = 10000000; 1MHz already set by device tree overlay */
1034 retval = spi_setup(spi);
1037 dev_dbg(&spi->dev, "configuration of SPI interface failed!\n");
1043 "spi interface setup: mode 0x%2x, %d bits per word, %dhz max speed",
1044 spi->mode, spi->bits_per_word, spi->max_speed_hz);
1047 /* Ping the chip by reading the version register */
1048 retval = spi_w8r8(spi, 0x10);
1054 dev_dbg(&spi->dev, "found pi433 (ver. 0x%x)", retval);
1057 dev_dbg(&spi->dev, "unknown chip version: 0x%x", retval);
1061 /* Allocate driver data */
1062 device = kzalloc(sizeof(*device), GFP_KERNEL);
1066 /* Initialize the driver data */
1068 device->rx_active = false;
1069 device->tx_active = false;
1070 device->interrupt_rx_allowed = false;
1072 /* init wait queues */
1073 init_waitqueue_head(&device->tx_wait_queue);
1074 init_waitqueue_head(&device->rx_wait_queue);
1075 init_waitqueue_head(&device->fifo_wait_queue);
1078 INIT_KFIFO(device->tx_fifo);
1080 /* init mutexes and locks */
1081 mutex_init(&device->tx_fifo_lock);
1082 mutex_init(&device->rx_lock);
1084 /* setup GPIO (including irq_handler) for the different DIOs */
1085 retval = setup_GPIOs(device);
1087 dev_dbg(&spi->dev, "setup of GPIOs failed");
1091 /* setup the radio module */
1092 SET_CHECKED(rf69_set_mode (spi, standby));
1093 SET_CHECKED(rf69_set_data_mode (spi, packet));
1094 SET_CHECKED(rf69_set_amplifier_0 (spi, optionOn));
1095 SET_CHECKED(rf69_set_amplifier_1 (spi, optionOff));
1096 SET_CHECKED(rf69_set_amplifier_2 (spi, optionOff));
1097 SET_CHECKED(rf69_set_output_power_level (spi, 13));
1098 SET_CHECKED(rf69_set_antenna_impedance (spi, fiftyOhm));
1100 /* start tx thread */
1101 device->tx_task_struct = kthread_run(pi433_tx_thread,
1104 if (IS_ERR(device->tx_task_struct)) {
1105 dev_dbg(device->dev, "start of send thread failed");
1106 goto send_thread_failed;
1109 /* determ minor number */
1110 retval = pi433_get_minor(device);
1112 dev_dbg(device->dev, "get of minor number failed");
1117 device->devt = MKDEV(MAJOR(pi433_dev), device->minor);
1118 device->dev = device_create(pi433_class,
1123 if (IS_ERR(device->dev)) {
1124 pr_err("pi433: device register failed\n");
1125 retval = PTR_ERR(device->dev);
1126 goto device_create_failed;
1129 dev_dbg(device->dev,
1130 "created device for major %d, minor %d\n",
1136 device->cdev = cdev_alloc();
1137 device->cdev->owner = THIS_MODULE;
1138 cdev_init(device->cdev, &pi433_fops);
1139 retval = cdev_add(device->cdev, device->devt, 1);
1141 dev_dbg(device->dev, "register of cdev failed");
1146 spi_set_drvdata(spi, device);
1151 device_destroy(pi433_class, device->devt);
1152 device_create_failed:
1153 pi433_free_minor(device);
1155 kthread_stop(device->tx_task_struct);
1164 static int pi433_remove(struct spi_device *spi)
1166 struct pi433_device *device = spi_get_drvdata(spi);
1171 /* make sure ops on existing fds can abort cleanly */
1174 kthread_stop(device->tx_task_struct);
1176 device_destroy(pi433_class, device->devt);
1178 cdev_del(device->cdev);
1180 pi433_free_minor(device);
1182 if (device->users == 0)
1188 static const struct of_device_id pi433_dt_ids[] = {
1189 { .compatible = "Smarthome-Wolf,pi433" },
1193 MODULE_DEVICE_TABLE(of, pi433_dt_ids);
1195 static struct spi_driver pi433_spi_driver = {
1198 .owner = THIS_MODULE,
1199 .of_match_table = of_match_ptr(pi433_dt_ids),
1201 .probe = pi433_probe,
1202 .remove = pi433_remove,
1204 /* NOTE: suspend/resume methods are not necessary here.
1205 * We don't do anything except pass the requests to/from
1206 * the underlying controller. The refrigerator handles
1207 * most issues; the controller driver handles the rest.
1211 /*-------------------------------------------------------------------------*/
1213 static int __init pi433_init(void)
1217 /* If MAX_MSG_SIZE is smaller then FIFO_SIZE, the driver won't
1218 * work stable - risk of buffer overflow
1220 if (MAX_MSG_SIZE < FIFO_SIZE)
1223 /* Claim device numbers. Then register a class
1224 * that will key udev/mdev to add/remove /dev nodes. Last, register
1225 * Last, register the driver which manages those device numbers.
1227 status = alloc_chrdev_region(&pi433_dev, 0 /*firstminor*/, N_PI433_MINORS /*count*/, "pi433" /*name*/);
1231 pi433_class = class_create(THIS_MODULE, "pi433");
1232 if (IS_ERR(pi433_class)) {
1233 unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1234 return PTR_ERR(pi433_class);
1237 status = spi_register_driver(&pi433_spi_driver);
1239 class_destroy(pi433_class);
1240 unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1246 module_init(pi433_init);
1248 static void __exit pi433_exit(void)
1250 spi_unregister_driver(&pi433_spi_driver);
1251 class_destroy(pi433_class);
1252 unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1254 module_exit(pi433_exit);
1256 MODULE_AUTHOR("Marcus Wolf, <linux@wolf-entwicklungen.de>");
1257 MODULE_DESCRIPTION("Driver for Pi433");
1258 MODULE_LICENSE("GPL");
1259 MODULE_ALIAS("spi:pi433");