forked from gschorcht/i2c-ch341-usb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
i2c-ch341-usb.c
1405 lines (1088 loc) · 46.1 KB
/
i2c-ch341-usb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Driver for the CH341 USB to I2C and GPIO adapter
*
* Copyright (c) 2017 Gunar Schorcht (gunar@schorcht.net)
*
* Derived from
*
* i2c-ch341-usb.c Copyright (c) 2016 Tse Lun Bien
* i2c-ch341.c Copyright (c) 2014 Marco Gittler
* i2c-tiny-usb.c Copyright (c) 2006-2007 Till Harbaum (Till@Harbaum.org)
*
* and extended by GPIO and interrupt handling capabilities.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*/
// uncomment following line to activate kernel debug handling
// #define DEBUG
#define DEBUG_PRINTK
#ifdef DEBUG_PRINTK
#define PRINTK(fmt,...) printk("%s: "fmt"\n", __func__, ##__VA_ARGS__)
#else
#define PRINTK(fmt,...)
#endif
#define CH341_IF_ADDR (&(ch341_dev->usb_if->dev))
#define DEV_ERR(d,f,...) dev_err (d,"%s: "f"\n", __FUNCTION__, ##__VA_ARGS__)
#define DEV_DBG(d,f,...) dev_dbg (d,"%s: "f"\n", __FUNCTION__, ##__VA_ARGS__)
#define DEV_INFO(d,f,...) dev_info(d,"%s: "f"\n", __FUNCTION__, ##__VA_ARGS__)
// check for condition and return with or without err code if it fails
#define CHECK_PARAM_RET(cond,err) if (!(cond)) return err;
#define CHECK_PARAM(cond) if (!(cond)) return;
#include <linux/version.h>
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,4,0)
#error The driver requires at least kernel version 3.4
#else
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/irq.h>
#include <linux/kthread.h>
/**
* ATTENTION:
*
* CH341_POLL_PERIOD_MS in milliseconds defines the rate at which GPIOs are
* read from CH341 via USB and thus the maximum rate at which changes on
* interrupt driven input ports can be recognized at all.
*
* This value must be at least 10 ms, but should be 20 ms or more (if
* possible) dependent on the performance of your system. Please check your
* syslog for messages like "GPIO poll period is too short by at least %n
* msecs". This message is thrown if the defined CH341_POLL_PERIOD_MS is
* shorter than the time required for one reading of the GPIOs.
*/
#define CH341_POLL_PERIOD_MS 10 // see above
#define CH341_GPIO_NUM_PINS 8 // Number of GPIO pins, DO NOT CHANGE
#define CH341_USB_MAX_BULK_SIZE 32 // CH341A wMaxPacketSize for ep_02 and ep_82
#define CH341_USB_MAX_INTR_SIZE 8 // CH341A wMaxPacketSize for ep_81
#define CH341_I2C_LOW_SPEED 0 // low speed - 20kHz
#define CH341_I2C_STANDARD_SPEED 1 // standard speed - 100kHz
#define CH341_I2C_FAST_SPEED 2 // fast speed - 400kHz
#define CH341_I2C_HIGH_SPEED 3 // high speed - 750kHz
#define CH341_CMD_I2C_STREAM 0xAA // I2C stream command
#define CH341_CMD_UIO_STREAM 0xAB // UIO stream command
#define CH341_CMD_I2C_STM_STA 0x74 // I2C set start condition
#define CH341_CMD_I2C_STM_STO 0x75 // I2C set stop condition
#define CH341_CMD_I2C_STM_OUT 0x80 // I2C output data
#define CH341_CMD_I2C_STM_IN 0xC0 // I2C input data
#define CH341_CMD_I2C_STM_SET 0x60 // I2C set configuration
#define CH341_CMD_I2C_STM_END 0x00 // I2C end command
#define CH341_CMD_UIO_STM_IN 0x00 // UIO interface IN command (D0~D7)
#define CH341_CMD_UIO_STM_OUT 0x80 // UIO interface OUT command (D0~D5)
#define CH341_CMD_UIO_STM_DIR 0x40 // UIO interface DIR command (D0~D5)
#define CH341_CMD_UIO_STM_END 0x20 // UIO interface END command
#define CH341_CMD_UIO_STM_US 0xc0 // UIO interface US command
#define CH341_PIN_MODE_OUT 0
#define CH341_PIN_MODE_IN 1
#define CH341_OK 0
/**
*
* Change the default values in *ch341_board_config* for your configuraton
*
* Configurable are:
*
* - Pin 15 (D0/CS0 ) as input/output (CH341_PIN_MODE_IN / CH341_PIN_MODE_OUT)
* - Pin 16 (D1/CS1 ) as input/output (CH341_PIN_MODE_IN / CH341_PIN_MODE_OUT)
* - Pin 17 (D2/CS2 ) as input/output (CH341_PIN_MODE_IN / CH341_PIN_MODE_OUT)
* - Pin 18 (D3/CS2 ) as input/output (CH341_PIN_MODE_IN / CH341_PIN_MODE_OUT)
* - Pin 19 (D4/DOUT2) as input/output (CH341_PIN_MODE_IN / CH341_PIN_MODE_OUT)
* - Pin 20 (D5/DOUT ) as input/output (CH341_PIN_MODE_IN / CH341_PIN_MODE_OUT)
* - Pin 21 (D6/DIN2 ) as input (CH341_PIN_MODE_IN)
* - Pin 22 (D7/DIN ) as input (CH341_PIN_MODE_IN)
*/
struct ch341_pin_config {
uint8_t pin; // pin number of CH341 chip
uint8_t mode; // GPIO mode
char* name; // GPIO name
bool hwirq; // connected to hardware interrupt (only one pin can have true)
};
struct ch341_pin_config ch341_board_config[CH341_GPIO_NUM_PINS] =
{
// pin GPIO mode GPIO name hwirq
{ 15, CH341_PIN_MODE_OUT , "gpio0" , 0 }, // used as output
{ 16, CH341_PIN_MODE_OUT , "gpio1" , 0 }, // used as output
{ 17, CH341_PIN_MODE_OUT , "gpio2" , 0 }, // used as output
{ 18, CH341_PIN_MODE_OUT , "gpio3" , 0 }, // used as output
{ 19, CH341_PIN_MODE_IN , "gpio4" , 1 }, // used as input with hardware IRQ
{ 20, CH341_PIN_MODE_IN , "gpio5" , 0 }, // used as input
{ 21, CH341_PIN_MODE_IN , "gpio6" , 0 }, // used as input
{ 22, CH341_PIN_MODE_IN , "gpio7" , 0 } // used as input
};
// device specific structure
struct ch341_device
{
// USB device description
struct usb_device* usb_dev; // usb device
struct usb_interface* usb_if; // usb interface
struct usb_endpoint_descriptor *ep_in; // usb endpoint bulk in
struct usb_endpoint_descriptor *ep_out; // usb endpoint bulk out
struct usb_endpoint_descriptor *ep_intr; // usb endpoint interrupt in
uint8_t in_buf [CH341_USB_MAX_BULK_SIZE]; // usb input buffer
uint8_t out_buf [CH341_USB_MAX_BULK_SIZE]; // usb outpu buffer
uint8_t intr_buf[CH341_USB_MAX_INTR_SIZE]; // usb interrupt buffer
struct urb* intr_urb;
// I2C device description
struct i2c_adapter i2c_dev; // i2c related things
// GPIO device description
struct gpio_chip gpio; // chip descriptor for GPIOs
uint8_t gpio_num; // number of pins used as GPIOs
uint8_t gpio_mask; // configuratoin mask defines IN/OUT pins
uint8_t gpio_io_data; // current value of CH341 I/O register
struct task_struct * gpio_thread; // GPIO poll thread
struct ch341_pin_config* gpio_pins [CH341_GPIO_NUM_PINS]; // pin configurations (gpio_num elements)
uint8_t gpio_bits [CH341_GPIO_NUM_PINS]; // bit of I/O data byte (gpio_num elements)
uint8_t gpio_values [CH341_GPIO_NUM_PINS]; // current values (gpio_num elements)
char* gpio_names [CH341_GPIO_NUM_PINS]; // pin names (gpio_num elements)
int gpio_irq_map[CH341_GPIO_NUM_PINS]; // GPIO to IRQ map (gpio_num elements)
// IRQ device description
struct irq_chip irq; // chip descriptor for IRQs
uint8_t irq_num; // number of pins with IRQs
int irq_base; // base IRQ allocated
struct irq_desc* irq_descs [CH341_GPIO_NUM_PINS]; // IRQ descriptors used (irq_num elements)
int irq_types [CH341_GPIO_NUM_PINS]; // IRQ types (irq_num elements)
bool irq_enabled [CH341_GPIO_NUM_PINS]; // IRQ enabled flag (irq_num elements)
int irq_gpio_map [CH341_GPIO_NUM_PINS]; // IRQ to GPIO pin map (irq_num elements)
int irq_hw; // IRQ for GPIO with hardware IRQ (default -1)
};
// ----- variables configurable during runtime ---------------------------
static uint speed = CH341_I2C_STANDARD_SPEED; // module parameter speed, default standard speed
static uint speed_last = CH341_I2C_FAST_SPEED + 1; // last used speed, default invalid
static uint poll_period = CH341_POLL_PERIOD_MS; // module parameter poll period
static bool enable_gpio = false; // enable/disable for GPIO support (removes IRQ overhead when not needed)
// ----- function prototypes ---------------------------------------------
static int ch341_usb_transfer (struct ch341_device *dev, int out_len, int in_len);
// ----- board configuration layer begin ---------------------------------
static int ch341_cfg_probe (struct ch341_device* ch341_dev)
{
struct ch341_pin_config* cfg;
int i;
CHECK_PARAM_RET (ch341_dev, -EINVAL);
ch341_dev->gpio_mask = 0x3f; // default
ch341_dev->gpio_num = 0;
ch341_dev->gpio_thread = 0;
ch341_dev->irq_num = 0;
ch341_dev->irq_base = 0;
ch341_dev->irq_hw = -1;
for (i = 0; i < CH341_GPIO_NUM_PINS; i++)
{
cfg = ch341_board_config + i;
if (cfg->pin == 0)
continue;
// --- check correct pin configuration ------------
// is pin configurable at all
if ((cfg->pin < 15) || (cfg->pin > 22))
{
DEV_ERR(CH341_IF_ADDR, "pin %d: is not configurable", cfg->pin);
return -EINVAL;
}
// is pin configured correctly as input in case of pin 21 and 22
if (((cfg->pin == 21) || (cfg->pin == 22)) && (cfg->mode != CH341_PIN_MODE_IN))
{
DEV_ERR(CH341_IF_ADDR, "pin %d: must be an input", cfg->pin);
return -EINVAL;
}
// --- read in pin configuration
// if pin is not configured as CS signal, set GPIO configuration
ch341_dev->gpio_names [ch341_dev->gpio_num] = cfg->name;
ch341_dev->gpio_pins [ch341_dev->gpio_num] = cfg;
ch341_dev->gpio_irq_map[ch341_dev->gpio_num] = -1; // no valid IRQ
// map CH341 pin to bit D0...D7 in the CH341 I/O data byte
ch341_dev->gpio_bits[ch341_dev->gpio_num] = (1 << (cfg->pin - 15));
// GPIO pins can generate IRQs when set to input mode
ch341_dev->gpio_irq_map[ch341_dev->gpio_num] = ch341_dev->irq_num;
ch341_dev->irq_gpio_map[ch341_dev->irq_num] = ch341_dev->gpio_num;
if (cfg->hwirq)
{
if (ch341_dev->irq_hw != -1)
{
DEV_ERR(CH341_IF_ADDR,
"pin %d: only one GPIO can be connected to the hardware IRQ",
cfg->pin);
return -EINVAL;
}
ch341_dev->irq_hw = ch341_dev->irq_num;
}
if (cfg->mode == CH341_PIN_MODE_IN)
// if pin is INPUT, it has to be masked out in GPIO direction mask
ch341_dev->gpio_mask &= ~ch341_dev->gpio_bits[ch341_dev->gpio_num];
if (enable_gpio) {
DEV_INFO (CH341_IF_ADDR, "%s %s gpio=%d irq=%d %s",
cfg->mode == CH341_PIN_MODE_IN ? "input " : "output",
cfg->name, ch341_dev->gpio_num, ch341_dev->irq_num,
cfg->hwirq ? "(hwirq)" : "");
}
ch341_dev->irq_num++;
ch341_dev->gpio_num++;
}
DEV_INFO (CH341_IF_ADDR, "GPIO functionality is %s", enable_gpio ? "enabled" : "disabled");
return CH341_OK;
}
static void ch341_cfg_remove (struct ch341_device* ch341_dev)
{
CHECK_PARAM (ch341_dev);
return;
}
// ----- board configuration layer end -----------------------------------
// ----- i2c layer begin -------------------------------------------------
static struct mutex ch341_lock;
static int ch341_i2c_set_speed (struct ch341_device *ch341_dev)
{
static char* ch341_i2c_speed_desc[] = { "20 kbps", "100 kbps", "400 kbps", "750 kbps" };
int result;
CHECK_PARAM_RET (speed != speed_last, CH341_OK)
if ((speed < CH341_I2C_LOW_SPEED) || (speed > CH341_I2C_HIGH_SPEED))
{
DEV_ERR (CH341_IF_ADDR, "parameter speed can only have values from 0 to 3");
speed = speed_last;
return -EINVAL;
}
DEV_INFO (CH341_IF_ADDR, "Change i2c bus speed to %s", ch341_i2c_speed_desc[speed]);
mutex_lock (&ch341_lock);
ch341_dev->out_buf[0] = CH341_CMD_I2C_STREAM;
ch341_dev->out_buf[1] = CH341_CMD_I2C_STM_SET | speed;
ch341_dev->out_buf[2] = CH341_CMD_I2C_STM_END;
result = ch341_usb_transfer (ch341_dev, 3, 0);
mutex_unlock (&ch341_lock);
if (result < 0)
{
DEV_ERR (CH341_IF_ADDR, "failure setting speed %d\n", result);
return result;
}
speed_last = speed;
return result;
}
static int ch341_i2c_read_inputs (struct ch341_device* ch341_dev)
{
int result;
if ((result = ch341_i2c_set_speed (ch341_dev)) < 0)
return result;
mutex_lock (&ch341_lock);
ch341_dev->out_buf[0] = CH341_CMD_UIO_STREAM;
ch341_dev->out_buf[1] = CH341_CMD_UIO_STM_DIR | ch341_dev->gpio_mask;
ch341_dev->out_buf[2] = CH341_CMD_UIO_STM_IN;
ch341_dev->out_buf[3] = CH341_CMD_UIO_STM_END;
result = ch341_usb_transfer(ch341_dev, 4, 1);
ch341_dev->gpio_io_data &= ch341_dev->gpio_mask;
ch341_dev->gpio_io_data |= ch341_dev->in_buf[0] & ~ch341_dev->gpio_mask;
mutex_unlock (&ch341_lock);
return (result < 0) ? result : CH341_OK;
}
static int ch341_i2c_write_outputs (struct ch341_device* ch341_dev)
{
int result;
if ((result = ch341_i2c_set_speed (ch341_dev)) < 0)
return result;
mutex_lock (&ch341_lock);
ch341_dev->out_buf[0] = CH341_CMD_UIO_STREAM;
ch341_dev->out_buf[1] = CH341_CMD_UIO_STM_DIR | ch341_dev->gpio_mask;
ch341_dev->out_buf[2] = CH341_CMD_UIO_STM_OUT | (ch341_dev->gpio_io_data & ch341_dev->gpio_mask);
ch341_dev->out_buf[3] = CH341_CMD_UIO_STM_END;
// DEV_DBG(CH341_IF_ADDR, "%02x", ch341_dev->out_buf[2]);
result = ch341_usb_transfer(ch341_dev, 4, 0);
mutex_unlock (&ch341_lock);
return (result < 0) ? result : CH341_OK;
}
static int ch341_i2c_check_dev(struct ch341_device *ch341_dev, uint8_t addr)
{
int retval;
ch341_dev->out_buf[0] = CH341_CMD_I2C_STREAM;
ch341_dev->out_buf[1] = CH341_CMD_I2C_STM_STA;
ch341_dev->out_buf[2] = CH341_CMD_I2C_STM_OUT; // NOTE: must be zero length otherwise it messes up the device
ch341_dev->out_buf[3] = (addr << 1) | 0x1;
ch341_dev->out_buf[4] = CH341_CMD_I2C_STM_IN; // NOTE: zero length here as well
ch341_dev->out_buf[5] = CH341_CMD_I2C_STM_STO;
ch341_dev->out_buf[6] = CH341_CMD_I2C_STM_END;
retval = ch341_usb_transfer(ch341_dev, 7, 1);
if (retval < 0)
return retval;
if (ch341_dev->in_buf[0] & 0x80)
return -ETIMEDOUT;
return 0;
}
static int ch341_i2c_transfer (struct i2c_adapter *adpt, struct i2c_msg *msgs, int num)
{
struct ch341_device* ch341_dev;
int result;
int ndxMsg;
int ndxByte;
int bytes_remaining; // Bytes of data for this msgs group remaining to transfer
int bytes_this_time; // Bytes being sent in this packet
int bytes_overhead; // Overhead bytes in this packet
int isFirstOrChange; // First packet or changing WR->RD or RD->WR we need a start/restart
int isLast; // Last packet (needs a stop)
uint8_t *pBuf; // Current buffer pointer in send/receive data
uint8_t* ob;
uint8_t* ib;
CHECK_PARAM_RET (adpt, -EINVAL);
CHECK_PARAM_RET (msgs, -EINVAL);
CHECK_PARAM_RET (num > 0, -EINVAL);
ch341_dev = (struct ch341_device *)adpt->algo_data;
CHECK_PARAM_RET (ch341_dev, -EIO);
mutex_lock (&ch341_lock);
result = ch341_i2c_check_dev(ch341_dev, msgs[0].addr);
if (result < 0)
{
// On device error, don't attempt to send messages.
// Instead, drop through, release mutex, and exit with error:
num = 0;
}
ob = ch341_dev->out_buf;
ib = ch341_dev->in_buf;
for (ndxMsg = 0; ndxMsg < num; ndxMsg++)
{
result = 0;
if (msgs[ndxMsg].flags & I2C_M_TEN)
{
DEV_ERR (CH341_IF_ADDR, "10 bit i2c addresses not supported");
result = -EINVAL;
break;
}
// First read or write operation triggers a start, as well as changing WR<->RD:
isFirstOrChange = ((ndxMsg == 0) || ((msgs[ndxMsg].flags & I2C_M_RD) != (msgs[ndxMsg-1].flags & I2C_M_RD)));
// Always send start on read, since we always send a stop on reads:
if (msgs[ndxMsg].flags & I2C_M_RD) isFirstOrChange = 1;
// Note: back-to-back writes will only cause a start on the first write and stop on the last, if it's the last group...
// WR : Start, Write, Stop
// WR,WR : Start, Write, Write, Stop
// WR,RD : Start, Write, Restart, Read, Stop
// WR,RD,RD : Start, Write, Restart, Read, Stop, Start, Read, Stop
// RD : Start, Read, Stop
// RD,WR : Start, Read, Stop, Start, Write, Stop
// RD,WR,WR : Start, Read, Stop, Start, Write, Write, Stop
isLast = (ndxMsg == (num-1));
bytes_remaining = msgs[ndxMsg].len;
pBuf = msgs[ndxMsg].buf;
// If we are receiving data or user requested length byte prefix, we
// must have a valid buffer pointer:
if (!pBuf && (bytes_remaining || (msgs[ndxMsg].flags & I2C_M_RECV_LEN))) {
result = -EINVAL;
break;
}
if ((msgs[ndxMsg].flags & (I2C_M_RECV_LEN | I2C_M_RD)) == (I2C_M_RECV_LEN | I2C_M_RD))
{
msgs[ndxMsg].buf[0] = 0; // Initialize length byte
++pBuf;
}
while (bytes_remaining || isFirstOrChange)
{
ndxByte = 0;
if (msgs[ndxMsg].flags & I2C_M_RD) // i2c read operation
{
bytes_this_time = min(bytes_remaining, CH341_USB_MAX_BULK_SIZE);
ob[ndxByte++] = CH341_CMD_I2C_STREAM;
if (isFirstOrChange)
{
ob[ndxByte++] = CH341_CMD_I2C_STM_STA; // START condition
ob[ndxByte++] = CH341_CMD_I2C_STM_OUT | 0x1; // write len (only address byte)
ob[ndxByte++] = (msgs[ndxMsg].addr << 1) | 0x1; // address byte with read flag
}
if (bytes_this_time)
{
if (bytes_this_time == bytes_remaining)
{
if (bytes_this_time > 1)
{
ob[ndxByte++] = CH341_CMD_I2C_STM_IN | (bytes_this_time-1); // ACK
}
ob[ndxByte++] = CH341_CMD_I2C_STM_IN; // not ACK
} else {
ob[ndxByte++] = CH341_CMD_I2C_STM_IN | bytes_this_time; // ACK
}
}
// if the message is the last one for the read, add STOP condition
if (bytes_this_time == bytes_remaining)
ob[ndxByte++] = CH341_CMD_I2C_STM_STO;
ob[ndxByte++] = CH341_CMD_I2C_STM_END;
// write address byte and start (if this is the first time) and read data
result = ch341_usb_transfer(ch341_dev, ndxByte, bytes_this_time);
if (result < 0) // Handle error condition
break;
// if data was read
if (bytes_this_time)
{
// FIXME?: Should it be an error if result!=bytes_this_time ??
// not sure if it's possible for device to send extra data though
if (result == 0) { // If we didn't receive data when we should, report I/O error
result = -EIO;
break;
}
if (msgs[ndxMsg].flags & I2C_M_RECV_LEN)
{
msgs[ndxMsg].buf[0] += bytes_this_time; // Add length byte
}
memcpy(pBuf, ib, bytes_this_time);
}
}
else // i2c write operation
{
bytes_overhead = 3 + (isFirstOrChange ? 2 : 0) + (isLast ? 1 : 0); // 3 for stream, end, and out size; 2 on first/change for start and I2C address; and last needs stop
bytes_this_time = min(bytes_remaining, (CH341_USB_MAX_BULK_SIZE - bytes_overhead));
ob[ndxByte++] = CH341_CMD_I2C_STREAM;
if (isFirstOrChange)
{
ob[ndxByte++] = CH341_CMD_I2C_STM_STA; // START condition
ob[ndxByte++] = CH341_CMD_I2C_STM_OUT | (bytes_this_time + 1);
ob[ndxByte++] = msgs[ndxMsg].addr << 1; // address byte with write flag
} else {
ob[ndxByte++] = CH341_CMD_I2C_STM_OUT | bytes_this_time;
}
memcpy(&ob[ndxByte], pBuf, bytes_this_time);
ndxByte += bytes_this_time;
// if the message is the last one, add STOP condition
if (isLast && (bytes_this_time == bytes_remaining))
ob[ndxByte++] = CH341_CMD_I2C_STM_STO;
ob[ndxByte++] = CH341_CMD_I2C_STM_END;
// write address byte and start (if this is the first time) and write data
result = ch341_usb_transfer(ch341_dev, ndxByte, 0);
if (result < 0) // Handle error condition
break;
}
pBuf += bytes_this_time;
bytes_remaining -= bytes_this_time;
isFirstOrChange = 0;
}
if (result < 0)
break;
}
mutex_unlock (&ch341_lock);
if (result < 0)
return result;
return num;
}
static u32 ch341_i2c_func (struct i2c_adapter *ch341_dev)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
}
static const struct i2c_algorithm ch341_i2c_algorithm =
{
.master_xfer = ch341_i2c_transfer,
.functionality = ch341_i2c_func,
};
static int ch341_i2c_probe (struct ch341_device* ch341_dev)
{
int result;
CHECK_PARAM_RET (ch341_dev, -EINVAL);
DEV_DBG (CH341_IF_ADDR, "start");
// setup i2c adapter description
ch341_dev->i2c_dev.owner = THIS_MODULE;
ch341_dev->i2c_dev.class = 0; // I2C_CLASS_HWMON;
ch341_dev->i2c_dev.algo = &ch341_i2c_algorithm;
ch341_dev->i2c_dev.algo_data = ch341_dev;
snprintf(ch341_dev->i2c_dev.name, sizeof(ch341_dev->i2c_dev.name),
"i2c-ch341-usb at bus %03d device %03d",
ch341_dev->usb_dev->bus->busnum, ch341_dev->usb_dev->devnum);
ch341_dev->i2c_dev.dev.parent = &ch341_dev->usb_if->dev;
// finally attach to i2c layer
if ((result = i2c_add_adapter(&ch341_dev->i2c_dev)) < 0)
return result;
DEV_INFO (CH341_IF_ADDR, "created i2c device /dev/i2c-%d", ch341_dev->i2c_dev.nr);
mutex_init (&ch341_lock);
// set ch341 i2c speed
speed_last = CH341_I2C_FAST_SPEED+1;
if ((result = ch341_i2c_set_speed (ch341_dev)) < 0)
return result;
DEV_DBG (CH341_IF_ADDR, "done");
return CH341_OK;
}
static void ch341_i2c_remove (struct ch341_device* ch341_dev)
{
CHECK_PARAM (ch341_dev);
if (ch341_dev->i2c_dev.nr)
i2c_del_adapter (&ch341_dev->i2c_dev);
return;
}
// ----- i2c layer end ---------------------------------------------------
// ----- irq layer begin -------------------------------------------------
void ch341_irq_enable_disable (struct irq_data *data, bool enable)
{
struct ch341_device *ch341_dev;
int irq;
CHECK_PARAM (data && (ch341_dev = irq_data_get_irq_chip_data(data)));
// calculate local IRQ
irq = data->irq - ch341_dev->irq_base;
// valid IRQ is in range 0 ... ch341_dev->irq_num-1, invalid IRQ is -1
if ((irq < 0) || (irq >= ch341_dev->irq_num)) return;
// enable local IRQ
ch341_dev->irq_enabled[irq] = enable;
DEV_INFO (CH341_IF_ADDR, "irq=%d enabled=%d",
data->irq, ch341_dev->irq_enabled[irq] ? 1 : 0);
}
void ch341_irq_enable (struct irq_data *data)
{
ch341_irq_enable_disable (data, true);
}
void ch341_irq_disable (struct irq_data *data)
{
ch341_irq_enable_disable (data, false);
}
int ch341_irq_set_type (struct irq_data *data, unsigned int type)
{
struct ch341_device *ch341_dev;
int irq;
CHECK_PARAM_RET (data && (ch341_dev = irq_data_get_irq_chip_data(data)), -EINVAL);
// calculate local IRQ
irq = data->irq - ch341_dev->irq_base;
// valid IRQ is in range 0 ... ch341_dev->irq_num-1, invalid IRQ is -1
if ((irq < 0) || (irq >= ch341_dev->irq_num)) return -EINVAL;
ch341_dev->irq_types[irq] = type;
DEV_INFO (CH341_IF_ADDR, "irq=%d flow_type=%d", data->irq, type);
return CH341_OK;
}
static int ch341_irq_check (struct ch341_device* ch341_dev, uint8_t irq,
uint8_t old, uint8_t new, bool hardware)
{
int type;
CHECK_PARAM_RET (old != new, CH341_OK)
CHECK_PARAM_RET (ch341_dev, -EINVAL);
CHECK_PARAM_RET (irq < ch341_dev->irq_num, -EINVAL);
// valid IRQ is in range 0 ... ch341_dev->irq_num-1, invalid IRQ is -1
if ((irq < 0) || (irq >= ch341_dev->irq_num)) return -EINVAL;
// if IRQ is disabled, just return with success
if (!ch341_dev->irq_enabled[irq]) return CH341_OK;
type = ch341_dev->irq_types[irq];
// for software IRQs dont check if IRQ is the hardware IRQ for rising edges
if (!hardware && (irq == ch341_dev->irq_hw) && (new > old))
return CH341_OK;
if (((type & IRQ_TYPE_EDGE_FALLING) && (old > new)) ||
((type & IRQ_TYPE_EDGE_RISING) && (new > old)))
{
// DEV_DBG (CH341_IF_ADDR, "%s irq=%d %d %s",
// hardware ? "hardware" : "software",
// irq, type, (old > new) ? "falling" : "rising");
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,3,0)
handle_simple_irq (ch341_dev->irq_descs[irq]);
#else
handle_simple_irq (ch341_dev->irq_base+irq, ch341_dev->irq_descs[irq]);
#endif
}
return CH341_OK;
}
static int ch341_irq_probe (struct ch341_device* ch341_dev)
{
int i;
int result;
CHECK_PARAM_RET (ch341_dev, -EINVAL);
DEV_DBG (CH341_IF_ADDR, "start");
ch341_dev->irq.name = "ch341";
ch341_dev->irq.irq_enable = ch341_irq_enable;
ch341_dev->irq.irq_disable = ch341_irq_disable;
ch341_dev->irq.irq_set_type = ch341_irq_set_type;
if (!ch341_dev->irq_num) return CH341_OK;
if ((result = irq_alloc_descs(-1, 0, ch341_dev->irq_num, 0)) < 0)
{
DEV_ERR (CH341_IF_ADDR, "failed to allocate IRQ descriptors");
return result;
}
ch341_dev->irq_base = result;
DEV_DBG (CH341_IF_ADDR, "irq_base=%d", ch341_dev->irq_base);
for (i = 0; i < ch341_dev->irq_num; i++)
{
ch341_dev->irq_descs[i] = irq_data_to_desc( irq_get_irq_data(ch341_dev->irq_base + i) );
ch341_dev->irq_enabled[i] = false;
irq_set_chip (ch341_dev->irq_base + i, &ch341_dev->irq);
irq_set_chip_data (ch341_dev->irq_base + i, ch341_dev);
irq_clear_status_flags(ch341_dev->irq_base + i, IRQ_NOREQUEST | IRQ_NOPROBE);
}
DEV_DBG (CH341_IF_ADDR, "done");
return CH341_OK;
}
static void ch341_irq_remove (struct ch341_device* ch341_dev)
{
CHECK_PARAM (ch341_dev);
if (ch341_dev->irq_base)
irq_free_descs (ch341_dev->irq_base, ch341_dev->irq_num);
return;
}
// ----- irq layer end ---------------------------------------------------
// ----- gpio layer begin ------------------------------------------------
void ch341_gpio_read_inputs (struct ch341_device* ch341_dev)
{
uint8_t old_io_data;
uint8_t old_value;
uint8_t new_value;
uint8_t gpio;
int i;
CHECK_PARAM (ch341_dev);
// DEV_DBG (CH341_IF_ADDR, "start");
// save old value
old_io_data = ch341_dev->gpio_io_data;
// read current values
ch341_i2c_read_inputs (ch341_dev);
for (i = 0; i < ch341_dev->irq_num; i++)
{
// determine local GPIO for each IRQ
gpio = ch341_dev->irq_gpio_map[i];
// determin old an new value of the bit
old_value = (old_io_data & ch341_dev->gpio_bits[gpio]) ? 1 : 0;
new_value = (ch341_dev->gpio_io_data & ch341_dev->gpio_bits[gpio]) ? 1 : 0;
// check for interrupt
ch341_irq_check (ch341_dev, i, old_value, new_value, false);
}
// DEV_DBG (CH341_IF_ADDR, "done");
}
// #define CH341_POLL_WITH_SLEEP
static int ch341_gpio_poll_function (void* argument)
{
struct ch341_device* ch341_dev = (struct ch341_device*)argument;
unsigned int next_poll_ms = jiffies_to_msecs(jiffies);
unsigned int jiffies_ms;
int drift_ms = 0;
int corr_ms = 0;
int sleep_ms = 0;
CHECK_PARAM_RET (ch341_dev, -EINVAL);
DEV_DBG (CH341_IF_ADDR, "start");
while (!kthread_should_stop())
{
// current time in ms
jiffies_ms = jiffies_to_msecs(jiffies);
drift_ms = jiffies_ms - next_poll_ms;
if (poll_period == 0)
{
poll_period = CH341_POLL_PERIOD_MS;
DEV_ERR (CH341_IF_ADDR,
"Poll period 0 ms is invalid, set back to the default of %d ms",
CH341_POLL_PERIOD_MS);
}
if (drift_ms < 0)
{
// period was to short, increase corr_ms by 1 ms
// DEV_DBG (CH341_IF_ADDR, "polling GPIO is %u ms too early", -drift_ms);
corr_ms = (corr_ms > 0) ? corr_ms - 1 : 0;
}
else if ((drift_ms > 0) && (drift_ms < poll_period))
{
// period was to long, decrease corr_ms by 1 ms
// DEV_DBG (CH341_IF_ADDR, "polling GPIO is %u ms too late", drift_ms);
corr_ms = (corr_ms < poll_period) ? corr_ms + 1 : 0;
}
next_poll_ms = jiffies_ms + poll_period;
// DEV_DBG (CH341_IF_ADDR, "read CH341 GPIOs");
ch341_gpio_read_inputs (ch341_dev);
jiffies_ms = jiffies_to_msecs(jiffies);
// if GPIO read took longer than poll period, do not sleep
if (jiffies_ms > next_poll_ms)
{
DEV_ERR (CH341_IF_ADDR,
"GPIO poll period is too short by at least %u msecs",
jiffies_ms - next_poll_ms);
}
else
{
sleep_ms = next_poll_ms - jiffies_ms - corr_ms;
#ifdef CH341_POLL_WITH_SLEEP
msleep ((sleep_ms <= 0) ? 1 : sleep_ms);
#else
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(msecs_to_jiffies((sleep_ms <= 0) ? 1 : sleep_ms));
#endif
}
}
#ifndef CH341_POLL_WITH_SLEEP
__set_current_state(TASK_RUNNING);
#endif
DEV_DBG (CH341_IF_ADDR, "stop");
return 0;
}
int ch341_gpio_get (struct gpio_chip *chip, unsigned offset)
{
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,5,0)
struct ch341_device* ch341_dev = (struct ch341_device*)gpiochip_get_data(chip);
#else
struct ch341_device* ch341_dev = container_of(chip, struct ch341_device, gpio);
#endif
int value;
CHECK_PARAM_RET (ch341_dev, -EINVAL);
CHECK_PARAM_RET (offset < ch341_dev->gpio_num, -EINVAL);
value = (ch341_dev->gpio_io_data & ch341_dev->gpio_bits[offset]) ? 1 : 0;
// DEV_DBG (CH341_IF_ADDR, "offset=%u value=%d io_data=%02x",
// offset, value, ch341_dev->gpio_io_data);
return value;
}
// FIXME: not tested at the moment (will be introduced with kernel 4.15.0)
int ch341_gpio_get_multiple (struct gpio_chip *chip,
unsigned long *mask, unsigned long *bits)
{
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,5,0)
struct ch341_device* ch341_dev = (struct ch341_device*)gpiochip_get_data(chip);
#else
struct ch341_device* ch341_dev = container_of(chip, struct ch341_device, gpio);
#endif
int i;
CHECK_PARAM_RET (ch341_dev, -EINVAL);
CHECK_PARAM_RET (mask, -EINVAL);
CHECK_PARAM_RET (bits, -EINVAL);
for (i = 0; i < ch341_dev->gpio_num; i++)
if (*mask & (1 << i))
{
*bits &= ~(1 << i);
*bits |= (((ch341_dev->gpio_io_data & ch341_dev->gpio_bits[i]) ? 1 : 0) << i);
}
// DEV_DBG (CH341_IF_ADDR, "mask=%08lx bit=%08lx io_data=%02x",
// *mask, *bits, ch341_dev->gpio_io_data);
return CH341_OK;
}
void ch341_gpio_set (struct gpio_chip *chip, unsigned offset, int value)
{
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,5,0)
struct ch341_device* ch341_dev = (struct ch341_device*)gpiochip_get_data(chip);
#else
struct ch341_device* ch341_dev = container_of(chip, struct ch341_device, gpio);
#endif
CHECK_PARAM (ch341_dev);
CHECK_PARAM (offset < ch341_dev->gpio_num);
if (value)
ch341_dev->gpio_io_data |= ch341_dev->gpio_bits[offset];
else
ch341_dev->gpio_io_data &= ~ch341_dev->gpio_bits[offset];
// DEV_DBG (CH341_IF_ADDR, "offset=%u value=%d io_data=%02x",
// offset, value, ch341_dev->gpio_io_data);
ch341_i2c_write_outputs (ch341_dev);
}
void ch341_gpio_set_multiple (struct gpio_chip *chip,
unsigned long *mask, unsigned long *bits)
{
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,5,0)
struct ch341_device* ch341_dev = (struct ch341_device*)gpiochip_get_data(chip);
#else
struct ch341_device* ch341_dev = container_of(chip, struct ch341_device, gpio);
#endif
int i;
CHECK_PARAM (ch341_dev);
CHECK_PARAM (mask);
CHECK_PARAM (bits);
for (i = 0; i < ch341_dev->gpio_num; i++)
if ((*mask & (1 << i)) && (ch341_dev->gpio_pins[i]->mode == CH341_PIN_MODE_OUT))
{
if (*bits & (1 << i))
ch341_dev->gpio_io_data |= ch341_dev->gpio_bits[i];
else
ch341_dev->gpio_io_data &= ~ch341_dev->gpio_bits[i];
}
// DEV_DBG (CH341_IF_ADDR, "mask=%08lx bit=%08lx io_data=%02x",
// *mask, *bits, ch341_dev->gpio_io_data);
ch341_i2c_write_outputs (ch341_dev);
return;
}
int ch341_gpio_get_direction (struct gpio_chip *chip, unsigned offset)
{
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,5,0)