xref: /linux/drivers/greybus/gb-beagleplay.c (revision c532de5a67a70f8533d495f8f2aaa9a0491c3ad0)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Beagleplay Linux Driver for Greybus
4  *
5  * Copyright (c) 2023 Ayush Singh <ayushdevel1325@gmail.com>
6  * Copyright (c) 2023 BeagleBoard.org Foundation
7  */
8 
9 #include <linux/unaligned.h>
10 #include <linux/crc32.h>
11 #include <linux/gpio/consumer.h>
12 #include <linux/firmware.h>
13 #include <linux/greybus.h>
14 #include <linux/serdev.h>
15 #include <linux/crc-ccitt.h>
16 #include <linux/circ_buf.h>
17 
18 #define CC1352_FIRMWARE_SIZE (704 * 1024)
19 #define CC1352_BOOTLOADER_TIMEOUT 2000
20 #define CC1352_BOOTLOADER_ACK 0xcc
21 #define CC1352_BOOTLOADER_NACK 0x33
22 
23 #define RX_HDLC_PAYLOAD 256
24 #define CRC_LEN 2
25 #define MAX_RX_HDLC (1 + RX_HDLC_PAYLOAD + CRC_LEN)
26 #define TX_CIRC_BUF_SIZE 1024
27 
28 #define ADDRESS_GREYBUS 0x01
29 #define ADDRESS_DBG 0x02
30 #define ADDRESS_CONTROL 0x03
31 
32 #define HDLC_FRAME 0x7E
33 #define HDLC_ESC 0x7D
34 #define HDLC_XOR 0x20
35 
36 #define CONTROL_SVC_START 0x01
37 #define CONTROL_SVC_STOP 0x02
38 
39 /* The maximum number of CPorts supported by Greybus Host Device */
40 #define GB_MAX_CPORTS 32
41 
42 /**
43  * struct gb_beagleplay - BeaglePlay Greybus driver
44  *
45  * @sd: underlying serdev device
46  *
47  * @gb_hd: greybus host device
48  *
49  * @tx_work: hdlc transmit work
50  * @tx_producer_lock: hdlc transmit data producer lock. acquired when appending data to buffer.
51  * @tx_consumer_lock: hdlc transmit data consumer lock. acquired when sending data over uart.
52  * @tx_circ_buf: hdlc transmit circular buffer.
53  * @tx_crc: hdlc transmit crc-ccitt fcs
54  *
55  * @rx_buffer_len: length of receive buffer filled.
56  * @rx_buffer: hdlc frame receive buffer
57  * @rx_in_esc: hdlc rx flag to indicate ESC frame
58  *
59  * @fwl: underlying firmware upload device
60  * @bootloader_backdoor_gpio: cc1352p7 boot gpio
61  * @rst_gpio: cc1352p7 reset gpio
62  * @flashing_mode: flag to indicate that flashing is currently in progress
63  * @fwl_ack_com: completion to signal an Ack/Nack
64  * @fwl_ack: Ack/Nack byte received
65  * @fwl_cmd_response_com: completion to signal a bootloader command response
66  * @fwl_cmd_response: bootloader command response data
67  * @fwl_crc32: crc32 of firmware to flash
68  * @fwl_reset_addr: flag to indicate if we need to send COMMAND_DOWNLOAD again
69  */
70 struct gb_beagleplay {
71 	struct serdev_device *sd;
72 
73 	struct gb_host_device *gb_hd;
74 
75 	struct work_struct tx_work;
76 	spinlock_t tx_producer_lock;
77 	spinlock_t tx_consumer_lock;
78 	struct circ_buf tx_circ_buf;
79 	u16 tx_crc;
80 
81 	u16 rx_buffer_len;
82 	bool rx_in_esc;
83 	u8 rx_buffer[MAX_RX_HDLC];
84 
85 	struct fw_upload *fwl;
86 	struct gpio_desc *bootloader_backdoor_gpio;
87 	struct gpio_desc *rst_gpio;
88 	bool flashing_mode;
89 	struct completion fwl_ack_com;
90 	u8 fwl_ack;
91 	struct completion fwl_cmd_response_com;
92 	u32 fwl_cmd_response;
93 	u32 fwl_crc32;
94 	bool fwl_reset_addr;
95 };
96 
97 /**
98  * struct hdlc_payload - Structure to represent part of HDCL frame payload data.
99  *
100  * @len: buffer length in bytes
101  * @buf: payload buffer
102  */
103 struct hdlc_payload {
104 	u16 len;
105 	void *buf;
106 };
107 
108 /**
109  * struct hdlc_greybus_frame - Structure to represent greybus HDLC frame payload
110  *
111  * @cport: cport id
112  * @hdr: greybus operation header
113  * @payload: greybus message payload
114  *
115  * The HDLC payload sent over UART for greybus address has cport preappended to greybus message
116  */
117 struct hdlc_greybus_frame {
118 	__le16 cport;
119 	struct gb_operation_msg_hdr hdr;
120 	u8 payload[];
121 } __packed;
122 
123 /**
124  * enum cc1352_bootloader_cmd: CC1352 Bootloader Commands
125  *
126  * @COMMAND_DOWNLOAD: Prepares flash programming
127  * @COMMAND_GET_STATUS: Returns the status of the last command that was  issued
128  * @COMMAND_SEND_DATA: Transfers data and programs flash
129  * @COMMAND_RESET: Performs a system reset
130  * @COMMAND_CRC32: Calculates CRC32 over a specified memory area
131  * @COMMAND_BANK_ERASE: Performs an erase of all of the customer-accessible
132  *                      flash sectors not protected by FCFG1 and CCFG
133  *                      writeprotect bits.
134  *
135  * CC1352 Bootloader serial bus commands
136  */
137 enum cc1352_bootloader_cmd {
138 	COMMAND_DOWNLOAD = 0x21,
139 	COMMAND_GET_STATUS = 0x23,
140 	COMMAND_SEND_DATA = 0x24,
141 	COMMAND_RESET = 0x25,
142 	COMMAND_CRC32 = 0x27,
143 	COMMAND_BANK_ERASE = 0x2c,
144 };
145 
146 /**
147  * enum cc1352_bootloader_status: CC1352 Bootloader COMMAND_GET_STATUS response
148  *
149  * @COMMAND_RET_SUCCESS: Status for successful command
150  * @COMMAND_RET_UNKNOWN_CMD: Status for unknown command
151  * @COMMAND_RET_INVALID_CMD: Status for invalid command (in other words,
152  *                           incorrect packet size)
153  * @COMMAND_RET_INVALID_ADR: Status for invalid input address
154  * @COMMAND_RET_FLASH_FAIL: Status for failing flash erase or program operation
155  */
156 enum cc1352_bootloader_status {
157 	COMMAND_RET_SUCCESS = 0x40,
158 	COMMAND_RET_UNKNOWN_CMD = 0x41,
159 	COMMAND_RET_INVALID_CMD = 0x42,
160 	COMMAND_RET_INVALID_ADR = 0x43,
161 	COMMAND_RET_FLASH_FAIL = 0x44,
162 };
163 
164 /**
165  * struct cc1352_bootloader_packet: CC1352 Bootloader Request Packet
166  *
167  * @len: length of packet + optional request data
168  * @checksum: 8-bit checksum excluding len
169  * @cmd: bootloader command
170  */
171 struct cc1352_bootloader_packet {
172 	u8 len;
173 	u8 checksum;
174 	u8 cmd;
175 } __packed;
176 
177 #define CC1352_BOOTLOADER_PKT_MAX_SIZE \
178 	(U8_MAX - sizeof(struct cc1352_bootloader_packet))
179 
180 /**
181  * struct cc1352_bootloader_download_cmd_data: CC1352 Bootloader COMMAND_DOWNLOAD request data
182  *
183  * @addr: address to start programming data into
184  * @size: size of data that will be sent
185  */
186 struct cc1352_bootloader_download_cmd_data {
187 	__be32 addr;
188 	__be32 size;
189 } __packed;
190 
191 /**
192  * struct cc1352_bootloader_crc32_cmd_data: CC1352 Bootloader COMMAND_CRC32 request data
193  *
194  * @addr: address where crc32 calculation starts
195  * @size: number of bytes comprised by crc32 calculation
196  * @read_repeat: number of read repeats for each data location
197  */
198 struct cc1352_bootloader_crc32_cmd_data {
199 	__be32 addr;
200 	__be32 size;
201 	__be32 read_repeat;
202 } __packed;
203 
204 static void hdlc_rx_greybus_frame(struct gb_beagleplay *bg, u8 *buf, u16 len)
205 {
206 	struct hdlc_greybus_frame *gb_frame = (struct hdlc_greybus_frame *)buf;
207 	u16 cport_id = le16_to_cpu(gb_frame->cport);
208 	u16 gb_msg_len = le16_to_cpu(gb_frame->hdr.size);
209 
210 	dev_dbg(&bg->sd->dev, "Greybus Operation %u type %X cport %u status %u received",
211 		gb_frame->hdr.operation_id, gb_frame->hdr.type, cport_id, gb_frame->hdr.result);
212 
213 	greybus_data_rcvd(bg->gb_hd, cport_id, (u8 *)&gb_frame->hdr, gb_msg_len);
214 }
215 
216 static void hdlc_rx_dbg_frame(const struct gb_beagleplay *bg, const char *buf, u16 len)
217 {
218 	dev_dbg(&bg->sd->dev, "CC1352 Log: %.*s", (int)len, buf);
219 }
220 
221 /**
222  * hdlc_write() - Consume HDLC Buffer.
223  * @bg: beagleplay greybus driver
224  *
225  * Assumes that consumer lock has been acquired.
226  */
227 static void hdlc_write(struct gb_beagleplay *bg)
228 {
229 	int written;
230 	/* Start consuming HDLC data */
231 	int head = smp_load_acquire(&bg->tx_circ_buf.head);
232 	int tail = bg->tx_circ_buf.tail;
233 	int count = CIRC_CNT_TO_END(head, tail, TX_CIRC_BUF_SIZE);
234 	const unsigned char *buf = &bg->tx_circ_buf.buf[tail];
235 
236 	if (count > 0) {
237 		written = serdev_device_write_buf(bg->sd, buf, count);
238 
239 		/* Finish consuming HDLC data */
240 		smp_store_release(&bg->tx_circ_buf.tail, (tail + written) & (TX_CIRC_BUF_SIZE - 1));
241 	}
242 }
243 
244 /**
245  * hdlc_append() - Queue HDLC data for sending.
246  * @bg: beagleplay greybus driver
247  * @value: hdlc byte to transmit
248  *
249  * Assumes that producer lock as been acquired.
250  */
251 static void hdlc_append(struct gb_beagleplay *bg, u8 value)
252 {
253 	int tail, head = bg->tx_circ_buf.head;
254 
255 	while (true) {
256 		tail = READ_ONCE(bg->tx_circ_buf.tail);
257 
258 		if (CIRC_SPACE(head, tail, TX_CIRC_BUF_SIZE) >= 1) {
259 			bg->tx_circ_buf.buf[head] = value;
260 
261 			/* Finish producing HDLC byte */
262 			smp_store_release(&bg->tx_circ_buf.head,
263 					  (head + 1) & (TX_CIRC_BUF_SIZE - 1));
264 			return;
265 		}
266 		dev_warn(&bg->sd->dev, "Tx circ buf full");
267 		usleep_range(3000, 5000);
268 	}
269 }
270 
271 static void hdlc_append_escaped(struct gb_beagleplay *bg, u8 value)
272 {
273 	if (value == HDLC_FRAME || value == HDLC_ESC) {
274 		hdlc_append(bg, HDLC_ESC);
275 		value ^= HDLC_XOR;
276 	}
277 	hdlc_append(bg, value);
278 }
279 
280 static void hdlc_append_tx_frame(struct gb_beagleplay *bg)
281 {
282 	bg->tx_crc = 0xFFFF;
283 	hdlc_append(bg, HDLC_FRAME);
284 }
285 
286 static void hdlc_append_tx_u8(struct gb_beagleplay *bg, u8 value)
287 {
288 	bg->tx_crc = crc_ccitt(bg->tx_crc, &value, 1);
289 	hdlc_append_escaped(bg, value);
290 }
291 
292 static void hdlc_append_tx_buf(struct gb_beagleplay *bg, const u8 *buf, u16 len)
293 {
294 	size_t i;
295 
296 	for (i = 0; i < len; i++)
297 		hdlc_append_tx_u8(bg, buf[i]);
298 }
299 
300 static void hdlc_append_tx_crc(struct gb_beagleplay *bg)
301 {
302 	bg->tx_crc ^= 0xffff;
303 	hdlc_append_escaped(bg, bg->tx_crc & 0xff);
304 	hdlc_append_escaped(bg, (bg->tx_crc >> 8) & 0xff);
305 }
306 
307 static void hdlc_transmit(struct work_struct *work)
308 {
309 	struct gb_beagleplay *bg = container_of(work, struct gb_beagleplay, tx_work);
310 
311 	spin_lock_bh(&bg->tx_consumer_lock);
312 	hdlc_write(bg);
313 	spin_unlock_bh(&bg->tx_consumer_lock);
314 }
315 
316 static void hdlc_tx_frames(struct gb_beagleplay *bg, u8 address, u8 control,
317 			   const struct hdlc_payload payloads[], size_t count)
318 {
319 	size_t i;
320 
321 	spin_lock(&bg->tx_producer_lock);
322 
323 	hdlc_append_tx_frame(bg);
324 	hdlc_append_tx_u8(bg, address);
325 	hdlc_append_tx_u8(bg, control);
326 
327 	for (i = 0; i < count; ++i)
328 		hdlc_append_tx_buf(bg, payloads[i].buf, payloads[i].len);
329 
330 	hdlc_append_tx_crc(bg);
331 	hdlc_append_tx_frame(bg);
332 
333 	spin_unlock(&bg->tx_producer_lock);
334 
335 	schedule_work(&bg->tx_work);
336 }
337 
338 static void hdlc_tx_s_frame_ack(struct gb_beagleplay *bg)
339 {
340 	hdlc_tx_frames(bg, bg->rx_buffer[0], (bg->rx_buffer[1] >> 1) & 0x7, NULL, 0);
341 }
342 
343 static void hdlc_rx_frame(struct gb_beagleplay *bg)
344 {
345 	u16 crc, len;
346 	u8 ctrl, *buf;
347 	u8 address = bg->rx_buffer[0];
348 
349 	crc = crc_ccitt(0xffff, bg->rx_buffer, bg->rx_buffer_len);
350 	if (crc != 0xf0b8) {
351 		dev_warn_ratelimited(&bg->sd->dev, "CRC failed from %02x: 0x%04x", address, crc);
352 		return;
353 	}
354 
355 	ctrl = bg->rx_buffer[1];
356 	buf = &bg->rx_buffer[2];
357 	len = bg->rx_buffer_len - 4;
358 
359 	/* I-Frame, send S-Frame ACK */
360 	if ((ctrl & 1) == 0)
361 		hdlc_tx_s_frame_ack(bg);
362 
363 	switch (address) {
364 	case ADDRESS_DBG:
365 		hdlc_rx_dbg_frame(bg, buf, len);
366 		break;
367 	case ADDRESS_GREYBUS:
368 		hdlc_rx_greybus_frame(bg, buf, len);
369 		break;
370 	default:
371 		dev_warn_ratelimited(&bg->sd->dev, "unknown frame %u", address);
372 	}
373 }
374 
375 static size_t hdlc_rx(struct gb_beagleplay *bg, const u8 *data, size_t count)
376 {
377 	size_t i;
378 	u8 c;
379 
380 	for (i = 0; i < count; ++i) {
381 		c = data[i];
382 
383 		switch (c) {
384 		case HDLC_FRAME:
385 			if (bg->rx_buffer_len)
386 				hdlc_rx_frame(bg);
387 
388 			bg->rx_buffer_len = 0;
389 			break;
390 		case HDLC_ESC:
391 			bg->rx_in_esc = true;
392 			break;
393 		default:
394 			if (bg->rx_in_esc) {
395 				c ^= 0x20;
396 				bg->rx_in_esc = false;
397 			}
398 
399 			if (bg->rx_buffer_len < MAX_RX_HDLC) {
400 				bg->rx_buffer[bg->rx_buffer_len] = c;
401 				bg->rx_buffer_len++;
402 			} else {
403 				dev_err_ratelimited(&bg->sd->dev, "RX Buffer Overflow");
404 				bg->rx_buffer_len = 0;
405 			}
406 		}
407 	}
408 
409 	return count;
410 }
411 
412 static int hdlc_init(struct gb_beagleplay *bg)
413 {
414 	INIT_WORK(&bg->tx_work, hdlc_transmit);
415 	spin_lock_init(&bg->tx_producer_lock);
416 	spin_lock_init(&bg->tx_consumer_lock);
417 	bg->tx_circ_buf.head = 0;
418 	bg->tx_circ_buf.tail = 0;
419 
420 	bg->tx_circ_buf.buf = devm_kmalloc(&bg->sd->dev, TX_CIRC_BUF_SIZE, GFP_KERNEL);
421 	if (!bg->tx_circ_buf.buf)
422 		return -ENOMEM;
423 
424 	bg->rx_buffer_len = 0;
425 	bg->rx_in_esc = false;
426 
427 	return 0;
428 }
429 
430 static void hdlc_deinit(struct gb_beagleplay *bg)
431 {
432 	flush_work(&bg->tx_work);
433 }
434 
435 /**
436  * csum8: Calculate 8-bit checksum on data
437  *
438  * @data: bytes to calculate 8-bit checksum of
439  * @size: number of bytes
440  * @base: starting value for checksum
441  */
442 static u8 csum8(const u8 *data, size_t size, u8 base)
443 {
444 	size_t i;
445 	u8 sum = base;
446 
447 	for (i = 0; i < size; ++i)
448 		sum += data[i];
449 
450 	return sum;
451 }
452 
453 static void cc1352_bootloader_send_ack(struct gb_beagleplay *bg)
454 {
455 	static const u8 ack[] = { 0x00, CC1352_BOOTLOADER_ACK };
456 
457 	serdev_device_write_buf(bg->sd, ack, sizeof(ack));
458 }
459 
460 static void cc1352_bootloader_send_nack(struct gb_beagleplay *bg)
461 {
462 	static const u8 nack[] = { 0x00, CC1352_BOOTLOADER_NACK };
463 
464 	serdev_device_write_buf(bg->sd, nack, sizeof(nack));
465 }
466 
467 /**
468  * cc1352_bootloader_pkt_rx: Process a CC1352 Bootloader Packet
469  *
470  * @bg: beagleplay greybus driver
471  * @data: packet buffer
472  * @count: packet buffer size
473  *
474  * @return: number of bytes processed
475  *
476  * Here are the steps to successfully receive a packet from cc1352 bootloader
477  * according to the docs:
478  * 1. Wait for nonzero data to be returned from the device. This is important
479  *    as the device may send zero bytes between a sent and a received data
480  *    packet. The first nonzero byte received is the size of the packet that is
481  *    being received.
482  * 2. Read the next byte, which is the checksum for the packet.
483  * 3. Read the data bytes from the device. During the data phase, packet size
484  *    minus 2 bytes is sent.
485  * 4. Calculate the checksum of the data bytes and verify it matches the
486  *    checksum received in the packet.
487  * 5. Send an acknowledge byte or a not-acknowledge byte to the device to
488  *    indicate the successful or unsuccessful reception of the packet.
489  */
490 static int cc1352_bootloader_pkt_rx(struct gb_beagleplay *bg, const u8 *data,
491 				    size_t count)
492 {
493 	bool is_valid = false;
494 
495 	switch (data[0]) {
496 	/* Skip 0x00 bytes.  */
497 	case 0x00:
498 		return 1;
499 	case CC1352_BOOTLOADER_ACK:
500 	case CC1352_BOOTLOADER_NACK:
501 		WRITE_ONCE(bg->fwl_ack, data[0]);
502 		complete(&bg->fwl_ack_com);
503 		return 1;
504 	case 3:
505 		if (count < 3)
506 			return 0;
507 		is_valid = data[1] == data[2];
508 		WRITE_ONCE(bg->fwl_cmd_response, (u32)data[2]);
509 		break;
510 	case 6:
511 		if (count < 6)
512 			return 0;
513 		is_valid = csum8(&data[2], sizeof(__be32), 0) == data[1];
514 		WRITE_ONCE(bg->fwl_cmd_response, get_unaligned_be32(&data[2]));
515 		break;
516 	default:
517 		return -EINVAL;
518 	}
519 
520 	if (is_valid) {
521 		cc1352_bootloader_send_ack(bg);
522 		complete(&bg->fwl_cmd_response_com);
523 	} else {
524 		dev_warn(&bg->sd->dev,
525 			 "Dropping bootloader packet with invalid checksum");
526 		cc1352_bootloader_send_nack(bg);
527 	}
528 
529 	return data[0];
530 }
531 
532 static size_t cc1352_bootloader_rx(struct gb_beagleplay *bg, const u8 *data,
533 				   size_t count)
534 {
535 	int ret;
536 	size_t off = 0;
537 
538 	memcpy(bg->rx_buffer + bg->rx_buffer_len, data, count);
539 	bg->rx_buffer_len += count;
540 
541 	do {
542 		ret = cc1352_bootloader_pkt_rx(bg, bg->rx_buffer + off,
543 					       bg->rx_buffer_len - off);
544 		if (ret < 0)
545 			return dev_err_probe(&bg->sd->dev, ret,
546 					     "Invalid Packet");
547 		off += ret;
548 	} while (ret > 0 && off < count);
549 
550 	bg->rx_buffer_len -= off;
551 	memmove(bg->rx_buffer, bg->rx_buffer + off, bg->rx_buffer_len);
552 
553 	return count;
554 }
555 
556 static size_t gb_tty_receive(struct serdev_device *sd, const u8 *data,
557 			     size_t count)
558 {
559 	struct gb_beagleplay *bg = serdev_device_get_drvdata(sd);
560 
561 	if (READ_ONCE(bg->flashing_mode))
562 		return cc1352_bootloader_rx(bg, data, count);
563 
564 	return hdlc_rx(bg, data, count);
565 }
566 
567 static void gb_tty_wakeup(struct serdev_device *serdev)
568 {
569 	struct gb_beagleplay *bg = serdev_device_get_drvdata(serdev);
570 
571 	if (!READ_ONCE(bg->flashing_mode))
572 		schedule_work(&bg->tx_work);
573 }
574 
575 static struct serdev_device_ops gb_beagleplay_ops = {
576 	.receive_buf = gb_tty_receive,
577 	.write_wakeup = gb_tty_wakeup,
578 };
579 
580 /**
581  * gb_message_send() - Send greybus message using HDLC over UART
582  *
583  * @hd: pointer to greybus host device
584  * @cport: AP cport where message originates
585  * @msg: greybus message to send
586  * @mask: gfp mask
587  *
588  * Greybus HDLC frame has the following payload:
589  * 1. le16 cport
590  * 2. gb_operation_msg_hdr msg_header
591  * 3. u8 *msg_payload
592  */
593 static int gb_message_send(struct gb_host_device *hd, u16 cport, struct gb_message *msg, gfp_t mask)
594 {
595 	struct gb_beagleplay *bg = dev_get_drvdata(&hd->dev);
596 	struct hdlc_payload payloads[3];
597 	__le16 cport_id = cpu_to_le16(cport);
598 
599 	dev_dbg(&hd->dev, "Sending greybus message with Operation %u, Type: %X on Cport %u",
600 		msg->header->operation_id, msg->header->type, cport);
601 
602 	if (le16_to_cpu(msg->header->size) > RX_HDLC_PAYLOAD)
603 		return dev_err_probe(&hd->dev, -E2BIG, "Greybus message too big");
604 
605 	payloads[0].buf = &cport_id;
606 	payloads[0].len = sizeof(cport_id);
607 	payloads[1].buf = msg->header;
608 	payloads[1].len = sizeof(*msg->header);
609 	payloads[2].buf = msg->payload;
610 	payloads[2].len = msg->payload_size;
611 
612 	hdlc_tx_frames(bg, ADDRESS_GREYBUS, 0x03, payloads, 3);
613 	greybus_message_sent(bg->gb_hd, msg, 0);
614 
615 	return 0;
616 }
617 
618 static void gb_message_cancel(struct gb_message *message)
619 {
620 }
621 
622 static struct gb_hd_driver gb_hdlc_driver = { .message_send = gb_message_send,
623 					      .message_cancel = gb_message_cancel };
624 
625 static void gb_beagleplay_start_svc(struct gb_beagleplay *bg)
626 {
627 	const u8 command = CONTROL_SVC_START;
628 	const struct hdlc_payload payload = { .len = 1, .buf = (void *)&command };
629 
630 	hdlc_tx_frames(bg, ADDRESS_CONTROL, 0x03, &payload, 1);
631 }
632 
633 static void gb_beagleplay_stop_svc(struct gb_beagleplay *bg)
634 {
635 	const u8 command = CONTROL_SVC_STOP;
636 	const struct hdlc_payload payload = { .len = 1, .buf = (void *)&command };
637 
638 	hdlc_tx_frames(bg, ADDRESS_CONTROL, 0x03, &payload, 1);
639 }
640 
641 static int cc1352_bootloader_wait_for_ack(struct gb_beagleplay *bg)
642 {
643 	int ret;
644 
645 	ret = wait_for_completion_timeout(
646 		&bg->fwl_ack_com, msecs_to_jiffies(CC1352_BOOTLOADER_TIMEOUT));
647 	if (ret < 0)
648 		return dev_err_probe(&bg->sd->dev, ret,
649 				     "Failed to acquire ack semaphore");
650 
651 	switch (READ_ONCE(bg->fwl_ack)) {
652 	case CC1352_BOOTLOADER_ACK:
653 		return 0;
654 	case CC1352_BOOTLOADER_NACK:
655 		return -EAGAIN;
656 	default:
657 		return -EINVAL;
658 	}
659 }
660 
661 static int cc1352_bootloader_sync(struct gb_beagleplay *bg)
662 {
663 	static const u8 sync_bytes[] = { 0x55, 0x55 };
664 
665 	serdev_device_write_buf(bg->sd, sync_bytes, sizeof(sync_bytes));
666 	return cc1352_bootloader_wait_for_ack(bg);
667 }
668 
669 static int cc1352_bootloader_get_status(struct gb_beagleplay *bg)
670 {
671 	int ret;
672 	static const struct cc1352_bootloader_packet pkt = {
673 		.len = sizeof(pkt),
674 		.checksum = COMMAND_GET_STATUS,
675 		.cmd = COMMAND_GET_STATUS
676 	};
677 
678 	serdev_device_write_buf(bg->sd, (const u8 *)&pkt, sizeof(pkt));
679 	ret = cc1352_bootloader_wait_for_ack(bg);
680 	if (ret < 0)
681 		return ret;
682 
683 	ret = wait_for_completion_timeout(
684 		&bg->fwl_cmd_response_com,
685 		msecs_to_jiffies(CC1352_BOOTLOADER_TIMEOUT));
686 	if (ret < 0)
687 		return dev_err_probe(&bg->sd->dev, ret,
688 				     "Failed to acquire last status semaphore");
689 
690 	switch (READ_ONCE(bg->fwl_cmd_response)) {
691 	case COMMAND_RET_SUCCESS:
692 		return 0;
693 	default:
694 		return -EINVAL;
695 	}
696 
697 	return 0;
698 }
699 
700 static int cc1352_bootloader_erase(struct gb_beagleplay *bg)
701 {
702 	int ret;
703 	static const struct cc1352_bootloader_packet pkt = {
704 		.len = sizeof(pkt),
705 		.checksum = COMMAND_BANK_ERASE,
706 		.cmd = COMMAND_BANK_ERASE
707 	};
708 
709 	serdev_device_write_buf(bg->sd, (const u8 *)&pkt, sizeof(pkt));
710 
711 	ret = cc1352_bootloader_wait_for_ack(bg);
712 	if (ret < 0)
713 		return ret;
714 
715 	return cc1352_bootloader_get_status(bg);
716 }
717 
718 static int cc1352_bootloader_reset(struct gb_beagleplay *bg)
719 {
720 	static const struct cc1352_bootloader_packet pkt = {
721 		.len = sizeof(pkt),
722 		.checksum = COMMAND_RESET,
723 		.cmd = COMMAND_RESET
724 	};
725 
726 	serdev_device_write_buf(bg->sd, (const u8 *)&pkt, sizeof(pkt));
727 
728 	return cc1352_bootloader_wait_for_ack(bg);
729 }
730 
731 /**
732  * cc1352_bootloader_empty_pkt: Calculate the number of empty bytes in the current packet
733  *
734  * @data: packet bytes array to check
735  * @size: number of bytes in array
736  */
737 static size_t cc1352_bootloader_empty_pkt(const u8 *data, size_t size)
738 {
739 	size_t i;
740 
741 	for (i = 0; i < size && data[i] == 0xff; ++i)
742 		continue;
743 
744 	return i;
745 }
746 
747 static int cc1352_bootloader_crc32(struct gb_beagleplay *bg, u32 *crc32)
748 {
749 	int ret;
750 	static const struct cc1352_bootloader_crc32_cmd_data cmd_data = {
751 		.addr = 0, .size = cpu_to_be32(704 * 1024), .read_repeat = 0
752 	};
753 	const struct cc1352_bootloader_packet pkt = {
754 		.len = sizeof(pkt) + sizeof(cmd_data),
755 		.checksum = csum8((const void *)&cmd_data, sizeof(cmd_data),
756 				  COMMAND_CRC32),
757 		.cmd = COMMAND_CRC32
758 	};
759 
760 	serdev_device_write_buf(bg->sd, (const u8 *)&pkt, sizeof(pkt));
761 	serdev_device_write_buf(bg->sd, (const u8 *)&cmd_data,
762 				sizeof(cmd_data));
763 
764 	ret = cc1352_bootloader_wait_for_ack(bg);
765 	if (ret < 0)
766 		return ret;
767 
768 	ret = wait_for_completion_timeout(
769 		&bg->fwl_cmd_response_com,
770 		msecs_to_jiffies(CC1352_BOOTLOADER_TIMEOUT));
771 	if (ret < 0)
772 		return dev_err_probe(&bg->sd->dev, ret,
773 				     "Failed to acquire last status semaphore");
774 
775 	*crc32 = READ_ONCE(bg->fwl_cmd_response);
776 
777 	return 0;
778 }
779 
780 static int cc1352_bootloader_download(struct gb_beagleplay *bg, u32 size,
781 				      u32 addr)
782 {
783 	int ret;
784 	const struct cc1352_bootloader_download_cmd_data cmd_data = {
785 		.addr = cpu_to_be32(addr),
786 		.size = cpu_to_be32(size),
787 	};
788 	const struct cc1352_bootloader_packet pkt = {
789 		.len = sizeof(pkt) + sizeof(cmd_data),
790 		.checksum = csum8((const void *)&cmd_data, sizeof(cmd_data),
791 				  COMMAND_DOWNLOAD),
792 		.cmd = COMMAND_DOWNLOAD
793 	};
794 
795 	serdev_device_write_buf(bg->sd, (const u8 *)&pkt, sizeof(pkt));
796 	serdev_device_write_buf(bg->sd, (const u8 *)&cmd_data,
797 				sizeof(cmd_data));
798 
799 	ret = cc1352_bootloader_wait_for_ack(bg);
800 	if (ret < 0)
801 		return ret;
802 
803 	return cc1352_bootloader_get_status(bg);
804 }
805 
806 static int cc1352_bootloader_send_data(struct gb_beagleplay *bg, const u8 *data,
807 				       size_t size)
808 {
809 	int ret, rem = min(size, CC1352_BOOTLOADER_PKT_MAX_SIZE);
810 	const struct cc1352_bootloader_packet pkt = {
811 		.len = sizeof(pkt) + rem,
812 		.checksum = csum8(data, rem, COMMAND_SEND_DATA),
813 		.cmd = COMMAND_SEND_DATA
814 	};
815 
816 	serdev_device_write_buf(bg->sd, (const u8 *)&pkt, sizeof(pkt));
817 	serdev_device_write_buf(bg->sd, data, rem);
818 
819 	ret = cc1352_bootloader_wait_for_ack(bg);
820 	if (ret < 0)
821 		return ret;
822 
823 	ret = cc1352_bootloader_get_status(bg);
824 	if (ret < 0)
825 		return ret;
826 
827 	return rem;
828 }
829 
830 static void gb_greybus_deinit(struct gb_beagleplay *bg)
831 {
832 	gb_hd_del(bg->gb_hd);
833 	gb_hd_put(bg->gb_hd);
834 }
835 
836 static int gb_greybus_init(struct gb_beagleplay *bg)
837 {
838 	int ret;
839 
840 	bg->gb_hd = gb_hd_create(&gb_hdlc_driver, &bg->sd->dev, TX_CIRC_BUF_SIZE, GB_MAX_CPORTS);
841 	if (IS_ERR(bg->gb_hd)) {
842 		dev_err(&bg->sd->dev, "Failed to create greybus host device");
843 		return PTR_ERR(bg->gb_hd);
844 	}
845 
846 	ret = gb_hd_add(bg->gb_hd);
847 	if (ret) {
848 		dev_err(&bg->sd->dev, "Failed to add greybus host device");
849 		goto free_gb_hd;
850 	}
851 	dev_set_drvdata(&bg->gb_hd->dev, bg);
852 
853 	return 0;
854 
855 free_gb_hd:
856 	gb_greybus_deinit(bg);
857 	return ret;
858 }
859 
860 static enum fw_upload_err cc1352_prepare(struct fw_upload *fw_upload,
861 					 const u8 *data, u32 size)
862 {
863 	int ret;
864 	u32 curr_crc32;
865 	struct gb_beagleplay *bg = fw_upload->dd_handle;
866 
867 	dev_info(&bg->sd->dev, "CC1352 Start Flashing...");
868 
869 	if (size != CC1352_FIRMWARE_SIZE)
870 		return FW_UPLOAD_ERR_INVALID_SIZE;
871 
872 	/* Might involve network calls */
873 	gb_greybus_deinit(bg);
874 	msleep(5 * MSEC_PER_SEC);
875 
876 	gb_beagleplay_stop_svc(bg);
877 	msleep(200);
878 	flush_work(&bg->tx_work);
879 
880 	serdev_device_wait_until_sent(bg->sd, CC1352_BOOTLOADER_TIMEOUT);
881 
882 	WRITE_ONCE(bg->flashing_mode, true);
883 
884 	gpiod_direction_output(bg->bootloader_backdoor_gpio, 0);
885 	gpiod_direction_output(bg->rst_gpio, 0);
886 	msleep(200);
887 
888 	gpiod_set_value(bg->rst_gpio, 1);
889 	msleep(200);
890 
891 	gpiod_set_value(bg->bootloader_backdoor_gpio, 1);
892 	msleep(200);
893 
894 	gpiod_direction_input(bg->bootloader_backdoor_gpio);
895 	gpiod_direction_input(bg->rst_gpio);
896 
897 	ret = cc1352_bootloader_sync(bg);
898 	if (ret < 0)
899 		return dev_err_probe(&bg->sd->dev, FW_UPLOAD_ERR_HW_ERROR,
900 				     "Failed to sync");
901 
902 	ret = cc1352_bootloader_crc32(bg, &curr_crc32);
903 	if (ret < 0)
904 		return dev_err_probe(&bg->sd->dev, FW_UPLOAD_ERR_HW_ERROR,
905 				     "Failed to fetch crc32");
906 
907 	bg->fwl_crc32 = crc32(0xffffffff, data, size) ^ 0xffffffff;
908 
909 	/* Check if attempting to reflash same firmware */
910 	if (bg->fwl_crc32 == curr_crc32) {
911 		dev_warn(&bg->sd->dev, "Skipping reflashing same image");
912 		cc1352_bootloader_reset(bg);
913 		WRITE_ONCE(bg->flashing_mode, false);
914 		msleep(200);
915 		gb_greybus_init(bg);
916 		gb_beagleplay_start_svc(bg);
917 		return FW_UPLOAD_ERR_FW_INVALID;
918 	}
919 
920 	ret = cc1352_bootloader_erase(bg);
921 	if (ret < 0)
922 		return dev_err_probe(&bg->sd->dev, FW_UPLOAD_ERR_HW_ERROR,
923 				     "Failed to erase");
924 
925 	bg->fwl_reset_addr = true;
926 
927 	return FW_UPLOAD_ERR_NONE;
928 }
929 
930 static void cc1352_cleanup(struct fw_upload *fw_upload)
931 {
932 	struct gb_beagleplay *bg = fw_upload->dd_handle;
933 
934 	WRITE_ONCE(bg->flashing_mode, false);
935 }
936 
937 static enum fw_upload_err cc1352_write(struct fw_upload *fw_upload,
938 				       const u8 *data, u32 offset, u32 size,
939 				       u32 *written)
940 {
941 	int ret;
942 	size_t empty_bytes;
943 	struct gb_beagleplay *bg = fw_upload->dd_handle;
944 
945 	/* Skip 0xff packets. Significant performance improvement */
946 	empty_bytes = cc1352_bootloader_empty_pkt(data + offset, size);
947 	if (empty_bytes >= CC1352_BOOTLOADER_PKT_MAX_SIZE) {
948 		bg->fwl_reset_addr = true;
949 		*written = empty_bytes;
950 		return FW_UPLOAD_ERR_NONE;
951 	}
952 
953 	if (bg->fwl_reset_addr) {
954 		ret = cc1352_bootloader_download(bg, size, offset);
955 		if (ret < 0)
956 			return dev_err_probe(&bg->sd->dev,
957 					     FW_UPLOAD_ERR_HW_ERROR,
958 					     "Failed to send download cmd");
959 
960 		bg->fwl_reset_addr = false;
961 	}
962 
963 	ret = cc1352_bootloader_send_data(bg, data + offset, size);
964 	if (ret < 0)
965 		return dev_err_probe(&bg->sd->dev, FW_UPLOAD_ERR_HW_ERROR,
966 				     "Failed to flash firmware");
967 	*written = ret;
968 
969 	return FW_UPLOAD_ERR_NONE;
970 }
971 
972 static enum fw_upload_err cc1352_poll_complete(struct fw_upload *fw_upload)
973 {
974 	u32 curr_crc32;
975 	struct gb_beagleplay *bg = fw_upload->dd_handle;
976 
977 	if (cc1352_bootloader_crc32(bg, &curr_crc32) < 0)
978 		return dev_err_probe(&bg->sd->dev, FW_UPLOAD_ERR_HW_ERROR,
979 				     "Failed to fetch crc32");
980 
981 	if (bg->fwl_crc32 != curr_crc32)
982 		return dev_err_probe(&bg->sd->dev, FW_UPLOAD_ERR_FW_INVALID,
983 				     "Invalid CRC32");
984 
985 	if (cc1352_bootloader_reset(bg) < 0)
986 		return dev_err_probe(&bg->sd->dev, FW_UPLOAD_ERR_HW_ERROR,
987 				     "Failed to reset");
988 
989 	dev_info(&bg->sd->dev, "CC1352 Flashing Successful");
990 	WRITE_ONCE(bg->flashing_mode, false);
991 	msleep(200);
992 
993 	if (gb_greybus_init(bg) < 0)
994 		return dev_err_probe(&bg->sd->dev, FW_UPLOAD_ERR_RW_ERROR,
995 				     "Failed to initialize greybus");
996 
997 	gb_beagleplay_start_svc(bg);
998 
999 	return FW_UPLOAD_ERR_NONE;
1000 }
1001 
1002 static void cc1352_cancel(struct fw_upload *fw_upload)
1003 {
1004 	struct gb_beagleplay *bg = fw_upload->dd_handle;
1005 
1006 	dev_info(&bg->sd->dev, "CC1352 Bootloader Cancel");
1007 
1008 	cc1352_bootloader_reset(bg);
1009 }
1010 
1011 static void gb_serdev_deinit(struct gb_beagleplay *bg)
1012 {
1013 	serdev_device_close(bg->sd);
1014 }
1015 
1016 static int gb_serdev_init(struct gb_beagleplay *bg)
1017 {
1018 	int ret;
1019 
1020 	serdev_device_set_drvdata(bg->sd, bg);
1021 	serdev_device_set_client_ops(bg->sd, &gb_beagleplay_ops);
1022 	ret = serdev_device_open(bg->sd);
1023 	if (ret)
1024 		return dev_err_probe(&bg->sd->dev, ret, "Unable to open serial device");
1025 
1026 	serdev_device_set_baudrate(bg->sd, 115200);
1027 	serdev_device_set_flow_control(bg->sd, false);
1028 
1029 	return 0;
1030 }
1031 
1032 static const struct fw_upload_ops cc1352_bootloader_ops = {
1033 	.prepare = cc1352_prepare,
1034 	.write = cc1352_write,
1035 	.poll_complete = cc1352_poll_complete,
1036 	.cancel = cc1352_cancel,
1037 	.cleanup = cc1352_cleanup
1038 };
1039 
1040 static int gb_fw_init(struct gb_beagleplay *bg)
1041 {
1042 	int ret;
1043 	struct fw_upload *fwl;
1044 	struct gpio_desc *desc;
1045 
1046 	bg->fwl = NULL;
1047 	bg->bootloader_backdoor_gpio = NULL;
1048 	bg->rst_gpio = NULL;
1049 	bg->flashing_mode = false;
1050 	bg->fwl_cmd_response = 0;
1051 	bg->fwl_ack = 0;
1052 	init_completion(&bg->fwl_ack_com);
1053 	init_completion(&bg->fwl_cmd_response_com);
1054 
1055 	desc = devm_gpiod_get(&bg->sd->dev, "bootloader-backdoor", GPIOD_IN);
1056 	if (IS_ERR(desc))
1057 		return PTR_ERR(desc);
1058 	bg->bootloader_backdoor_gpio = desc;
1059 
1060 	desc = devm_gpiod_get(&bg->sd->dev, "reset", GPIOD_IN);
1061 	if (IS_ERR(desc)) {
1062 		ret = PTR_ERR(desc);
1063 		goto free_boot;
1064 	}
1065 	bg->rst_gpio = desc;
1066 
1067 	fwl = firmware_upload_register(THIS_MODULE, &bg->sd->dev, "cc1352p7",
1068 				       &cc1352_bootloader_ops, bg);
1069 	if (IS_ERR(fwl)) {
1070 		ret = PTR_ERR(fwl);
1071 		goto free_reset;
1072 	}
1073 	bg->fwl = fwl;
1074 
1075 	return 0;
1076 
1077 free_reset:
1078 	devm_gpiod_put(&bg->sd->dev, bg->rst_gpio);
1079 	bg->rst_gpio = NULL;
1080 free_boot:
1081 	devm_gpiod_put(&bg->sd->dev, bg->bootloader_backdoor_gpio);
1082 	bg->bootloader_backdoor_gpio = NULL;
1083 	return ret;
1084 }
1085 
1086 static void gb_fw_deinit(struct gb_beagleplay *bg)
1087 {
1088 	firmware_upload_unregister(bg->fwl);
1089 }
1090 
1091 static int gb_beagleplay_probe(struct serdev_device *serdev)
1092 {
1093 	int ret = 0;
1094 	struct gb_beagleplay *bg;
1095 
1096 	bg = devm_kmalloc(&serdev->dev, sizeof(*bg), GFP_KERNEL);
1097 	if (!bg)
1098 		return -ENOMEM;
1099 
1100 	bg->sd = serdev;
1101 	ret = gb_serdev_init(bg);
1102 	if (ret)
1103 		return ret;
1104 
1105 	ret = hdlc_init(bg);
1106 	if (ret)
1107 		goto free_serdev;
1108 
1109 	ret = gb_fw_init(bg);
1110 	if (ret)
1111 		goto free_hdlc;
1112 
1113 	ret = gb_greybus_init(bg);
1114 	if (ret)
1115 		goto free_fw;
1116 
1117 	gb_beagleplay_start_svc(bg);
1118 
1119 	return 0;
1120 
1121 free_fw:
1122 	gb_fw_deinit(bg);
1123 free_hdlc:
1124 	hdlc_deinit(bg);
1125 free_serdev:
1126 	gb_serdev_deinit(bg);
1127 	return ret;
1128 }
1129 
1130 static void gb_beagleplay_remove(struct serdev_device *serdev)
1131 {
1132 	struct gb_beagleplay *bg = serdev_device_get_drvdata(serdev);
1133 
1134 	gb_fw_deinit(bg);
1135 	gb_greybus_deinit(bg);
1136 	gb_beagleplay_stop_svc(bg);
1137 	hdlc_deinit(bg);
1138 	gb_serdev_deinit(bg);
1139 }
1140 
1141 static const struct of_device_id gb_beagleplay_of_match[] = {
1142 	{
1143 		.compatible = "ti,cc1352p7",
1144 	},
1145 	{},
1146 };
1147 MODULE_DEVICE_TABLE(of, gb_beagleplay_of_match);
1148 
1149 static struct serdev_device_driver gb_beagleplay_driver = {
1150 	.probe = gb_beagleplay_probe,
1151 	.remove = gb_beagleplay_remove,
1152 	.driver = {
1153 		.name = "gb_beagleplay",
1154 		.of_match_table = gb_beagleplay_of_match,
1155 	},
1156 };
1157 
1158 module_serdev_device_driver(gb_beagleplay_driver);
1159 
1160 MODULE_LICENSE("GPL");
1161 MODULE_AUTHOR("Ayush Singh <ayushdevel1325@gmail.com>");
1162 MODULE_DESCRIPTION("A Greybus driver for BeaglePlay");
1163