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