summaryrefslogtreecommitdiffstats
path: root/drivers/dma/nbpfaxi.c
blob: 50559338239b6ec586e1366314bac315c7cf3269 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
/*
 * Copyright (C) 2013-2014 Renesas Electronics Europe Ltd.
 * Author: Guennadi Liakhovetski <g.liakhovetski@gmx.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 */

#include <linux/bitmap.h>
#include <linux/bitops.h>
#include <linux/clk.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/log2.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_dma.h>
#include <linux/platform_device.h>
#include <linux/slab.h>

#include <dt-bindings/dma/nbpfaxi.h>

#include "dmaengine.h"

#define NBPF_REG_CHAN_OFFSET	0
#define NBPF_REG_CHAN_SIZE	0x40

/* Channel Current Transaction Byte register */
#define NBPF_CHAN_CUR_TR_BYTE	0x20

/* Channel Status register */
#define NBPF_CHAN_STAT	0x24
#define NBPF_CHAN_STAT_EN	1
#define NBPF_CHAN_STAT_TACT	4
#define NBPF_CHAN_STAT_ERR	0x10
#define NBPF_CHAN_STAT_END	0x20
#define NBPF_CHAN_STAT_TC	0x40
#define NBPF_CHAN_STAT_DER	0x400

/* Channel Control register */
#define NBPF_CHAN_CTRL	0x28
#define NBPF_CHAN_CTRL_SETEN	1
#define NBPF_CHAN_CTRL_CLREN	2
#define NBPF_CHAN_CTRL_STG	4
#define NBPF_CHAN_CTRL_SWRST	8
#define NBPF_CHAN_CTRL_CLRRQ	0x10
#define NBPF_CHAN_CTRL_CLREND	0x20
#define NBPF_CHAN_CTRL_CLRTC	0x40
#define NBPF_CHAN_CTRL_SETSUS	0x100
#define NBPF_CHAN_CTRL_CLRSUS	0x200

/* Channel Configuration register */
#define NBPF_CHAN_CFG	0x2c
#define NBPF_CHAN_CFG_SEL	7		/* terminal SELect: 0..7 */
#define NBPF_CHAN_CFG_REQD	8		/* REQuest Direction: DMAREQ is 0: input, 1: output */
#define NBPF_CHAN_CFG_LOEN	0x10		/* LOw ENable: low DMA request line is: 0: inactive, 1: active */
#define NBPF_CHAN_CFG_HIEN	0x20		/* HIgh ENable: high DMA request line is: 0: inactive, 1: active */
#define NBPF_CHAN_CFG_LVL	0x40		/* LeVeL: DMA request line is sensed as 0: edge, 1: level */
#define NBPF_CHAN_CFG_AM	0x700		/* ACK Mode: 0: Pulse mode, 1: Level mode, b'1x: Bus Cycle */
#define NBPF_CHAN_CFG_SDS	0xf000		/* Source Data Size: 0: 8 bits,... , 7: 1024 bits */
#define NBPF_CHAN_CFG_DDS	0xf0000		/* Destination Data Size: as above */
#define NBPF_CHAN_CFG_SAD	0x100000	/* Source ADdress counting: 0: increment, 1: fixed */
#define NBPF_CHAN_CFG_DAD	0x200000	/* Destination ADdress counting: 0: increment, 1: fixed */
#define NBPF_CHAN_CFG_TM	0x400000	/* Transfer Mode: 0: single, 1: block TM */
#define NBPF_CHAN_CFG_DEM	0x1000000	/* DMAEND interrupt Mask */
#define NBPF_CHAN_CFG_TCM	0x2000000	/* DMATCO interrupt Mask */
#define NBPF_CHAN_CFG_SBE	0x8000000	/* Sweep Buffer Enable */
#define NBPF_CHAN_CFG_RSEL	0x10000000	/* RM: Register Set sELect */
#define NBPF_CHAN_CFG_RSW	0x20000000	/* RM: Register Select sWitch */
#define NBPF_CHAN_CFG_REN	0x40000000	/* RM: Register Set Enable */
#define NBPF_CHAN_CFG_DMS	0x80000000	/* 0: register mode (RM), 1: link mode (LM) */

#define NBPF_CHAN_NXLA	0x38
#define NBPF_CHAN_CRLA	0x3c

/* Link Header field */
#define NBPF_HEADER_LV	1
#define NBPF_HEADER_LE	2
#define NBPF_HEADER_WBD	4
#define NBPF_HEADER_DIM	8

#define NBPF_CTRL	0x300
#define NBPF_CTRL_PR	1		/* 0: fixed priority, 1: round robin */
#define NBPF_CTRL_LVINT	2		/* DMAEND and DMAERR signalling: 0: pulse, 1: level */

#define NBPF_DSTAT_ER	0x314
#define NBPF_DSTAT_END	0x318

#define NBPF_DMA_BUSWIDTHS \
	(BIT(DMA_SLAVE_BUSWIDTH_UNDEFINED) | \
	 BIT(DMA_SLAVE_BUSWIDTH_1_BYTE) | \
	 BIT(DMA_SLAVE_BUSWIDTH_2_BYTES) | \
	 BIT(DMA_SLAVE_BUSWIDTH_4_BYTES) | \
	 BIT(DMA_SLAVE_BUSWIDTH_8_BYTES))

struct nbpf_config {
	int num_channels;
	int buffer_size;
};

/*
 * We've got 3 types of objects, used to describe DMA transfers:
 * 1. high-level descriptor, containing a struct dma_async_tx_descriptor object
 *	in it, used to communicate with the user
 * 2. hardware DMA link descriptors, that we pass to DMAC for DMA transfer
 *	queuing, these must be DMAable, using either the streaming DMA API or
 *	allocated from coherent memory - one per SG segment
 * 3. one per SG segment descriptors, used to manage HW link descriptors from
 *	(2). They do not have to be DMAable. They can either be (a) allocated
 *	together with link descriptors as mixed (DMA / CPU) objects, or (b)
 *	separately. Even if allocated separately it would be best to link them
 *	to link descriptors once during channel resource allocation and always
 *	use them as a single object.
 * Therefore for both cases (a) and (b) at run-time objects (2) and (3) shall be
 * treated as a single SG segment descriptor.
 */

struct nbpf_link_reg {
	u32	header;
	u32	src_addr;
	u32	dst_addr;
	u32	transaction_size;
	u32	config;
	u32	interval;
	u32	extension;
	u32	next;
} __packed;

struct nbpf_device;
struct nbpf_channel;
struct nbpf_desc;

struct nbpf_link_desc {
	struct nbpf_link_reg *hwdesc;
	dma_addr_t hwdesc_dma_addr;
	struct nbpf_desc *desc;
	struct list_head node;
};

/**
 * struct nbpf_desc - DMA transfer descriptor
 * @async_tx:	dmaengine object
 * @user_wait:	waiting for a user ack
 * @length:	total transfer length
 * @sg:		list of hardware descriptors, represented by struct nbpf_link_desc
 * @node:	member in channel descriptor lists
 */
struct nbpf_desc {
	struct dma_async_tx_descriptor async_tx;
	bool user_wait;
	size_t length;
	struct nbpf_channel *chan;
	struct list_head sg;
	struct list_head node;
};

/* Take a wild guess: allocate 4 segments per descriptor */
#define NBPF_SEGMENTS_PER_DESC 4
#define NBPF_DESCS_PER_PAGE ((PAGE_SIZE - sizeof(struct list_head)) /	\
	(sizeof(struct nbpf_desc) +					\
	 NBPF_SEGMENTS_PER_DESC *					\
	 (sizeof(struct nbpf_link_desc) + sizeof(struct nbpf_link_reg))))
#define NBPF_SEGMENTS_PER_PAGE (NBPF_SEGMENTS_PER_DESC * NBPF_DESCS_PER_PAGE)

struct nbpf_desc_page {
	struct list_head node;
	struct nbpf_desc desc[NBPF_DESCS_PER_PAGE];
	struct nbpf_link_desc ldesc[NBPF_SEGMENTS_PER_PAGE];
	struct nbpf_link_reg hwdesc[NBPF_SEGMENTS_PER_PAGE];
};

/**
 * struct nbpf_channel - one DMAC channel
 * @dma_chan:	standard dmaengine channel object
 * @base:	register address base
 * @nbpf:	DMAC
 * @name:	IRQ name
 * @irq:	IRQ number
 * @slave_addr:	address for slave DMA
 * @slave_width:slave data size in bytes
 * @slave_burst:maximum slave burst size in bytes
 * @terminal:	DMA terminal, assigned to this channel
 * @dmarq_cfg:	DMA request line configuration - high / low, edge / level for NBPF_CHAN_CFG
 * @flags:	configuration flags from DT
 * @lock:	protect descriptor lists
 * @free_links:	list of free link descriptors
 * @free:	list of free descriptors
 * @queued:	list of queued descriptors
 * @active:	list of descriptors, scheduled for processing
 * @done:	list of completed descriptors, waiting post-processing
 * @desc_page:	list of additionally allocated descriptor pages - if any
 */
struct nbpf_channel {
	struct dma_chan dma_chan;
	struct tasklet_struct tasklet;
	void __iomem *base;
	struct nbpf_device *nbpf;
	char name[16];
	int irq;
	dma_addr_t slave_src_addr;
	size_t slave_src_width;
	size_t slave_src_burst;
	dma_addr_t slave_dst_addr;
	size_t slave_dst_width;
	size_t slave_dst_burst;
	unsigned int terminal;
	u32 dmarq_cfg;
	unsigned long flags;
	spinlock_t lock;
	struct list_head free_links;
	struct list_head free;
	struct list_head queued;
	struct list_head active;
	struct list_head done;
	struct list_head desc_page;
	struct nbpf_desc *running;
	bool paused;
};

struct nbpf_device {
	struct dma_device dma_dev;
	void __iomem *base;
	u32 max_burst_mem_read;
	u32 max_burst_mem_write;
	struct clk *clk;
	const struct nbpf_config *config;
	unsigned int eirq;
	struct nbpf_channel chan[];
};

enum nbpf_model {
	NBPF1B4,
	NBPF1B8,
	NBPF1B16,
	NBPF4B4,
	NBPF4B8,
	NBPF4B16,
	NBPF8B4,
	NBPF8B8,
	NBPF8B16,
};

static struct nbpf_config nbpf_cfg[] = {
	[NBPF1B4] = {
		.num_channels = 1,
		.buffer_size = 4,
	},
	[NBPF1B8] = {
		.num_channels = 1,
		.buffer_size = 8,
	},
	[NBPF1B16] = {
		.num_channels = 1,
		.buffer_size = 16,
	},
	[NBPF4B4] = {
		.num_channels = 4,
		.buffer_size = 4,
	},
	[NBPF4B8] = {
		.num_channels = 4,
		.buffer_size = 8,
	},
	[NBPF4B16] = {
		.num_channels = 4,
		.buffer_size = 16,
	},
	[NBPF8B4] = {
		.num_channels = 8,
		.buffer_size = 4,
	},
	[NBPF8B8] = {
		.num_channels = 8,
		.buffer_size = 8,
	},
	[NBPF8B16] = {
		.num_channels = 8,
		.buffer_size = 16,
	},
};

#define nbpf_to_chan(d) container_of(d, struct nbpf_channel, dma_chan)

/*
 * dmaengine drivers seem to have a lot in common and instead of sharing more
 * code, they reimplement those common algorithms independently. In this driver
 * we try to separate the hardware-specific part from the (largely) generic
 * part. This improves code readability and makes it possible in the future to
 * reuse the generic code in form of a helper library. That generic code should
 * be suitable for various DMA controllers, using transfer descriptors in RAM
 * and pushing one SG list at a time to the DMA controller.
 */

/*		Hardware-specific part		*/

static inline u32 nbpf_chan_read(struct nbpf_channel *chan,
				 unsigned int offset)
{
	u32 data = ioread32(chan->base + offset);
	dev_dbg(chan->dma_chan.device->dev, "%s(0x%p + 0x%x) = 0x%x\n",
		__func__, chan->base, offset, data);
	return data;
}

static inline void nbpf_chan_write(struct nbpf_channel *chan,
				   unsigned int offset, u32 data)
{
	iowrite32(data, chan->base + offset);
	dev_dbg(chan->dma_chan.device->dev, "%s(0x%p + 0x%x) = 0x%x\n",
		__func__, chan->base, offset, data);
}

static inline u32 nbpf_read(struct nbpf_device *nbpf,
			    unsigned int offset)
{
	u32 data = ioread32(nbpf->base + offset);
	dev_dbg(nbpf->dma_dev.dev, "%s(0x%p + 0x%x) = 0x%x\n",
		__func__, nbpf->base, offset, data);
	return data;
}

static inline void nbpf_write(struct nbpf_device *nbpf,
			      unsigned int offset, u32 data)
{
	iowrite32(data, nbpf->base + offset);
	dev_dbg(nbpf->dma_dev.dev, "%s(0x%p + 0x%x) = 0x%x\n",
		__func__, nbpf->base, offset, data);
}

static void nbpf_chan_halt(struct nbpf_channel *chan)
{
	nbpf_chan_write(chan, NBPF_CHAN_CTRL, NBPF_CHAN_CTRL_CLREN);
}

static bool nbpf_status_get(struct nbpf_channel *chan)
{
	u32 status = nbpf_read(chan->nbpf, NBPF_DSTAT_END);

	return status & BIT(chan - chan->nbpf->chan);
}

static void nbpf_status_ack(struct nbpf_channel *chan)
{
	nbpf_chan_write(chan, NBPF_CHAN_CTRL, NBPF_CHAN_CTRL_CLREND);
}

static u32 nbpf_error_get(struct nbpf_device *nbpf)
{
	return nbpf_read(nbpf, NBPF_DSTAT_ER);
}

static struct nbpf_channel *nbpf_error_get_channel(struct nbpf_device *nbpf, u32 error)
{
	return nbpf->chan + __ffs(error);
}

static void nbpf_error_clear(struct nbpf_channel *chan)
{
	u32 status;
	int i;

	/* Stop the channel, make sure DMA has been aborted */
	nbpf_chan_halt(chan);

	for (i = 1000; i; i--) {
		status = nbpf_chan_read(chan, NBPF_CHAN_STAT);
		if (!(status & NBPF_CHAN_STAT_TACT))
			break;
		cpu_relax();
	}

	if (!i)
		dev_err(chan->dma_chan.device->dev,
			"%s(): abort timeout, channel status 0x%x\n", __func__, status);

	nbpf_chan_write(chan, NBPF_CHAN_CTRL, NBPF_CHAN_CTRL_SWRST);
}

static int nbpf_start(struct nbpf_desc *desc)
{
	struct nbpf_channel *chan = desc->chan;
	struct nbpf_link_desc *ldesc = list_first_entry(&desc->sg, struct nbpf_link_desc, node);

	nbpf_chan_write(chan, NBPF_CHAN_NXLA, (u32)ldesc->hwdesc_dma_addr);
	nbpf_chan_write(chan, NBPF_CHAN_CTRL, NBPF_CHAN_CTRL_SETEN | NBPF_CHAN_CTRL_CLRSUS);
	chan->paused = false;

	/* Software trigger MEMCPY - only MEMCPY uses the block mode */
	if (ldesc->hwdesc->config & NBPF_CHAN_CFG_TM)
		nbpf_chan_write(chan, NBPF_CHAN_CTRL, NBPF_CHAN_CTRL_STG);

	dev_dbg(chan->nbpf->dma_dev.dev, "%s(): next 0x%x, cur 0x%x\n", __func__,
		nbpf_chan_read(chan, NBPF_CHAN_NXLA), nbpf_chan_read(chan, NBPF_CHAN_CRLA));

	return 0;
}

static void nbpf_chan_prepare(struct nbpf_channel *chan)
{
	chan->dmarq_cfg = (chan->flags & NBPF_SLAVE_RQ_HIGH ? NBPF_CHAN_CFG_HIEN : 0) |
		(chan->flags & NBPF_SLAVE_RQ_LOW ? NBPF_CHAN_CFG_LOEN : 0) |
		(chan->flags & NBPF_SLAVE_RQ_LEVEL ?
		 NBPF_CHAN_CFG_LVL | (NBPF_CHAN_CFG_AM & 0x200) : 0) |
		chan->terminal;
}

static void nbpf_chan_prepare_default(struct nbpf_channel *chan)
{
	/* Don't output DMAACK */
	chan->dmarq_cfg = NBPF_CHAN_CFG_AM & 0x400;
	chan->terminal = 0;
	chan->flags = 0;
}

static void nbpf_chan_configure(struct nbpf_channel *chan)
{
	/*
	 * We assume, that only the link mode and DMA request line configuration
	 * have to be set in the configuration register manually. Dynamic
	 * per-transfer configuration will be loaded from transfer descriptors.
	 */
	nbpf_chan_write(chan, NBPF_CHAN_CFG, NBPF_CHAN_CFG_DMS | chan->dmarq_cfg);
}

static u32 nbpf_xfer_ds(struct nbpf_device *nbpf, size_t size,
			enum dma_transfer_direction direction)
{
	int max_burst = nbpf->config->buffer_size * 8;

	if (nbpf->max_burst_mem_read || nbpf->max_burst_mem_write) {
		switch (direction) {
		case DMA_MEM_TO_MEM:
			max_burst = min_not_zero(nbpf->max_burst_mem_read,
						 nbpf->max_burst_mem_write);
			break;
		case DMA_MEM_TO_DEV:
			if (nbpf->max_burst_mem_read)
				max_burst = nbpf->max_burst_mem_read;
			break;
		case DMA_DEV_TO_MEM:
			if (nbpf->max_burst_mem_write)
				max_burst = nbpf->max_burst_mem_write;
			break;
		case DMA_DEV_TO_DEV:
		default:
			break;
		}
	}

	/* Maximum supported bursts depend on the buffer size */
	return min_t(int, __ffs(size), ilog2(max_burst));
}

static size_t nbpf_xfer_size(struct nbpf_device *nbpf,
			     enum dma_slave_buswidth width, u32 burst)
{
	size_t size;

	if (!burst)
		burst = 1;

	switch (width) {
	case DMA_SLAVE_BUSWIDTH_8_BYTES:
		size = 8 * burst;
		break;

	case DMA_SLAVE_BUSWIDTH_4_BYTES:
		size = 4 * burst;
		break;

	case DMA_SLAVE_BUSWIDTH_2_BYTES:
		size = 2 * burst;
		break;

	default:
		pr_warn("%s(): invalid bus width %u\n", __func__, width);
	case DMA_SLAVE_BUSWIDTH_1_BYTE:
		size = burst;
	}

	return nbpf_xfer_ds(nbpf, size, DMA_TRANS_NONE);
}

/*
 * We need a way to recognise slaves, whose data is sent "raw" over the bus,
 * i.e. it isn't known in advance how many bytes will be received. Therefore
 * the slave driver has to provide a "large enough" buffer and either read the
 * buffer, when it is full, or detect, that some data has arrived, then wait for
 * a timeout, if no more data arrives - receive what's already there. We want to
 * handle such slaves in a special way to allow an optimised mode for other
 * users, for whom the amount of data is known in advance. So far there's no way
 * to recognise such slaves. We use a data-width check to distinguish between
 * the SD host and the PL011 UART.
 */

static int nbpf_prep_one(struct nbpf_link_desc *ldesc,
			 enum dma_transfer_direction direction,
			 dma_addr_t src, dma_addr_t dst, size_t size, bool last)
{
	struct nbpf_link_reg *hwdesc = ldesc->hwdesc;
	struct nbpf_desc *desc = ldesc->desc;
	struct nbpf_channel *chan = desc->chan;
	struct device *dev = chan->dma_chan.device->dev;
	size_t mem_xfer, slave_xfer;
	bool can_burst;

	hwdesc->header = NBPF_HEADER_WBD | NBPF_HEADER_LV |
		(last ? NBPF_HEADER_LE : 0);

	hwdesc->src_addr = src;
	hwdesc->dst_addr = dst;
	hwdesc->transaction_size = size;

	/*
	 * set config: SAD, DAD, DDS, SDS, etc.
	 * Note on transfer sizes: the DMAC can perform unaligned DMA transfers,
	 * but it is important to have transaction size a multiple of both
	 * receiver and transmitter transfer sizes. It is also possible to use
	 * different RAM and device transfer sizes, and it does work well with
	 * some devices, e.g. with V08R07S01E SD host controllers, which can use
	 * 128 byte transfers. But this doesn't work with other devices,
	 * especially when the transaction size is unknown. This is the case,
	 * e.g. with serial drivers like amba-pl011.c. For reception it sets up
	 * the transaction size of 4K and if fewer bytes are received, it
	 * pauses DMA and reads out data received via DMA as well as those left
	 * in the Rx FIFO. For this to work with the RAM side using burst
	 * transfers we enable the SBE bit and terminate the transfer in our
	 * .device_pause handler.
	 */
	mem_xfer = nbpf_xfer_ds(chan->nbpf, size, direction);

	switch (direction) {
	case DMA_DEV_TO_MEM:
		can_burst = chan->slave_src_width >= 3;
		slave_xfer = min(mem_xfer, can_burst ?
				 chan->slave_src_burst : chan->slave_src_width);
		/*
		 * Is the slave narrower than 64 bits, i.e. isn't using the full
		 * bus width and cannot use bursts?
		 */
		if (mem_xfer > chan->slave_src_burst && !can_burst)
			mem_xfer = chan->slave_src_burst;
		/* Device-to-RAM DMA is unreliable without REQD set */
		hwdesc->config = NBPF_CHAN_CFG_SAD | (NBPF_CHAN_CFG_DDS & (mem_xfer << 16)) |
			(NBPF_CHAN_CFG_SDS & (slave_xfer << 12)) | NBPF_CHAN_CFG_REQD |
			NBPF_CHAN_CFG_SBE;
		break;

	case DMA_MEM_TO_DEV:
		slave_xfer = min(mem_xfer, chan->slave_dst_width >= 3 ?
				 chan->slave_dst_burst : chan->slave_dst_width);
		hwdesc->config = NBPF_CHAN_CFG_DAD | (NBPF_CHAN_CFG_SDS & (mem_xfer << 12)) |
			(NBPF_CHAN_CFG_DDS & (slave_xfer << 16)) | NBPF_CHAN_CFG_REQD;
		break;

	case DMA_MEM_TO_MEM:
		hwdesc->config = NBPF_CHAN_CFG_TCM | NBPF_CHAN_CFG_TM |
			(NBPF_CHAN_CFG_SDS & (mem_xfer << 12)) |
			(NBPF_CHAN_CFG_DDS & (mem_xfer << 16));
		break;

	default:
		return -EINVAL;
	}

	hwdesc->config |= chan->dmarq_cfg | (last ? 0 : NBPF_CHAN_CFG_DEM) |
		NBPF_CHAN_CFG_DMS;

	dev_dbg(dev, "%s(): desc @ %pad: hdr 0x%x, cfg 0x%x, %zu @ %pad -> %pad\n",
		__func__, &ldesc->hwdesc_dma_addr, hwdesc->header,
		hwdesc->config, size, &src, &dst);

	dma_sync_single_for_device(dev, ldesc->hwdesc_dma_addr, sizeof(*hwdesc),
				   DMA_TO_DEVICE);

	return 0;
}

static size_t nbpf_bytes_left(struct nbpf_channel *chan)
{
	return nbpf_chan_read(chan, NBPF_CHAN_CUR_TR_BYTE);
}

static void nbpf_configure(struct nbpf_device *nbpf)
{
	nbpf_write(nbpf, NBPF_CTRL, NBPF_CTRL_LVINT);
}

/*		Generic part			*/

/* DMA ENGINE functions */
static void nbpf_issue_pending(struct dma_chan *dchan)
{
	struct nbpf_channel *chan = nbpf_to_chan(dchan);
	unsigned long flags;

	dev_dbg(dchan->device->dev, "Entry %s()\n", __func__);

	spin_lock_irqsave(&chan->lock, flags);
	if (list_empty(&chan->queued))
		goto unlock;

	list_splice_tail_init(&chan->queued, &chan->active);

	if (!chan->running) {
		struct nbpf_desc *desc = list_first_entry(&chan->active,
						struct nbpf_desc, node);
		if (!nbpf_start(desc))
			chan->running = desc;
	}

unlock:
	spin_unlock_irqrestore(&chan->lock, flags);
}

static enum dma_status nbpf_tx_status(struct dma_chan *dchan,
		dma_cookie_t cookie, struct dma_tx_state *state)
{
	struct nbpf_channel *chan = nbpf_to_chan(dchan);
	enum dma_status status = dma_cookie_status(dchan, cookie, state);

	if (state) {
		dma_cookie_t running;
		unsigned long flags;

		spin_lock_irqsave(&chan->lock, flags);
		running = chan->running ? chan->running->async_tx.cookie : -EINVAL;

		if (cookie == running) {
			state->residue = nbpf_bytes_left(chan);
			dev_dbg(dchan->device->dev, "%s(): residue %u\n", __func__,
				state->residue);
		} else if (status == DMA_IN_PROGRESS) {
			struct nbpf_desc *desc;
			bool found = false;

			list_for_each_entry(desc, &chan->active, node)
				if (desc->async_tx.cookie == cookie) {
					found = true;
					break;
				}

			if (!found)
				list_for_each_entry(desc, &chan->queued, node)
					if (desc->async_tx.cookie == cookie) {
						found = true;
						break;

					}

			state->residue = found ? desc->length : 0;
		}

		spin_unlock_irqrestore(&chan->lock, flags);
	}

	if (chan->paused)
		status = DMA_PAUSED;

	return status;
}

static dma_cookie_t nbpf_tx_submit(struct dma_async_tx_descriptor *tx)
{
	struct nbpf_desc *desc = container_of(tx, struct nbpf_desc, async_tx);
	struct nbpf_channel *chan = desc->chan;
	unsigned long flags;
	dma_cookie_t cookie;

	spin_lock_irqsave(&chan->lock, flags);
	cookie = dma_cookie_assign(tx);
	list_add_tail(&desc->node, &chan->queued);
	spin_unlock_irqrestore(&chan->lock, flags);

	dev_dbg(chan->dma_chan.device->dev, "Entry %s(%d)\n", __func__, cookie);

	return cookie;
}

static int nbpf_desc_page_alloc(struct nbpf_channel *chan)
{
	struct dma_chan *dchan = &chan->dma_chan;
	struct nbpf_desc_page *dpage = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
	struct nbpf_link_desc *ldesc;
	struct nbpf_link_reg *hwdesc;
	struct nbpf_desc *desc;
	LIST_HEAD(head);
	LIST_HEAD(lhead);
	int i;
	struct device *dev = dchan->device->dev;

	if (!dpage)
		return -ENOMEM;

	dev_dbg(dev, "%s(): alloc %lu descriptors, %lu segments, total alloc %zu\n",
		__func__, NBPF_DESCS_PER_PAGE, NBPF_SEGMENTS_PER_PAGE, sizeof(*dpage));

	for (i = 0, ldesc = dpage->ldesc, hwdesc = dpage->hwdesc;
	     i < ARRAY_SIZE(dpage->ldesc);
	     i++, ldesc++, hwdesc++) {
		ldesc->hwdesc = hwdesc;
		list_add_tail(&ldesc->node, &lhead);
		ldesc->hwdesc_dma_addr = dma_map_single(dchan->device->dev,
					hwdesc, sizeof(*hwdesc), DMA_TO_DEVICE);

		dev_dbg(dev, "%s(): mapped 0x%p to %pad\n", __func__,
			hwdesc, &ldesc->hwdesc_dma_addr);
	}

	for (i = 0, desc = dpage->desc;
	     i < ARRAY_SIZE(dpage->desc);
	     i++, desc++) {
		dma_async_tx_descriptor_init(&desc->async_tx, dchan);
		desc->async_tx.tx_submit = nbpf_tx_submit;
		desc->chan = chan;
		INIT_LIST_HEAD(&desc->sg);
		list_add_tail(&desc->node, &head);
	}

	/*
	 * This function cannot be called from interrupt context, so, no need to
	 * save flags
	 */
	spin_lock_irq(&chan->lock);
	list_splice_tail(&lhead, &chan->free_links);
	list_splice_tail(&head, &chan->free);
	list_add(&dpage->node, &chan->desc_page);
	spin_unlock_irq(&chan->lock);

	return ARRAY_SIZE(dpage->desc);
}

static void nbpf_desc_put(struct nbpf_desc *desc)
{
	struct nbpf_channel *chan = desc->chan;
	struct nbpf_link_desc *ldesc, *tmp;
	unsigned long flags;

	spin_lock_irqsave(&chan->lock, flags);
	list_for_each_entry_safe(ldesc, tmp, &desc->sg, node)
		list_move(&ldesc->node, &chan->free_links);

	list_add(&desc->node, &chan->free);
	spin_unlock_irqrestore(&chan->lock, flags);
}

static void nbpf_scan_acked(struct nbpf_channel *chan)
{
	struct nbpf_desc *desc, *tmp;
	unsigned long flags;
	LIST_HEAD(head);

	spin_lock_irqsave(&chan->lock, flags);
	list_for_each_entry_safe(desc, tmp, &chan->done, node)
		if (async_tx_test_ack(&desc->async_tx) && desc->user_wait) {
			list_move(&desc->node, &head);
			desc->user_wait = false;
		}
	spin_unlock_irqrestore(&chan->lock, flags);

	list_for_each_entry_safe(desc, tmp, &head, node) {
		list_del(&desc->node);
		nbpf_desc_put(desc);
	}
}

/*
 * We have to allocate descriptors with the channel lock dropped. This means,
 * before we re-acquire the lock buffers can be taken already, so we have to
 * re-check after re-acquiring the lock and possibly retry, if buffers are gone
 * again.
 */
static struct nbpf_desc *nbpf_desc_get(struct nbpf_channel *chan, size_t len)
{
	struct nbpf_desc *desc = NULL;
	struct nbpf_link_desc *ldesc, *prev = NULL;

	nbpf_scan_acked(chan);

	spin_lock_irq(&chan->lock);

	do {
		int i = 0, ret;

		if (list_empty(&chan->free)) {
			/* No more free descriptors */
			spin_unlock_irq(&chan->lock);
			ret = nbpf_desc_page_alloc(chan);
			if (ret < 0)
				return NULL;
			spin_lock_irq(&chan->lock);
			continue;
		}
		desc = list_first_entry(&chan->free, struct nbpf_desc, node);
		list_del(&desc->node);

		do {
			if (list_empty(&chan->free_links)) {
				/* No more free link descriptors */
				spin_unlock_irq(&chan->lock);
				ret = nbpf_desc_page_alloc(chan);
				if (ret < 0) {
					nbpf_desc_put(desc);
					return NULL;
				}
				spin_lock_irq(&chan->lock);
				continue;
			}

			ldesc = list_first_entry(&chan->free_links,
						 struct nbpf_link_desc, node);
			ldesc->desc = desc;
			if (prev)
				prev->hwdesc->next = (u32)ldesc->hwdesc_dma_addr;

			prev = ldesc;
			list_move_tail(&ldesc->node, &desc->sg);

			i++;
		} while (i < len);
	} while (!desc);

	prev->hwdesc->next = 0;

	spin_unlock_irq(&chan->lock);

	return desc;
}

static void nbpf_chan_idle(struct nbpf_channel *chan)
{
	struct nbpf_desc *desc, *tmp;
	unsigned long flags;
	LIST_HEAD(head);

	spin_lock_irqsave(&chan->lock, flags);

	list_splice_init(&chan->done, &head);
	list_splice_init(&chan->active, &head);
	list_splice_init(&chan->queued, &head);

	chan->running = NULL;

	spin_unlock_irqrestore(&chan->lock, flags);

	list_for_each_entry_safe(desc, tmp, &head, node) {
		dev_dbg(chan->nbpf->dma_dev.dev, "%s(): force-free desc %p cookie %d\n",
			__func__, desc, desc->async_tx.cookie);
		list_del(&desc->node);
		nbpf_desc_put(desc);
	}
}

static int nbpf_pause(struct dma_chan *dchan)
{
	struct nbpf_channel *chan = nbpf_to_chan(dchan);

	dev_dbg(dchan->device->dev, "Entry %s\n", __func__);

	chan->paused = true;
	nbpf_chan_write(chan, NBPF_CHAN_CTRL, NBPF_CHAN_CTRL_SETSUS);
	/* See comment in nbpf_prep_one() */
	nbpf_chan_write(chan, NBPF_CHAN_CTRL, NBPF_CHAN_CTRL_CLREN);

	return 0;
}

static int nbpf_terminate_all(struct dma_chan *dchan)
{
	struct nbpf_channel *chan = nbpf_to_chan(dchan);

	dev_dbg(dchan->device->dev, "Entry %s\n", __func__);
	dev_dbg(dchan->device->dev, "Terminating\n");

	nbpf_chan_halt(chan);
	nbpf_chan_idle(chan);

	return 0;
}

static int nbpf_config(struct dma_chan *dchan,
		       struct dma_slave_config *config)
{
	struct nbpf_channel *chan = nbpf_to_chan(dchan);

	dev_dbg(dchan->device->dev, "Entry %s\n", __func__);

	/*
	 * We could check config->slave_id to match chan->terminal here,
	 * but with DT they would be coming from the same source, so
	 * such a check would be superflous
	 */

	chan->slave_dst_addr = config->dst_addr;
	chan->slave_dst_width = nbpf_xfer_size(chan->nbpf,
					       config->dst_addr_width, 1);
	chan->slave_dst_burst = nbpf_xfer_size(chan->nbpf,
					       config->dst_addr_width,
					       config->dst_maxburst);
	chan->slave_src_addr = config->src_addr;
	chan->slave_src_width = nbpf_xfer_size(chan->nbpf,
					       config->src_addr_width, 1);
	chan->slave_src_burst = nbpf_xfer_size(chan->nbpf,
					       config->src_addr_width,
					       config->src_maxburst);

	return 0;
}

static struct dma_async_tx_descriptor *nbpf_prep_sg(struct nbpf_channel *chan,
		struct scatterlist *src_sg, struct scatterlist *dst_sg,
		size_t len, enum dma_transfer_direction direction,
		unsigned long flags)
{
	struct nbpf_link_desc *ldesc;
	struct scatterlist *mem_sg;
	struct nbpf_desc *desc;
	bool inc_src, inc_dst;
	size_t data_len = 0;
	int i = 0;

	switch (direction) {
	case DMA_DEV_TO_MEM:
		mem_sg = dst_sg;
		inc_src = false;
		inc_dst = true;
		break;

	case DMA_MEM_TO_DEV:
		mem_sg = src_sg;
		inc_src = true;
		inc_dst = false;
		break;

	default:
	case DMA_MEM_TO_MEM:
		mem_sg = src_sg;
		inc_src = true;
		inc_dst = true;
	}

	desc = nbpf_desc_get(chan, len);
	if (!desc)
		return NULL;

	desc->async_tx.flags = flags;
	desc->async_tx.cookie = -EBUSY;
	desc->user_wait = false;

	/*
	 * This is a private descriptor list, and we own the descriptor. No need
	 * to lock.
	 */
	list_for_each_entry(ldesc, &desc->sg, node) {
		int ret = nbpf_prep_one(ldesc, direction,
					sg_dma_address(src_sg),
					sg_dma_address(dst_sg),
					sg_dma_len(mem_sg),
					i == len - 1);
		if (ret < 0) {
			nbpf_desc_put(desc);
			return NULL;
		}
		data_len += sg_dma_len(mem_sg);
		if (inc_src)
			src_sg = sg_next(src_sg);
		if (inc_dst)
			dst_sg = sg_next(dst_sg);
		mem_sg = direction == DMA_DEV_TO_MEM ? dst_sg : src_sg;
		i++;
	}

	desc->length = data_len;

	/* The user has to return the descriptor to us ASAP via .tx_submit() */
	return &desc->async_tx;
}

static struct dma_async_tx_descriptor *nbpf_prep_memcpy(
	struct dma_chan *dchan, dma_addr_t dst, dma_addr_t src,
	size_t len, unsigned long flags)
{
	struct nbpf_channel *chan = nbpf_to_chan(dchan);
	struct scatterlist dst_sg;
	struct scatterlist src_sg;

	sg_init_table(&dst_sg, 1);
	sg_init_table(&src_sg, 1);

	sg_dma_address(&dst_sg) = dst;
	sg_dma_address(&src_sg) = src;

	sg_dma_len(&dst_sg) = len;
	sg_dma_len(&src_sg) = len;

	dev_dbg(dchan->device->dev, "%s(): %zu @ %pad -> %pad\n",
		__func__, len, &src, &dst);

	return nbpf_prep_sg(chan, &src_sg, &dst_sg, 1,
			    DMA_MEM_TO_MEM, flags);
}

static struct dma_async_tx_descriptor *nbpf_prep_slave_sg(
	struct dma_chan *dchan, struct scatterlist *sgl, unsigned int sg_len,
	enum dma_transfer_direction direction, unsigned long flags, void *context)
{
	struct nbpf_channel *chan = nbpf_to_chan(dchan);
	struct scatterlist slave_sg;

	dev_dbg(dchan->device->dev, "Entry %s()\n", __func__);

	sg_init_table(&slave_sg, 1);

	switch (direction) {
	case DMA_MEM_TO_DEV:
		sg_dma_address(&slave_sg) = chan->slave_dst_addr;
		return nbpf_prep_sg(chan, sgl, &slave_sg, sg_len,
				    direction, flags);

	case DMA_DEV_TO_MEM:
		sg_dma_address(&slave_sg) = chan->slave_src_addr;
		return nbpf_prep_sg(chan, &slave_sg, sgl, sg_len,
				    direction, flags);

	default:
		return NULL;
	}
}

static int nbpf_alloc_chan_resources(struct dma_chan *dchan)
{
	struct nbpf_channel *chan = nbpf_to_chan(dchan);
	int ret;

	INIT_LIST_HEAD(&chan->free);
	INIT_LIST_HEAD(&chan->free_links);
	INIT_LIST_HEAD(&chan->queued);
	INIT_LIST_HEAD(&chan->active);
	INIT_LIST_HEAD(&chan->done);

	ret = nbpf_desc_page_alloc(chan);
	if (ret < 0)
		return ret;

	dev_dbg(dchan->device->dev, "Entry %s(): terminal %u\n", __func__,
		chan->terminal);

	nbpf_chan_configure(chan);

	return ret;
}

static void nbpf_free_chan_resources(struct dma_chan *dchan)
{
	struct nbpf_channel *chan = nbpf_to_chan(dchan);
	struct nbpf_desc_page *dpage, *tmp;

	dev_dbg(dchan->device->dev, "Entry %s()\n", __func__);

	nbpf_chan_halt(chan);
	nbpf_chan_idle(chan);
	/* Clean up for if a channel is re-used for MEMCPY after slave DMA */
	nbpf_chan_prepare_default(chan);

	list_for_each_entry_safe(dpage, tmp, &chan->desc_page, node) {
		struct nbpf_link_desc *ldesc;
		int i;
		list_del(&dpage->node);
		for (i = 0, ldesc = dpage->ldesc;
		     i < ARRAY_SIZE(dpage->ldesc);
		     i++, ldesc++)
			dma_unmap_single(dchan->device->dev, ldesc->hwdesc_dma_addr,
					 sizeof(*ldesc->hwdesc), DMA_TO_DEVICE);
		free_page((unsigned long)dpage);
	}
}

static struct dma_chan *nbpf_of_xlate(struct of_phandle_args *dma_spec,
				      struct of_dma *ofdma)
{
	struct nbpf_device *nbpf = ofdma->of_dma_data;
	struct dma_chan *dchan;
	struct nbpf_channel *chan;

	if (dma_spec->args_count != 2)
		return NULL;

	dchan = dma_get_any_slave_channel(&nbpf->dma_dev);
	if (!dchan)
		return NULL;

	dev_dbg(dchan->device->dev, "Entry %s(%s)\n", __func__,
		dma_spec->np->name);

	chan = nbpf_to_chan(dchan);

	chan->terminal = dma_spec->args[0];
	chan->flags = dma_spec->args[1];

	nbpf_chan_prepare(chan);
	nbpf_chan_configure(chan);

	return dchan;
}

static void nbpf_chan_tasklet(unsigned long data)
{
	struct nbpf_channel *chan = (struct nbpf_channel *)data;
	struct nbpf_desc *desc, *tmp;
	struct dmaengine_desc_callback cb;

	while (!list_empty(&chan->done)) {
		bool found = false, must_put, recycling = false;

		spin_lock_irq(&chan->lock);

		list_for_each_entry_safe(desc, tmp, &chan->done, node) {
			if (!desc->user_wait) {
				/* Newly completed descriptor, have to process */
				found = true;
				break;
			} else if (async_tx_test_ack(&desc->async_tx)) {
				/*
				 * This descriptor was waiting for a user ACK,
				 * it can be recycled now.
				 */
				list_del(&desc->node);
				spin_unlock_irq(&chan->lock);
				nbpf_desc_put(desc);
				recycling = true;
				break;
			}
		}

		if (recycling)
			continue;

		if (!found) {
			/* This can happen if TERMINATE_ALL has been called */
			spin_unlock_irq(&chan->lock);
			break;
		}

		dma_cookie_complete(&desc->async_tx);

		/*
		 * With released lock we cannot dereference desc, maybe it's
		 * still on the "done" list
		 */
		if (async_tx_test_ack(&desc->async_tx)) {
			list_del(&desc->node);
			must_put = true;
		} else {
			desc->user_wait = true;
			must_put = false;
		}

		dmaengine_desc_get_callback(&desc->async_tx, &cb);

		/* ack and callback completed descriptor */
		spin_unlock_irq(&chan->lock);

		dmaengine_desc_callback_invoke(&cb, NULL);

		if (must_put)
			nbpf_desc_put(desc);
	}
}

static irqreturn_t nbpf_chan_irq(int irq, void *dev)
{
	struct nbpf_channel *chan = dev;
	bool done = nbpf_status_get(chan);
	struct nbpf_desc *desc;
	irqreturn_t ret;
	bool bh = false;

	if (!done)
		return IRQ_NONE;

	nbpf_status_ack(chan);

	dev_dbg(&chan->dma_chan.dev->device, "%s()\n", __func__);

	spin_lock(&chan->lock);
	desc = chan->running;
	if (WARN_ON(!desc)) {
		ret = IRQ_NONE;
		goto unlock;
	} else {
		ret = IRQ_HANDLED;
		bh = true;
	}

	list_move_tail(&desc->node, &chan->done);
	chan->running = NULL;

	if (!list_empty(&chan->active)) {
		desc = list_first_entry(&chan->active,
					struct nbpf_desc, node);
		if (!nbpf_start(desc))
			chan->running = desc;
	}

unlock:
	spin_unlock(&chan->lock);

	if (bh)
		tasklet_schedule(&chan->tasklet);

	return ret;
}

static irqreturn_t nbpf_err_irq(int irq, void *dev)
{
	struct nbpf_device *nbpf = dev;
	u32 error = nbpf_error_get(nbpf);

	dev_warn(nbpf->dma_dev.dev, "DMA error IRQ %u\n", irq);

	if (!error)
		return IRQ_NONE;

	do {
		struct nbpf_channel *chan = nbpf_error_get_channel(nbpf, error);
		/* On error: abort all queued transfers, no callback */
		nbpf_error_clear(chan);
		nbpf_chan_idle(chan);
		error = nbpf_error_get(nbpf);
	} while (error);

	return IRQ_HANDLED;
}

static int nbpf_chan_probe(struct nbpf_device *nbpf, int n)
{
	struct dma_device *dma_dev = &nbpf->dma_dev;
	struct nbpf_channel *chan = nbpf->chan + n;
	int ret;

	chan->nbpf = nbpf;
	chan->base = nbpf->base + NBPF_REG_CHAN_OFFSET + NBPF_REG_CHAN_SIZE * n;
	INIT_LIST_HEAD(&chan->desc_page);
	spin_lock_init(&chan->lock);
	chan->dma_chan.device = dma_dev;
	dma_cookie_init(&chan->dma_chan);
	nbpf_chan_prepare_default(chan);

	dev_dbg(dma_dev->dev, "%s(): channel %d: -> %p\n", __func__, n, chan->base);

	snprintf(chan->name, sizeof(chan->name), "nbpf %d", n);

	tasklet_init(&chan->tasklet, nbpf_chan_tasklet, (unsigned long)chan);
	ret = devm_request_irq(dma_dev->dev, chan->irq,
			nbpf_chan_irq, IRQF_SHARED,
			chan->name, chan);
	if (ret < 0)
		return ret;

	/* Add the channel to DMA device channel list */
	list_add_tail(&chan->dma_chan.device_node,
		      &dma_dev->channels);

	return 0;
}

static const struct of_device_id nbpf_match[] = {
	{.compatible = "renesas,nbpfaxi64dmac1b4",	.data = &nbpf_cfg[NBPF1B4]},
	{.compatible = "renesas,nbpfaxi64dmac1b8",	.data = &nbpf_cfg[NBPF1B8]},
	{.compatible = "renesas,nbpfaxi64dmac1b16",	.data = &nbpf_cfg[NBPF1B16]},
	{.compatible = "renesas,nbpfaxi64dmac4b4",	.data = &nbpf_cfg[NBPF4B4]},
	{.compatible = "renesas,nbpfaxi64dmac4b8",	.data = &nbpf_cfg[NBPF4B8]},
	{.compatible = "renesas,nbpfaxi64dmac4b16",	.data = &nbpf_cfg[NBPF4B16]},
	{.compatible = "renesas,nbpfaxi64dmac8b4",	.data = &nbpf_cfg[NBPF8B4]},
	{.compatible = "renesas,nbpfaxi64dmac8b8",	.data = &nbpf_cfg[NBPF8B8]},
	{.compatible = "renesas,nbpfaxi64dmac8b16",	.data = &nbpf_cfg[NBPF8B16]},
	{}
};
MODULE_DEVICE_TABLE(of, nbpf_match);

static int nbpf_probe(struct platform_device *pdev)
{
	struct device *dev = &pdev->dev;
	struct device_node *np = dev->of_node;
	struct nbpf_device *nbpf;
	struct dma_device *dma_dev;
	struct resource *iomem, *irq_res;
	const struct nbpf_config *cfg;
	int num_channels;
	int ret, irq, eirq, i;
	int irqbuf[9] /* maximum 8 channels + error IRQ */;
	unsigned int irqs = 0;

	BUILD_BUG_ON(sizeof(struct nbpf_desc_page) > PAGE_SIZE);

	/* DT only */
	if (!np)
		return -ENODEV;

	cfg = of_device_get_match_data(dev);
	num_channels = cfg->num_channels;

	nbpf = devm_kzalloc(dev, sizeof(*nbpf) + num_channels *
			    sizeof(nbpf->chan[0]), GFP_KERNEL);
	if (!nbpf)
		return -ENOMEM;

	dma_dev = &nbpf->dma_dev;
	dma_dev->dev = dev;

	iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	nbpf->base = devm_ioremap_resource(dev, iomem);
	if (IS_ERR(nbpf->base))
		return PTR_ERR(nbpf->base);

	nbpf->clk = devm_clk_get(dev, NULL);
	if (IS_ERR(nbpf->clk))
		return PTR_ERR(nbpf->clk);

	of_property_read_u32(np, "max-burst-mem-read",
			     &nbpf->max_burst_mem_read);
	of_property_read_u32(np, "max-burst-mem-write",
			     &nbpf->max_burst_mem_write);

	nbpf->config = cfg;

	for (i = 0; irqs < ARRAY_SIZE(irqbuf); i++) {
		irq_res = platform_get_resource(pdev, IORESOURCE_IRQ, i);
		if (!irq_res)
			break;

		for (irq = irq_res->start; irq <= irq_res->end;
		     irq++, irqs++)
			irqbuf[irqs] = irq;
	}

	/*
	 * 3 IRQ resource schemes are supported:
	 * 1. 1 shared IRQ for error and all channels
	 * 2. 2 IRQs: one for error and one shared for all channels
	 * 3. 1 IRQ for error and an own IRQ for each channel
	 */
	if (irqs != 1 && irqs != 2 && irqs != num_channels + 1)
		return -ENXIO;

	if (irqs == 1) {
		eirq = irqbuf[0];

		for (i = 0; i <= num_channels; i++)
			nbpf->chan[i].irq = irqbuf[0];
	} else {
		eirq = platform_get_irq_byname(pdev, "error");
		if (eirq < 0)
			return eirq;

		if (irqs == num_channels + 1) {
			struct nbpf_channel *chan;

			for (i = 0, chan = nbpf->chan; i <= num_channels;
			     i++, chan++) {
				/* Skip the error IRQ */
				if (irqbuf[i] == eirq)
					i++;
				chan->irq = irqbuf[i];
			}

			if (chan != nbpf->chan + num_channels)
				return -EINVAL;
		} else {
			/* 2 IRQs and more than one channel */
			if (irqbuf[0] == eirq)
				irq = irqbuf[1];
			else
				irq = irqbuf[0];

			for (i = 0; i <= num_channels; i++)
				nbpf->chan[i].irq = irq;
		}
	}

	ret = devm_request_irq(dev, eirq, nbpf_err_irq,
			       IRQF_SHARED, "dma error", nbpf);
	if (ret < 0)
		return ret;
	nbpf->eirq = eirq;

	INIT_LIST_HEAD(&dma_dev->channels);

	/* Create DMA Channel */
	for (i = 0; i < num_channels; i++) {
		ret = nbpf_chan_probe(nbpf, i);
		if (ret < 0)
			return ret;
	}

	dma_cap_set(DMA_MEMCPY, dma_dev->cap_mask);
	dma_cap_set(DMA_SLAVE, dma_dev->cap_mask);
	dma_cap_set(DMA_PRIVATE, dma_dev->cap_mask);

	/* Common and MEMCPY operations */
	dma_dev->device_alloc_chan_resources
		= nbpf_alloc_chan_resources;
	dma_dev->device_free_chan_resources = nbpf_free_chan_resources;
	dma_dev->device_prep_dma_memcpy = nbpf_prep_memcpy;
	dma_dev->device_tx_status = nbpf_tx_status;
	dma_dev->device_issue_pending = nbpf_issue_pending;

	/*
	 * If we drop support for unaligned MEMCPY buffer addresses and / or
	 * lengths by setting
	 * dma_dev->copy_align = 4;
	 * then we can set transfer length to 4 bytes in nbpf_prep_one() for
	 * DMA_MEM_TO_MEM
	 */

	/* Compulsory for DMA_SLAVE fields */
	dma_dev->device_prep_slave_sg = nbpf_prep_slave_sg;
	dma_dev->device_config = nbpf_config;
	dma_dev->device_pause = nbpf_pause;
	dma_dev->device_terminate_all = nbpf_terminate_all;

	dma_dev->src_addr_widths = NBPF_DMA_BUSWIDTHS;
	dma_dev->dst_addr_widths = NBPF_DMA_BUSWIDTHS;
	dma_dev->directions = BIT(DMA_DEV_TO_MEM) | BIT(DMA_MEM_TO_DEV);

	platform_set_drvdata(pdev, nbpf);

	ret = clk_prepare_enable(nbpf->clk);
	if (ret < 0)
		return ret;

	nbpf_configure(nbpf);

	ret = dma_async_device_register(dma_dev);
	if (ret < 0)
		goto e_clk_off;

	ret = of_dma_controller_register(np, nbpf_of_xlate, nbpf);
	if (ret < 0)
		goto e_dma_dev_unreg;

	return 0;

e_dma_dev_unreg:
	dma_async_device_unregister(dma_dev);
e_clk_off:
	clk_disable_unprepare(nbpf->clk);

	return ret;
}

static int nbpf_remove(struct platform_device *pdev)
{
	struct nbpf_device *nbpf = platform_get_drvdata(pdev);
	int i;

	devm_free_irq(&pdev->dev, nbpf->eirq, nbpf);

	for (i = 0; i < nbpf->config->num_channels; i++) {
		struct nbpf_channel *chan = nbpf->chan + i;

		devm_free_irq(&pdev->dev, chan->irq, chan);

		tasklet_kill(&chan->tasklet);
	}

	of_dma_controller_free(pdev->dev.of_node);
	dma_async_device_unregister(&nbpf->dma_dev);
	clk_disable_unprepare(nbpf->clk);

	return 0;
}

static const struct platform_device_id nbpf_ids[] = {
	{"nbpfaxi64dmac1b4",	(kernel_ulong_t)&nbpf_cfg[NBPF1B4]},
	{"nbpfaxi64dmac1b8",	(kernel_ulong_t)&nbpf_cfg[NBPF1B8]},
	{"nbpfaxi64dmac1b16",	(kernel_ulong_t)&nbpf_cfg[NBPF1B16]},
	{"nbpfaxi64dmac4b4",	(kernel_ulong_t)&nbpf_cfg[NBPF4B4]},
	{"nbpfaxi64dmac4b8",	(kernel_ulong_t)&nbpf_cfg[NBPF4B8]},
	{"nbpfaxi64dmac4b16",	(kernel_ulong_t)&nbpf_cfg[NBPF4B16]},
	{"nbpfaxi64dmac8b4",	(kernel_ulong_t)&nbpf_cfg[NBPF8B4]},
	{"nbpfaxi64dmac8b8",	(kernel_ulong_t)&nbpf_cfg[NBPF8B8]},
	{"nbpfaxi64dmac8b16",	(kernel_ulong_t)&nbpf_cfg[NBPF8B16]},
	{},
};
MODULE_DEVICE_TABLE(platform, nbpf_ids);

#ifdef CONFIG_PM
static int nbpf_runtime_suspend(struct device *dev)
{
	struct nbpf_device *nbpf = platform_get_drvdata(to_platform_device(dev));
	clk_disable_unprepare(nbpf->clk);
	return 0;
}

static int nbpf_runtime_resume(struct device *dev)
{
	struct nbpf_device *nbpf = platform_get_drvdata(to_platform_device(dev));
	return clk_prepare_enable(nbpf->clk);
}
#endif

static const struct dev_pm_ops nbpf_pm_ops = {
	SET_RUNTIME_PM_OPS(nbpf_runtime_suspend, nbpf_runtime_resume, NULL)
};

static struct platform_driver nbpf_driver = {
	.driver = {
		.name = "dma-nbpf",
		.of_match_table = nbpf_match,
		.pm = &nbpf_pm_ops,
	},
	.id_table = nbpf_ids,
	.probe = nbpf_probe,
	.remove = nbpf_remove,
};

module_platform_driver(nbpf_driver);

MODULE_AUTHOR("Guennadi Liakhovetski <g.liakhovetski@gmx.de>");
MODULE_DESCRIPTION("dmaengine driver for NBPFAXI64* DMACs");
MODULE_LICENSE("GPL v2");