forked from gschorcht/spi-ch341-usb
-
Notifications
You must be signed in to change notification settings - Fork 4
/
spi-ch341-usb.c
1792 lines (1412 loc) · 59.8 KB
/
spi-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 SPI and GPIO adapter
*
* Copyright (c) 2017 Gunar Schorcht ([email protected])
*
* 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 ([email protected])
*
* 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,10,0)
#error The driver requires at least kernel version 3.10
#else
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/spi/spi.h>
#include <linux/gpio.h>
#include <linux/irq.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 100 // see above
#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_CMD_PARA_INIT 0xB1
#define CH341_CMD_GET_STATUS 0xA0 // See ch341_spi_get_status
#define CH341_CMD_SET_OUTPUT 0xA1
#define CH341_CMD_SPI_STREAM 0xA8 // SPI command
#define CH341_CMD_UIO_STREAM 0xAB // UIO 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_SPI_MAX_NUM_DEVICES 3
#define CH341_SPI_BUS_NUM 0
#define CH341_SPI_MODALIAS "spidev"
#define CH341_SPI_MODE SPI_MODE_0
#define CH341_SPI_MIN_FREQ 400
#define CH341_SPI_MAX_FREQ 1e6
#define CH341_SPI_MIN_BITS_PER_WORD 4
#define CH341_SPI_MAX_BITS_PER_WORD 32
#define CH341_PIN_MODE_OUT 0
#define CH341_PIN_MODE_IN 1
#define CH341_PIN_MODE_CS 2
#define CH341_OK 0
/**
*
* Change the default values in *ch341_board_config* for your configuraton
*
* Configurable are:
*
* - Pin 15 (D0/CS0 ) as input/output/CS (CH341_PIN_MODE_IN/CH341_PIN_MODE_OUT/CH341_PIN_MODE_CS)
* - Pin 16 (D1/CS1 ) as input/output/CS (CH341_PIN_MODE_IN/CH341_PIN_MODE_OUT/CH341_PIN_MODE_CS)
* - Pin 17 (D2/CS2 ) as input/output/CS (CH341_PIN_MODE_IN/CH341_PIN_MODE_OUT/CH341_PIN_MODE_CS)
* - Pin 19 (D4/DOUT2) as input/output (CH341_PIN_MODE_IN/CH341_PIN_MODE_OUT)
* - Pin 21 (D6/DIN2 ) as input (CH341_PIN_MODE_IN)
*
* Pins 18 (sck), 20 (mosi), 22 (miso) have fix configuraton and are used as SPI signals.
*
* Note: To keep compatibility with the original version of this driver, I'm still tracking "pin numbers" in the
* board_config. But usually it is more meaningful to use the following bit numbers in the gpio_io_data work:
*
* bit 0-7 CH341 D7-D0,
bit 8 对应 CH341 的 ERR#引脚, (pin 5)
bit 9 对应 CH341 的 PEMP 引脚, (pin 6)
bit 10 对应 CH341 的 INT#引脚, (pin 7)
bit 11 对应 CH341 的 SLCT 引脚, (pin 8)
bit 13 对应 CH341 的 BUSY/WAIT#引脚, (pin 27)
bit 14 对应 CH341 的 AUTOFD#/DATAS#引脚, (pin 4)
bit 15 对应 CH341 的 SLCTIN#/ADDRS#引脚, (pin 3)
bit 23 对应 CH341 的 SDA 引脚 (pin 23)
*/
struct ch341_pin_config {
uint8_t bitNum; // pin number of CH341 chip
uint8_t mode; // GPIO mode
const char* name; // GPIO name
bool hwirq; // connected to hardware interrupt (only one pin can have true)
};
// Which bitnums be used for inputs or outputs, note: only used for non-spi D0-D7, other bits do not support change of direction at all
#define CH341_IN_OK_MASK 0x0000ef50 // gpio4, gpio6, none of the status bits, no MISO,MOSI, SCK
#define CH341_OUT_OK_MASK 0x000f0017 // cs0, cs1, cs2, gpio4 only
// Which bitnums can be used as a chip select
#define CH341_CS_OK_MASK 0x0007
// the bitmqask for MISO/MOSI/SCK
#define CH341_GPIO_SPI_MASK 0xa8
// bitmask for SPI SCK
#define SCK_H 0x08
#define CH341_MOSI_MASK 0x20
struct ch341_pin_config ch341_board_config[] =
{
// bitnum GPIO mode GPIO name hwirq
{ 0, CH341_PIN_MODE_CS , "cs0" , 0 }, // used as a chip select by default
{ 1, CH341_PIN_MODE_CS , "cs1" , 0 }, // used as a chip select by default
{ 2, CH341_PIN_MODE_CS , "cs2" , 0 }, // used as a chip select by default
// { 3, CH341_PIN_MODE_IN , "sck" , 0 }, // expose to userspace to allow readonly access (for hardware debugging)
{ 4, CH341_PIN_MODE_IN , "gpio4" , 0 }, // used as input with hardware IRQ
// { 5, CH341_PIN_MODE_IN , "mosi" , 0 }, // expose to userspace to allow readonly access (for hardware debugging)
{ 6, CH341_PIN_MODE_IN , "gpio6" , 0 }, // used as input (only)
// { 7, CH341_PIN_MODE_IN , "miso" , 0 }, // expose to userspace to allow readonly access (for hardware debugging)
{ 8, CH341_PIN_MODE_IN , "err" , 0 },
{ 9, CH341_PIN_MODE_IN , "pemp" , 0 },
{ 10, CH341_PIN_MODE_IN , "int" , 1 },
{ 11, CH341_PIN_MODE_IN , "slct" , 0 },
{ 13, CH341_PIN_MODE_IN , "wait" , 0 },
{ 14, CH341_PIN_MODE_IN , "autofd" , 0 },
{ 15, CH341_PIN_MODE_IN , "addr" , 0 },
{ 16, CH341_PIN_MODE_OUT, "ini" , 0 },
{ 17, CH341_PIN_MODE_OUT, "write" , 0 },
{ 18, CH341_PIN_MODE_OUT, "scl" , 0 },
{ 19, CH341_PIN_MODE_OUT, "sda" , 0 } // Example code says this is GPIO 29 but I think that is a typo (leaving out for now)
};
#define CH341_GPIO_NUM_PINS (sizeof(ch341_board_config) / sizeof(ch341_board_config[0]))
static struct spi_board_info ch341_spi_devices[CH341_SPI_MAX_NUM_DEVICES];
struct spi_board_info ch341_spi_device_template =
{
.modalias = "spidev",
.max_speed_hz = CH341_SPI_MAX_FREQ,
.bus_num = 0,
.chip_select = 0,
.mode = SPI_MODE_0,
};
// 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;
// SPI device description
struct spi_master* master; // spi master
struct spi_device* slaves[CH341_SPI_MAX_NUM_DEVICES];
int slave_num;
// GPIO device description
struct gpio_chip gpio; // chip descriptor for GPIOs
uint8_t gpio_num; // number of pins used as GPIOs
uint32_t gpio_mask; // configuratoin mask defines IN/OUT pins
uint32_t gpio_io_data; // current value of CH341 I/O register
struct task_struct * gpio_thread; // GPIO poll thread
struct completion gpio_thread_complete; // Used to wait for thread exit
struct ch341_pin_config* gpio_pins [CH341_GPIO_NUM_PINS]; // pin configurations (gpio_num elements)
uint32_t gpio_bits [CH341_GPIO_NUM_PINS]; // bitmask in status word (gpio_num elements)
const 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)
uint32_t gpio_out_ok_mask; // set bits indicate pins which can be outputs
uint32_t gpio_in_ok_mask; // set bits indicate pins which can be inputs
// 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
#if LINUX_VERSION_CODE < KERNEL_VERSION(4,3,0)
struct irq_desc * irq_descs [CH341_GPIO_NUM_PINS]; // IRQ descriptors used (irq_num elements)
#endif
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 poll_period = CH341_POLL_PERIOD_MS; // module parameter poll period
// ----- 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;
ch341_dev->gpio_out_ok_mask = CH341_OUT_OK_MASK;
ch341_dev->gpio_in_ok_mask = CH341_IN_OK_MASK;
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++)
{
uint32_t msk;
cfg = ch341_board_config + i;
// --- check correct pin configuration ------------
msk = 1 << cfg->bitNum;
// is pin configured correctly as input
if (!(msk & CH341_OUT_OK_MASK) && cfg->mode != CH341_PIN_MODE_IN)
{
DEV_ERR(CH341_IF_ADDR, "bit %d: must be an input", cfg->bitNum);
return -EINVAL;
}
// is pin configurable as CS signal
else if (!(msk & CH341_CS_OK_MASK) && cfg->mode == CH341_PIN_MODE_CS)
{
DEV_ERR(CH341_IF_ADDR, "bit %d: can't be used as CS signal", cfg->bitNum);
return -EINVAL;
}
// --- read in pin configuration
ch341_dev->gpio_bits[ch341_dev->gpio_num] = msk;
if (cfg->mode == CH341_PIN_MODE_CS)
{
// if pin is CS signal, set SPI slave device configuration
ch341_spi_devices[ch341_dev->slave_num] = ch341_spi_device_template;
ch341_spi_devices[ch341_dev->slave_num].bus_num = CH341_SPI_BUS_NUM;
ch341_spi_devices[ch341_dev->slave_num].mode = CH341_SPI_MODE;
ch341_spi_devices[ch341_dev->slave_num].chip_select = cfg->bitNum;
// cs pins can't be changed to be inputs
ch341_dev->gpio_in_ok_mask &= ~msk;
DEV_INFO (CH341_IF_ADDR, "output %s SPI slave with cs=%d",
cfg->name, ch341_spi_devices[ch341_dev->slave_num].chip_select);
ch341_dev->slave_num++;
}
// now expose as a GPIO (note: even if a pin is a chip select, we also expose it as a GPIO, so apps can do low level control if needed)
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
// 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,
"bit %d: only one GPIO can be connected to the hardware IRQ",
cfg->bitNum);
return -EINVAL;
}
ch341_dev->irq_hw = ch341_dev->irq_num;
}
if (cfg->mode == CH341_PIN_MODE_IN && (msk & CH341_IN_OK_MASK))
// if pin is INPUT, it has to be masked out in GPIO direction mask
ch341_dev->gpio_mask &= ~msk;
else
ch341_dev->gpio_mask |= msk;
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++;
}
if (ch341_dev->slave_num == 0)
{
DEV_ERR(CH341_IF_ADDR, "at least one of the pins 15 ... 17 has to be configured as CS signal");
return -EINVAL;
}
return CH341_OK;
}
static void ch341_cfg_remove (struct ch341_device* ch341_dev)
{
CHECK_PARAM (ch341_dev);
return;
}
// ----- board configuration layer end -----------------------------------
// ----- spi layer begin -------------------------------------------------
static struct mutex ch341_lock;
#define ch341_spi_maser_to_dev(m) *((struct ch341_device**)spi_master_get_devdata(m))
/*
Get Status Reverse Engineering
A note for future developers @icenowy reverse engineered the windows DLL getstatus operation. @geeksville used this great information
to add an implementation for this linux driver.
Her email is here:
I reverse-engineered the CH341GetInput function in the DLL.
bool CH341GetInput(ULONG iIndex,PULONG iStatus)
{
bool ret;
bool wr_ret;
byte buf [3];
ULONG dev_index;
// 0x2cac 19 CH341GetInput
dev_index = iIndex;
if (CH341ICVersions[iIndex] < 0x20) {
ret = CH341GetStatus(iIndex,iStatus); // IC Ver is original CH341
}
else {
iIndex = 0;
buf[0] = 0xa0;
wr_ret = CH341WriteRead(dev_index,1,buf,0x20,1,&iIndex,buf);
if (wr_ret == 0) {
ret = false;
}
else {
*iStatus = ((buf[2] & 0x80) << 8 | buf[1] & 0xef) << 8 |
(uint)buf[0];
ret = true;
}
}
return ret;
}
CH341WriteRead seems to be doing bulk transfer, and new CH341F chips
should not be IC Ver 0x10 (IC ver has 3 values, 0x10, 0x20 and 0x30).
For this function, the result format is
位 7-位 0 对应 CH341 的 D7-D0 引脚,
位 8 对应 CH341 的 ERR#引脚,
位 9 对应 CH341 的 PEMP 引脚,
位 10 对应 CH341 的 INT#引脚,
位 11 对应 CH341 的 SLCT 引脚,
位 13 对应 CH341 的 BUSY/WAIT#引脚,
位 14 对应 CH341 的 AUTOFD#/DATAS#引脚,
位 15 对应 CH341 的 SLCTIN#/ADDRS#引脚,
位 23 对应 CH341 的 SDA 引脚
*/
static int ch341_spi_get_status (struct ch341_device* ch341_dev)
{
int result;
uint32_t status;
mutex_lock (&ch341_lock);
ch341_dev->out_buf[0] = CH341_CMD_GET_STATUS;
result = ch341_usb_transfer(ch341_dev, 1, 3);
status = ((ch341_dev->in_buf[2] & 0x80) << 16) | ((ch341_dev->in_buf[1] & 0xef) << 8) | ch341_dev->in_buf[0];
status &= ~CH341_GPIO_SPI_MASK; // Don't readback bogus SPI pin values
ch341_dev->gpio_io_data = (ch341_dev->gpio_io_data & ch341_dev->gpio_mask) | (~ch341_dev->gpio_mask & status); // these bits include current GPIO values (and more), only change bits not marked as outputs
mutex_unlock (&ch341_lock);
return (result < 0) ? result : CH341_OK;
}
/* No longer used, we now use the get_status operation found by @icesnoy - because it returns all pins (not just the gpios)
static int ch341_spi_read_inputs (struct ch341_device* ch341_dev)
{
int 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;
}
*/
/**
* A new more generalized version of write_outputs that can write ALL of the possible output pins
*
* Based on this example code:
*
* ********************************************************************
* FUNCTION : Set direction and output data of CH341
* arg:
* Data : Control direction and data
* iEnbale : set direction and data enable
* --> Bit16 High : effect on Bit15~8 of iSetDataOut
* --> Bit17 High : effect on Bit15~8 of iSetDirOut
* --> Bit18 High : effect on Bit7~0 of iSetDataOut
* --> Bit19 High : effect on Bit7~0 of iSetDirOut
* --> Bit20 High : effect on Bit23~16 of iSetDataOut
* iSetDirOut : set io direction
* -- > Bit High : Output
* -- > Bit Low : Input
* iSetDataOut : set io data
* Output:
* -- > Bit High : High level
* -- > Bit Low : Low level
* Note:
* Bit7~Bit0<==>D7-D0
* Bit8<==>ERR# Bit9<==>PEMP Bit10<==>INT# Bit11<==>SLCT Bit13<==>WAIT# Bit14<==>DATAS#/READ# Bit15<==>ADDRS#/ADDR/ALE
* The pins below can only be used in output mode:
* Bit16<==>RESET# Bit17<==>WRITE# Bit18<==>SCL Bit29<==>SDA
* ********************************************************************
BOOL CH34xSetOutput( ULONG iEnable, ULONG iSetDirOut, ULONG iSetDataOut)
{
ULONG mLength;
UCHAR mBuffer[32];
mBuffer[0] = CH341A_CMD_SET_OUTPUT;
mBuffer[1] = 0x6A;
mBuffer[2] = (UCHAR)( iEnable & 0x1F );
mBuffer[3] = (UCHAR)( iSetDataOut >> 8 & 0xEF );
mBuffer[4] = (UCHAR)( iSetDirOut >> 8 & 0xEF | 0x10 );
mBuffer[5] = (UCHAR)( iSetDataOut & 0xFF );
mBuffer[6] = (UCHAR)( iSetDirOut & 0xFF );
mBuffer[7] = (UCHAR)( iSetDataOut >> 16 & 0x0F );
mBuffer[8] = 0;
mBuffer[9] = 0;
mBuffer[10] = 0;
mLength = 11;
if ( CH34xWriteData( mBuffer, &mLength ) ) { //Write Data
if ( mLength >= 8 ) return( true);
}
return( false);
}
*/
static int ch341_spi_write_outputs (struct ch341_device* ch341_dev)
{
int result;
uint32_t data;
mutex_lock (&ch341_lock);
data = ch341_dev->gpio_io_data & ch341_dev->gpio_mask;
// FIXME - set idle SCK based on clock phase
// (spi->mode & SPI_CPOL)
ch341_dev->out_buf[0] = CH341_CMD_SET_OUTPUT;
ch341_dev->out_buf[1] = 0x6a; // (data & 0xff & ~CH341_GPIO_SPI_MASK);
ch341_dev->out_buf[2] = 0x1f; // (ch341_dev->gpio_mask & 0xff & ~CH341_GPIO_SPI_MASK) | SCK_H; // 0x1f; // FIXME?
ch341_dev->out_buf[3] = (data >> 8) & 0xef;
ch341_dev->out_buf[4] = ((ch341_dev->gpio_mask >> 8) & 0xef) | 0x10;
ch341_dev->out_buf[5] = (data & 0xff & ~CH341_GPIO_SPI_MASK) | CH341_MOSI_MASK; // FIXME, set SCK state based on CPOL
ch341_dev->out_buf[6] = (ch341_dev->gpio_mask & 0xff & ~CH341_GPIO_SPI_MASK) | SCK_H | CH341_MOSI_MASK; // Never accidentally drive the SPI signals as GPIOs
ch341_dev->out_buf[7] = (data >> 16) & 0x0f;
ch341_dev->out_buf[8] = 0;
ch341_dev->out_buf[9] = 0;
ch341_dev->out_buf[10] = 0;
// DEV_DBG(CH341_IF_ADDR, "mask=0x%08x data=0x%08x", ch341_dev->gpio_mask, data);
result = ch341_usb_transfer(ch341_dev, 11, 0);
mutex_unlock (&ch341_lock);
return (result < 0) ? result : CH341_OK;
}
/* THis old implementation of write_outputs wrote just D0-5
static int ch341_spi_write_outputs (struct ch341_device* ch341_dev)
{
int 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_GPIO_OUT_MASK);
ch341_dev->out_buf[2] = CH341_CMD_UIO_STM_OUT | (ch341_dev->gpio_io_data & ch341_dev->gpio_mask & CH341_GPIO_OUT_MASK);
ch341_dev->out_buf[3] = CH341_CMD_UIO_STM_END;
DEV_DBG(CH341_IF_ADDR, "mask=0x%08x dir=0x%02x val=0x%02x", ch341_dev->gpio_mask, ch341_dev->out_buf[1], ch341_dev->out_buf[2]);
result = ch341_usb_transfer(ch341_dev, 4, 0);
mutex_unlock (&ch341_lock);
return (result < 0) ? result : CH341_OK;
}
*/
/** NOT USED YET (possibly never)
* Based on example code
* //Init Parallel Mode
//iMode-> 00/01 EPP
//iMode-> 02 MEM
static int CH34xInitParallel( unsigned char iMode, struct ch34x_pis *dev )
{
int retval;
__u8 RequestType = VENDOR_WRITE_TYPE;
__u8 Request = CH34x_PARA_INIT;
__u16 Value = ( iMode << 8 )|( iMode < 0x00000100 ? 0x02 : 0x00 );
__u16 Index = 0;
__u16 len = 0;
retval = usb_control_msg( dev->udev,
usb_sndctrlpipe(dev->udev, 0), Request,
RequestType, Value, Index, NULL, len, 1000);
return retval;
} */
static int ch341_init_parallel (struct ch341_device* ch341_dev)
{
int result;
mutex_lock (&ch341_lock);
ch341_dev->out_buf[0] = CH341_CMD_PARA_INIT;
ch341_dev->out_buf[1] = 0x02;
ch341_dev->out_buf[2] = 0;
DEV_DBG(CH341_IF_ADDR, "init");
result = ch341_usb_transfer(ch341_dev, 3, 0);
mutex_unlock (&ch341_lock);
return (result < 0) ? result : CH341_OK;
}
static uint8_t ch341_spi_swap_byte(const uint8_t byte)
{
uint8_t orig = byte;
uint8_t swap = 0;
int i;
for (i = 0; i < 8; ++i)
{
swap = swap << 1;
swap |= (orig & 1);
orig = orig >> 1;
}
return swap;
}
static const int cs_bits[CH341_SPI_MAX_NUM_DEVICES] = { 0x01, 0x02, 0x04 };
static int ch341_spi_set_cs (struct spi_device *spi, bool active)
{
struct ch341_device* ch341_dev;
int result;
uint32_t old_gpio;
CHECK_PARAM_RET (spi, -EINVAL);
CHECK_PARAM_RET (ch341_dev = ch341_spi_maser_to_dev(spi->master), -EINVAL);
// DEV_DBG (CH341_IF_ADDR, "active %s", active ? "true" : "false");
if (spi->chip_select > CH341_SPI_MAX_NUM_DEVICES)
{
DEV_ERR (CH341_IF_ADDR, "invalid CS value %d, 0~%d are available",
spi->chip_select, CH341_SPI_MAX_NUM_DEVICES-1);
return -EINVAL;
}
old_gpio = ch341_dev->gpio_io_data;
if (active)
ch341_dev->gpio_io_data &= ~cs_bits[spi->chip_select];
else
ch341_dev->gpio_io_data |= cs_bits[spi->chip_select];
if(ch341_dev->gpio_io_data != old_gpio)
{
// if no pin change, don't bother sending a USB transation
ch341_dev->out_buf[0] = CH341_CMD_UIO_STREAM;
ch341_dev->out_buf[1] = CH341_CMD_UIO_STM_DIR | (ch341_dev->gpio_mask & 0xff) | SCK_H; // FIXME, set SCK state based on CPOL
ch341_dev->out_buf[2] = CH341_CMD_UIO_STM_OUT | (ch341_dev->gpio_io_data & ch341_dev->gpio_mask & 0xff);
ch341_dev->out_buf[3] = CH341_CMD_UIO_STM_END;
// DEV_DBG(CH341_IF_ADDR, "mask=0x%x dir=0x%02x val=0x%02x", ch341_dev->gpio_mask, ch341_dev->out_buf[1], ch341_dev->out_buf[2]);
result = ch341_usb_transfer(ch341_dev, 4, 0);
return (result < 0) ? result : CH341_OK;
}
else
{
return CH341_OK;
}
}
// Implementation of bit banging protocol uses following IOs to be compatible
// with the hardware SPI interface
//
// D7 D6 D5 D4 D3 D2 D1 D0
// MISO IN2 MOSI OUT2 SCK CS2 CS1 CS0
static int ch341_spi_bitbang (struct ch341_device* ch341_dev,
struct spi_device *spi,
const uint8_t* tx, uint8_t* rx, int len)
{
uint8_t byte, bit;
uint8_t* io = ch341_dev->out_buf;
int result = 0;
int k = 0;
int i, b;
// CPOL=0, CPHA=0 data must be stable while clock is high, can be changed while clock is low
// mode 0 data sampled on raising clock edge
//
// CPOL=0, CPHA=1 data must be stable while clock is low, can be changed while clock is high
// mode=1 data sampled on falling clock edge
//
// CPOL=1, CPHA=0 data must be stable while clock is low, can be changed while clock is high
// mode=2 data sampled on falling clock edge
//
// CPOL=1, CPHA=1 data must be stable while clock is high, can be changed while clock is low
// mode=3 data sampled on raising clock edge
uint8_t SCK_L = 0;
uint8_t CPOL = (spi->mode & SPI_CPOL) ? 0x08 : 0;
uint8_t CS_H = cs_bits[spi->chip_select];
uint8_t CS_L = 0;
uint8_t MOSI_H = 0x20;
uint8_t MASK = ch341_dev->gpio_mask;
uint8_t DATA = ch341_dev->gpio_io_data & ch341_dev->gpio_mask;
uint8_t mode = spi->mode & SPI_MODE_3;
bool lsb = spi->mode & SPI_LSB_FIRST;
// DEV_DBG (CH341_IF_ADDR, "start");
// mask SPI GPIO data
DATA &= ~MOSI_H & ~SCK_H & ~CS_H;
k = 0;
io[k++] = CH341_CMD_UIO_STREAM;
io[k++] = CH341_CMD_UIO_STM_OUT | DATA | CS_H | CPOL; // set defaults CS#=HIGH, SCK=CPOL
io[k++] = CH341_CMD_UIO_STM_DIR | MASK; // input: MISO, IN2; output MOSI, OUT2, SCK, CS#;
io[k++] = CH341_CMD_UIO_STM_OUT | DATA | CS_L | CPOL; // start with CS0=LOW, SCK=CPOL
io[k++] = CH341_CMD_UIO_STM_END;
if ((result = ch341_usb_transfer(ch341_dev, k, 0)) < 0)
return result;
for (b = 0; b < len; b++)
{
k = 0;
io[k++] = CH341_CMD_UIO_STREAM;
byte = lsb ? ch341_spi_swap_byte(tx[b]) : tx[b];
for (i = 0; i < 8; i++)
{
bit = byte & 0x80 ? 0x20 : 0; // lsb
byte = byte << 1;
if (mode == SPI_MODE_0 || mode == SPI_MODE_3)
{
io[k++] = CH341_CMD_UIO_STM_OUT | DATA | CS_L | SCK_L | bit; // keep CS0=LOW, set SCK=LOW , set MOSI
io[k++] = CH341_CMD_UIO_STM_OUT | DATA | CS_L | SCK_H | bit; // keep CS0=LOW, set SCK=HIGH, keep MOSI
io[k++] = CH341_CMD_UIO_STM_IN; // read MISO
}
else
{
io[k++] = CH341_CMD_UIO_STM_OUT | DATA | CS_L | SCK_L | bit; // keep CS0=LOW, set SCK=HIGH, set MOSI
io[k++] = CH341_CMD_UIO_STM_OUT | DATA | CS_L | SCK_H | bit; // keep CS0=LOW, set SCK=LOW , keep MOSI
io[k++] = CH341_CMD_UIO_STM_IN; // read MISO
}
}
io[k++] = CH341_CMD_UIO_STM_OUT | DATA | CS_L | CPOL; // keep CS0=LOW, SCK=CPOL, MOSI=LOW
io[k++] = CH341_CMD_UIO_STM_END;
if ((result = ch341_usb_transfer(ch341_dev, k, 8)) < 0)
return result;
byte = 0;
for (i = 0; i < 8; i++)
{
byte = byte << 1;
byte = byte | ((ch341_dev->in_buf[i] & 0x80) ? 1 : 0);
}
rx[b] = lsb ? ch341_spi_swap_byte(byte) : byte;
}
k = 0;
io[k++] = CH341_CMD_UIO_STREAM;
io[k++] = CH341_CMD_UIO_STM_OUT | DATA | CS_H | CPOL; // default status: CS#=HIGH, SCK=CPOL
io[k++] = CH341_CMD_UIO_STM_END;
if ((result = ch341_usb_transfer(ch341_dev, k, 0)) < 0)
return result;
// save last I/O data byte
DATA = ch341_dev->gpio_io_data;
DATA &= ~MOSI_H & ~SCK_H & ~CS_H;
DATA |= CS_H | CPOL;
// DEV_DBG (CH341_IF_ADDR, "done");
return 0;
}
static void ch341_set_cs(struct spi_device *spi, bool enable) {
// struct ch341_device* ch341_dev = ch341_spi_maser_to_dev(spi->master);
// DEV_DBG (CH341_IF_ADDR, "cs=%d", enable);
ch341_spi_set_cs (spi, enable);
}
static int ch341_spi_transfer_low(struct spi_master *master,
struct spi_device *spi,
struct spi_transfer* t)
{
struct ch341_device* ch341_dev = ch341_spi_maser_to_dev(spi->master);
const uint8_t* tx;
uint8_t* rx;
bool lsb;
int result = 0;
int i;
CHECK_PARAM_RET (ch341_dev, EIO);
CHECK_PARAM_RET (master , EIO);
CHECK_PARAM_RET (spi , EIO);
CHECK_PARAM_RET (t , EIO);
CHECK_PARAM_RET (t->len <= CH341_USB_MAX_BULK_SIZE, EIO);
// DEV_DBG (CH341_IF_ADDR, "");
// use slow bitbang implementation for SPI_MODE_1, SPI_MODE_2 and SPI_MODE_3
if (spi->mode & SPI_MODE_3) {
result = ch341_spi_bitbang (ch341_dev, spi, t->tx_buf, t->rx_buf, t->len);
}
else
{
// otherwise the faster hardware implementation
lsb = spi->mode & SPI_LSB_FIRST;
tx = t->tx_buf;
rx = t->rx_buf;
// activate cs (always)
ch341_spi_set_cs (spi, true);
// fill output buffer with command and output data, controller expects lsb first
ch341_dev->out_buf[0] = CH341_CMD_SPI_STREAM;
for (i = 0; i < t->len; i++) {
uint8_t b = lsb ? tx[i] : ch341_spi_swap_byte(tx[i]);
ch341_dev->out_buf[i+1] = b;
// DEV_DBG (CH341_IF_ADDR, "outb=0x%02x", tx[i]);
}
// transfer output and input data
if(t->len)
result = ch341_usb_transfer(ch341_dev, t->len + 1, t->len);
// deactivate cs
if (t->cs_change) // we must be running on an older kernel, newer kernels would have called set_cs instead
ch341_spi_set_cs (spi, false);
// fill input data with input buffer, controller delivers lsb first
if (result >= 0 && rx)
for (i = 0; i < t->len; i++) {
rx[i] = lsb ? ch341_dev->in_buf[i] : ch341_spi_swap_byte(ch341_dev->in_buf[i]);
// DEV_DBG (CH341_IF_ADDR, "inb=0x%02x", rx[i]);
}
}
if(t->len == 1) // show bytes transfered if in the common single byte case
DEV_DBG (CH341_IF_ADDR, "len=%u, csChange=%d, result=%d, txb=0x%02x, rxb=0x%02x", t->len, t->cs_change, result, tx[0], rx[0]);
else
DEV_DBG (CH341_IF_ADDR, "len=%u, csChange=%d, result=%d", t->len, t->cs_change, result);
return result;
}
static int ch341_spi_transfer_one(struct spi_master *master,
struct spi_device *spi,
struct spi_transfer* t)
{
int result;
// DEV_DBG (CH341_IF_ADDR, "");
mutex_lock (&ch341_lock);
result = ch341_spi_transfer_low(master, spi, t);
spi_finalize_current_transfer(master);
mutex_unlock (&ch341_lock);
return result;
}
/*
* spi_transfer_one_message - Workaround for cs deassertion (IMO bug) in recent kernels (aprox >=5.10)
* replace the kernel version with our impl
*/
static int spi_transfer_one_message(struct spi_master *master,
struct spi_message *msg)
{
struct spi_device *spi = msg->spi;
// struct ch341_device* ch341_dev = ch341_spi_maser_to_dev(master);
struct spi_transfer *xfer;
int ret = 0;
mutex_lock (&ch341_lock);
ch341_set_cs(msg->spi, true);
msg->actual_length = 0;
list_for_each_entry(xfer, &msg->transfers, transfer_list) {
ret = ch341_spi_transfer_low(master, spi, xfer);
msg->actual_length += xfer->len;
}
msg->status = ret;
spi_finalize_current_message(master);
mutex_unlock (&ch341_lock);
if(ret > 0) // transfer_one_message does not want a count as a result, just 0 for success
ret = 0;
// DEV_DBG (CH341_IF_ADDR, "ret=%d", ret);
return ret;
}
static int ch341_spi_probe (struct ch341_device* ch341_dev)
{
int bus = 0;
int result;
int i;
CHECK_PARAM_RET (ch341_dev, -EINVAL);
DEV_DBG (CH341_IF_ADDR, "start");
// allocate a new SPI master with a pointer to ch341_device as device data
ch341_dev->master = spi_alloc_master(CH341_IF_ADDR, sizeof(struct ch341_device*));
if (!ch341_dev->master)
{
DEV_ERR (CH341_IF_ADDR, "SPI master allocation failed");
return -ENOMEM;
}
// save the pointer to ch341_dev in the SPI master device data field
ch341_spi_maser_to_dev (ch341_dev->master) = ch341_dev;
// set SPI master configuration
ch341_dev->master->bus_num = -1;
ch341_dev->master->num_chipselect = CH341_SPI_MAX_NUM_DEVICES;
ch341_dev->master->mode_bits = SPI_MODE_3 | SPI_LSB_FIRST;
ch341_dev->master->flags = SPI_MASTER_MUST_RX | SPI_MASTER_MUST_TX;
#if LINUX_VERSION_CODE <= KERNEL_VERSION(5,0,0)
ch341_dev->master->bits_per_word_mask = SPI_BIT_MASK(8);
#else
ch341_dev->master->bits_per_word_mask = SPI_BPW_MASK(8);
#endif
// ch341_dev->master->transfer_one = ch341_spi_transfer_one;
ch341_dev->master->transfer_one_message = spi_transfer_one_message;
ch341_dev->master->set_cs = ch341_set_cs;
ch341_dev->master->max_speed_hz = CH341_SPI_MAX_FREQ;
ch341_dev->master->min_speed_hz = CH341_SPI_MIN_FREQ;
// register the new master
if ((result = spi_register_master (ch341_dev->master)))
{
DEV_ERR(CH341_IF_ADDR, "could not register SPI master");
spi_master_put(ch341_dev->master);
// in case of error, reset the master to avoid crash during free
ch341_dev->master = 0;
return result;
}
// create SPI slaves
for (i = 0; i < ch341_dev->slave_num; i++)
{
ch341_spi_devices[i].bus_num = ch341_dev->master->bus_num;
if ((ch341_dev->slaves[i] = spi_new_device(ch341_dev->master, &ch341_spi_devices[i])))
{
DEV_INFO (CH341_IF_ADDR, "SPI device /dev/spidev%d.%d created",
ch341_dev->master->bus_num, ch341_spi_devices[i].chip_select);
ch341_spi_set_cs (ch341_dev->slaves[i], false);
}
}
mutex_init (&ch341_lock);
DEV_DBG (CH341_IF_ADDR, "done");
return CH341_OK;
}
static void ch341_spi_remove (struct ch341_device* ch341_dev)
{
CHECK_PARAM (ch341_dev);
// Not needed because spi_unregister_master (spi_unregister_controller) will do this automatically
/* for (i = 0; i < ch341_dev->slave_num; i++)
if (ch341_dev->slaves[i])
spi_unregister_device (ch341_dev->slaves[i]);
*/
if (ch341_dev->master)
{
spi_unregister_master (ch341_dev->master);
// based on inspection of existing spi drivers in the kernel, this seems unnecessary (and possibly harmful)
// spi_master_put (ch341_dev->master);
}
return;
}
// ----- spi layer end ---------------------------------------------------
// ----- irq layer begin -------------------------------------------------
void ch341_irq_enable_disable (struct irq_data *data, bool enable)