xref: /openbmc/linux/drivers/staging/pi433/pi433_if.c (revision decb929f)
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/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>
40 #ifdef CONFIG_COMPAT
41 #include <linux/compat.h>
42 #endif
43 #include <linux/debugfs.h>
44 #include <linux/seq_file.h>
45 
46 #include "pi433_if.h"
47 #include "rf69.h"
48 
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 NUM_DIO			2
53 
54 static dev_t pi433_dev;
55 static DEFINE_IDR(pi433_idr);
56 static DEFINE_MUTEX(minor_lock); /* Protect idr accesses */
57 static struct dentry *root_dir;	/* debugfs root directory for the driver */
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 		retval = gpiod_direction_input(device->gpiod[i]);
1022 		if (retval)
1023 			return retval;
1024 
1025 		/* configure irq */
1026 		device->irq_num[i] = gpiod_to_irq(device->gpiod[i]);
1027 		if (device->irq_num[i] < 0) {
1028 			device->gpiod[i] = ERR_PTR(-EINVAL);
1029 			return device->irq_num[i];
1030 		}
1031 		retval = request_irq(device->irq_num[i],
1032 				     DIO_irq_handler[i],
1033 				     0, /* flags */
1034 				     name,
1035 				     device);
1036 
1037 		if (retval)
1038 			return retval;
1039 
1040 		dev_dbg(&device->spi->dev, "%s successfully configured\n", name);
1041 	}
1042 
1043 	return 0;
1044 }
1045 
free_gpio(struct pi433_device * device)1046 static void free_gpio(struct pi433_device *device)
1047 {
1048 	int i;
1049 
1050 	for (i = 0; i < NUM_DIO; i++) {
1051 		/* check if gpiod is valid */
1052 		if (IS_ERR(device->gpiod[i]))
1053 			continue;
1054 
1055 		free_irq(device->irq_num[i], device);
1056 		gpiod_put(device->gpiod[i]);
1057 	}
1058 }
1059 
pi433_get_minor(struct pi433_device * device)1060 static int pi433_get_minor(struct pi433_device *device)
1061 {
1062 	int retval = -ENOMEM;
1063 
1064 	mutex_lock(&minor_lock);
1065 	retval = idr_alloc(&pi433_idr, device, 0, N_PI433_MINORS, GFP_KERNEL);
1066 	if (retval >= 0) {
1067 		device->minor = retval;
1068 		retval = 0;
1069 	} else if (retval == -ENOSPC) {
1070 		dev_err(&device->spi->dev, "too many pi433 devices\n");
1071 		retval = -EINVAL;
1072 	}
1073 	mutex_unlock(&minor_lock);
1074 	return retval;
1075 }
1076 
pi433_free_minor(struct pi433_device * dev)1077 static void pi433_free_minor(struct pi433_device *dev)
1078 {
1079 	mutex_lock(&minor_lock);
1080 	idr_remove(&pi433_idr, dev->minor);
1081 	mutex_unlock(&minor_lock);
1082 }
1083 
1084 /*-------------------------------------------------------------------------*/
1085 
1086 static const struct file_operations pi433_fops = {
1087 	.owner =	THIS_MODULE,
1088 	/*
1089 	 * REVISIT switch to aio primitives, so that userspace
1090 	 * gets more complete API coverage.  It'll simplify things
1091 	 * too, except for the locking.
1092 	 */
1093 	.write =	pi433_write,
1094 	.read =		pi433_read,
1095 	.unlocked_ioctl = pi433_ioctl,
1096 	.compat_ioctl = compat_ptr_ioctl,
1097 	.open =		pi433_open,
1098 	.release =	pi433_release,
1099 	.llseek =	no_llseek,
1100 };
1101 
pi433_debugfs_regs_show(struct seq_file * m,void * p)1102 static int pi433_debugfs_regs_show(struct seq_file *m, void *p)
1103 {
1104 	struct pi433_device *dev;
1105 	u8 reg_data[114];
1106 	int i;
1107 	char *fmt = "0x%02x, 0x%02x\n";
1108 	int ret;
1109 
1110 	dev = m->private;
1111 
1112 	mutex_lock(&dev->tx_fifo_lock);
1113 	mutex_lock(&dev->rx_lock);
1114 
1115 	// wait for on-going operations to finish
1116 	ret = wait_event_interruptible(dev->rx_wait_queue, !dev->tx_active);
1117 	if (ret)
1118 		goto out_unlock;
1119 
1120 	ret = wait_event_interruptible(dev->tx_wait_queue, !dev->rx_active);
1121 	if (ret)
1122 		goto out_unlock;
1123 
1124 	// skip FIFO register (0x0) otherwise this can affect some of uC ops
1125 	for (i = 1; i < 0x50; i++)
1126 		reg_data[i] = rf69_read_reg(dev->spi, i);
1127 
1128 	reg_data[REG_TESTLNA] = rf69_read_reg(dev->spi, REG_TESTLNA);
1129 	reg_data[REG_TESTPA1] = rf69_read_reg(dev->spi, REG_TESTPA1);
1130 	reg_data[REG_TESTPA2] = rf69_read_reg(dev->spi, REG_TESTPA2);
1131 	reg_data[REG_TESTDAGC] = rf69_read_reg(dev->spi, REG_TESTDAGC);
1132 	reg_data[REG_TESTAFC] = rf69_read_reg(dev->spi, REG_TESTAFC);
1133 
1134 	seq_puts(m, "# reg, val\n");
1135 
1136 	for (i = 1; i < 0x50; i++)
1137 		seq_printf(m, fmt, i, reg_data[i]);
1138 
1139 	seq_printf(m, fmt, REG_TESTLNA, reg_data[REG_TESTLNA]);
1140 	seq_printf(m, fmt, REG_TESTPA1, reg_data[REG_TESTPA1]);
1141 	seq_printf(m, fmt, REG_TESTPA2, reg_data[REG_TESTPA2]);
1142 	seq_printf(m, fmt, REG_TESTDAGC, reg_data[REG_TESTDAGC]);
1143 	seq_printf(m, fmt, REG_TESTAFC, reg_data[REG_TESTAFC]);
1144 
1145 out_unlock:
1146 	mutex_unlock(&dev->rx_lock);
1147 	mutex_unlock(&dev->tx_fifo_lock);
1148 
1149 	return ret;
1150 }
1151 DEFINE_SHOW_ATTRIBUTE(pi433_debugfs_regs);
1152 
1153 /*-------------------------------------------------------------------------*/
1154 
pi433_probe(struct spi_device * spi)1155 static int pi433_probe(struct spi_device *spi)
1156 {
1157 	struct pi433_device	*device;
1158 	int			retval;
1159 	struct dentry		*entry;
1160 
1161 	/* setup spi parameters */
1162 	spi->mode = 0x00;
1163 	spi->bits_per_word = 8;
1164 	/*
1165 	 * spi->max_speed_hz = 10000000;
1166 	 * 1MHz already set by device tree overlay
1167 	 */
1168 
1169 	retval = spi_setup(spi);
1170 	if (retval) {
1171 		dev_dbg(&spi->dev, "configuration of SPI interface failed!\n");
1172 		return retval;
1173 	}
1174 
1175 	dev_dbg(&spi->dev,
1176 		"spi interface setup: mode 0x%2x, %d bits per word, %dhz max speed\n",
1177 		spi->mode, spi->bits_per_word, spi->max_speed_hz);
1178 
1179 	/* read chip version */
1180 	retval = rf69_get_version(spi);
1181 	if (retval < 0)
1182 		return retval;
1183 
1184 	switch (retval) {
1185 	case 0x24:
1186 		dev_dbg(&spi->dev, "found pi433 (ver. 0x%x)\n", retval);
1187 		break;
1188 	default:
1189 		dev_dbg(&spi->dev, "unknown chip version: 0x%x\n", retval);
1190 		return -ENODEV;
1191 	}
1192 
1193 	/* Allocate driver data */
1194 	device = kzalloc(sizeof(*device), GFP_KERNEL);
1195 	if (!device)
1196 		return -ENOMEM;
1197 
1198 	/* Initialize the driver data */
1199 	device->spi = spi;
1200 	device->rx_active = false;
1201 	device->tx_active = false;
1202 	device->interrupt_rx_allowed = false;
1203 
1204 	/* init rx buffer */
1205 	device->rx_buffer = kmalloc(MAX_MSG_SIZE, GFP_KERNEL);
1206 	if (!device->rx_buffer) {
1207 		retval = -ENOMEM;
1208 		goto RX_failed;
1209 	}
1210 
1211 	/* init wait queues */
1212 	init_waitqueue_head(&device->tx_wait_queue);
1213 	init_waitqueue_head(&device->rx_wait_queue);
1214 	init_waitqueue_head(&device->fifo_wait_queue);
1215 
1216 	/* init fifo */
1217 	INIT_KFIFO(device->tx_fifo);
1218 
1219 	/* init mutexes and locks */
1220 	mutex_init(&device->tx_fifo_lock);
1221 	mutex_init(&device->rx_lock);
1222 
1223 	/* setup GPIO (including irq_handler) for the different DIOs */
1224 	retval = setup_gpio(device);
1225 	if (retval) {
1226 		dev_dbg(&spi->dev, "setup of GPIOs failed\n");
1227 		goto GPIO_failed;
1228 	}
1229 
1230 	/* setup the radio module */
1231 	retval = rf69_set_mode(spi, standby);
1232 	if (retval < 0)
1233 		goto minor_failed;
1234 	retval = rf69_set_data_mode(spi, DATAMODUL_MODE_PACKET);
1235 	if (retval < 0)
1236 		goto minor_failed;
1237 	retval = rf69_enable_amplifier(spi, MASK_PALEVEL_PA0);
1238 	if (retval < 0)
1239 		goto minor_failed;
1240 	retval = rf69_disable_amplifier(spi, MASK_PALEVEL_PA1);
1241 	if (retval < 0)
1242 		goto minor_failed;
1243 	retval = rf69_disable_amplifier(spi, MASK_PALEVEL_PA2);
1244 	if (retval < 0)
1245 		goto minor_failed;
1246 	retval = rf69_set_output_power_level(spi, 13);
1247 	if (retval < 0)
1248 		goto minor_failed;
1249 	retval = rf69_set_antenna_impedance(spi, fifty_ohm);
1250 	if (retval < 0)
1251 		goto minor_failed;
1252 
1253 	/* determ minor number */
1254 	retval = pi433_get_minor(device);
1255 	if (retval) {
1256 		dev_dbg(&spi->dev, "get of minor number failed\n");
1257 		goto minor_failed;
1258 	}
1259 
1260 	/* create device */
1261 	device->devt = MKDEV(MAJOR(pi433_dev), device->minor);
1262 	device->dev = device_create(pi433_class,
1263 				    &spi->dev,
1264 				    device->devt,
1265 				    device,
1266 				    "pi433.%d",
1267 				    device->minor);
1268 	if (IS_ERR(device->dev)) {
1269 		pr_err("pi433: device register failed\n");
1270 		retval = PTR_ERR(device->dev);
1271 		goto device_create_failed;
1272 	} else {
1273 		dev_dbg(device->dev,
1274 			"created device for major %d, minor %d\n",
1275 			MAJOR(pi433_dev),
1276 			device->minor);
1277 	}
1278 
1279 	/* start tx thread */
1280 	device->tx_task_struct = kthread_run(pi433_tx_thread,
1281 					     device,
1282 					     "pi433.%d_tx_task",
1283 					     device->minor);
1284 	if (IS_ERR(device->tx_task_struct)) {
1285 		dev_dbg(device->dev, "start of send thread failed\n");
1286 		retval = PTR_ERR(device->tx_task_struct);
1287 		goto send_thread_failed;
1288 	}
1289 
1290 	/* create cdev */
1291 	device->cdev = cdev_alloc();
1292 	if (!device->cdev) {
1293 		dev_dbg(device->dev, "allocation of cdev failed\n");
1294 		retval = -ENOMEM;
1295 		goto cdev_failed;
1296 	}
1297 	device->cdev->owner = THIS_MODULE;
1298 	cdev_init(device->cdev, &pi433_fops);
1299 	retval = cdev_add(device->cdev, device->devt, 1);
1300 	if (retval) {
1301 		dev_dbg(device->dev, "register of cdev failed\n");
1302 		goto del_cdev;
1303 	}
1304 
1305 	/* spi setup */
1306 	spi_set_drvdata(spi, device);
1307 
1308 	entry = debugfs_create_dir(dev_name(device->dev), root_dir);
1309 	debugfs_create_file("regs", 0400, entry, device, &pi433_debugfs_regs_fops);
1310 
1311 	return 0;
1312 
1313 del_cdev:
1314 	cdev_del(device->cdev);
1315 cdev_failed:
1316 	kthread_stop(device->tx_task_struct);
1317 send_thread_failed:
1318 	device_destroy(pi433_class, device->devt);
1319 device_create_failed:
1320 	pi433_free_minor(device);
1321 minor_failed:
1322 	free_gpio(device);
1323 GPIO_failed:
1324 	kfree(device->rx_buffer);
1325 RX_failed:
1326 	kfree(device);
1327 
1328 	return retval;
1329 }
1330 
pi433_remove(struct spi_device * spi)1331 static void pi433_remove(struct spi_device *spi)
1332 {
1333 	struct pi433_device	*device = spi_get_drvdata(spi);
1334 
1335 	debugfs_lookup_and_remove(dev_name(device->dev), root_dir);
1336 
1337 	/* free GPIOs */
1338 	free_gpio(device);
1339 
1340 	/* make sure ops on existing fds can abort cleanly */
1341 	device->spi = NULL;
1342 
1343 	kthread_stop(device->tx_task_struct);
1344 
1345 	device_destroy(pi433_class, device->devt);
1346 
1347 	cdev_del(device->cdev);
1348 
1349 	pi433_free_minor(device);
1350 
1351 	kfree(device->rx_buffer);
1352 	kfree(device);
1353 }
1354 
1355 static const struct of_device_id pi433_dt_ids[] = {
1356 	{ .compatible = "Smarthome-Wolf,pi433" },
1357 	{},
1358 };
1359 
1360 MODULE_DEVICE_TABLE(of, pi433_dt_ids);
1361 
1362 static struct spi_driver pi433_spi_driver = {
1363 	.driver = {
1364 		.name =		"pi433",
1365 		.owner =	THIS_MODULE,
1366 		.of_match_table = of_match_ptr(pi433_dt_ids),
1367 	},
1368 	.probe =	pi433_probe,
1369 	.remove =	pi433_remove,
1370 
1371 	/*
1372 	 * NOTE:  suspend/resume methods are not necessary here.
1373 	 * We don't do anything except pass the requests to/from
1374 	 * the underlying controller.  The refrigerator handles
1375 	 * most issues; the controller driver handles the rest.
1376 	 */
1377 };
1378 
1379 /*-------------------------------------------------------------------------*/
1380 
pi433_init(void)1381 static int __init pi433_init(void)
1382 {
1383 	int status;
1384 
1385 	/*
1386 	 * If MAX_MSG_SIZE is smaller then FIFO_SIZE, the driver won't
1387 	 * work stable - risk of buffer overflow
1388 	 */
1389 	if (MAX_MSG_SIZE < FIFO_SIZE)
1390 		return -EINVAL;
1391 
1392 	/*
1393 	 * Claim device numbers.  Then register a class
1394 	 * that will key udev/mdev to add/remove /dev nodes.
1395 	 * Last, register the driver which manages those device numbers.
1396 	 */
1397 	status = alloc_chrdev_region(&pi433_dev, 0, N_PI433_MINORS, "pi433");
1398 	if (status < 0)
1399 		return status;
1400 
1401 	pi433_class = class_create("pi433");
1402 	if (IS_ERR(pi433_class)) {
1403 		unregister_chrdev(MAJOR(pi433_dev),
1404 				  pi433_spi_driver.driver.name);
1405 		return PTR_ERR(pi433_class);
1406 	}
1407 
1408 	root_dir = debugfs_create_dir(KBUILD_MODNAME, NULL);
1409 
1410 	status = spi_register_driver(&pi433_spi_driver);
1411 	if (status < 0) {
1412 		class_destroy(pi433_class);
1413 		unregister_chrdev(MAJOR(pi433_dev),
1414 				  pi433_spi_driver.driver.name);
1415 	}
1416 
1417 	return status;
1418 }
1419 
1420 module_init(pi433_init);
1421 
pi433_exit(void)1422 static void __exit pi433_exit(void)
1423 {
1424 	spi_unregister_driver(&pi433_spi_driver);
1425 	class_destroy(pi433_class);
1426 	unregister_chrdev(MAJOR(pi433_dev), pi433_spi_driver.driver.name);
1427 	debugfs_remove(root_dir);
1428 }
1429 module_exit(pi433_exit);
1430 
1431 MODULE_AUTHOR("Marcus Wolf, <linux@wolf-entwicklungen.de>");
1432 MODULE_DESCRIPTION("Driver for Pi433");
1433 MODULE_LICENSE("GPL");
1434 MODULE_ALIAS("spi:pi433");
1435