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