aboutsummaryrefslogtreecommitdiff
path: root/sys/dev/sound/pci/hdspe-pcm.c
blob: e7fa0390459520b1f4039c3fc87b0c042e402d84 (plain) (blame)
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
/*-
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Copyright (c) 2012-2021 Ruslan Bukin <br@bsdpad.com>
 * Copyright (c) 2023-2024 Florian Walpen <dev@submerge.ch>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * RME HDSPe driver for FreeBSD (pcm-part).
 * Supported cards: AIO, RayDAT.
 */

#include <dev/sound/pcm/sound.h>
#include <dev/sound/pci/hdspe.h>

#include <dev/pci/pcireg.h>
#include <dev/pci/pcivar.h>

#include <mixer_if.h>

#define HDSPE_MATRIX_MAX	8

struct hdspe_latency {
	uint32_t n;
	uint32_t period;
	float ms;
};

static struct hdspe_latency latency_map[] = {
	{ 7,   32, 0.7 },
	{ 0,   64, 1.5 },
	{ 1,  128,   3 },
	{ 2,  256,   6 },
	{ 3,  512,  12 },
	{ 4, 1024,  23 },
	{ 5, 2048,  46 },
	{ 6, 4096,  93 },

	{ 0,    0,   0 },
};

struct hdspe_rate {
	uint32_t speed;
	uint32_t reg;
};

static struct hdspe_rate rate_map[] = {
	{  32000, (HDSPE_FREQ_32000) },
	{  44100, (HDSPE_FREQ_44100) },
	{  48000, (HDSPE_FREQ_48000) },
	{  64000, (HDSPE_FREQ_32000 | HDSPE_FREQ_DOUBLE) },
	{  88200, (HDSPE_FREQ_44100 | HDSPE_FREQ_DOUBLE) },
	{  96000, (HDSPE_FREQ_48000 | HDSPE_FREQ_DOUBLE) },
	{ 128000, (HDSPE_FREQ_32000 | HDSPE_FREQ_QUAD)   },
	{ 176400, (HDSPE_FREQ_44100 | HDSPE_FREQ_QUAD)   },
	{ 192000, (HDSPE_FREQ_48000 | HDSPE_FREQ_QUAD)   },

	{ 0, 0 },
};

static uint32_t
hdspe_channel_play_ports(struct hdspe_channel *hc)
{
	return (hc->ports & (HDSPE_CHAN_AIO_ALL | HDSPE_CHAN_RAY_ALL));
}

static uint32_t
hdspe_channel_rec_ports(struct hdspe_channel *hc)
{
	return (hc->ports & (HDSPE_CHAN_AIO_ALL_REC | HDSPE_CHAN_RAY_ALL));
}

static unsigned int
hdspe_adat_width(uint32_t speed)
{
	if (speed > 96000)
		return (2);
	if (speed > 48000)
		return (4);
	return (8);
}

static uint32_t
hdspe_port_first(uint32_t ports)
{
	return (ports & (~(ports - 1)));	/* Extract first bit set. */
}

static uint32_t
hdspe_port_first_row(uint32_t ports)
{
	uint32_t ends;

	/* Restrict ports to one set with contiguous slots. */
	if (ports & HDSPE_CHAN_AIO_LINE)
		ports = HDSPE_CHAN_AIO_LINE;	/* Gap in the AIO slots here. */
	else if (ports & HDSPE_CHAN_AIO_ALL)
		ports &= HDSPE_CHAN_AIO_ALL;	/* Rest of the AIO slots. */
	else if (ports & HDSPE_CHAN_RAY_ALL)
		ports &= HDSPE_CHAN_RAY_ALL;	/* All RayDAT slots. */

	/* Ends of port rows are followed by a port which is not in the set. */
	ends = ports & (~(ports >> 1));
	/* First row of contiguous ports ends in the first row end. */
	return (ports & (ends ^ (ends - 1)));
}

static unsigned int
hdspe_channel_count(uint32_t ports, uint32_t adat_width)
{
	unsigned int count = 0;

	if (ports & HDSPE_CHAN_AIO_ALL) {
		/* AIO ports. */
		if (ports & HDSPE_CHAN_AIO_LINE)
			count += 2;
		if (ports & HDSPE_CHAN_AIO_PHONE)
			count += 2;
		if (ports & HDSPE_CHAN_AIO_AES)
			count += 2;
		if (ports & HDSPE_CHAN_AIO_SPDIF)
			count += 2;
		if (ports & HDSPE_CHAN_AIO_ADAT)
			count += adat_width;
	} else if (ports & HDSPE_CHAN_RAY_ALL) {
		/* RayDAT ports. */
		if (ports & HDSPE_CHAN_RAY_AES)
			count += 2;
		if (ports & HDSPE_CHAN_RAY_SPDIF)
			count += 2;
		if (ports & HDSPE_CHAN_RAY_ADAT1)
			count += adat_width;
		if (ports & HDSPE_CHAN_RAY_ADAT2)
			count += adat_width;
		if (ports & HDSPE_CHAN_RAY_ADAT3)
			count += adat_width;
		if (ports & HDSPE_CHAN_RAY_ADAT4)
			count += adat_width;
	}

	return (count);
}

static unsigned int
hdspe_channel_offset(uint32_t subset, uint32_t ports, unsigned int adat_width)
{
	uint32_t preceding;

	/* Make sure we have a subset of ports. */
	subset &= ports;
	/* Include all ports preceding the first one of the subset. */
	preceding = ports & (~subset & (subset - 1));

	if (preceding & HDSPE_CHAN_AIO_ALL)
		preceding &= HDSPE_CHAN_AIO_ALL;	/* Contiguous AIO slots. */
	else if (preceding & HDSPE_CHAN_RAY_ALL)
		preceding &= HDSPE_CHAN_RAY_ALL;	/* Contiguous RayDAT slots. */

	return (hdspe_channel_count(preceding, adat_width));
}

static unsigned int
hdspe_port_slot_offset(uint32_t port, unsigned int adat_width)
{
	/* Exctract the first port (lowest bit) if set of ports. */
	switch (hdspe_port_first(port)) {
	/* AIO ports */
	case HDSPE_CHAN_AIO_LINE:
		return (0);
	case HDSPE_CHAN_AIO_PHONE:
		return (6);
	case HDSPE_CHAN_AIO_AES:
		return (8);
	case HDSPE_CHAN_AIO_SPDIF:
		return (10);
	case HDSPE_CHAN_AIO_ADAT:
		return (12);

	/* RayDAT ports */
	case HDSPE_CHAN_RAY_AES:
		return (0);
	case HDSPE_CHAN_RAY_SPDIF:
		return (2);
	case HDSPE_CHAN_RAY_ADAT1:
		return (4);
	case HDSPE_CHAN_RAY_ADAT2:
		return (4 + adat_width);
	case HDSPE_CHAN_RAY_ADAT3:
		return (4 + 2 * adat_width);
	case HDSPE_CHAN_RAY_ADAT4:
		return (4 + 3 * adat_width);
	default:
		return (0);
	}
}

static unsigned int
hdspe_port_slot_width(uint32_t ports, unsigned int adat_width)
{
	uint32_t row;

	/* Count number of contiguous slots from the first physical port. */
	row = hdspe_port_first_row(ports);
	return (hdspe_channel_count(row, adat_width));
}

static int
hdspe_hw_mixer(struct sc_chinfo *ch, unsigned int dst,
    unsigned int src, unsigned short data)
{
	struct sc_pcminfo *scp;
	struct sc_info *sc;
	int offs;

	scp = ch->parent;
	sc = scp->sc;

	offs = 0;
	if (ch->dir == PCMDIR_PLAY)
		offs = 64;

	hdspe_write_4(sc, HDSPE_MIXER_BASE +
	    ((offs + src + 128 * dst) * sizeof(uint32_t)),
	    data & 0xFFFF);

	return (0);
};

static int
hdspechan_setgain(struct sc_chinfo *ch)
{
	struct sc_info *sc;
	uint32_t port, ports;
	unsigned int slot, end_slot;
	unsigned short volume;

	sc = ch->parent->sc;

	/* Iterate through all physical ports of the channel. */
	ports = ch->ports;
	port = hdspe_port_first(ports);
	while (port != 0) {
		/* Get slot range of the physical port. */
		slot =
		    hdspe_port_slot_offset(port, hdspe_adat_width(sc->speed));
		end_slot = slot +
		    hdspe_port_slot_width(port, hdspe_adat_width(sc->speed));

		/* Treat first slot as left channel. */
		volume = ch->lvol * HDSPE_MAX_GAIN / 100;
		for (; slot < end_slot; slot++) {
			hdspe_hw_mixer(ch, slot, slot, volume);
			/* Subsequent slots all get the right channel volume. */
			volume = ch->rvol * HDSPE_MAX_GAIN / 100;
		}

		ports &= ~port;
		port = hdspe_port_first(ports);
	}

	return (0);
}

static int
hdspemixer_init(struct snd_mixer *m)
{
	struct sc_pcminfo *scp;
	struct sc_info *sc;
	int mask;

	scp = mix_getdevinfo(m);
	sc = scp->sc;
	if (sc == NULL)
		return (-1);

	mask = SOUND_MASK_PCM;

	if (hdspe_channel_play_ports(scp->hc))
		mask |= SOUND_MASK_VOLUME;

	if (hdspe_channel_rec_ports(scp->hc))
		mask |= SOUND_MASK_RECLEV;

	snd_mtxlock(sc->lock);
	pcm_setflags(scp->dev, pcm_getflags(scp->dev) | SD_F_SOFTPCMVOL);
	mix_setdevs(m, mask);
	snd_mtxunlock(sc->lock);

	return (0);
}

static int
hdspemixer_set(struct snd_mixer *m, unsigned dev,
    unsigned left, unsigned right)
{
	struct sc_pcminfo *scp;
	struct sc_chinfo *ch;
	int i;

	scp = mix_getdevinfo(m);

#if 0
	device_printf(scp->dev, "hdspemixer_set() %d %d\n",
	    left, right);
#endif

	for (i = 0; i < scp->chnum; i++) {
		ch = &scp->chan[i];
		if ((dev == SOUND_MIXER_VOLUME && ch->dir == PCMDIR_PLAY) ||
		    (dev == SOUND_MIXER_RECLEV && ch->dir == PCMDIR_REC)) {
			ch->lvol = left;
			ch->rvol = right;
			if (ch->run)
				hdspechan_setgain(ch);
		}
	}

	return (0);
}

static kobj_method_t hdspemixer_methods[] = {
	KOBJMETHOD(mixer_init,      hdspemixer_init),
	KOBJMETHOD(mixer_set,       hdspemixer_set),
	KOBJMETHOD_END
};
MIXER_DECLARE(hdspemixer);

static void
hdspechan_enable(struct sc_chinfo *ch, int value)
{
	struct sc_pcminfo *scp;
	struct sc_info *sc;
	uint32_t row, ports;
	int reg;
	unsigned int slot, end_slot;

	scp = ch->parent;
	sc = scp->sc;

	if (ch->dir == PCMDIR_PLAY)
		reg = HDSPE_OUT_ENABLE_BASE;
	else
		reg = HDSPE_IN_ENABLE_BASE;

	ch->run = value;

	/* Iterate through rows of ports with contiguous slots. */
	ports = ch->ports;
	row = hdspe_port_first_row(ports);
	while (row != 0) {
		slot =
		    hdspe_port_slot_offset(row, hdspe_adat_width(sc->speed));
		end_slot = slot +
		    hdspe_port_slot_width(row, hdspe_adat_width(sc->speed));

		for (; slot < end_slot; slot++) {
			hdspe_write_1(sc, reg + (4 * slot), value);
		}

		ports &= ~row;
		row = hdspe_port_first_row(ports);
	}
}

static int
hdspe_running(struct sc_info *sc)
{
	struct sc_pcminfo *scp;
	struct sc_chinfo *ch;
	device_t *devlist;
	int devcount;
	int i, j;
	int err;

	if ((err = device_get_children(sc->dev, &devlist, &devcount)) != 0)
		goto bad;

	for (i = 0; i < devcount; i++) {
		scp = device_get_ivars(devlist[i]);
		for (j = 0; j < scp->chnum; j++) {
			ch = &scp->chan[j];
			if (ch->run)
				goto bad;
		}
	}

	free(devlist, M_TEMP);

	return (0);
bad:

#if 0
	device_printf(sc->dev, "hdspe is running\n");
#endif

	free(devlist, M_TEMP);

	return (1);
}

static void
hdspe_start_audio(struct sc_info *sc)
{

	sc->ctrl_register |= (HDSPE_AUDIO_INT_ENABLE | HDSPE_ENABLE);
	hdspe_write_4(sc, HDSPE_CONTROL_REG, sc->ctrl_register);
}

static void
hdspe_stop_audio(struct sc_info *sc)
{

	if (hdspe_running(sc) == 1)
		return;

	sc->ctrl_register &= ~(HDSPE_AUDIO_INT_ENABLE | HDSPE_ENABLE);
	hdspe_write_4(sc, HDSPE_CONTROL_REG, sc->ctrl_register);
}

static void
buffer_mux_write(uint32_t *dma, uint32_t *pcm, unsigned int pos,
    unsigned int samples, unsigned int slots, unsigned int channels)
{
	int slot;

	for (; samples > 0; samples--) {
		for (slot = 0; slot < slots; slot++) {
			dma[slot * HDSPE_CHANBUF_SAMPLES + pos] =
			    pcm[pos * channels + slot];
		}
		pos = (pos + 1) % HDSPE_CHANBUF_SAMPLES;
	}
}

static void
buffer_mux_port(uint32_t *dma, uint32_t *pcm, uint32_t subset, uint32_t ports,
    unsigned int pos, unsigned int samples, unsigned int adat_width,
    unsigned int pcm_width)
{
	unsigned int slot_offset, slots;
	unsigned int channels, chan_pos;

	/* Translate DMA slot offset to DMA buffer offset. */
	slot_offset = hdspe_port_slot_offset(subset, adat_width);
	dma += slot_offset * HDSPE_CHANBUF_SAMPLES;

	/* Channel position of the port subset and total number of channels. */
	chan_pos = hdspe_channel_offset(subset, ports, pcm_width);
	pcm += chan_pos;
	channels = hdspe_channel_count(ports, pcm_width);

	/* Only copy as much as supported by both hardware and pcm channel. */
	slots = hdspe_port_slot_width(subset, MIN(adat_width, pcm_width));

	/* Let the compiler inline and loop unroll common cases. */
	if (slots == 2)
		buffer_mux_write(dma, pcm, pos, samples, 2, channels);
	else if (slots == 4)
		buffer_mux_write(dma, pcm, pos, samples, 4, channels);
	else if (slots == 8)
		buffer_mux_write(dma, pcm, pos, samples, 8, channels);
	else
		buffer_mux_write(dma, pcm, pos, samples, slots, channels);
}

static void
buffer_demux_read(uint32_t *dma, uint32_t *pcm, unsigned int pos,
    unsigned int samples, unsigned int slots, unsigned int channels)
{
	int slot;

	for (; samples > 0; samples--) {
		for (slot = 0; slot < slots; slot++) {
			pcm[pos * channels + slot] =
			    dma[slot * HDSPE_CHANBUF_SAMPLES + pos];
		}
		pos = (pos + 1) % HDSPE_CHANBUF_SAMPLES;
	}
}

static void
buffer_demux_port(uint32_t *dma, uint32_t *pcm, uint32_t subset, uint32_t ports,
    unsigned int pos, unsigned int samples, unsigned int adat_width,
    unsigned int pcm_width)
{
	unsigned int slot_offset, slots;
	unsigned int channels, chan_pos;

	/* Translate port slot offset to DMA buffer offset. */
	slot_offset = hdspe_port_slot_offset(subset, adat_width);
	dma += slot_offset * HDSPE_CHANBUF_SAMPLES;

	/* Channel position of the port subset and total number of channels. */
	chan_pos = hdspe_channel_offset(subset, ports, pcm_width);
	pcm += chan_pos;
	channels = hdspe_channel_count(ports, pcm_width);

	/* Only copy as much as supported by both hardware and pcm channel. */
	slots = hdspe_port_slot_width(subset, MIN(adat_width, pcm_width));

	/* Let the compiler inline and loop unroll common cases. */
	if (slots == 2)
		buffer_demux_read(dma, pcm, pos, samples, 2, channels);
	else if (slots == 4)
		buffer_demux_read(dma, pcm, pos, samples, 4, channels);
	else if (slots == 8)
		buffer_demux_read(dma, pcm, pos, samples, 8, channels);
	else
		buffer_demux_read(dma, pcm, pos, samples, slots, channels);
}


/* Copy data between DMA and PCM buffers. */
static void
buffer_copy(struct sc_chinfo *ch)
{
	struct sc_pcminfo *scp;
	struct sc_info *sc;
	uint32_t row, ports;
	uint32_t dma_pos;
	unsigned int pos, length, offset;
	unsigned int n;
	unsigned int adat_width, pcm_width;

	scp = ch->parent;
	sc = scp->sc;

	n = AFMT_CHANNEL(ch->format); /* n channels */

	/* Let pcm formats differ from current hardware ADAT width. */
	adat_width = hdspe_adat_width(sc->speed);
	if (n == hdspe_channel_count(ch->ports, 2))
		pcm_width = 2;
	else if (n == hdspe_channel_count(ch->ports, 4))
		pcm_width = 4;
	else
		pcm_width = 8;

	/* Derive buffer position and length to be copied. */
	if (ch->dir == PCMDIR_PLAY) {
		/* Position per channel is n times smaller than PCM. */
		pos = sndbuf_getreadyptr(ch->buffer) / n;
		length = sndbuf_getready(ch->buffer) / n;
		/* Copy no more than 2 periods in advance. */
		if (length > (sc->period * 4 * 2))
			length = (sc->period * 4 * 2);
		/* Skip what was already copied last time. */
		offset = (ch->position + HDSPE_CHANBUF_SIZE) - pos;
		offset %= HDSPE_CHANBUF_SIZE;
		if (offset <= length) {
			pos = (pos + offset) % HDSPE_CHANBUF_SIZE;
			length -= offset;
		}
	} else {
		/* Position per channel is n times smaller than PCM. */
		pos = sndbuf_getfreeptr(ch->buffer) / n;
		/* Get DMA buffer write position. */
		dma_pos = hdspe_read_2(sc, HDSPE_STATUS_REG);
		dma_pos &= HDSPE_BUF_POSITION_MASK;
		/* Copy what is newly available. */
		length = (dma_pos + HDSPE_CHANBUF_SIZE) - pos;
		length %= HDSPE_CHANBUF_SIZE;
	}

	/* Position and length in samples (4 bytes). */
	pos /= 4;
	length /= 4;

	/* Iterate through rows of ports with contiguous slots. */
	ports = ch->ports;
	if (pcm_width == adat_width)
		row = hdspe_port_first_row(ports);
	else
		row = hdspe_port_first(ports);

	while (row != 0) {
		if (ch->dir == PCMDIR_PLAY)
			buffer_mux_port(sc->pbuf, ch->data, row, ch->ports, pos,
			    length, adat_width, pcm_width);
		else
			buffer_demux_port(sc->rbuf, ch->data, row, ch->ports,
			    pos, length, adat_width, pcm_width);

		ports &= ~row;
		if (pcm_width == adat_width)
			row = hdspe_port_first_row(ports);
		else
			row = hdspe_port_first(ports);
	}

	ch->position = ((pos + length) * 4) % HDSPE_CHANBUF_SIZE;
}

static int
clean(struct sc_chinfo *ch)
{
	struct sc_pcminfo *scp;
	struct sc_info *sc;
	uint32_t *buf;
	uint32_t row, ports;
	unsigned int offset, slots;

	scp = ch->parent;
	sc = scp->sc;
	buf = sc->rbuf;

	if (ch->dir == PCMDIR_PLAY)
		buf = sc->pbuf;

	/* Iterate through rows of ports with contiguous slots. */
	ports = ch->ports;
	row = hdspe_port_first_row(ports);
	while (row != 0) {
		offset = hdspe_port_slot_offset(row,
		    hdspe_adat_width(sc->speed));
		slots = hdspe_port_slot_width(row, hdspe_adat_width(sc->speed));

		bzero(buf + offset * HDSPE_CHANBUF_SAMPLES,
		    slots * HDSPE_CHANBUF_SIZE);

		ports &= ~row;
		row = hdspe_port_first_row(ports);
	}

	ch->position = 0;

	return (0);
}

/* Channel interface. */
static void *
hdspechan_init(kobj_t obj, void *devinfo, struct snd_dbuf *b,
    struct pcm_channel *c, int dir)
{
	struct sc_pcminfo *scp;
	struct sc_chinfo *ch;
	struct sc_info *sc;
	int num;

	scp = devinfo;
	sc = scp->sc;

	snd_mtxlock(sc->lock);
	num = scp->chnum;

	ch = &scp->chan[num];

	if (dir == PCMDIR_PLAY)
		ch->ports = hdspe_channel_play_ports(scp->hc);
	else
		ch->ports = hdspe_channel_rec_ports(scp->hc);

	ch->run = 0;
	ch->lvol = 0;
	ch->rvol = 0;

	/* Support all possible ADAT widths as channel formats. */
	ch->cap_fmts[0] =
	    SND_FORMAT(AFMT_S32_LE, hdspe_channel_count(ch->ports, 2), 0);
	ch->cap_fmts[1] =
	    SND_FORMAT(AFMT_S32_LE, hdspe_channel_count(ch->ports, 4), 0);
	ch->cap_fmts[2] =
	    SND_FORMAT(AFMT_S32_LE, hdspe_channel_count(ch->ports, 8), 0);
	ch->cap_fmts[3] = 0;
	ch->caps = malloc(sizeof(struct pcmchan_caps), M_HDSPE, M_NOWAIT);
	*(ch->caps) = (struct pcmchan_caps) {32000, 192000, ch->cap_fmts, 0};

	/* Allocate maximum buffer size. */
	ch->size = HDSPE_CHANBUF_SIZE * hdspe_channel_count(ch->ports, 8);
	ch->data = malloc(ch->size, M_HDSPE, M_NOWAIT);
	ch->position = 0;

	ch->buffer = b;
	ch->channel = c;
	ch->parent = scp;

	ch->dir = dir;

	snd_mtxunlock(sc->lock);

	if (sndbuf_setup(ch->buffer, ch->data, ch->size) != 0) {
		device_printf(scp->dev, "Can't setup sndbuf.\n");
		return (NULL);
	}

	return (ch);
}

static int
hdspechan_trigger(kobj_t obj, void *data, int go)
{
	struct sc_pcminfo *scp;
	struct sc_chinfo *ch;
	struct sc_info *sc;

	ch = data;
	scp = ch->parent;
	sc = scp->sc;

	snd_mtxlock(sc->lock);
	switch (go) {
	case PCMTRIG_START:
#if 0
		device_printf(scp->dev, "hdspechan_trigger(): start\n");
#endif
		hdspechan_enable(ch, 1);
		hdspechan_setgain(ch);
		hdspe_start_audio(sc);
		break;

	case PCMTRIG_STOP:
	case PCMTRIG_ABORT:
#if 0
		device_printf(scp->dev, "hdspechan_trigger(): stop or abort\n");
#endif
		clean(ch);
		hdspechan_enable(ch, 0);
		hdspe_stop_audio(sc);
		break;

	case PCMTRIG_EMLDMAWR:
	case PCMTRIG_EMLDMARD:
		if(ch->run)
			buffer_copy(ch);
		break;
	}

	snd_mtxunlock(sc->lock);

	return (0);
}

static uint32_t
hdspechan_getptr(kobj_t obj, void *data)
{
	struct sc_pcminfo *scp;
	struct sc_chinfo *ch;
	struct sc_info *sc;
	uint32_t ret, pos;

	ch = data;
	scp = ch->parent;
	sc = scp->sc;

	snd_mtxlock(sc->lock);
	ret = hdspe_read_2(sc, HDSPE_STATUS_REG);
	snd_mtxunlock(sc->lock);

	pos = ret & HDSPE_BUF_POSITION_MASK;
	pos *= AFMT_CHANNEL(ch->format); /* Hardbuf with multiple channels. */

	return (pos);
}

static int
hdspechan_free(kobj_t obj, void *data)
{
	struct sc_pcminfo *scp;
	struct sc_chinfo *ch;
	struct sc_info *sc;

	ch = data;
	scp = ch->parent;
	sc = scp->sc;

#if 0
	device_printf(scp->dev, "hdspechan_free()\n");
#endif

	snd_mtxlock(sc->lock);
	if (ch->data != NULL) {
		free(ch->data, M_HDSPE);
		ch->data = NULL;
	}
	if (ch->caps != NULL) {
		free(ch->caps, M_HDSPE);
		ch->caps = NULL;
	}
	snd_mtxunlock(sc->lock);

	return (0);
}

static int
hdspechan_setformat(kobj_t obj, void *data, uint32_t format)
{
	struct sc_chinfo *ch;

	ch = data;

#if 0
	struct sc_pcminfo *scp = ch->parent;
	device_printf(scp->dev, "hdspechan_setformat(%d)\n", format);
#endif

	ch->format = format;

	return (0);
}

static uint32_t
hdspechan_setspeed(kobj_t obj, void *data, uint32_t speed)
{
	struct sc_pcminfo *scp;
	struct hdspe_rate *hr;
	struct sc_chinfo *ch;
	struct sc_info *sc;
	long long period;
	int threshold;
	int i;

	ch = data;
	scp = ch->parent;
	sc = scp->sc;
	hr = NULL;

#if 0
	device_printf(scp->dev, "hdspechan_setspeed(%d)\n", speed);
#endif

	if (hdspe_running(sc) == 1)
		goto end;

	if (sc->force_speed > 0)
		speed = sc->force_speed;

	/* First look for equal frequency. */
	for (i = 0; rate_map[i].speed != 0; i++) {
		if (rate_map[i].speed == speed)
			hr = &rate_map[i];
	}

	/* If no match, just find nearest. */
	if (hr == NULL) {
		for (i = 0; rate_map[i].speed != 0; i++) {
			hr = &rate_map[i];
			threshold = hr->speed + ((rate_map[i + 1].speed != 0) ?
			    ((rate_map[i + 1].speed - hr->speed) >> 1) : 0);
			if (speed < threshold)
				break;
		}
	}

	switch (sc->type) {
	case HDSPE_RAYDAT:
	case HDSPE_AIO:
		period = HDSPE_FREQ_AIO;
		break;
	default:
		/* Unsupported card. */
		goto end;
	}

	/* Write frequency on the device. */
	sc->ctrl_register &= ~HDSPE_FREQ_MASK;
	sc->ctrl_register |= hr->reg;
	hdspe_write_4(sc, HDSPE_CONTROL_REG, sc->ctrl_register);

	speed = hr->speed;
	if (speed > 96000)
		speed /= 4;
	else if (speed > 48000)
		speed /= 2;

	/* Set DDS value. */
	period /= speed;
	hdspe_write_4(sc, HDSPE_FREQ_REG, period);

	sc->speed = hr->speed;
end:

	return (sc->speed);
}

static uint32_t
hdspechan_setblocksize(kobj_t obj, void *data, uint32_t blocksize)
{
	struct hdspe_latency *hl;
	struct sc_pcminfo *scp;
	struct sc_chinfo *ch;
	struct sc_info *sc;
	int threshold;
	int i;

	ch = data;
	scp = ch->parent;
	sc = scp->sc;
	hl = NULL;

#if 0
	device_printf(scp->dev, "hdspechan_setblocksize(%d)\n", blocksize);
#endif

	if (hdspe_running(sc) == 1)
		goto end;

	if (blocksize > HDSPE_LAT_BYTES_MAX)
		blocksize = HDSPE_LAT_BYTES_MAX;
	else if (blocksize < HDSPE_LAT_BYTES_MIN)
		blocksize = HDSPE_LAT_BYTES_MIN;

	blocksize /= 4 /* samples */;

	if (sc->force_period > 0)
		blocksize = sc->force_period;

	/* First look for equal latency. */
	for (i = 0; latency_map[i].period != 0; i++) {
		if (latency_map[i].period == blocksize)
			hl = &latency_map[i];
	}

	/* If no match, just find nearest. */
	if (hl == NULL) {
		for (i = 0; latency_map[i].period != 0; i++) {
			hl = &latency_map[i];
			threshold = hl->period + ((latency_map[i + 1].period != 0) ?
			    ((latency_map[i + 1].period - hl->period) >> 1) : 0);
			if (blocksize < threshold)
				break;
		}
	}

	snd_mtxlock(sc->lock);
	sc->ctrl_register &= ~HDSPE_LAT_MASK;
	sc->ctrl_register |= hdspe_encode_latency(hl->n);
	hdspe_write_4(sc, HDSPE_CONTROL_REG, sc->ctrl_register);
	sc->period = hl->period;
	snd_mtxunlock(sc->lock);

#if 0
	device_printf(scp->dev, "New period=%d\n", sc->period);
#endif

	sndbuf_resize(ch->buffer,
	    (HDSPE_CHANBUF_SIZE * AFMT_CHANNEL(ch->format)) / (sc->period * 4),
	    (sc->period * 4));
end:

	return (sndbuf_getblksz(ch->buffer));
}

static uint32_t hdspe_bkp_fmt[] = {
	SND_FORMAT(AFMT_S32_LE, 2, 0),
	0
};

static struct pcmchan_caps hdspe_bkp_caps = {32000, 192000, hdspe_bkp_fmt, 0};

static struct pcmchan_caps *
hdspechan_getcaps(kobj_t obj, void *data)
{
	struct sc_chinfo *ch;

	ch = data;

#if 0
	struct sc_pcminfo *scl = ch->parent;
	device_printf(scp->dev, "hdspechan_getcaps()\n");
#endif

	if (ch->caps != NULL)
		return (ch->caps);

	return (&hdspe_bkp_caps);
}

static kobj_method_t hdspechan_methods[] = {
	KOBJMETHOD(channel_init,         hdspechan_init),
	KOBJMETHOD(channel_free,         hdspechan_free),
	KOBJMETHOD(channel_setformat,    hdspechan_setformat),
	KOBJMETHOD(channel_setspeed,     hdspechan_setspeed),
	KOBJMETHOD(channel_setblocksize, hdspechan_setblocksize),
	KOBJMETHOD(channel_trigger,      hdspechan_trigger),
	KOBJMETHOD(channel_getptr,       hdspechan_getptr),
	KOBJMETHOD(channel_getcaps,      hdspechan_getcaps),
	KOBJMETHOD_END
};
CHANNEL_DECLARE(hdspechan);

static int
hdspe_pcm_probe(device_t dev)
{

#if 0
	device_printf(dev,"hdspe_pcm_probe()\n");
#endif

	return (0);
}

static uint32_t
hdspe_pcm_intr(struct sc_pcminfo *scp)
{
	struct sc_chinfo *ch;
	struct sc_info *sc;
	int i;

	sc = scp->sc;

	for (i = 0; i < scp->chnum; i++) {
		ch = &scp->chan[i];
		snd_mtxunlock(sc->lock);
		chn_intr(ch->channel);
		snd_mtxlock(sc->lock);
	}

	return (0);
}

static int
hdspe_pcm_attach(device_t dev)
{
	char status[SND_STATUSLEN];
	struct sc_pcminfo *scp;
	const char *buf;
	uint32_t pcm_flags;
	int err;
	int play, rec;

	scp = device_get_ivars(dev);
	scp->ih = &hdspe_pcm_intr;

	if (scp->hc->ports & HDSPE_CHAN_AIO_ALL)
		buf = "AIO";
	else if (scp->hc->ports & HDSPE_CHAN_RAY_ALL)
		buf = "RayDAT";
	else
		buf = "?";
	device_set_descf(dev, "HDSPe %s [%s]", buf, scp->hc->descr);

	/*
	 * We don't register interrupt handler with snd_setup_intr
	 * in pcm device. Mark pcm device as MPSAFE manually.
	 */
	pcm_flags = pcm_getflags(dev) | SD_F_MPSAFE;
	if (hdspe_channel_count(scp->hc->ports, 8) > HDSPE_MATRIX_MAX)
		/* Disable vchan conversion, too many channels. */
		pcm_flags |= SD_F_BITPERFECT;
	pcm_setflags(dev, pcm_flags);

	play = (hdspe_channel_play_ports(scp->hc)) ? 1 : 0;
	rec = (hdspe_channel_rec_ports(scp->hc)) ? 1 : 0;
	err = pcm_register(dev, scp, play, rec);
	if (err) {
		device_printf(dev, "Can't register pcm.\n");
		return (ENXIO);
	}

	scp->chnum = 0;
	if (play) {
		pcm_addchan(dev, PCMDIR_PLAY, &hdspechan_class, scp);
		scp->chnum++;
	}

	if (rec) {
		pcm_addchan(dev, PCMDIR_REC, &hdspechan_class, scp);
		scp->chnum++;
	}

	snprintf(status, SND_STATUSLEN, "port 0x%jx irq %jd on %s",
	    rman_get_start(scp->sc->cs),
	    rman_get_start(scp->sc->irq),
	    device_get_nameunit(device_get_parent(dev)));
	pcm_setstatus(dev, status);

	mixer_init(dev, &hdspemixer_class, scp);

	return (0);
}

static int
hdspe_pcm_detach(device_t dev)
{
	int err;

	err = pcm_unregister(dev);
	if (err) {
		device_printf(dev, "Can't unregister device.\n");
		return (err);
	}

	return (0);
}

static device_method_t hdspe_pcm_methods[] = {
	DEVMETHOD(device_probe,     hdspe_pcm_probe),
	DEVMETHOD(device_attach,    hdspe_pcm_attach),
	DEVMETHOD(device_detach,    hdspe_pcm_detach),
	{ 0, 0 }
};

static driver_t hdspe_pcm_driver = {
	"pcm",
	hdspe_pcm_methods,
	PCM_SOFTC_SIZE,
};

DRIVER_MODULE(snd_hdspe_pcm, hdspe, hdspe_pcm_driver, 0, 0);
MODULE_DEPEND(snd_hdspe, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER);
MODULE_VERSION(snd_hdspe, 1);