1 // SPDX-License-Identifier: GPL-2.0+
3 * userspace interface for pi433 radio module
5 * Pi433 is a 433MHz radio module for the Raspberry Pi.
6 * It is based on the HopeRf Module RFM69CW. Therefore inside of this
7 * driver, you'll find an abstraction of the rf69 chip.
9 * If needed, this driver could be extended, to also support other
10 * devices, basing on HopeRfs rf69.
12 * The driver can also be extended, to support other modules of
13 * HopeRf with a similar interace - e. g. RFM69HCW, RFM12, RFM95, ...
15 * Copyright (C) 2016 Wolf-Entwicklungen
16 * Marcus Wolf <linux@wolf-entwicklungen.de>
21 #include <linux/init.h>
22 #include <linux/module.h>
23 #include <linux/idr.h>
24 #include <linux/ioctl.h>
25 #include <linux/uaccess.h>
27 #include <linux/device.h>
28 #include <linux/cdev.h>
29 #include <linux/err.h>
30 #include <linux/kfifo.h>
31 #include <linux/errno.h>
32 #include <linux/mutex.h>
34 #include <linux/interrupt.h>
35 #include <linux/irq.h>
36 #include <linux/gpio/consumer.h>
37 #include <linux/kthread.h>
38 #include <linux/wait.h>
39 #include <linux/spi/spi.h>
41 #include <linux/compat.h>
43 #include <linux/debugfs.h>
44 #include <linux/seq_file.h>
49 #define N_PI433_MINORS BIT(MINORBITS) /*32*/ /* ... up to 256 */
50 #define MAX_MSG_SIZE 900 /* min: FIFO_SIZE! */
51 #define MSG_FIFO_SIZE 65536 /* 65536 = 2^16 */
52 #define FIFO_THRESHOLD 15 /* bytes */
55 static dev_t pi433_dev;
56 static DEFINE_IDR(pi433_idr);
57 static DEFINE_MUTEX(minor_lock); /* Protect idr accesses */
58 static struct dentry *root_dir; /* debugfs root directory for the driver */
60 /* mainly for udev to create /dev/pi433 */
61 static const struct class pi433_class = {
66 * tx config is instance specific
67 * so with each open a new tx config struct is needed
70 * rx config is device specific
71 * so we have just one rx config, ebedded in device struct
74 /* device handling related values */
79 struct spi_device *spi;
81 /* irq related values */
82 struct gpio_desc *gpiod[NUM_DIO];
84 u8 irq_state[NUM_DIO];
86 /* tx related values */
87 STRUCT_KFIFO_REC_1(MSG_FIFO_SIZE) tx_fifo;
88 struct mutex tx_fifo_lock; /* serialize userspace writers */
89 struct task_struct *tx_task_struct;
90 wait_queue_head_t tx_wait_queue;
92 char buffer[MAX_MSG_SIZE];
94 /* rx related values */
95 struct pi433_rx_cfg rx_cfg;
97 unsigned int rx_buffer_size;
100 unsigned int rx_position;
101 struct mutex rx_lock; /* protects rx_* variable accesses */
102 wait_queue_head_t rx_wait_queue;
104 /* fifo wait queue */
105 struct task_struct *fifo_task_struct;
106 wait_queue_head_t fifo_wait_queue;
111 bool interrupt_rx_allowed;
114 struct pi433_instance {
115 struct pi433_device *device;
116 struct pi433_tx_cfg tx_cfg;
119 bool tx_cfg_initialized;
122 /*-------------------------------------------------------------------------*/
124 /* GPIO interrupt handlers */
125 static irqreturn_t DIO0_irq_handler(int irq, void *dev_id)
127 struct pi433_device *device = dev_id;
129 if (device->irq_state[DIO0] == DIO_PACKET_SENT) {
130 device->free_in_fifo = FIFO_SIZE;
131 dev_dbg(device->dev, "DIO0 irq: Packet sent\n");
132 wake_up_interruptible(&device->fifo_wait_queue);
133 } else if (device->irq_state[DIO0] == DIO_RSSI_DIO0) {
134 dev_dbg(device->dev, "DIO0 irq: RSSI level over threshold\n");
135 wake_up_interruptible(&device->rx_wait_queue);
136 } else if (device->irq_state[DIO0] == DIO_PAYLOAD_READY) {
137 dev_dbg(device->dev, "DIO0 irq: Payload ready\n");
138 device->free_in_fifo = 0;
139 wake_up_interruptible(&device->fifo_wait_queue);
145 static irqreturn_t DIO1_irq_handler(int irq, void *dev_id)
147 struct pi433_device *device = dev_id;
149 if (device->irq_state[DIO1] == DIO_FIFO_NOT_EMPTY_DIO1) {
150 device->free_in_fifo = FIFO_SIZE;
151 } else if (device->irq_state[DIO1] == DIO_FIFO_LEVEL) {
152 if (device->rx_active)
153 device->free_in_fifo = FIFO_THRESHOLD - 1;
155 device->free_in_fifo = FIFO_SIZE - FIFO_THRESHOLD - 1;
158 "DIO1 irq: %d bytes free in fifo\n", device->free_in_fifo);
159 wake_up_interruptible(&device->fifo_wait_queue);
164 /*-------------------------------------------------------------------------*/
167 rf69_set_rx_cfg(struct pi433_device *dev, struct pi433_rx_cfg *rx_cfg)
172 /* receiver config */
173 ret = rf69_set_frequency(dev->spi, rx_cfg->frequency);
176 ret = rf69_set_modulation(dev->spi, rx_cfg->modulation);
179 ret = rf69_set_bit_rate(dev->spi, rx_cfg->bit_rate);
182 ret = rf69_set_antenna_impedance(dev->spi, rx_cfg->antenna_impedance);
185 ret = rf69_set_rssi_threshold(dev->spi, rx_cfg->rssi_threshold);
188 ret = rf69_set_ook_threshold_dec(dev->spi, rx_cfg->threshold_decrement);
191 ret = rf69_set_bandwidth(dev->spi, rx_cfg->bw_mantisse,
192 rx_cfg->bw_exponent);
195 ret = rf69_set_bandwidth_during_afc(dev->spi, rx_cfg->bw_mantisse,
196 rx_cfg->bw_exponent);
199 ret = rf69_set_dagc(dev->spi, rx_cfg->dagc);
203 dev->rx_bytes_to_drop = rx_cfg->bytes_to_drop;
207 if (rx_cfg->enable_sync == OPTION_ON) {
208 ret = rf69_enable_sync(dev->spi);
212 ret = rf69_set_fifo_fill_condition(dev->spi,
213 after_sync_interrupt);
217 ret = rf69_disable_sync(dev->spi);
221 ret = rf69_set_fifo_fill_condition(dev->spi, always);
225 if (rx_cfg->enable_length_byte == OPTION_ON) {
226 ret = rf69_set_packet_format(dev->spi, packet_length_var);
230 ret = rf69_set_packet_format(dev->spi, packet_length_fix);
234 ret = rf69_set_address_filtering(dev->spi,
235 rx_cfg->enable_address_filtering);
239 if (rx_cfg->enable_crc == OPTION_ON) {
240 ret = rf69_enable_crc(dev->spi);
244 ret = rf69_disable_crc(dev->spi);
250 ret = rf69_set_sync_size(dev->spi, rx_cfg->sync_length);
253 if (rx_cfg->enable_length_byte == OPTION_ON) {
254 ret = rf69_set_payload_length(dev->spi, 0xff);
257 } else if (rx_cfg->fixed_message_length != 0) {
258 payload_length = rx_cfg->fixed_message_length;
259 if (rx_cfg->enable_length_byte == OPTION_ON)
261 if (rx_cfg->enable_address_filtering != filtering_off)
263 ret = rf69_set_payload_length(dev->spi, payload_length);
267 ret = rf69_set_payload_length(dev->spi, 0);
273 if (rx_cfg->enable_sync == OPTION_ON) {
274 ret = rf69_set_sync_values(dev->spi, rx_cfg->sync_pattern);
278 if (rx_cfg->enable_address_filtering != filtering_off) {
279 ret = rf69_set_node_address(dev->spi, rx_cfg->node_address);
282 ret = rf69_set_broadcast_address(dev->spi,
283 rx_cfg->broadcast_address);
292 rf69_set_tx_cfg(struct pi433_device *dev, struct pi433_tx_cfg *tx_cfg)
296 ret = rf69_set_frequency(dev->spi, tx_cfg->frequency);
299 ret = rf69_set_modulation(dev->spi, tx_cfg->modulation);
302 ret = rf69_set_bit_rate(dev->spi, tx_cfg->bit_rate);
305 ret = rf69_set_deviation(dev->spi, tx_cfg->dev_frequency);
308 ret = rf69_set_pa_ramp(dev->spi, tx_cfg->pa_ramp);
311 ret = rf69_set_modulation_shaping(dev->spi, tx_cfg->mod_shaping);
314 ret = rf69_set_tx_start_condition(dev->spi, tx_cfg->tx_start_condition);
318 /* packet format enable */
319 if (tx_cfg->enable_preamble == OPTION_ON) {
320 ret = rf69_set_preamble_length(dev->spi,
321 tx_cfg->preamble_length);
325 ret = rf69_set_preamble_length(dev->spi, 0);
330 if (tx_cfg->enable_sync == OPTION_ON) {
331 ret = rf69_set_sync_size(dev->spi, tx_cfg->sync_length);
334 ret = rf69_set_sync_values(dev->spi, tx_cfg->sync_pattern);
337 ret = rf69_enable_sync(dev->spi);
341 ret = rf69_disable_sync(dev->spi);
346 if (tx_cfg->enable_length_byte == OPTION_ON) {
347 ret = rf69_set_packet_format(dev->spi, packet_length_var);
351 ret = rf69_set_packet_format(dev->spi, packet_length_fix);
356 if (tx_cfg->enable_crc == OPTION_ON) {
357 ret = rf69_enable_crc(dev->spi);
361 ret = rf69_disable_crc(dev->spi);
369 /*-------------------------------------------------------------------------*/
371 static int pi433_start_rx(struct pi433_device *dev)
375 /* return without action, if no pending read request */
379 /* setup for receiving */
380 retval = rf69_set_rx_cfg(dev, &dev->rx_cfg);
385 retval = rf69_set_dio_mapping(dev->spi, DIO0, DIO_RSSI_DIO0);
388 dev->irq_state[DIO0] = DIO_RSSI_DIO0;
389 irq_set_irq_type(dev->irq_num[DIO0], IRQ_TYPE_EDGE_RISING);
391 /* setup fifo level interrupt */
392 retval = rf69_set_fifo_threshold(dev->spi, FIFO_SIZE - FIFO_THRESHOLD);
395 retval = rf69_set_dio_mapping(dev->spi, DIO1, DIO_FIFO_LEVEL);
398 dev->irq_state[DIO1] = DIO_FIFO_LEVEL;
399 irq_set_irq_type(dev->irq_num[DIO1], IRQ_TYPE_EDGE_RISING);
401 /* set module to receiving mode */
402 retval = rf69_set_mode(dev->spi, receive);
409 /*-------------------------------------------------------------------------*/
411 static int pi433_receive(void *data)
413 struct pi433_device *dev = data;
414 struct spi_device *spi = dev->spi;
415 int bytes_to_read, bytes_total;
418 dev->interrupt_rx_allowed = false;
420 /* wait for any tx to finish */
421 dev_dbg(dev->dev, "rx: going to wait for any tx to finish\n");
422 retval = wait_event_interruptible(dev->rx_wait_queue, !dev->tx_active);
424 /* wait was interrupted */
425 dev->interrupt_rx_allowed = true;
426 wake_up_interruptible(&dev->tx_wait_queue);
430 /* prepare status vars */
431 dev->free_in_fifo = FIFO_SIZE;
432 dev->rx_position = 0;
433 dev->rx_bytes_dropped = 0;
435 /* setup radio module to listen for something "in the air" */
436 retval = pi433_start_rx(dev);
440 /* now check RSSI, if low wait for getting high (RSSI interrupt) */
441 while (!(rf69_read_reg(spi, REG_IRQFLAGS1) & MASK_IRQFLAGS1_RSSI)) {
442 /* allow tx to interrupt us while waiting for high RSSI */
443 dev->interrupt_rx_allowed = true;
444 wake_up_interruptible(&dev->tx_wait_queue);
446 /* wait for RSSI level to become high */
447 dev_dbg(dev->dev, "rx: going to wait for high RSSI level\n");
448 retval = wait_event_interruptible(dev->rx_wait_queue,
449 rf69_read_reg(spi, REG_IRQFLAGS1) &
450 MASK_IRQFLAGS1_RSSI);
451 if (retval) /* wait was interrupted */
453 dev->interrupt_rx_allowed = false;
455 /* cross check for ongoing tx */
460 /* configure payload ready irq */
461 retval = rf69_set_dio_mapping(spi, DIO0, DIO_PAYLOAD_READY);
464 dev->irq_state[DIO0] = DIO_PAYLOAD_READY;
465 irq_set_irq_type(dev->irq_num[DIO0], IRQ_TYPE_EDGE_RISING);
467 /* fixed or unlimited length? */
468 if (dev->rx_cfg.fixed_message_length != 0) {
469 if (dev->rx_cfg.fixed_message_length > dev->rx_buffer_size) {
473 bytes_total = dev->rx_cfg.fixed_message_length;
474 dev_dbg(dev->dev, "rx: msg len set to %d by fixed length\n",
477 bytes_total = dev->rx_buffer_size;
478 dev_dbg(dev->dev, "rx: msg len set to %d as requested by read\n",
482 /* length byte enabled? */
483 if (dev->rx_cfg.enable_length_byte == OPTION_ON) {
484 retval = wait_event_interruptible(dev->fifo_wait_queue,
485 dev->free_in_fifo < FIFO_SIZE);
486 if (retval) /* wait was interrupted */
489 rf69_read_fifo(spi, (u8 *)&bytes_total, 1);
490 if (bytes_total > dev->rx_buffer_size) {
495 dev_dbg(dev->dev, "rx: msg len reset to %d due to length byte\n",
499 /* address byte enabled? */
500 if (dev->rx_cfg.enable_address_filtering != filtering_off) {
505 retval = wait_event_interruptible(dev->fifo_wait_queue,
506 dev->free_in_fifo < FIFO_SIZE);
507 if (retval) /* wait was interrupted */
510 rf69_read_fifo(spi, &dummy, 1);
512 dev_dbg(dev->dev, "rx: address byte stripped off\n");
516 while (dev->rx_position < bytes_total) {
517 if (!(rf69_read_reg(spi, REG_IRQFLAGS2) & MASK_IRQFLAGS2_PAYLOAD_READY)) {
518 retval = wait_event_interruptible(dev->fifo_wait_queue,
519 dev->free_in_fifo < FIFO_SIZE);
520 if (retval) /* wait was interrupted */
524 /* need to drop bytes or acquire? */
525 if (dev->rx_bytes_to_drop > dev->rx_bytes_dropped)
526 bytes_to_read = dev->rx_bytes_to_drop -
527 dev->rx_bytes_dropped;
529 bytes_to_read = bytes_total - dev->rx_position;
531 /* access the fifo */
532 if (bytes_to_read > FIFO_SIZE - dev->free_in_fifo)
533 bytes_to_read = FIFO_SIZE - dev->free_in_fifo;
534 retval = rf69_read_fifo(spi,
535 &dev->rx_buffer[dev->rx_position],
537 if (retval) /* read failed */
540 dev->free_in_fifo += bytes_to_read;
542 /* adjust status vars */
543 if (dev->rx_bytes_to_drop > dev->rx_bytes_dropped)
544 dev->rx_bytes_dropped += bytes_to_read;
546 dev->rx_position += bytes_to_read;
549 /* rx done, wait was interrupted or error occurred */
551 dev->interrupt_rx_allowed = true;
552 if (rf69_set_mode(dev->spi, standby))
553 pr_err("rf69_set_mode(): radio module failed to go standby\n");
554 wake_up_interruptible(&dev->tx_wait_queue);
562 static int pi433_tx_thread(void *data)
564 struct pi433_device *device = data;
565 struct spi_device *spi = device->spi;
566 struct pi433_tx_cfg tx_cfg;
568 bool rx_interrupted = false;
569 int position, repetitions;
573 /* wait for fifo to be populated or for request to terminate*/
574 dev_dbg(device->dev, "thread: going to wait for new messages\n");
575 wait_event_interruptible(device->tx_wait_queue,
576 (!kfifo_is_empty(&device->tx_fifo) ||
577 kthread_should_stop()));
578 if (kthread_should_stop())
582 * get data from fifo in the following order:
587 retval = kfifo_out(&device->tx_fifo, &tx_cfg, sizeof(tx_cfg));
588 if (retval != sizeof(tx_cfg)) {
590 "reading tx_cfg from fifo failed: got %d byte(s), expected %d\n",
591 retval, (unsigned int)sizeof(tx_cfg));
595 retval = kfifo_out(&device->tx_fifo, &size, sizeof(size_t));
596 if (retval != sizeof(size_t)) {
598 "reading msg size from fifo failed: got %d, expected %d\n",
599 retval, (unsigned int)sizeof(size_t));
603 /* use fixed message length, if requested */
604 if (tx_cfg.fixed_message_length != 0)
605 size = tx_cfg.fixed_message_length;
607 /* increase size, if len byte is requested */
608 if (tx_cfg.enable_length_byte == OPTION_ON)
611 /* increase size, if adr byte is requested */
612 if (tx_cfg.enable_address_byte == OPTION_ON)
616 memset(device->buffer, 0, size);
619 /* add length byte, if requested */
620 if (tx_cfg.enable_length_byte == OPTION_ON)
622 * according to spec, length byte itself must be
623 * excluded from the length calculation
625 device->buffer[position++] = size - 1;
627 /* add adr byte, if requested */
628 if (tx_cfg.enable_address_byte == OPTION_ON)
629 device->buffer[position++] = tx_cfg.address_byte;
631 /* finally get message data from fifo */
632 retval = kfifo_out(&device->tx_fifo, &device->buffer[position],
633 sizeof(device->buffer) - position);
635 "read %d message byte(s) from fifo queue.\n", retval);
638 * if rx is active, we need to interrupt the waiting for
639 * incoming telegrams, to be able to send something.
640 * We are only allowed, if currently no reception takes
641 * place otherwise we need to wait for the incoming telegram
644 wait_event_interruptible(device->tx_wait_queue,
645 !device->rx_active ||
646 device->interrupt_rx_allowed);
649 * prevent race conditions
650 * irq will be reenabled after tx config is set
652 disable_irq(device->irq_num[DIO0]);
653 device->tx_active = true;
655 /* clear fifo, set fifo threshold, set payload length */
656 retval = rf69_set_mode(spi, standby); /* this clears the fifo */
660 if (device->rx_active && !rx_interrupted) {
662 * rx is currently waiting for a telegram;
663 * we need to set the radio module to standby
665 rx_interrupted = true;
668 retval = rf69_set_fifo_threshold(spi, FIFO_THRESHOLD);
671 if (tx_cfg.enable_length_byte == OPTION_ON) {
672 retval = rf69_set_payload_length(spi, size * tx_cfg.repetitions);
676 retval = rf69_set_payload_length(spi, 0);
681 /* configure the rf chip */
682 retval = rf69_set_tx_cfg(device, &tx_cfg);
686 /* enable fifo level interrupt */
687 retval = rf69_set_dio_mapping(spi, DIO1, DIO_FIFO_LEVEL);
690 device->irq_state[DIO1] = DIO_FIFO_LEVEL;
691 irq_set_irq_type(device->irq_num[DIO1], IRQ_TYPE_EDGE_FALLING);
693 /* enable packet sent interrupt */
694 retval = rf69_set_dio_mapping(spi, DIO0, DIO_PACKET_SENT);
697 device->irq_state[DIO0] = DIO_PACKET_SENT;
698 irq_set_irq_type(device->irq_num[DIO0], IRQ_TYPE_EDGE_RISING);
699 enable_irq(device->irq_num[DIO0]); /* was disabled by rx active check */
701 /* enable transmission */
702 retval = rf69_set_mode(spi, transmit);
706 /* transfer this msg (and repetitions) to chip fifo */
707 device->free_in_fifo = FIFO_SIZE;
709 repetitions = tx_cfg.repetitions;
710 while ((repetitions > 0) && (size > position)) {
711 if ((size - position) > device->free_in_fifo) {
712 /* msg to big for fifo - take a part */
713 int write_size = device->free_in_fifo;
715 device->free_in_fifo = 0;
717 &device->buffer[position],
719 position += write_size;
721 /* msg fits into fifo - take all */
722 device->free_in_fifo -= size;
725 &device->buffer[position],
727 position = 0; /* reset for next repetition */
730 retval = wait_event_interruptible(device->fifo_wait_queue,
731 device->free_in_fifo > 0);
733 dev_dbg(device->dev, "ABORT\n");
738 /* we are done. Wait for packet to get sent */
740 "thread: wait for packet to get sent/fifo to be empty\n");
741 wait_event_interruptible(device->fifo_wait_queue,
742 device->free_in_fifo == FIFO_SIZE ||
743 kthread_should_stop());
744 if (kthread_should_stop())
747 /* STOP_TRANSMISSION */
748 dev_dbg(device->dev, "thread: Packet sent. Set mode to stby.\n");
749 retval = rf69_set_mode(spi, standby);
753 /* everything sent? */
754 if (kfifo_is_empty(&device->tx_fifo)) {
756 if (rx_interrupted) {
757 rx_interrupted = false;
758 pi433_start_rx(device);
760 device->tx_active = false;
761 wake_up_interruptible(&device->rx_wait_queue);
766 /*-------------------------------------------------------------------------*/
769 pi433_read(struct file *filp, char __user *buf, size_t size, loff_t *f_pos)
771 struct pi433_instance *instance;
772 struct pi433_device *device;
776 /* check, whether internal buffer is big enough for requested size */
777 if (size > MAX_MSG_SIZE)
780 instance = filp->private_data;
781 device = instance->device;
783 /* just one read request at a time */
784 mutex_lock(&device->rx_lock);
785 if (device->rx_active) {
786 mutex_unlock(&device->rx_lock);
790 device->rx_active = true;
791 mutex_unlock(&device->rx_lock);
793 /* start receiving */
794 /* will block until something was received*/
795 device->rx_buffer_size = size;
796 bytes_received = pi433_receive(device);
799 mutex_lock(&device->rx_lock);
800 device->rx_active = false;
801 mutex_unlock(&device->rx_lock);
803 /* if read was successful copy to user space*/
804 if (bytes_received > 0) {
805 retval = copy_to_user(buf, device->rx_buffer, bytes_received);
810 return bytes_received;
814 pi433_write(struct file *filp, const char __user *buf,
815 size_t count, loff_t *f_pos)
817 struct pi433_instance *instance;
818 struct pi433_device *device;
820 unsigned int required, available, copied;
822 instance = filp->private_data;
823 device = instance->device;
826 * check, whether internal buffer (tx thread) is big enough
829 if (count > MAX_MSG_SIZE)
833 * check if tx_cfg has been initialized otherwise we won't be able to
834 * config the RF trasmitter correctly due to invalid settings
836 if (!instance->tx_cfg_initialized) {
837 dev_notice_once(device->dev,
838 "write: failed due to unconfigured tx_cfg (see PI433_IOC_WR_TX_CFG)\n");
843 * write the following sequence into fifo:
848 mutex_lock(&device->tx_fifo_lock);
850 required = sizeof(instance->tx_cfg) + sizeof(size_t) + count;
851 available = kfifo_avail(&device->tx_fifo);
852 if (required > available) {
853 dev_dbg(device->dev, "write to fifo failed: %d bytes required but %d available\n",
854 required, available);
855 mutex_unlock(&device->tx_fifo_lock);
859 retval = kfifo_in(&device->tx_fifo, &instance->tx_cfg,
860 sizeof(instance->tx_cfg));
861 if (retval != sizeof(instance->tx_cfg))
864 retval = kfifo_in(&device->tx_fifo, &count, sizeof(size_t));
865 if (retval != sizeof(size_t))
868 retval = kfifo_from_user(&device->tx_fifo, buf, count, &copied);
869 if (retval || copied != count)
872 mutex_unlock(&device->tx_fifo_lock);
875 wake_up_interruptible(&device->tx_wait_queue);
876 dev_dbg(device->dev, "write: generated new msg with %d bytes.\n", copied);
881 dev_warn(device->dev,
882 "write to fifo failed, non recoverable: 0x%x\n", retval);
883 mutex_unlock(&device->tx_fifo_lock);
887 static long pi433_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
889 struct pi433_instance *instance;
890 struct pi433_device *device;
891 struct pi433_tx_cfg tx_cfg;
892 void __user *argp = (void __user *)arg;
894 /* Check type and command number */
895 if (_IOC_TYPE(cmd) != PI433_IOC_MAGIC)
898 instance = filp->private_data;
899 device = instance->device;
905 case PI433_IOC_RD_TX_CFG:
906 if (copy_to_user(argp, &instance->tx_cfg,
907 sizeof(struct pi433_tx_cfg)))
910 case PI433_IOC_WR_TX_CFG:
911 if (copy_from_user(&tx_cfg, argp, sizeof(struct pi433_tx_cfg)))
913 mutex_lock(&device->tx_fifo_lock);
914 memcpy(&instance->tx_cfg, &tx_cfg, sizeof(struct pi433_tx_cfg));
915 instance->tx_cfg_initialized = true;
916 mutex_unlock(&device->tx_fifo_lock);
918 case PI433_IOC_RD_RX_CFG:
919 if (copy_to_user(argp, &device->rx_cfg,
920 sizeof(struct pi433_rx_cfg)))
923 case PI433_IOC_WR_RX_CFG:
924 mutex_lock(&device->rx_lock);
926 /* during pendig read request, change of config not allowed */
927 if (device->rx_active) {
928 mutex_unlock(&device->rx_lock);
932 if (copy_from_user(&device->rx_cfg, argp,
933 sizeof(struct pi433_rx_cfg))) {
934 mutex_unlock(&device->rx_lock);
938 mutex_unlock(&device->rx_lock);
947 /*-------------------------------------------------------------------------*/
949 static int pi433_open(struct inode *inode, struct file *filp)
951 struct pi433_device *device;
952 struct pi433_instance *instance;
954 mutex_lock(&minor_lock);
955 device = idr_find(&pi433_idr, iminor(inode));
956 mutex_unlock(&minor_lock);
958 pr_debug("device: minor %d unknown.\n", iminor(inode));
962 instance = kzalloc(sizeof(*instance), GFP_KERNEL);
966 /* setup instance data*/
967 instance->device = device;
969 /* instance data as context */
970 filp->private_data = instance;
971 stream_open(inode, filp);
976 static int pi433_release(struct inode *inode, struct file *filp)
978 struct pi433_instance *instance;
980 instance = filp->private_data;
982 filp->private_data = NULL;
987 /*-------------------------------------------------------------------------*/
989 static int setup_gpio(struct pi433_device *device)
994 const irq_handler_t DIO_irq_handler[NUM_DIO] = {
999 for (i = 0; i < NUM_DIO; i++) {
1000 /* "construct" name and get the gpio descriptor */
1001 snprintf(name, sizeof(name), "DIO%d", i);
1002 device->gpiod[i] = gpiod_get(&device->spi->dev, name,
1005 if (device->gpiod[i] == ERR_PTR(-ENOENT)) {
1006 dev_dbg(&device->spi->dev,
1007 "Could not find entry for %s. Ignoring.\n", name);
1011 if (device->gpiod[i] == ERR_PTR(-EBUSY))
1012 dev_dbg(&device->spi->dev, "%s is busy.\n", name);
1014 if (IS_ERR(device->gpiod[i])) {
1015 retval = PTR_ERR(device->gpiod[i]);
1016 /* release already allocated gpios */
1017 for (i--; i >= 0; i--) {
1018 free_irq(device->irq_num[i], device);
1019 gpiod_put(device->gpiod[i]);
1024 /* configure the pin */
1025 retval = gpiod_direction_input(device->gpiod[i]);
1030 device->irq_num[i] = gpiod_to_irq(device->gpiod[i]);
1031 if (device->irq_num[i] < 0) {
1032 device->gpiod[i] = ERR_PTR(-EINVAL);
1033 return device->irq_num[i];
1035 retval = request_irq(device->irq_num[i],
1044 dev_dbg(&device->spi->dev, "%s successfully configured\n", name);
1050 static void free_gpio(struct pi433_device *device)
1054 for (i = 0; i < NUM_DIO; i++) {
1055 /* check if gpiod is valid */
1056 if (IS_ERR(device->gpiod[i]))
1059 free_irq(device->irq_num[i], device);
1060 gpiod_put(device->gpiod[i]);
1064 static int pi433_get_minor(struct pi433_device *device)
1066 int retval = -ENOMEM;
1068 mutex_lock(&minor_lock);
1069 retval = idr_alloc(&pi433_idr, device, 0, N_PI433_MINORS, GFP_KERNEL);
1071 device->minor = retval;
1073 } else if (retval == -ENOSPC) {
1074 dev_err(&device->spi->dev, "too many pi433 devices\n");
1077 mutex_unlock(&minor_lock);
1081 static void pi433_free_minor(struct pi433_device *dev)
1083 mutex_lock(&minor_lock);
1084 idr_remove(&pi433_idr, dev->minor);
1085 mutex_unlock(&minor_lock);
1088 /*-------------------------------------------------------------------------*/
1090 static const struct file_operations pi433_fops = {
1091 .owner = THIS_MODULE,
1093 * REVISIT switch to aio primitives, so that userspace
1094 * gets more complete API coverage. It'll simplify things
1095 * too, except for the locking.
1097 .write = pi433_write,
1099 .unlocked_ioctl = pi433_ioctl,
1100 .compat_ioctl = compat_ptr_ioctl,
1102 .release = pi433_release,
1103 .llseek = no_llseek,
1106 static int pi433_debugfs_regs_show(struct seq_file *m, void *p)
1108 struct pi433_device *dev;
1111 char *fmt = "0x%02x, 0x%02x\n";
1116 mutex_lock(&dev->tx_fifo_lock);
1117 mutex_lock(&dev->rx_lock);
1119 // wait for on-going operations to finish
1120 ret = wait_event_interruptible(dev->rx_wait_queue, !dev->tx_active);
1124 ret = wait_event_interruptible(dev->tx_wait_queue, !dev->rx_active);
1128 // skip FIFO register (0x0) otherwise this can affect some of uC ops
1129 for (i = 1; i < 0x50; i++)
1130 reg_data[i] = rf69_read_reg(dev->spi, i);
1132 reg_data[REG_TESTLNA] = rf69_read_reg(dev->spi, REG_TESTLNA);
1133 reg_data[REG_TESTPA1] = rf69_read_reg(dev->spi, REG_TESTPA1);
1134 reg_data[REG_TESTPA2] = rf69_read_reg(dev->spi, REG_TESTPA2);
1135 reg_data[REG_TESTDAGC] = rf69_read_reg(dev->spi, REG_TESTDAGC);
1136 reg_data[REG_TESTAFC] = rf69_read_reg(dev->spi, REG_TESTAFC);
1138 seq_puts(m, "# reg, val\n");
1140 for (i = 1; i < 0x50; i++)
1141 seq_printf(m, fmt, i, reg_data[i]);
1143 seq_printf(m, fmt, REG_TESTLNA, reg_data[REG_TESTLNA]);
1144 seq_printf(m, fmt, REG_TESTPA1, reg_data[REG_TESTPA1]);
1145 seq_printf(m, fmt, REG_TESTPA2, reg_data[REG_TESTPA2]);
1146 seq_printf(m, fmt, REG_TESTDAGC, reg_data[REG_TESTDAGC]);
1147 seq_printf(m, fmt, REG_TESTAFC, reg_data[REG_TESTAFC]);
1150 mutex_unlock(&dev->rx_lock);
1151 mutex_unlock(&dev->tx_fifo_lock);
1155 DEFINE_SHOW_ATTRIBUTE(pi433_debugfs_regs);
1157 /*-------------------------------------------------------------------------*/
1159 static int pi433_probe(struct spi_device *spi)
1161 struct pi433_device *device;
1163 struct dentry *entry;
1165 /* setup spi parameters */
1167 spi->bits_per_word = 8;
1169 * spi->max_speed_hz = 10000000;
1170 * 1MHz already set by device tree overlay
1173 retval = spi_setup(spi);
1175 dev_dbg(&spi->dev, "configuration of SPI interface failed!\n");
1180 "spi interface setup: mode 0x%2x, %d bits per word, %dhz max speed\n",
1181 spi->mode, spi->bits_per_word, spi->max_speed_hz);
1183 /* read chip version */
1184 retval = rf69_get_version(spi);
1190 dev_dbg(&spi->dev, "found pi433 (ver. 0x%x)\n", retval);
1193 dev_dbg(&spi->dev, "unknown chip version: 0x%x\n", retval);
1197 /* Allocate driver data */
1198 device = kzalloc(sizeof(*device), GFP_KERNEL);
1202 /* Initialize the driver data */
1204 device->rx_active = false;
1205 device->tx_active = false;
1206 device->interrupt_rx_allowed = false;
1208 /* init rx buffer */
1209 device->rx_buffer = kmalloc(MAX_MSG_SIZE, GFP_KERNEL);
1210 if (!device->rx_buffer) {
1215 /* init wait queues */
1216 init_waitqueue_head(&device->tx_wait_queue);
1217 init_waitqueue_head(&device->rx_wait_queue);
1218 init_waitqueue_head(&device->fifo_wait_queue);
1221 INIT_KFIFO(device->tx_fifo);
1223 /* init mutexes and locks */
1224 mutex_init(&device->tx_fifo_lock);
1225 mutex_init(&device->rx_lock);
1227 /* setup GPIO (including irq_handler) for the different DIOs */
1228 retval = setup_gpio(device);
1230 dev_dbg(&spi->dev, "setup of GPIOs failed\n");
1234 /* setup the radio module */
1235 retval = rf69_set_mode(spi, standby);
1238 retval = rf69_set_data_mode(spi, DATAMODUL_MODE_PACKET);
1241 retval = rf69_enable_amplifier(spi, MASK_PALEVEL_PA0);
1244 retval = rf69_disable_amplifier(spi, MASK_PALEVEL_PA1);
1247 retval = rf69_disable_amplifier(spi, MASK_PALEVEL_PA2);
1250 retval = rf69_set_output_power_level(spi, 13);
1253 retval = rf69_set_antenna_impedance(spi, fifty_ohm);
1257 /* determ minor number */
1258 retval = pi433_get_minor(device);
1260 dev_dbg(&spi->dev, "get of minor number failed\n");
1265 device->devt = MKDEV(MAJOR(pi433_dev), device->minor);
1266 device->dev = device_create(&pi433_class,
1272 if (IS_ERR(device->dev)) {
1273 pr_err("pi433: device register failed\n");
1274 retval = PTR_ERR(device->dev);
1275 goto device_create_failed;
1277 dev_dbg(device->dev,
1278 "created device for major %d, minor %d\n",
1283 /* start tx thread */
1284 device->tx_task_struct = kthread_run(pi433_tx_thread,
1288 if (IS_ERR(device->tx_task_struct)) {
1289 dev_dbg(device->dev, "start of send thread failed\n");
1290 retval = PTR_ERR(device->tx_task_struct);
1291 goto send_thread_failed;
1295 device->cdev = cdev_alloc();
1296 if (!device->cdev) {
1297 dev_dbg(device->dev, "allocation of cdev failed\n");
1301 device->cdev->owner = THIS_MODULE;
1302 cdev_init(device->cdev, &pi433_fops);
1303 retval = cdev_add(device->cdev, device->devt, 1);
1305 dev_dbg(device->dev, "register of cdev failed\n");
1310 spi_set_drvdata(spi, device);
1312 entry = debugfs_create_dir(dev_name(device->dev), root_dir);
1313 debugfs_create_file("regs", 0400, entry, device, &pi433_debugfs_regs_fops);
1318 cdev_del(device->cdev);
1320 kthread_stop(device->tx_task_struct);
1322 device_destroy(&pi433_class, device->devt);
1323 device_create_failed:
1324 pi433_free_minor(device);
1328 kfree(device->rx_buffer);
1335 static void pi433_remove(struct spi_device *spi)
1337 struct pi433_device *device = spi_get_drvdata(spi);
1339 debugfs_lookup_and_remove(dev_name(device->dev), root_dir);
1344 /* make sure ops on existing fds can abort cleanly */
1347 kthread_stop(device->tx_task_struct);
1349 device_destroy(&pi433_class, device->devt);
1351 cdev_del(device->cdev);
1353 pi433_free_minor(device);
1355 kfree(device->rx_buffer);
1359 static const struct of_device_id pi433_dt_ids[] = {
1360 { .compatible = "Smarthome-Wolf,pi433" },
1364 MODULE_DEVICE_TABLE(of, pi433_dt_ids);
1366 static struct spi_driver pi433_spi_driver = {
1369 .owner = THIS_MODULE,
1370 .of_match_table = of_match_ptr(pi433_dt_ids),
1372 .probe = pi433_probe,
1373 .remove = pi433_remove,
1376 * NOTE: suspend/resume methods are not necessary here.
1377 * We don't do anything except pass the requests to/from
1378 * the underlying controller. The refrigerator handles
1379 * most issues; the controller driver handles the rest.
1383 /*-------------------------------------------------------------------------*/
1385 static int __init pi433_init(void)
1390 * If MAX_MSG_SIZE is smaller then FIFO_SIZE, the driver won't
1391 * work stable - risk of buffer overflow
1393 if (MAX_MSG_SIZE < FIFO_SIZE)
1397 * Claim device numbers. Then register a class
1398 * that will key udev/mdev to add/remove /dev nodes.
1399 * Last, register the driver which manages those device numbers.
1401 status = alloc_chrdev_region(&pi433_dev, 0, N_PI433_MINORS, "pi433");
1405 status = class_register(&pi433_class);
1407 unregister_chrdev(MAJOR(pi433_dev),
1408 pi433_spi_driver.driver.name);
1412 root_dir = debugfs_create_dir(KBUILD_MODNAME, NULL);
1414 status = spi_register_driver(&pi433_spi_driver);
1416 class_unregister(&pi433_class);
1417 unregister_chrdev(MAJOR(pi433_dev),
1418 pi433_spi_driver.driver.name);
1424 module_init(pi433_init);
1426 static void __exit pi433_exit(void)
1428 spi_unregister_driver(&pi433_spi_driver);
1429 class_unregister(&pi433_class);
1430 unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1431 debugfs_remove(root_dir);
1433 module_exit(pi433_exit);
1435 MODULE_AUTHOR("Marcus Wolf, <linux@wolf-entwicklungen.de>");
1436 MODULE_DESCRIPTION("Driver for Pi433");
1437 MODULE_LICENSE("GPL");
1438 MODULE_ALIAS("spi:pi433");