1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * I2C Link Layer for ST21NFCA HCI based Driver
4 * Copyright (C) 2014  STMicroelectronics SAS. All rights reserved.
5 */
6
7#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
8
9#include <linux/crc-ccitt.h>
10#include <linux/module.h>
11#include <linux/i2c.h>
12#include <linux/gpio/consumer.h>
13#include <linux/of_irq.h>
14#include <linux/of_gpio.h>
15#include <linux/acpi.h>
16#include <linux/interrupt.h>
17#include <linux/delay.h>
18#include <linux/nfc.h>
19#include <linux/firmware.h>
20
21#include <net/nfc/hci.h>
22#include <net/nfc/llc.h>
23#include <net/nfc/nfc.h>
24
25#include "st21nfca.h"
26
27/*
28 * Every frame starts with ST21NFCA_SOF_EOF and ends with ST21NFCA_SOF_EOF.
29 * Because ST21NFCA_SOF_EOF is a possible data value, there is a mecanism
30 * called byte stuffing has been introduced.
31 *
32 * if byte == ST21NFCA_SOF_EOF or ST21NFCA_ESCAPE_BYTE_STUFFING
33 * - insert ST21NFCA_ESCAPE_BYTE_STUFFING (escape byte)
34 * - xor byte with ST21NFCA_BYTE_STUFFING_MASK
35 */
36#define ST21NFCA_SOF_EOF		0x7e
37#define ST21NFCA_BYTE_STUFFING_MASK	0x20
38#define ST21NFCA_ESCAPE_BYTE_STUFFING	0x7d
39
40/* SOF + 00 */
41#define ST21NFCA_FRAME_HEADROOM			2
42
43/* 2 bytes crc + EOF */
44#define ST21NFCA_FRAME_TAILROOM 3
45#define IS_START_OF_FRAME(buf) (buf[0] == ST21NFCA_SOF_EOF && \
46				buf[1] == 0)
47
48#define ST21NFCA_HCI_DRIVER_NAME "st21nfca_hci"
49#define ST21NFCA_HCI_I2C_DRIVER_NAME "st21nfca_hci_i2c"
50
51struct st21nfca_i2c_phy {
52	struct i2c_client *i2c_dev;
53	struct nfc_hci_dev *hdev;
54
55	struct gpio_desc *gpiod_ena;
56	struct st21nfca_se_status se_status;
57
58	struct sk_buff *pending_skb;
59	int current_read_len;
60	/*
61	 * crc might have fail because i2c macro
62	 * is disable due to other interface activity
63	 */
64	int crc_trials;
65
66	int powered;
67	int run_mode;
68
69	/*
70	 * < 0 if hardware error occured (e.g. i2c err)
71	 * and prevents normal operation.
72	 */
73	int hard_fault;
74	struct mutex phy_lock;
75};
76
77static const u8 len_seq[] = { 16, 24, 12, 29 };
78static const u16 wait_tab[] = { 2, 3, 5, 15, 20, 40};
79
80#define I2C_DUMP_SKB(info, skb)					\
81do {								\
82	pr_debug("%s:\n", info);				\
83	print_hex_dump(KERN_DEBUG, "i2c: ", DUMP_PREFIX_OFFSET,	\
84		       16, 1, (skb)->data, (skb)->len, 0);	\
85} while (0)
86
87/*
88 * In order to get the CLF in a known state we generate an internal reboot
89 * using a proprietary command.
90 * Once the reboot is completed, we expect to receive a ST21NFCA_SOF_EOF
91 * fill buffer.
92 */
93static int st21nfca_hci_platform_init(struct st21nfca_i2c_phy *phy)
94{
95	u16 wait_reboot[] = { 50, 300, 1000 };
96	char reboot_cmd[] = { 0x7E, 0x66, 0x48, 0xF6, 0x7E };
97	u8 tmp[ST21NFCA_HCI_LLC_MAX_SIZE];
98	int i, r = -1;
99
100	for (i = 0; i < ARRAY_SIZE(wait_reboot) && r < 0; i++) {
101		r = i2c_master_send(phy->i2c_dev, reboot_cmd,
102				    sizeof(reboot_cmd));
103		if (r < 0)
104			msleep(wait_reboot[i]);
105	}
106	if (r < 0)
107		return r;
108
109	/* CLF is spending about 20ms to do an internal reboot */
110	msleep(20);
111	r = -1;
112	for (i = 0; i < ARRAY_SIZE(wait_reboot) && r < 0; i++) {
113		r = i2c_master_recv(phy->i2c_dev, tmp,
114				    ST21NFCA_HCI_LLC_MAX_SIZE);
115		if (r < 0)
116			msleep(wait_reboot[i]);
117	}
118	if (r < 0)
119		return r;
120
121	for (i = 0; i < ST21NFCA_HCI_LLC_MAX_SIZE &&
122		tmp[i] == ST21NFCA_SOF_EOF; i++)
123		;
124
125	if (r != ST21NFCA_HCI_LLC_MAX_SIZE)
126		return -ENODEV;
127
128	usleep_range(1000, 1500);
129	return 0;
130}
131
132static int st21nfca_hci_i2c_enable(void *phy_id)
133{
134	struct st21nfca_i2c_phy *phy = phy_id;
135
136	gpiod_set_value(phy->gpiod_ena, 1);
137	phy->powered = 1;
138	phy->run_mode = ST21NFCA_HCI_MODE;
139
140	usleep_range(10000, 15000);
141
142	return 0;
143}
144
145static void st21nfca_hci_i2c_disable(void *phy_id)
146{
147	struct st21nfca_i2c_phy *phy = phy_id;
148
149	gpiod_set_value(phy->gpiod_ena, 0);
150
151	phy->powered = 0;
152}
153
154static void st21nfca_hci_add_len_crc(struct sk_buff *skb)
155{
156	u16 crc;
157	u8 tmp;
158
159	*(u8 *)skb_push(skb, 1) = 0;
160
161	crc = crc_ccitt(0xffff, skb->data, skb->len);
162	crc = ~crc;
163
164	tmp = crc & 0x00ff;
165	skb_put_u8(skb, tmp);
166
167	tmp = (crc >> 8) & 0x00ff;
168	skb_put_u8(skb, tmp);
169}
170
171static void st21nfca_hci_remove_len_crc(struct sk_buff *skb)
172{
173	skb_pull(skb, ST21NFCA_FRAME_HEADROOM);
174	skb_trim(skb, skb->len - ST21NFCA_FRAME_TAILROOM);
175}
176
177/*
178 * Writing a frame must not return the number of written bytes.
179 * It must return either zero for success, or <0 for error.
180 * In addition, it must not alter the skb
181 */
182static int st21nfca_hci_i2c_write(void *phy_id, struct sk_buff *skb)
183{
184	int r = -1, i, j;
185	struct st21nfca_i2c_phy *phy = phy_id;
186	struct i2c_client *client = phy->i2c_dev;
187	u8 tmp[ST21NFCA_HCI_LLC_MAX_SIZE * 2];
188
189	I2C_DUMP_SKB("st21nfca_hci_i2c_write", skb);
190
191	if (phy->hard_fault != 0)
192		return phy->hard_fault;
193
194	/*
195	 * Compute CRC before byte stuffing computation on frame
196	 * Note st21nfca_hci_add_len_crc is doing a byte stuffing
197	 * on its own value
198	 */
199	st21nfca_hci_add_len_crc(skb);
200
201	/* add ST21NFCA_SOF_EOF on tail */
202	skb_put_u8(skb, ST21NFCA_SOF_EOF);
203	/* add ST21NFCA_SOF_EOF on head */
204	*(u8 *)skb_push(skb, 1) = ST21NFCA_SOF_EOF;
205
206	/*
207	 * Compute byte stuffing
208	 * if byte == ST21NFCA_SOF_EOF or ST21NFCA_ESCAPE_BYTE_STUFFING
209	 * insert ST21NFCA_ESCAPE_BYTE_STUFFING (escape byte)
210	 * xor byte with ST21NFCA_BYTE_STUFFING_MASK
211	 */
212	tmp[0] = skb->data[0];
213	for (i = 1, j = 1; i < skb->len - 1; i++, j++) {
214		if (skb->data[i] == ST21NFCA_SOF_EOF
215		    || skb->data[i] == ST21NFCA_ESCAPE_BYTE_STUFFING) {
216			tmp[j] = ST21NFCA_ESCAPE_BYTE_STUFFING;
217			j++;
218			tmp[j] = skb->data[i] ^ ST21NFCA_BYTE_STUFFING_MASK;
219		} else {
220			tmp[j] = skb->data[i];
221		}
222	}
223	tmp[j] = skb->data[i];
224	j++;
225
226	/*
227	 * Manage sleep mode
228	 * Try 3 times to send data with delay between each
229	 */
230	mutex_lock(&phy->phy_lock);
231	for (i = 0; i < ARRAY_SIZE(wait_tab) && r < 0; i++) {
232		r = i2c_master_send(client, tmp, j);
233		if (r < 0)
234			msleep(wait_tab[i]);
235	}
236	mutex_unlock(&phy->phy_lock);
237
238	if (r >= 0) {
239		if (r != j)
240			r = -EREMOTEIO;
241		else
242			r = 0;
243	}
244
245	st21nfca_hci_remove_len_crc(skb);
246
247	return r;
248}
249
250static int get_frame_size(u8 *buf, int buflen)
251{
252	int len = 0;
253
254	if (buf[len + 1] == ST21NFCA_SOF_EOF)
255		return 0;
256
257	for (len = 1; len < buflen && buf[len] != ST21NFCA_SOF_EOF; len++)
258		;
259
260	return len;
261}
262
263static int check_crc(u8 *buf, int buflen)
264{
265	u16 crc;
266
267	crc = crc_ccitt(0xffff, buf, buflen - 2);
268	crc = ~crc;
269
270	if (buf[buflen - 2] != (crc & 0xff) || buf[buflen - 1] != (crc >> 8)) {
271		pr_err(ST21NFCA_HCI_DRIVER_NAME
272		       ": CRC error 0x%x != 0x%x 0x%x\n", crc, buf[buflen - 1],
273		       buf[buflen - 2]);
274
275		pr_info(DRIVER_DESC ": %s : BAD CRC\n", __func__);
276		print_hex_dump(KERN_DEBUG, "crc: ", DUMP_PREFIX_NONE,
277			       16, 2, buf, buflen, false);
278		return -EPERM;
279	}
280	return 0;
281}
282
283/*
284 * Prepare received data for upper layer.
285 * Received data include byte stuffing, crc and sof/eof
286 * which is not usable by hci part.
287 * returns:
288 * frame size without sof/eof, header and byte stuffing
289 * -EBADMSG : frame was incorrect and discarded
290 */
291static int st21nfca_hci_i2c_repack(struct sk_buff *skb)
292{
293	int i, j, r, size;
294
295	if (skb->len < 1 || (skb->len > 1 && skb->data[1] != 0))
296		return -EBADMSG;
297
298	size = get_frame_size(skb->data, skb->len);
299	if (size > 0) {
300		skb_trim(skb, size);
301		/* remove ST21NFCA byte stuffing for upper layer */
302		for (i = 1, j = 0; i < skb->len; i++) {
303			if (skb->data[i + j] ==
304					(u8) ST21NFCA_ESCAPE_BYTE_STUFFING) {
305				skb->data[i] = skb->data[i + j + 1]
306						| ST21NFCA_BYTE_STUFFING_MASK;
307				i++;
308				j++;
309			}
310			skb->data[i] = skb->data[i + j];
311		}
312		/* remove byte stuffing useless byte */
313		skb_trim(skb, i - j);
314		/* remove ST21NFCA_SOF_EOF from head */
315		skb_pull(skb, 1);
316
317		r = check_crc(skb->data, skb->len);
318		if (r != 0)
319			return -EBADMSG;
320
321		/* remove headbyte */
322		skb_pull(skb, 1);
323		/* remove crc. Byte Stuffing is already removed here */
324		skb_trim(skb, skb->len - 2);
325		return skb->len;
326	}
327	return 0;
328}
329
330/*
331 * Reads an shdlc frame and returns it in a newly allocated sk_buff. Guarantees
332 * that i2c bus will be flushed and that next read will start on a new frame.
333 * returned skb contains only LLC header and payload.
334 * returns:
335 * frame size : if received frame is complete (find ST21NFCA_SOF_EOF at
336 * end of read)
337 * -EAGAIN : if received frame is incomplete (not find ST21NFCA_SOF_EOF
338 * at end of read)
339 * -EREMOTEIO : i2c read error (fatal)
340 * -EBADMSG : frame was incorrect and discarded
341 * (value returned from st21nfca_hci_i2c_repack)
342 * -EIO : if no ST21NFCA_SOF_EOF is found after reaching
343 * the read length end sequence
344 */
345static int st21nfca_hci_i2c_read(struct st21nfca_i2c_phy *phy,
346				 struct sk_buff *skb)
347{
348	int r, i;
349	u8 len;
350	u8 buf[ST21NFCA_HCI_LLC_MAX_PAYLOAD];
351	struct i2c_client *client = phy->i2c_dev;
352
353	if (phy->current_read_len < ARRAY_SIZE(len_seq)) {
354		len = len_seq[phy->current_read_len];
355
356		/*
357		 * Add retry mecanism
358		 * Operation on I2C interface may fail in case of operation on
359		 * RF or SWP interface
360		 */
361		r = 0;
362		mutex_lock(&phy->phy_lock);
363		for (i = 0; i < ARRAY_SIZE(wait_tab) && r <= 0; i++) {
364			r = i2c_master_recv(client, buf, len);
365			if (r < 0)
366				msleep(wait_tab[i]);
367		}
368		mutex_unlock(&phy->phy_lock);
369
370		if (r != len) {
371			phy->current_read_len = 0;
372			return -EREMOTEIO;
373		}
374
375		/*
376		 * The first read sequence does not start with SOF.
377		 * Data is corrupeted so we drop it.
378		 */
379		if (!phy->current_read_len && !IS_START_OF_FRAME(buf)) {
380			skb_trim(skb, 0);
381			phy->current_read_len = 0;
382			return -EIO;
383		} else if (phy->current_read_len && IS_START_OF_FRAME(buf)) {
384			/*
385			 * Previous frame transmission was interrupted and
386			 * the frame got repeated.
387			 * Received frame start with ST21NFCA_SOF_EOF + 00.
388			 */
389			skb_trim(skb, 0);
390			phy->current_read_len = 0;
391		}
392
393		skb_put_data(skb, buf, len);
394
395		if (skb->data[skb->len - 1] == ST21NFCA_SOF_EOF) {
396			phy->current_read_len = 0;
397			return st21nfca_hci_i2c_repack(skb);
398		}
399		phy->current_read_len++;
400		return -EAGAIN;
401	}
402	return -EIO;
403}
404
405/*
406 * Reads an shdlc frame from the chip. This is not as straightforward as it
407 * seems. The frame format is data-crc, and corruption can occur anywhere
408 * while transiting on i2c bus, such that we could read an invalid data.
409 * The tricky case is when we read a corrupted data or crc. We must detect
410 * this here in order to determine that data can be transmitted to the hci
411 * core. This is the reason why we check the crc here.
412 * The CLF will repeat a frame until we send a RR on that frame.
413 *
414 * On ST21NFCA, IRQ goes in idle when read starts. As no size information are
415 * available in the incoming data, other IRQ might come. Every IRQ will trigger
416 * a read sequence with different length and will fill the current frame.
417 * The reception is complete once we reach a ST21NFCA_SOF_EOF.
418 */
419static irqreturn_t st21nfca_hci_irq_thread_fn(int irq, void *phy_id)
420{
421	struct st21nfca_i2c_phy *phy = phy_id;
422
423	int r;
424
425	if (!phy || irq != phy->i2c_dev->irq) {
426		WARN_ON_ONCE(1);
427		return IRQ_NONE;
428	}
429
430	if (phy->hard_fault != 0)
431		return IRQ_HANDLED;
432
433	r = st21nfca_hci_i2c_read(phy, phy->pending_skb);
434	if (r == -EREMOTEIO) {
435		phy->hard_fault = r;
436
437		nfc_hci_recv_frame(phy->hdev, NULL);
438
439		return IRQ_HANDLED;
440	} else if (r == -EAGAIN || r == -EIO) {
441		return IRQ_HANDLED;
442	} else if (r == -EBADMSG && phy->crc_trials < ARRAY_SIZE(wait_tab)) {
443		/*
444		 * With ST21NFCA, only one interface (I2C, RF or SWP)
445		 * may be active at a time.
446		 * Having incorrect crc is usually due to i2c macrocell
447		 * deactivation in the middle of a transmission.
448		 * It may generate corrupted data on i2c.
449		 * We give sometime to get i2c back.
450		 * The complete frame will be repeated.
451		 */
452		msleep(wait_tab[phy->crc_trials]);
453		phy->crc_trials++;
454		phy->current_read_len = 0;
455		kfree_skb(phy->pending_skb);
456	} else if (r > 0) {
457		/*
458		 * We succeeded to read data from the CLF and
459		 * data is valid.
460		 * Reset counter.
461		 */
462		nfc_hci_recv_frame(phy->hdev, phy->pending_skb);
463		phy->crc_trials = 0;
464	} else {
465		kfree_skb(phy->pending_skb);
466	}
467
468	phy->pending_skb = alloc_skb(ST21NFCA_HCI_LLC_MAX_SIZE * 2, GFP_KERNEL);
469	if (phy->pending_skb == NULL) {
470		phy->hard_fault = -ENOMEM;
471		nfc_hci_recv_frame(phy->hdev, NULL);
472	}
473
474	return IRQ_HANDLED;
475}
476
477static const struct nfc_phy_ops i2c_phy_ops = {
478	.write = st21nfca_hci_i2c_write,
479	.enable = st21nfca_hci_i2c_enable,
480	.disable = st21nfca_hci_i2c_disable,
481};
482
483static const struct acpi_gpio_params enable_gpios = { 1, 0, false };
484
485static const struct acpi_gpio_mapping acpi_st21nfca_gpios[] = {
486	{ "enable-gpios", &enable_gpios, 1 },
487	{},
488};
489
490static int st21nfca_hci_i2c_probe(struct i2c_client *client)
491{
492	struct device *dev = &client->dev;
493	struct st21nfca_i2c_phy *phy;
494	int r;
495
496	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
497		nfc_err(&client->dev, "Need I2C_FUNC_I2C\n");
498		return -ENODEV;
499	}
500
501	phy = devm_kzalloc(&client->dev, sizeof(struct st21nfca_i2c_phy),
502			   GFP_KERNEL);
503	if (!phy)
504		return -ENOMEM;
505
506	phy->i2c_dev = client;
507	phy->pending_skb = alloc_skb(ST21NFCA_HCI_LLC_MAX_SIZE * 2, GFP_KERNEL);
508	if (phy->pending_skb == NULL)
509		return -ENOMEM;
510
511	phy->current_read_len = 0;
512	phy->crc_trials = 0;
513	mutex_init(&phy->phy_lock);
514	i2c_set_clientdata(client, phy);
515
516	r = devm_acpi_dev_add_driver_gpios(dev, acpi_st21nfca_gpios);
517	if (r)
518		dev_dbg(dev, "Unable to add GPIO mapping table\n");
519
520	/* Get EN GPIO from resource provider */
521	phy->gpiod_ena = devm_gpiod_get(dev, "enable", GPIOD_OUT_LOW);
522	if (IS_ERR(phy->gpiod_ena)) {
523		nfc_err(dev, "Unable to get ENABLE GPIO\n");
524		r = PTR_ERR(phy->gpiod_ena);
525		goto out_free;
526	}
527
528	phy->se_status.is_ese_present =
529			device_property_read_bool(&client->dev, "ese-present");
530	phy->se_status.is_uicc_present =
531			device_property_read_bool(&client->dev, "uicc-present");
532
533	r = st21nfca_hci_platform_init(phy);
534	if (r < 0) {
535		nfc_err(&client->dev, "Unable to reboot st21nfca\n");
536		goto out_free;
537	}
538
539	r = devm_request_threaded_irq(&client->dev, client->irq, NULL,
540				st21nfca_hci_irq_thread_fn,
541				IRQF_ONESHOT,
542				ST21NFCA_HCI_DRIVER_NAME, phy);
543	if (r < 0) {
544		nfc_err(&client->dev, "Unable to register IRQ handler\n");
545		goto out_free;
546	}
547
548	r = st21nfca_hci_probe(phy, &i2c_phy_ops, LLC_SHDLC_NAME,
549			       ST21NFCA_FRAME_HEADROOM,
550			       ST21NFCA_FRAME_TAILROOM,
551			       ST21NFCA_HCI_LLC_MAX_PAYLOAD,
552			       &phy->hdev,
553			       &phy->se_status);
554	if (r)
555		goto out_free;
556
557	return 0;
558
559out_free:
560	kfree_skb(phy->pending_skb);
561	return r;
562}
563
564static void st21nfca_hci_i2c_remove(struct i2c_client *client)
565{
566	struct st21nfca_i2c_phy *phy = i2c_get_clientdata(client);
567
568	st21nfca_hci_remove(phy->hdev);
569
570	if (phy->powered)
571		st21nfca_hci_i2c_disable(phy);
572	kfree_skb(phy->pending_skb);
573}
574
575static const struct i2c_device_id st21nfca_hci_i2c_id_table[] = {
576	{ST21NFCA_HCI_DRIVER_NAME, 0},
577	{}
578};
579MODULE_DEVICE_TABLE(i2c, st21nfca_hci_i2c_id_table);
580
581static const struct acpi_device_id st21nfca_hci_i2c_acpi_match[] __maybe_unused = {
582	{"SMO2100", 0},
583	{}
584};
585MODULE_DEVICE_TABLE(acpi, st21nfca_hci_i2c_acpi_match);
586
587static const struct of_device_id of_st21nfca_i2c_match[] __maybe_unused = {
588	{ .compatible = "st,st21nfca-i2c", },
589	{ .compatible = "st,st21nfca_i2c", },
590	{}
591};
592MODULE_DEVICE_TABLE(of, of_st21nfca_i2c_match);
593
594static struct i2c_driver st21nfca_hci_i2c_driver = {
595	.driver = {
596		.name = ST21NFCA_HCI_I2C_DRIVER_NAME,
597		.of_match_table = of_match_ptr(of_st21nfca_i2c_match),
598		.acpi_match_table = ACPI_PTR(st21nfca_hci_i2c_acpi_match),
599	},
600	.probe = st21nfca_hci_i2c_probe,
601	.id_table = st21nfca_hci_i2c_id_table,
602	.remove = st21nfca_hci_i2c_remove,
603};
604module_i2c_driver(st21nfca_hci_i2c_driver);
605
606MODULE_LICENSE("GPL");
607MODULE_DESCRIPTION(DRIVER_DESC);
608