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 printk("DIO0 irq: Packet sent\n"); // TODO: printk() should include KERN_ facility level
140 wake_up_interruptible(&device->fifo_wait_queue);
142 else if (device->irq_state[DIO0] == DIO_Rssi_DIO0)
144 printk("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 printk("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;
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);
176 /*-------------------------------------------------------------------------*/
179 rf69_set_rx_cfg(struct pi433_device *dev, struct pi433_rx_cfg *rx_cfg)
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));
195 dev->rx_bytes_to_drop = rx_cfg->bytes_to_drop;
199 SET_CHECKED(rf69_set_sync_enable(dev->spi, rx_cfg->enable_sync));
200 if (rx_cfg->enable_sync == optionOn)
202 SET_CHECKED(rf69_set_fifo_fill_condition(dev->spi, afterSyncInterrupt));
206 SET_CHECKED(rf69_set_fifo_fill_condition(dev->spi, always));
208 if (rx_cfg->enable_length_byte == optionOn) {
209 ret = rf69_set_packet_format(dev->spi, packetLengthVar);
213 ret = rf69_set_packet_format(dev->spi, packetLengthFix);
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));
221 SET_CHECKED(rf69_set_sync_size(dev->spi, rx_cfg->sync_length));
222 if (rx_cfg->enable_length_byte == optionOn)
224 SET_CHECKED(rf69_set_payload_length(dev->spi, 0xff));
226 else if (rx_cfg->fixed_message_length != 0)
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));
235 SET_CHECKED(rf69_set_payload_length(dev->spi, 0));
239 if (rx_cfg->enable_sync == optionOn)
241 SET_CHECKED(rf69_set_sync_values(dev->spi, rx_cfg->sync_pattern));
243 if (rx_cfg->enable_address_filtering != filteringOff)
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));
253 rf69_set_tx_cfg(struct pi433_device *dev, struct pi433_tx_cfg *tx_cfg)
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));
265 /* packet format enable */
266 if (tx_cfg->enable_preamble == optionOn)
268 SET_CHECKED(rf69_set_preamble_length(dev->spi, tx_cfg->preamble_length));
272 SET_CHECKED(rf69_set_preamble_length(dev->spi, 0));
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);
280 ret = rf69_set_packet_format(dev->spi, packetLengthFix);
284 SET_CHECKED(rf69_set_crc_enable (dev->spi, tx_cfg->enable_crc));
286 /* configure sync, if enabled */
287 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)
416 dev_dbg(dev->dev, "rx: msg len reset to %d due to length byte", bytes_total);
419 /* address byte enabled? */
420 if (dev->rx_cfg.enable_address_filtering != filteringOff)
426 retval = wait_event_interruptible(dev->fifo_wait_queue,
427 dev->free_in_fifo < FIFO_SIZE);
428 if (retval) goto abort; /* wait was interrupted */
430 rf69_read_fifo(spi, &dummy, 1);
432 dev_dbg(dev->dev, "rx: address byte stripped off");
436 while (dev->rx_position < bytes_total)
438 if ( !rf69_get_flag(dev->spi, payloadReady) )
440 retval = wait_event_interruptible(dev->fifo_wait_queue,
441 dev->free_in_fifo < FIFO_SIZE);
442 if (retval) goto abort; /* wait was interrupted */
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;
449 bytes_to_read = bytes_total - dev->rx_position;
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],
458 if (retval) goto abort; /* read failed */
459 dev->free_in_fifo += bytes_to_read;
461 /* adjust status vars */
462 if (dev->rx_bytes_to_drop > dev->rx_bytes_dropped)
463 dev->rx_bytes_dropped += bytes_to_read;
465 dev->rx_position += bytes_to_read;
469 /* rx done, wait was interrupted or error occured */
471 dev->interrupt_rx_allowed = true;
472 SET_CHECKED(rf69_set_mode(dev->spi, standby));
473 wake_up_interruptible(&dev->tx_wait_queue);
482 pi433_tx_thread(void *data)
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;
489 bool rx_interrupted = false;
490 int position, repetitions;
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() )
503 /* get data from fifo in the following order:
508 mutex_lock(&device->tx_fifo_lock);
510 retval = kfifo_out(&device->tx_fifo, &tx_cfg, sizeof(tx_cfg));
511 if (retval != sizeof(tx_cfg))
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);
518 retval = kfifo_out(&device->tx_fifo, &size, sizeof(size_t));
519 if (retval != sizeof(size_t))
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);
526 /* use fixed message length, if requested */
527 if (tx_cfg.fixed_message_length != 0)
528 size = tx_cfg.fixed_message_length;
530 /* increase size, if len byte is requested */
531 if (tx_cfg.enable_length_byte == optionOn)
534 /* increase size, if adr byte is requested */
535 if (tx_cfg.enable_address_byte == optionOn)
539 memset(buffer, 0, size);
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 */
546 /* add adr byte, if requested */
547 if (tx_cfg.enable_address_byte == optionOn)
548 buffer[position++] = tx_cfg.address_byte;
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);
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
561 wait_event_interruptible(device->tx_wait_queue,
562 !device->rx_active ||
563 device->interrupt_rx_allowed == true);
565 /* prevent race conditions
566 * irq will be reenabled after tx config is set
568 disable_irq(device->irq_num[DIO0]);
569 device->tx_active = true;
571 if (device->rx_active && rx_interrupted == false)
573 /* rx is currently waiting for a telegram;
574 * we need to set the radio module to standby
576 SET_CHECKED(rf69_set_mode(device->spi, standby));
577 rx_interrupted = true;
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)
585 SET_CHECKED(rf69_set_payload_length(spi, size * tx_cfg.repetitions));
589 SET_CHECKED(rf69_set_payload_length(spi, 0));
592 /* configure the rf chip */
593 rf69_set_tx_cfg(device, &tx_cfg);
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);
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 */
606 /* enable transmission */
607 SET_CHECKED(rf69_set_mode(spi, transmit));
609 /* transfer this msg (and repetitions) to chip fifo */
610 device->free_in_fifo = FIFO_SIZE;
612 repetitions = tx_cfg.repetitions;
613 while( (repetitions > 0) && (size > position) )
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;
625 { /* msg fits into fifo - take all */
626 device->free_in_fifo -= size;
631 position = 0; /* reset for next repetition */
634 retval = wait_event_interruptible(device->fifo_wait_queue,
635 device->free_in_fifo > 0);
636 if (retval) { printk("ABORT\n"); goto abort; }
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");
647 /* STOP_TRANSMISSION */
648 dev_dbg(device->dev, "thread: Packet sent. Set mode to stby.");
649 SET_CHECKED(rf69_set_mode(spi, standby));
651 /* everything sent? */
652 if ( kfifo_is_empty(&device->tx_fifo) )
657 rx_interrupted = false;
658 pi433_start_rx(device);
660 device->tx_active = false;
661 wake_up_interruptible(&device->rx_wait_queue);
666 /*-------------------------------------------------------------------------*/
669 pi433_read(struct file *filp, char __user *buf, size_t size, loff_t *f_pos)
671 struct pi433_instance *instance;
672 struct pi433_device *device;
676 /* check, whether internal buffer is big enough for requested size */
677 if (size > MAX_MSG_SIZE)
680 instance = filp->private_data;
681 device = instance->device;
683 /* just one read request at a time */
684 mutex_lock(&device->rx_lock);
685 if (device->rx_active)
687 mutex_unlock(&device->rx_lock);
692 device->rx_active = true;
693 mutex_unlock(&device->rx_lock);
696 /* start receiving */
697 /* will block until something was received*/
698 device->rx_buffer_size = size;
699 bytes_received = pi433_receive(device);
702 mutex_lock(&device->rx_lock);
703 device->rx_active = false;
704 mutex_unlock(&device->rx_lock);
706 /* if read was successful copy to user space*/
707 if (bytes_received > 0)
709 retval = copy_to_user(buf, device->rx_buffer, bytes_received);
714 return bytes_received;
719 pi433_write(struct file *filp, const char __user *buf,
720 size_t count, loff_t *f_pos)
722 struct pi433_instance *instance;
723 struct pi433_device *device;
726 instance = filp->private_data;
727 device = instance->device;
729 /* check, whether internal buffer (tx thread) is big enough for requested size */
730 if (count > MAX_MSG_SIZE)
733 /* write the following sequence into fifo:
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) )
743 retval = kfifo_in (&device->tx_fifo, &count, sizeof(size_t));
744 if ( retval != sizeof(size_t) )
747 retval = kfifo_from_user(&device->tx_fifo, buf, count, &copied);
748 if (retval || copied != count)
751 mutex_unlock(&device->tx_fifo_lock);
754 wake_up_interruptible(&device->tx_wait_queue);
755 dev_dbg(device->dev, "write: generated new msg with %d bytes.", copied);
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);
768 pi433_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
772 struct pi433_instance *instance;
773 struct pi433_device *device;
776 /* Check type and command number */
777 if (_IOC_TYPE(cmd) != PI433_IOC_MAGIC)
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.
784 if (_IOC_DIR(cmd) & _IOC_READ)
785 err = !access_ok(VERIFY_WRITE,
789 if (err == 0 && _IOC_DIR(cmd) & _IOC_WRITE)
790 err = !access_ok(VERIFY_READ,
796 /* TODO? guard against device removal before, or while,
797 * we issue this ioctl. --> device_get()
799 instance = filp->private_data;
800 device = instance->device;
806 case PI433_IOC_RD_TX_CFG:
807 tmp = _IOC_SIZE(cmd);
808 if ( (tmp == 0) || ((tmp % sizeof(struct pi433_tx_cfg)) != 0) )
814 if (__copy_to_user((void __user *)arg,
823 case PI433_IOC_WR_TX_CFG:
824 tmp = _IOC_SIZE(cmd);
825 if ( (tmp == 0) || ((tmp % sizeof(struct pi433_tx_cfg)) != 0) )
831 if (__copy_from_user(&instance->tx_cfg,
841 case PI433_IOC_RD_RX_CFG:
842 tmp = _IOC_SIZE(cmd);
843 if ( (tmp == 0) || ((tmp % sizeof(struct pi433_rx_cfg)) != 0) ) {
848 if (__copy_to_user((void __user *)arg,
857 case PI433_IOC_WR_RX_CFG:
858 tmp = _IOC_SIZE(cmd);
859 mutex_lock(&device->rx_lock);
861 /* during pendig read request, change of config not allowed */
862 if (device->rx_active) {
864 mutex_unlock(&device->rx_lock);
868 if ( (tmp == 0) || ((tmp % sizeof(struct pi433_rx_cfg)) != 0) ) {
870 mutex_unlock(&device->rx_lock);
874 if (__copy_from_user(&device->rx_cfg,
879 mutex_unlock(&device->rx_lock);
883 mutex_unlock(&device->rx_lock);
894 pi433_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
896 return pi433_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
899 #define pi433_compat_ioctl NULL
900 #endif /* CONFIG_COMPAT */
902 /*-------------------------------------------------------------------------*/
904 static int pi433_open(struct inode *inode, struct file *filp)
906 struct pi433_device *device;
907 struct pi433_instance *instance;
909 mutex_lock(&minor_lock);
910 device = idr_find(&pi433_idr, iminor(inode));
911 mutex_unlock(&minor_lock);
913 pr_debug("device: minor %d unknown.\n", iminor(inode));
917 if (!device->rx_buffer) {
918 device->rx_buffer = kmalloc(MAX_MSG_SIZE, GFP_KERNEL);
919 if (!device->rx_buffer)
921 dev_dbg(device->dev, "open/ENOMEM\n");
927 instance = kzalloc(sizeof(*instance), GFP_KERNEL);
930 kfree(device->rx_buffer);
931 device->rx_buffer = NULL;
935 /* setup instance data*/
936 instance->device = device;
937 instance->tx_cfg.bit_rate = 4711;
938 // TODO: fill instance->tx_cfg;
940 /* instance data as context */
941 filp->private_data = instance;
942 nonseekable_open(inode, filp);
947 static int pi433_release(struct inode *inode, struct file *filp)
949 struct pi433_instance *instance;
950 struct pi433_device *device;
952 instance = filp->private_data;
953 device = instance->device;
955 filp->private_data = NULL;
960 if (!device->users) {
961 kfree(device->rx_buffer);
962 device->rx_buffer = NULL;
963 if (device->spi == NULL)
971 /*-------------------------------------------------------------------------*/
973 static int setup_GPIOs(struct pi433_device *device)
978 const irq_handler_t DIO_irq_handler[NUM_DIO] = {
983 for (i=0; i<NUM_DIO; i++)
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*/);
989 if (device->gpiod[i] == ERR_PTR(-ENOENT))
991 dev_dbg(&device->spi->dev, "Could not find entry for %s. Ignoring.", name);
995 if (device->gpiod[i] == ERR_PTR(-EBUSY))
996 dev_dbg(&device->spi->dev, "%s is busy.", name);
998 if ( IS_ERR(device->gpiod[i]) )
1000 retval = PTR_ERR(device->gpiod[i]);
1001 /* release already allocated gpios */
1002 for (i--; i>=0; i--)
1004 free_irq(device->irq_num[i], device);
1005 gpiod_put(device->gpiod[i]);
1011 /* configure the pin */
1012 gpiod_unexport(device->gpiod[i]);
1013 retval = gpiod_direction_input(device->gpiod[i]);
1014 if (retval) return retval;
1018 device->irq_num[i] = gpiod_to_irq(device->gpiod[i]);
1019 if (device->irq_num[i] < 0)
1021 device->gpiod[i] = ERR_PTR(-EINVAL);//(struct gpio_desc *)device->irq_num[i];
1022 return device->irq_num[i];
1024 retval = request_irq(device->irq_num[i],
1033 dev_dbg(&device->spi->dev, "%s succesfully configured", name);
1039 static void free_GPIOs(struct pi433_device *device)
1043 for (i=0; i<NUM_DIO; i++)
1045 /* check if gpiod is valid */
1046 if ( IS_ERR(device->gpiod[i]) )
1049 free_irq(device->irq_num[i], device);
1050 gpiod_put(device->gpiod[i]);
1055 static int pi433_get_minor(struct pi433_device *device)
1057 int retval = -ENOMEM;
1059 mutex_lock(&minor_lock);
1060 retval = idr_alloc(&pi433_idr, device, 0, N_PI433_MINORS, GFP_KERNEL);
1062 device->minor = retval;
1064 } else if (retval == -ENOSPC) {
1065 dev_err(device->dev, "too many pi433 devices\n");
1068 mutex_unlock(&minor_lock);
1072 static void pi433_free_minor(struct pi433_device *dev)
1074 mutex_lock(&minor_lock);
1075 idr_remove(&pi433_idr, dev->minor);
1076 mutex_unlock(&minor_lock);
1078 /*-------------------------------------------------------------------------*/
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.
1086 .write = pi433_write,
1088 .unlocked_ioctl = pi433_ioctl,
1089 .compat_ioctl = pi433_compat_ioctl,
1091 .release = pi433_release,
1092 .llseek = no_llseek,
1095 /*-------------------------------------------------------------------------*/
1097 static int pi433_probe(struct spi_device *spi)
1099 struct pi433_device *device;
1102 /* setup spi parameters */
1104 spi->bits_per_word = 8;
1105 /* spi->max_speed_hz = 10000000; 1MHz already set by device tree overlay */
1107 retval = spi_setup(spi);
1110 dev_dbg(&spi->dev, "configuration of SPI interface failed!\n");
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);
1120 /* Ping the chip by reading the version register */
1121 retval = spi_w8r8(spi, 0x10);
1127 dev_dbg(&spi->dev, "found pi433 (ver. 0x%x)", retval);
1130 dev_dbg(&spi->dev, "unknown chip version: 0x%x", retval);
1134 /* Allocate driver data */
1135 device = kzalloc(sizeof(*device), GFP_KERNEL);
1139 /* Initialize the driver data */
1141 device->rx_active = false;
1142 device->tx_active = false;
1143 device->interrupt_rx_allowed = false;
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);
1151 INIT_KFIFO(device->tx_fifo);
1153 /* init mutexes and locks */
1154 mutex_init(&device->tx_fifo_lock);
1155 mutex_init(&device->rx_lock);
1157 /* setup GPIO (including irq_handler) for the different DIOs */
1158 retval = setup_GPIOs(device);
1161 dev_dbg(&spi->dev, "setup of GPIOs failed");
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));
1174 /* start tx thread */
1175 device->tx_task_struct = kthread_run(pi433_tx_thread,
1178 if (IS_ERR(device->tx_task_struct))
1180 dev_dbg(device->dev, "start of send thread failed");
1181 goto send_thread_failed;
1184 /* determ minor number */
1185 retval = pi433_get_minor(device);
1188 dev_dbg(device->dev, "get of minor number failed");
1193 device->devt = MKDEV(MAJOR(pi433_dev), device->minor);
1194 device->dev = device_create(pi433_class,
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;
1205 dev_dbg(device->dev,
1206 "created device for major %d, minor %d\n",
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);
1218 dev_dbg(device->dev, "register of cdev failed");
1223 spi_set_drvdata(spi, device);
1228 device_destroy(pi433_class, device->devt);
1229 device_create_failed:
1230 pi433_free_minor(device);
1232 kthread_stop(device->tx_task_struct);
1241 static int pi433_remove(struct spi_device *spi)
1243 struct pi433_device *device = spi_get_drvdata(spi);
1248 /* make sure ops on existing fds can abort cleanly */
1251 kthread_stop(device->tx_task_struct);
1253 device_destroy(pi433_class, device->devt);
1255 cdev_del(device->cdev);
1257 pi433_free_minor(device);
1259 if (device->users == 0)
1265 static const struct of_device_id pi433_dt_ids[] = {
1266 { .compatible = "Smarthome-Wolf,pi433" },
1270 MODULE_DEVICE_TABLE(of, pi433_dt_ids);
1272 static struct spi_driver pi433_spi_driver = {
1275 .owner = THIS_MODULE,
1276 .of_match_table = of_match_ptr(pi433_dt_ids),
1278 .probe = pi433_probe,
1279 .remove = pi433_remove,
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.
1288 /*-------------------------------------------------------------------------*/
1290 static int __init pi433_init(void)
1294 /* If MAX_MSG_SIZE is smaller then FIFO_SIZE, the driver won't
1295 * work stable - risk of buffer overflow
1297 if (MAX_MSG_SIZE < FIFO_SIZE)
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.
1304 status = alloc_chrdev_region(&pi433_dev, 0 /*firstminor*/, N_PI433_MINORS /*count*/, "pi433" /*name*/);
1308 pi433_class = class_create(THIS_MODULE, "pi433");
1309 if (IS_ERR(pi433_class))
1311 unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1312 return PTR_ERR(pi433_class);
1315 status = spi_register_driver(&pi433_spi_driver);
1318 class_destroy(pi433_class);
1319 unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1325 module_init(pi433_init);
1327 static void __exit pi433_exit(void)
1329 spi_unregister_driver(&pi433_spi_driver);
1330 class_destroy(pi433_class);
1331 unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1333 module_exit(pi433_exit);
1335 MODULE_AUTHOR("Marcus Wolf, <linux@wolf-entwicklungen.de>");
1336 MODULE_DESCRIPTION("Driver for Pi433");
1337 MODULE_LICENSE("GPL");
1338 MODULE_ALIAS("spi:pi433");