summaryrefslogtreecommitdiffstats
path: root/drivers/block/xd.c
blob: ebf3025721d148866aeb0f5be68fbd4e6fdfb7ea (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
/*
 * This file contains the driver for an XT hard disk controller
 * (at least the DTC 5150X) for Linux.
 *
 * Author: Pat Mackinlay, pat@it.com.au
 * Date: 29/09/92
 * 
 * Revised: 01/01/93, ...
 *
 * Ref: DTC 5150X Controller Specification (thanks to Kevin Fowler,
 *   kevinf@agora.rain.com)
 * Also thanks to: Salvador Abreu, Dave Thaler, Risto Kankkunen and
 *   Wim Van Dorst.
 *
 * Revised: 04/04/94 by Risto Kankkunen
 *   Moved the detection code from xd_init() to xd_geninit() as it needed
 *   interrupts enabled and Linus didn't want to enable them in that first
 *   phase. xd_geninit() is the place to do these kinds of things anyway,
 *   he says.
 *
 * Modularized: 04/10/96 by Todd Fries, tfries@umr.edu
 *
 * Revised: 13/12/97 by Andrzej Krzysztofowicz, ankry@mif.pg.gda.pl
 *   Fixed some problems with disk initialization and module initiation.
 *   Added support for manual geometry setting (except Seagate controllers)
 *   in form:
 *      xd_geo=<cyl_xda>,<head_xda>,<sec_xda>[,<cyl_xdb>,<head_xdb>,<sec_xdb>]
 *   Recovered DMA access. Abridged messages. Added support for DTC5051CX,
 *   WD1002-27X & XEBEC controllers. Driver uses now some jumper settings.
 *   Extended ioctl() support.
 *
 * Bugfix: 15/02/01, Paul G. - inform queue layer of tiny xd_maxsect.
 *
 */

#include <linux/module.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/genhd.h>
#include <linux/hdreg.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/wait.h>
#include <linux/blkdev.h>
#include <linux/blkpg.h>
#include <linux/delay.h>

#include <asm/system.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/dma.h>

#include "xd.h"

static void __init do_xd_setup (int *integers);
#ifdef MODULE
static int xd[5] = { -1,-1,-1,-1, };
#endif

#define XD_DONT_USE_DMA		0  /* Initial value. may be overriden using
				      "nodma" module option */
#define XD_INIT_DISK_DELAY	(30)  /* 30 ms delay during disk initialization */

/* Above may need to be increased if a problem with the 2nd drive detection
   (ST11M controller) or resetting a controller (WD) appears */

static XD_INFO xd_info[XD_MAXDRIVES];

/* If you try this driver and find that your card is not detected by the driver at bootup, you need to add your BIOS
   signature and details to the following list of signatures. A BIOS signature is a string embedded into the first
   few bytes of your controller's on-board ROM BIOS. To find out what yours is, use something like MS-DOS's DEBUG
   command. Run DEBUG, and then you can examine your BIOS signature with:

	d xxxx:0000

   where xxxx is the segment of your controller (like C800 or D000 or something). On the ASCII dump at the right, you should
   be able to see a string mentioning the manufacturer's copyright etc. Add this string into the table below. The parameters
   in the table are, in order:

	offset			; this is the offset (in bytes) from the start of your ROM where the signature starts
	signature		; this is the actual text of the signature
	xd_?_init_controller	; this is the controller init routine used by your controller
	xd_?_init_drive		; this is the drive init routine used by your controller

   The controllers directly supported at the moment are: DTC 5150x, WD 1004A27X, ST11M/R and override. If your controller is
   made by the same manufacturer as one of these, try using the same init routines as they do. If that doesn't work, your
   best bet is to use the "override" routines. These routines use a "portable" method of getting the disk's geometry, and
   may work with your card. If none of these seem to work, try sending me some email and I'll see what I can do <grin>.

   NOTE: You can now specify your XT controller's parameters from the command line in the form xd=TYPE,IRQ,IO,DMA. The driver
   should be able to detect your drive's geometry from this info. (eg: xd=0,5,0x320,3 is the "standard"). */

#include <asm/page.h>
#define xd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL,get_order(size))
#define xd_dma_mem_free(addr, size) free_pages(addr, get_order(size))
static char *xd_dma_buffer;

static XD_SIGNATURE xd_sigs[] __initdata = {
	{ 0x0000,"Override geometry handler",NULL,xd_override_init_drive,"n unknown" }, /* Pat Mackinlay, pat@it.com.au */
	{ 0x0008,"[BXD06 (C) DTC 17-MAY-1985]",xd_dtc_init_controller,xd_dtc5150cx_init_drive," DTC 5150CX" }, /* Andrzej Krzysztofowicz, ankry@mif.pg.gda.pl */
	{ 0x000B,"CRD18A   Not an IBM rom. (C) Copyright Data Technology Corp. 05/31/88",xd_dtc_init_controller,xd_dtc_init_drive," DTC 5150X" }, /* Todd Fries, tfries@umr.edu */
	{ 0x000B,"CXD23A Not an IBM ROM (C)Copyright Data Technology Corp 12/03/88",xd_dtc_init_controller,xd_dtc_init_drive," DTC 5150X" }, /* Pat Mackinlay, pat@it.com.au */
	{ 0x0008,"07/15/86(C) Copyright 1986 Western Digital Corp.",xd_wd_init_controller,xd_wd_init_drive," Western Dig. 1002-27X" }, /* Andrzej Krzysztofowicz, ankry@mif.pg.gda.pl */
	{ 0x0008,"06/24/88(C) Copyright 1988 Western Digital Corp.",xd_wd_init_controller,xd_wd_init_drive," Western Dig. WDXT-GEN2" }, /* Dan Newcombe, newcombe@aa.csc.peachnet.edu */
	{ 0x0015,"SEAGATE ST11 BIOS REVISION",xd_seagate_init_controller,xd_seagate_init_drive," Seagate ST11M/R" }, /* Salvador Abreu, spa@fct.unl.pt */
	{ 0x0010,"ST11R BIOS",xd_seagate_init_controller,xd_seagate_init_drive," Seagate ST11M/R" }, /* Risto Kankkunen, risto.kankkunen@cs.helsinki.fi */
	{ 0x0010,"ST11 BIOS v1.7",xd_seagate_init_controller,xd_seagate_init_drive," Seagate ST11R" }, /* Alan Hourihane, alanh@fairlite.demon.co.uk */
	{ 0x1000,"(c)Copyright 1987 SMS",xd_omti_init_controller,xd_omti_init_drive,"n OMTI 5520" }, /* Dirk Melchers, dirk@merlin.nbg.sub.org */
	{ 0x0006,"COPYRIGHT XEBEC (C) 1984",xd_xebec_init_controller,xd_xebec_init_drive," XEBEC" }, /* Andrzej Krzysztofowicz, ankry@mif.pg.gda.pl */
	{ 0x0008,"(C) Copyright 1984 Western Digital Corp", xd_wd_init_controller, xd_wd_init_drive," Western Dig. 1002s-wx2" },
	{ 0x0008,"(C) Copyright 1986 Western Digital Corporation", xd_wd_init_controller, xd_wd_init_drive," 1986 Western Digital" }, /* jfree@sovereign.org */
};

static unsigned int xd_bases[] __initdata =
{
	0xC8000, 0xCA000, 0xCC000,
	0xCE000, 0xD0000, 0xD2000,
	0xD4000, 0xD6000, 0xD8000,
	0xDA000, 0xDC000, 0xDE000,
	0xE0000
};

static DEFINE_SPINLOCK(xd_lock);

static struct gendisk *xd_gendisk[2];

static int xd_getgeo(struct block_device *bdev, struct hd_geometry *geo);

static struct block_device_operations xd_fops = {
	.owner	= THIS_MODULE,
	.ioctl	= xd_ioctl,
	.getgeo = xd_getgeo,
};
static DECLARE_WAIT_QUEUE_HEAD(xd_wait_int);
static u_char xd_drives, xd_irq = 5, xd_dma = 3, xd_maxsectors;
static u_char xd_override __initdata = 0, xd_type __initdata = 0;
static u_short xd_iobase = 0x320;
static int xd_geo[XD_MAXDRIVES*3] __initdata = { 0, };

static volatile int xdc_busy;
static struct timer_list xd_watchdog_int;

static volatile u_char xd_error;
static int nodma = XD_DONT_USE_DMA;

static struct request_queue *xd_queue;

/* xd_init: register the block device number and set up pointer tables */
static int __init xd_init(void)
{
	u_char i,controller;
	unsigned int address;
	int err;

#ifdef MODULE
	{
		u_char count = 0;
		for (i = 4; i > 0; i--)
			if (((xd[i] = xd[i-1]) >= 0) && !count)
				count = i;
		if ((xd[0] = count))
			do_xd_setup(xd);
	}
#endif

	init_timer (&xd_watchdog_int); xd_watchdog_int.function = xd_watchdog;

	if (!xd_dma_buffer)
		xd_dma_buffer = (char *)xd_dma_mem_alloc(xd_maxsectors * 0x200);
	if (!xd_dma_buffer) {
		printk(KERN_ERR "xd: Out of memory.\n");
		return -ENOMEM;
	}

	err = -EBUSY;
	if (register_blkdev(XT_DISK_MAJOR, "xd"))
		goto out1;

	err = -ENOMEM;
	xd_queue = blk_init_queue(do_xd_request, &xd_lock);
	if (!xd_queue)
		goto out1a;

	if (xd_detect(&controller,&address)) {

		printk("Detected a%s controller (type %d) at address %06x\n",
			xd_sigs[controller].name,controller,address);
		if (!request_region(xd_iobase,4,"xd")) {
			printk("xd: Ports at 0x%x are not available\n",
				xd_iobase);
			goto out2;
		}
		if (controller)
			xd_sigs[controller].init_controller(address);
		xd_drives = xd_initdrives(xd_sigs[controller].init_drive);
		
		printk("Detected %d hard drive%s (using IRQ%d & DMA%d)\n",
			xd_drives,xd_drives == 1 ? "" : "s",xd_irq,xd_dma);
	}

	err = -ENODEV;
	if (!xd_drives)
		goto out3;

	for (i = 0; i < xd_drives; i++) {
		XD_INFO *p = &xd_info[i];
		struct gendisk *disk = alloc_disk(64);
		if (!disk)
			goto Enomem;
		p->unit = i;
		disk->major = XT_DISK_MAJOR;
		disk->first_minor = i<<6;
		sprintf(disk->disk_name, "xd%c", i+'a');
		disk->fops = &xd_fops;
		disk->private_data = p;
		disk->queue = xd_queue;
		set_capacity(disk, p->heads * p->cylinders * p->sectors);
		printk(" %s: CHS=%d/%d/%d\n", disk->disk_name,
			p->cylinders, p->heads, p->sectors);
		xd_gendisk[i] = disk;
	}

	err = -EBUSY;
	if (request_irq(xd_irq,xd_interrupt_handler, 0, "XT hard disk", NULL)) {
		printk("xd: unable to get IRQ%d\n",xd_irq);
		goto out4;
	}

	if (request_dma(xd_dma,"xd")) {
		printk("xd: unable to get DMA%d\n",xd_dma);
		goto out5;
	}

	/* xd_maxsectors depends on controller - so set after detection */
	blk_queue_max_sectors(xd_queue, xd_maxsectors);

	for (i = 0; i < xd_drives; i++)
		add_disk(xd_gendisk[i]);

	return 0;

out5:
	free_irq(xd_irq, NULL);
out4:
	for (i = 0; i < xd_drives; i++)
		put_disk(xd_gendisk[i]);
out3:
	release_region(xd_iobase,4);
out2:
	blk_cleanup_queue(xd_queue);
out1a:
	unregister_blkdev(XT_DISK_MAJOR, "xd");
out1:
	if (xd_dma_buffer)
		xd_dma_mem_free((unsigned long)xd_dma_buffer,
				xd_maxsectors * 0x200);
	return err;
Enomem:
	err = -ENOMEM;
	while (i--)
		put_disk(xd_gendisk[i]);
	goto out3;
}

/* xd_detect: scan the possible BIOS ROM locations for the signature strings */
static u_char __init xd_detect (u_char *controller, unsigned int *address)
{
	int i, j;

	if (xd_override)
	{
		*controller = xd_type;
		*address = 0;
		return(1);
	}

	for (i = 0; i < ARRAY_SIZE(xd_bases); i++) {
		void __iomem *p = ioremap(xd_bases[i], 0x2000);
		if (!p)
			continue;
		for (j = 1; j < ARRAY_SIZE(xd_sigs); j++) {
			const char *s = xd_sigs[j].string;
			if (check_signature(p + xd_sigs[j].offset, s, strlen(s))) {
				*controller = j;
				xd_type = j;
				*address = xd_bases[i];
				iounmap(p);
				return 1;
			}
		}
		iounmap(p);
	}
	return 0;
}

/* do_xd_request: handle an incoming request */
static void do_xd_request (request_queue_t * q)
{
	struct request *req;

	if (xdc_busy)
		return;

	while ((req = elv_next_request(q)) != NULL) {
		unsigned block = req->sector;
		unsigned count = req->nr_sectors;
		int rw = rq_data_dir(req);
		XD_INFO *disk = req->rq_disk->private_data;
		int res = 0;
		int retry;

		if (!blk_fs_request(req)) {
			end_request(req, 0);
			continue;
		}
		if (block + count > get_capacity(req->rq_disk)) {
			end_request(req, 0);
			continue;
		}
		if (rw != READ && rw != WRITE) {
			printk("do_xd_request: unknown request\n");
			end_request(req, 0);
			continue;
		}
		for (retry = 0; (retry < XD_RETRIES) && !res; retry++)
			res = xd_readwrite(rw, disk, req->buffer, block, count);
		end_request(req, res);	/* wrap up, 0 = fail, 1 = success */
	}
}

static int xd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
	XD_INFO *p = bdev->bd_disk->private_data;

	geo->heads = p->heads;
	geo->sectors = p->sectors;
	geo->cylinders = p->cylinders;
	return 0;
}

/* xd_ioctl: handle device ioctl's */
static int xd_ioctl (struct inode *inode,struct file *file,u_int cmd,u_long arg)
{
	switch (cmd) {
		case HDIO_SET_DMA:
			if (!capable(CAP_SYS_ADMIN)) return -EACCES;
			if (xdc_busy) return -EBUSY;
			nodma = !arg;
			if (nodma && xd_dma_buffer) {
				xd_dma_mem_free((unsigned long)xd_dma_buffer,
						xd_maxsectors * 0x200);
				xd_dma_buffer = NULL;
			} else if (!nodma && !xd_dma_buffer) {
				xd_dma_buffer = (char *)xd_dma_mem_alloc(xd_maxsectors * 0x200);
				if (!xd_dma_buffer) {
					nodma = XD_DONT_USE_DMA;
					return -ENOMEM;
				}
			}
			return 0;
		case HDIO_GET_DMA:
			return put_user(!nodma, (long __user *) arg);
		case HDIO_GET_MULTCOUNT:
			return put_user(xd_maxsectors, (long __user *) arg);
		default:
			return -EINVAL;
	}
}

/* xd_readwrite: handle a read/write request */
static int xd_readwrite (u_char operation,XD_INFO *p,char *buffer,u_int block,u_int count)
{
	int drive = p->unit;
	u_char cmdblk[6],sense[4];
	u_short track,cylinder;
	u_char head,sector,control,mode = PIO_MODE,temp;
	char **real_buffer;
	register int i;
	
#ifdef DEBUG_READWRITE
	printk("xd_readwrite: operation = %s, drive = %d, buffer = 0x%X, block = %d, count = %d\n",operation == READ ? "read" : "write",drive,buffer,block,count);
#endif /* DEBUG_READWRITE */

	spin_unlock_irq(&xd_lock);

	control = p->control;
	if (!xd_dma_buffer)
		xd_dma_buffer = (char *)xd_dma_mem_alloc(xd_maxsectors * 0x200);
	while (count) {
		temp = count < xd_maxsectors ? count : xd_maxsectors;

		track = block / p->sectors;
		head = track % p->heads;
		cylinder = track / p->heads;
		sector = block % p->sectors;

#ifdef DEBUG_READWRITE
		printk("xd_readwrite: drive = %d, head = %d, cylinder = %d, sector = %d, count = %d\n",drive,head,cylinder,sector,temp);
#endif /* DEBUG_READWRITE */

		if (xd_dma_buffer) {
			mode = xd_setup_dma(operation == READ ? DMA_MODE_READ : DMA_MODE_WRITE,(u_char *)(xd_dma_buffer),temp * 0x200);
			real_buffer = &xd_dma_buffer;
			for (i=0; i < (temp * 0x200); i++)
				xd_dma_buffer[i] = buffer[i];
		}
		else
			real_buffer = &buffer;

		xd_build(cmdblk,operation == READ ? CMD_READ : CMD_WRITE,drive,head,cylinder,sector,temp & 0xFF,control);

		switch (xd_command(cmdblk,mode,(u_char *)(*real_buffer),(u_char *)(*real_buffer),sense,XD_TIMEOUT)) {
			case 1:
				printk("xd%c: %s timeout, recalibrating drive\n",'a'+drive,(operation == READ ? "read" : "write"));
				xd_recalibrate(drive);
				spin_lock_irq(&xd_lock);
				return (0);
			case 2:
				if (sense[0] & 0x30) {
					printk("xd%c: %s - ",'a'+drive,(operation == READ ? "reading" : "writing"));
					switch ((sense[0] & 0x30) >> 4) {
					case 0: printk("drive error, code = 0x%X",sense[0] & 0x0F);
						break;
					case 1: printk("controller error, code = 0x%X",sense[0] & 0x0F);
						break;
					case 2: printk("command error, code = 0x%X",sense[0] & 0x0F);
						break;
					case 3: printk("miscellaneous error, code = 0x%X",sense[0] & 0x0F);
						break;
					}
				}
				if (sense[0] & 0x80)
					printk(" - CHS = %d/%d/%d\n",((sense[2] & 0xC0) << 2) | sense[3],sense[1] & 0x1F,sense[2] & 0x3F);
				/*	reported drive number = (sense[1] & 0xE0) >> 5 */
				else
					printk(" - no valid disk address\n");
				spin_lock_irq(&xd_lock);
				return (0);
		}
		if (xd_dma_buffer)
			for (i=0; i < (temp * 0x200); i++)
				buffer[i] = xd_dma_buffer[i];

		count -= temp, buffer += temp * 0x200, block += temp;
	}
	spin_lock_irq(&xd_lock);
	return (1);
}

/* xd_recalibrate: recalibrate a given drive and reset controller if necessary */
static void xd_recalibrate (u_char drive)
{
	u_char cmdblk[6];
	
	xd_build(cmdblk,CMD_RECALIBRATE,drive,0,0,0,0,0);
	if (xd_command(cmdblk,PIO_MODE,NULL,NULL,NULL,XD_TIMEOUT * 8))
		printk("xd%c: warning! error recalibrating, controller may be unstable\n", 'a'+drive);
}

/* xd_interrupt_handler: interrupt service routine */
static irqreturn_t xd_interrupt_handler(int irq, void *dev_id,
					struct pt_regs *regs)
{
	if (inb(XD_STATUS) & STAT_INTERRUPT) {							/* check if it was our device */
#ifdef DEBUG_OTHER
		printk("xd_interrupt_handler: interrupt detected\n");
#endif /* DEBUG_OTHER */
		outb(0,XD_CONTROL);								/* acknowledge interrupt */
		wake_up(&xd_wait_int);	/* and wake up sleeping processes */
		return IRQ_HANDLED;
	}
	else
		printk("xd: unexpected interrupt\n");
	return IRQ_NONE;
}

/* xd_setup_dma: set up the DMA controller for a data transfer */
static u_char xd_setup_dma (u_char mode,u_char *buffer,u_int count)
{
	unsigned long f;
	
	if (nodma)
		return (PIO_MODE);
	if (((unsigned long) buffer & 0xFFFF0000) != (((unsigned long) buffer + count) & 0xFFFF0000)) {
#ifdef DEBUG_OTHER
		printk("xd_setup_dma: using PIO, transfer overlaps 64k boundary\n");
#endif /* DEBUG_OTHER */
		return (PIO_MODE);
	}
	
	f=claim_dma_lock();
	disable_dma(xd_dma);
	clear_dma_ff(xd_dma);
	set_dma_mode(xd_dma,mode);
	set_dma_addr(xd_dma, (unsigned long) buffer);
	set_dma_count(xd_dma,count);
	
	release_dma_lock(f);

	return (DMA_MODE);			/* use DMA and INT */
}

/* xd_build: put stuff into an array in a format suitable for the controller */
static u_char *xd_build (u_char *cmdblk,u_char command,u_char drive,u_char head,u_short cylinder,u_char sector,u_char count,u_char control)
{
	cmdblk[0] = command;
	cmdblk[1] = ((drive & 0x07) << 5) | (head & 0x1F);
	cmdblk[2] = ((cylinder & 0x300) >> 2) | (sector & 0x3F);
	cmdblk[3] = cylinder & 0xFF;
	cmdblk[4] = count;
	cmdblk[5] = control;
	
	return (cmdblk);
}

static void xd_watchdog (unsigned long unused)
{
	xd_error = 1;
	wake_up(&xd_wait_int);
}

/* xd_waitport: waits until port & mask == flags or a timeout occurs. return 1 for a timeout */
static inline u_char xd_waitport (u_short port,u_char flags,u_char mask,u_long timeout)
{
	u_long expiry = jiffies + timeout;
	int success;

	xdc_busy = 1;
	while ((success = ((inb(port) & mask) != flags)) && time_before(jiffies, expiry))
		schedule_timeout_uninterruptible(1);
	xdc_busy = 0;
	return (success);
}

static inline u_int xd_wait_for_IRQ (void)
{
	unsigned long flags;
	xd_watchdog_int.expires = jiffies + 8 * HZ;
	add_timer(&xd_watchdog_int);
	
	flags=claim_dma_lock();
	enable_dma(xd_dma);
	release_dma_lock(flags);
	
	sleep_on(&xd_wait_int);
	del_timer(&xd_watchdog_int);
	xdc_busy = 0;
	
	flags=claim_dma_lock();
	disable_dma(xd_dma);
	release_dma_lock(flags);
	
	if (xd_error) {
		printk("xd: missed IRQ - command aborted\n");
		xd_error = 0;
		return (1);
	}
	return (0);
}

/* xd_command: handle all data transfers necessary for a single command */
static u_int xd_command (u_char *command,u_char mode,u_char *indata,u_char *outdata,u_char *sense,u_long timeout)
{
	u_char cmdblk[6],csb,complete = 0;

#ifdef DEBUG_COMMAND
	printk("xd_command: command = 0x%X, mode = 0x%X, indata = 0x%X, outdata = 0x%X, sense = 0x%X\n",command,mode,indata,outdata,sense);
#endif /* DEBUG_COMMAND */

	outb(0,XD_SELECT);
	outb(mode,XD_CONTROL);

	if (xd_waitport(XD_STATUS,STAT_SELECT,STAT_SELECT,timeout))
		return (1);

	while (!complete) {
		if (xd_waitport(XD_STATUS,STAT_READY,STAT_READY,timeout))
			return (1);

		switch (inb(XD_STATUS) & (STAT_COMMAND | STAT_INPUT)) {
			case 0:
				if (mode == DMA_MODE) {
					if (xd_wait_for_IRQ())
						return (1);
				} else
					outb(outdata ? *outdata++ : 0,XD_DATA);
				break;
			case STAT_INPUT:
				if (mode == DMA_MODE) {
					if (xd_wait_for_IRQ())
						return (1);
				} else
					if (indata)
						*indata++ = inb(XD_DATA);
					else
						inb(XD_DATA);
				break;
			case STAT_COMMAND:
				outb(command ? *command++ : 0,XD_DATA);
				break;
			case STAT_COMMAND | STAT_INPUT:
				complete = 1;
				break;
		}
	}
	csb = inb(XD_DATA);

	if (xd_waitport(XD_STATUS,0,STAT_SELECT,timeout))					/* wait until deselected */
		return (1);

	if (csb & CSB_ERROR) {									/* read sense data if error */
		xd_build(cmdblk,CMD_SENSE,(csb & CSB_LUN) >> 5,0,0,0,0,0);
		if (xd_command(cmdblk,0,sense,NULL,NULL,XD_TIMEOUT))
			printk("xd: warning! sense command failed!\n");
	}

#ifdef DEBUG_COMMAND
	printk("xd_command: completed with csb = 0x%X\n",csb);
#endif /* DEBUG_COMMAND */

	return (csb & CSB_ERROR);
}

static u_char __init xd_initdrives (void (*init_drive)(u_char drive))
{
	u_char cmdblk[6],i,count = 0;

	for (i = 0; i < XD_MAXDRIVES; i++) {
		xd_build(cmdblk,CMD_TESTREADY,i,0,0,0,0,0);
		if (!xd_command(cmdblk,PIO_MODE,NULL,NULL,NULL,XD_TIMEOUT*8)) {
			msleep_interruptible(XD_INIT_DISK_DELAY);

			init_drive(count);
			count++;

			msleep_interruptible(XD_INIT_DISK_DELAY);
		}
	}
	return (count);
}

static void __init xd_manual_geo_set (u_char drive)
{
	xd_info[drive].heads = (u_char)(xd_geo[3 * drive + 1]);
	xd_info[drive].cylinders = (u_short)(xd_geo[3 * drive]);
	xd_info[drive].sectors = (u_char)(xd_geo[3 * drive + 2]);
}

static void __init xd_dtc_init_controller (unsigned int address)
{
	switch (address) {
		case 0x00000:
		case 0xC8000:	break;			/*initial: 0x320 */
		case 0xCA000:	xd_iobase = 0x324; 
		case 0xD0000:				/*5150CX*/
		case 0xD8000:	break;			/*5150CX & 5150XL*/
		default:        printk("xd_dtc_init_controller: unsupported BIOS address %06x\n",address);
				break;
	}
	xd_maxsectors = 0x01;		/* my card seems to have trouble doing multi-block transfers? */

	outb(0,XD_RESET);		/* reset the controller */
}


static void __init xd_dtc5150cx_init_drive (u_char drive)
{
	/* values from controller's BIOS - BIOS chip may be removed */
	static u_short geometry_table[][4] = {
		{0x200,8,0x200,0x100},
		{0x267,2,0x267,0x267},
		{0x264,4,0x264,0x80},
		{0x132,4,0x132,0x0},
		{0x132,2,0x80, 0x132},
		{0x177,8,0x177,0x0},
		{0x132,8,0x84, 0x0},
		{},  /* not used */
		{0x132,6,0x80, 0x100},
		{0x200,6,0x100,0x100},
		{0x264,2,0x264,0x80},
		{0x280,4,0x280,0x100},
		{0x2B9,3,0x2B9,0x2B9},
		{0x2B9,5,0x2B9,0x2B9},
		{0x280,6,0x280,0x100},
		{0x132,4,0x132,0x0}};
	u_char n;

	n = inb(XD_JUMPER);
	n = (drive ? n : (n >> 2)) & 0x33;
	n = (n | (n >> 2)) & 0x0F;
	if (xd_geo[3*drive])
		xd_manual_geo_set(drive);
	else
		if (n != 7) {	
			xd_info[drive].heads = (u_char)(geometry_table[n][1]);			/* heads */
			xd_info[drive].cylinders = geometry_table[n][0];	/* cylinders */
			xd_info[drive].sectors = 17;				/* sectors */
#if 0
			xd_info[drive].rwrite = geometry_table[n][2];	/* reduced write */
			xd_info[drive].precomp = geometry_table[n][3]		/* write precomp */
			xd_info[drive].ecc = 0x0B;				/* ecc length */
#endif /* 0 */
		}
		else {
			printk("xd%c: undetermined drive geometry\n",'a'+drive);
			return;
		}
	xd_info[drive].control = 5;				/* control byte */
	xd_setparam(CMD_DTCSETPARAM,drive,xd_info[drive].heads,xd_info[drive].cylinders,geometry_table[n][2],geometry_table[n][3],0x0B);
	xd_recalibrate(drive);
}

static void __init xd_dtc_init_drive (u_char drive)
{
	u_char cmdblk[6],buf[64];

	xd_build(cmdblk,CMD_DTCGETGEOM,drive,0,0,0,0,0);
	if (!xd_command(cmdblk,PIO_MODE,buf,NULL,NULL,XD_TIMEOUT * 2)) {
		xd_info[drive].heads = buf[0x0A];			/* heads */
		xd_info[drive].cylinders = ((u_short *) (buf))[0x04];	/* cylinders */
		xd_info[drive].sectors = 17;				/* sectors */
		if (xd_geo[3*drive])
			xd_manual_geo_set(drive);
#if 0
		xd_info[drive].rwrite = ((u_short *) (buf + 1))[0x05];	/* reduced write */
		xd_info[drive].precomp = ((u_short *) (buf + 1))[0x06];	/* write precomp */
		xd_info[drive].ecc = buf[0x0F];				/* ecc length */
#endif /* 0 */
		xd_info[drive].control = 0;				/* control byte */

		xd_setparam(CMD_DTCSETPARAM,drive,xd_info[drive].heads,xd_info[drive].cylinders,((u_short *) (buf + 1))[0x05],((u_short *) (buf + 1))[0x06],buf[0x0F]);
		xd_build(cmdblk,CMD_DTCSETSTEP,drive,0,0,0,0,7);
		if (xd_command(cmdblk,PIO_MODE,NULL,NULL,NULL,XD_TIMEOUT * 2))
			printk("xd_dtc_init_drive: error setting step rate for xd%c\n", 'a'+drive);
	}
	else
		printk("xd_dtc_init_drive: error reading geometry for xd%c\n", 'a'+drive);
}

static void __init xd_wd_init_controller (unsigned int address)
{
	switch (address) {
		case 0x00000:
		case 0xC8000:	break;			/*initial: 0x320 */
		case 0xCA000:	xd_iobase = 0x324; break;
		case 0xCC000:   xd_iobase = 0x328; break;
		case 0xCE000:   xd_iobase = 0x32C; break;
		case 0xD0000:	xd_iobase = 0x328; break; /* ? */
		case 0xD8000:	xd_iobase = 0x32C; break; /* ? */
		default:        printk("xd_wd_init_controller: unsupported BIOS address %06x\n",address);
				break;
	}
	xd_maxsectors = 0x01;		/* this one doesn't wrap properly either... */

	outb(0,XD_RESET);		/* reset the controller */

	msleep(XD_INIT_DISK_DELAY);
}

static void __init xd_wd_init_drive (u_char drive)
{
	/* values from controller's BIOS - BIOS may be disabled */
	static u_short geometry_table[][4] = {
		{0x264,4,0x1C2,0x1C2},   /* common part */
		{0x132,4,0x099,0x0},
		{0x267,2,0x1C2,0x1C2},
		{0x267,4,0x1C2,0x1C2},

		{0x334,6,0x335,0x335},   /* 1004 series RLL */
		{0x30E,4,0x30F,0x3DC},
		{0x30E,2,0x30F,0x30F},
		{0x267,4,0x268,0x268},

		{0x3D5,5,0x3D6,0x3D6},   /* 1002 series RLL */
		{0x3DB,7,0x3DC,0x3DC},
		{0x264,4,0x265,0x265},
		{0x267,4,0x268,0x268}};

	u_char cmdblk[6],buf[0x200];
	u_char n = 0,rll,jumper_state,use_jumper_geo;
	u_char wd_1002 = (xd_sigs[xd_type].string[7] == '6');
	
	jumper_state = ~(inb(0x322));
	if (jumper_state & 0x40)
		xd_irq = 9;
	rll = (jumper_state & 0x30) ? (0x04 << wd_1002) : 0;
	xd_build(cmdblk,CMD_READ,drive,0,0,0,1,0);
	if (!xd_command(cmdblk,PIO_MODE,buf,NULL,NULL,XD_TIMEOUT * 2)) {
		xd_info[drive].heads = buf[0x1AF];				/* heads */
		xd_info[drive].cylinders = ((u_short *) (buf + 1))[0xD6];	/* cylinders */
		xd_info[drive].sectors = 17;					/* sectors */
		if (xd_geo[3*drive])
			xd_manual_geo_set(drive);
#if 0
		xd_info[drive].rwrite = ((u_short *) (buf))[0xD8];		/* reduced write */
		xd_info[drive].wprecomp = ((u_short *) (buf))[0xDA];		/* write precomp */
		xd_info[drive].ecc = buf[0x1B4];				/* ecc length */
#endif /* 0 */
		xd_info[drive].control = buf[0x1B5];				/* control byte */
		use_jumper_geo = !(xd_info[drive].heads) || !(xd_info[drive].cylinders);
		if (xd_geo[3*drive]) {
			xd_manual_geo_set(drive);
			xd_info[drive].control = rll ? 7 : 5;
		}
		else if (use_jumper_geo) {
			n = (((jumper_state & 0x0F) >> (drive << 1)) & 0x03) | rll;
			xd_info[drive].cylinders = geometry_table[n][0];
			xd_info[drive].heads = (u_char)(geometry_table[n][1]);
			xd_info[drive].control = rll ? 7 : 5;
#if 0
			xd_info[drive].rwrite = geometry_table[n][2];
			xd_info[drive].wprecomp = geometry_table[n][3];
			xd_info[drive].ecc = 0x0B;
#endif /* 0 */
		}
		if (!wd_1002) {
			if (use_jumper_geo)
				xd_setparam(CMD_WDSETPARAM,drive,xd_info[drive].heads,xd_info[drive].cylinders,
					geometry_table[n][2],geometry_table[n][3],0x0B);
			else
				xd_setparam(CMD_WDSETPARAM,drive,xd_info[drive].heads,xd_info[drive].cylinders,
					((u_short *) (buf))[0xD8],((u_short *) (buf))[0xDA],buf[0x1B4]);
		}
	/* 1002 based RLL controller requests converted addressing, but reports physical 
	   (physical 26 sec., logical 17 sec.) 
	   1004 based ???? */
		if (rll & wd_1002) {
			if ((xd_info[drive].cylinders *= 26,
			     xd_info[drive].cylinders /= 17) > 1023)
				xd_info[drive].cylinders = 1023;  /* 1024 ? */
#if 0
			xd_info[drive].rwrite *= 26; 
			xd_info[drive].rwrite /= 17;
			xd_info[drive].wprecomp *= 26
			xd_info[drive].wprecomp /= 17;
#endif /* 0 */
		}
	}
	else
		printk("xd_wd_init_drive: error reading geometry for xd%c\n",'a'+drive);	

}

static void __init xd_seagate_init_controller (unsigned int address)
{
	switch (address) {
		case 0x00000:
		case 0xC8000:	break;			/*initial: 0x320 */
		case 0xD0000:	xd_iobase = 0x324; break;
		case 0xD8000:	xd_iobase = 0x328; break;
		case 0xE0000:	xd_iobase = 0x32C; break;
		default:	printk("xd_seagate_init_controller: unsupported BIOS address %06x\n",address);
				break;
	}
	xd_maxsectors = 0x40;

	outb(0,XD_RESET);		/* reset the controller */
}

static void __init xd_seagate_init_drive (u_char drive)
{
	u_char cmdblk[6],buf[0x200];

	xd_build(cmdblk,CMD_ST11GETGEOM,drive,0,0,0,1,0);
	if (!xd_command(cmdblk,PIO_MODE,buf,NULL,NULL,XD_TIMEOUT * 2)) {
		xd_info[drive].heads = buf[0x04];				/* heads */
		xd_info[drive].cylinders = (buf[0x02] << 8) | buf[0x03];	/* cylinders */
		xd_info[drive].sectors = buf[0x05];				/* sectors */
		xd_info[drive].control = 0;					/* control byte */
	}
	else
		printk("xd_seagate_init_drive: error reading geometry from xd%c\n", 'a'+drive);
}

/* Omti support courtesy Dirk Melchers */
static void __init xd_omti_init_controller (unsigned int address)
{
	switch (address) {
		case 0x00000:
		case 0xC8000:	break;			/*initial: 0x320 */
		case 0xD0000:	xd_iobase = 0x324; break;
		case 0xD8000:	xd_iobase = 0x328; break;
		case 0xE0000:	xd_iobase = 0x32C; break;
		default:	printk("xd_omti_init_controller: unsupported BIOS address %06x\n",address);
				break;
	}
	
	xd_maxsectors = 0x40;

	outb(0,XD_RESET);		/* reset the controller */
}

static void __init xd_omti_init_drive (u_char drive)
{
	/* gets infos from drive */
	xd_override_init_drive(drive);

	/* set other parameters, Hardcoded, not that nice :-) */
	xd_info[drive].control = 2;
}

/* Xebec support (AK) */
static void __init xd_xebec_init_controller (unsigned int address)
{
/* iobase may be set manually in range 0x300 - 0x33C
      irq may be set manually to 2(9),3,4,5,6,7
      dma may be set manually to 1,2,3
	(How to detect them ???)
BIOS address may be set manually in range 0x0 - 0xF8000
If you need non-standard settings use the xd=... command */

	switch (address) {
		case 0x00000:
		case 0xC8000:	/* initially: xd_iobase==0x320 */
		case 0xD0000:
		case 0xD2000:
		case 0xD4000:
		case 0xD6000:
		case 0xD8000:
		case 0xDA000:
		case 0xDC000:
		case 0xDE000:
		case 0xE0000:	break;
		default:	printk("xd_xebec_init_controller: unsupported BIOS address %06x\n",address);
				break;
		}

	xd_maxsectors = 0x01;
	outb(0,XD_RESET);		/* reset the controller */

	msleep(XD_INIT_DISK_DELAY);
}

static void __init xd_xebec_init_drive (u_char drive)
{
	/* values from controller's BIOS - BIOS chip may be removed */
	static u_short geometry_table[][5] = {
		{0x132,4,0x080,0x080,0x7},
		{0x132,4,0x080,0x080,0x17},
		{0x264,2,0x100,0x100,0x7},
		{0x264,2,0x100,0x100,0x17},
		{0x132,8,0x080,0x080,0x7},
		{0x132,8,0x080,0x080,0x17},
		{0x264,4,0x100,0x100,0x6},
		{0x264,4,0x100,0x100,0x17},
		{0x2BC,5,0x2BC,0x12C,0x6},
		{0x3A5,4,0x3A5,0x3A5,0x7},
		{0x26C,6,0x26C,0x26C,0x7},
		{0x200,8,0x200,0x100,0x17},
		{0x400,5,0x400,0x400,0x7},
		{0x400,6,0x400,0x400,0x7},
		{0x264,8,0x264,0x200,0x17},
		{0x33E,7,0x33E,0x200,0x7}};
	u_char n;

	n = inb(XD_JUMPER) & 0x0F; /* BIOS's drive number: same geometry 
					is assumed for BOTH drives */
	if (xd_geo[3*drive])
		xd_manual_geo_set(drive);
	else {
		xd_info[drive].heads = (u_char)(geometry_table[n][1]);			/* heads */
		xd_info[drive].cylinders = geometry_table[n][0];	/* cylinders */
		xd_info[drive].sectors = 17;				/* sectors */
#if 0
		xd_info[drive].rwrite = geometry_table[n][2];	/* reduced write */
		xd_info[drive].precomp = geometry_table[n][3]		/* write precomp */
		xd_info[drive].ecc = 0x0B;				/* ecc length */
#endif /* 0 */
	}
	xd_info[drive].control = geometry_table[n][4];			/* control byte */
	xd_setparam(CMD_XBSETPARAM,drive,xd_info[drive].heads,xd_info[drive].cylinders,geometry_table[n][2],geometry_table[n][3],0x0B);
	xd_recalibrate(drive);
}

/* xd_override_init_drive: this finds disk geometry in a "binary search" style, narrowing in on the "correct" number of heads
   etc. by trying values until it gets the highest successful value. Idea courtesy Salvador Abreu (spa@fct.unl.pt). */
static void __init xd_override_init_drive (u_char drive)
{
	u_short min[] = { 0,0,0 },max[] = { 16,1024,64 },test[] = { 0,0,0 };
	u_char cmdblk[6],i;

	if (xd_geo[3*drive])
		xd_manual_geo_set(drive);
	else {
		for (i = 0; i < 3; i++) {
			while (min[i] != max[i] - 1) {
				test[i] = (min[i] + max[i]) / 2;
				xd_build(cmdblk,CMD_SEEK,drive,(u_char) test[0],(u_short) test[1],(u_char) test[2],0,0);
				if (!xd_command(cmdblk,PIO_MODE,NULL,NULL,NULL,XD_TIMEOUT * 2))
					min[i] = test[i];
				else
					max[i] = test[i];
			}
			test[i] = min[i];
		}
		xd_info[drive].heads = (u_char) min[0] + 1;
		xd_info[drive].cylinders = (u_short) min[1] + 1;
		xd_info[drive].sectors = (u_char) min[2] + 1;
	}
	xd_info[drive].control = 0;
}

/* xd_setup: initialise controller from command line parameters */
static void __init do_xd_setup (int *integers)
{
	switch (integers[0]) {
		case 4: if (integers[4] < 0)
				nodma = 1;
			else if (integers[4] < 8)
				xd_dma = integers[4];
		case 3: if ((integers[3] > 0) && (integers[3] <= 0x3FC))
				xd_iobase = integers[3];
		case 2: if ((integers[2] > 0) && (integers[2] < 16))
				xd_irq = integers[2];
		case 1: xd_override = 1;
			if ((integers[1] >= 0) && (integers[1] < ARRAY_SIZE(xd_sigs)))
				xd_type = integers[1];
		case 0: break;
		default:printk("xd: too many parameters for xd\n");
	}
	xd_maxsectors = 0x01;
}

/* xd_setparam: set the drive characteristics */
static void __init xd_setparam (u_char command,u_char drive,u_char heads,u_short cylinders,u_short rwrite,u_short wprecomp,u_char ecc)
{
	u_char cmdblk[14];

	xd_build(cmdblk,command,drive,0,0,0,0,0);
	cmdblk[6] = (u_char) (cylinders >> 8) & 0x03;
	cmdblk[7] = (u_char) (cylinders & 0xFF);
	cmdblk[8] = heads & 0x1F;
	cmdblk[9] = (u_char) (rwrite >> 8) & 0x03;
	cmdblk[10] = (u_char) (rwrite & 0xFF);
	cmdblk[11] = (u_char) (wprecomp >> 8) & 0x03;
	cmdblk[12] = (u_char) (wprecomp & 0xFF);
	cmdblk[13] = ecc;

	/* Some controllers require geometry info as data, not command */

	if (xd_command(cmdblk,PIO_MODE,NULL,&cmdblk[6],NULL,XD_TIMEOUT * 2))
		printk("xd: error setting characteristics for xd%c\n", 'a'+drive);
}


#ifdef MODULE

module_param_array(xd, int, NULL, 0);
module_param_array(xd_geo, int, NULL, 0);
module_param(nodma, bool, 0);

MODULE_LICENSE("GPL");

void cleanup_module(void)
{
	int i;
	unregister_blkdev(XT_DISK_MAJOR, "xd");
	for (i = 0; i < xd_drives; i++) {
		del_gendisk(xd_gendisk[i]);
		put_disk(xd_gendisk[i]);
	}
	blk_cleanup_queue(xd_queue);
	release_region(xd_iobase,4);
	if (xd_drives) {
		free_irq(xd_irq, NULL);
		free_dma(xd_dma);
		if (xd_dma_buffer)
			xd_dma_mem_free((unsigned long)xd_dma_buffer, xd_maxsectors * 0x200);
	}
}
#else

static int __init xd_setup (char *str)
{
	int ints[5];
	get_options (str, ARRAY_SIZE (ints), ints);
	do_xd_setup (ints);
	return 1;
}

/* xd_manual_geo_init: initialise drive geometry from command line parameters
   (used only for WD drives) */
static int __init xd_manual_geo_init (char *str)
{
	int i, integers[1 + 3*XD_MAXDRIVES];

	get_options (str, ARRAY_SIZE (integers), integers);
	if (integers[0]%3 != 0) {
		printk("xd: incorrect number of parameters for xd_geo\n");
		return 1;
	}
	for (i = 0; (i < integers[0]) && (i < 3*XD_MAXDRIVES); i++)
		xd_geo[i] = integers[i+1];
	return 1;
}

__setup ("xd=", xd_setup);
__setup ("xd_geo=", xd_manual_geo_init);

#endif /* MODULE */

module_init(xd_init);
MODULE_ALIAS_BLOCKDEV_MAJOR(XT_DISK_MAJOR);
a id='n5413' href='#n5413'>5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446
/*
 *	Crystal SoundFusion CS46xx driver
 *
 *	Copyright 1998-2001 Cirrus Logic Corporation <pcaudio@crystal.cirrus.com>
 *						<twoller@crystal.cirrus.com>
 *	Copyright 1999-2000 Jaroslav Kysela <perex@suse.cz>
 *	Copyright 2000 Alan Cox <alan@redhat.com>
 *
 *	The core of this code is taken from the ALSA project driver by 
 *	Jaroslav. Please send Jaroslav the credit for the driver and 
 *	report bugs in this port to <alan@redhat.com>
 *
 *	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; either version 2 of the License, or
 *	(at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *	Current maintainers:
 *		Cirrus Logic Corporation, Thomas Woller (tw)
 *			<twoller@crystal.cirrus.com>
 *		Nils Faerber (nf)
 *			<nils@kernelconcepts.de>
 *		Thanks to David Pollard for testing.
 *
 *	Changes:
 *	20000909-nf	Changed cs_read, cs_write and drain_dac
 *	20001025-tw	Separate Playback/Capture structs and buffers.
 *			Added Scatter/Gather support for Playback.
 *			Added Capture.
 *	20001027-nf	Port to kernel 2.4.0-test9, some clean-ups
 *			Start of powermanagement support (CS46XX_PM).
 *	20001128-tw	Add module parm for default buffer order.
 *			added DMA_GFP flag to kmalloc dma buffer allocs.
 *			backfill silence to eliminate stuttering on
 *			underruns.
 *	20001201-tw	add resyncing of swptr on underruns.
 *	20001205-tw-nf	fixed GETOSPACE ioctl() after open()
 *	20010113-tw	patch from Hans Grobler general cleanup.
 *	20010117-tw	2.4.0 pci cleanup, wrapper code for 2.2.16-2.4.0
 *	20010118-tw	basic PM support for 2.2.16+ and 2.4.0/2.4.2.
 *	20010228-dh	patch from David Huggins - cs_update_ptr recursion.
 *	20010409-tw	add hercules game theatre XP amp code.
 *	20010420-tw	cleanup powerdown/up code.
 *	20010521-tw	eliminate pops, and fixes for powerdown.
 *	20010525-tw	added fixes for thinkpads with powerdown logic.
 *	20010723-sh     patch from Horms (Simon Horman) -
 *	                SOUND_PCM_READ_BITS returns bits as set in driver
 *	                rather than a logical or of the possible values.
 *	                Various ioctls handle the case where the device
 *	                is open for reading or writing but not both better.
 *
 *	Status:
 *	Playback/Capture supported from 8k-48k.
 *	16Bit Signed LE & 8Bit Unsigned, with Mono or Stereo supported.
 *
 *	APM/PM - 2.2.x APM is enabled and functioning fine. APM can also
 *	be enabled for 2.4.x by modifying the CS46XX_ACPI_SUPPORT macro
 *	definition.
 *
 *      Hercules Game Theatre XP - the EGPIO2 pin controls the external Amp,
 *	so, use the drain/polarity to enable.  
 *	hercules_egpio_disable set to 1, will force a 0 to EGPIODR.
 *
 *	VTB Santa Cruz - the GPIO7/GPIO8 on the Secondary Codec control
 *	the external amplifier for the "back" speakers, since we do not
 *	support the secondary codec then this external amp is also not
 *	turned on.
 */
 
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/sound.h>
#include <linux/slab.h>
#include <linux/soundcard.h>
#include <linux/pci.h>
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/ac97_codec.h>
#include <linux/mutex.h>

#include <asm/io.h>
#include <asm/dma.h>
#include <asm/uaccess.h>

#include "cs46xxpm.h"
#include "cs46xx_wrapper-24.h"
#include "cs461x.h"

/* MIDI buffer sizes */
#define CS_MIDIINBUF  500
#define CS_MIDIOUTBUF 500

#define ADC_RUNNING	1
#define DAC_RUNNING	2

#define CS_FMT_16BIT	1		/* These are fixed in fact */
#define CS_FMT_STEREO	2
#define CS_FMT_MASK	3

#define CS_TYPE_ADC	1
#define CS_TYPE_DAC	2

#define CS_TRUE 	1
#define CS_FALSE 	0

#define CS_INC_USE_COUNT(m) (atomic_inc(m))
#define CS_DEC_USE_COUNT(m) (atomic_dec(m))
#define CS_DEC_AND_TEST(m) (atomic_dec_and_test(m))
#define CS_IN_USE(m) (atomic_read(m) != 0)

#define CS_DBGBREAKPOINT {__asm__("INT $3");}
/*
 *	CS461x definitions
 */
 
#define CS461X_BA0_SIZE		0x2000
#define CS461X_BA1_DATA0_SIZE	0x3000
#define CS461X_BA1_DATA1_SIZE	0x3800
#define CS461X_BA1_PRG_SIZE	0x7000
#define CS461X_BA1_REG_SIZE	0x0100

#define GOF_PER_SEC	200

#define CSDEBUG_INTERFACE 1
#define CSDEBUG 1
/*
 * Turn on/off debugging compilation by using 1/0 respectively for CSDEBUG
 *
 *
 * CSDEBUG is usual mode is set to 1, then use the
 * cs_debuglevel and cs_debugmask to turn on or off debugging.
 * Debug level of 1 has been defined to be kernel errors and info
 * that should be printed on any released driver.
 */
#if CSDEBUG
#define CS_DBGOUT(mask,level,x) if ((cs_debuglevel >= (level)) && ((mask) & cs_debugmask)) {x;}
#else
#define CS_DBGOUT(mask,level,x) 
#endif
/*
 * cs_debugmask areas
 */
#define CS_INIT	 	0x00000001		/* initialization and probe functions */
#define CS_ERROR 	0x00000002		/* tmp debugging bit placeholder */
#define CS_INTERRUPT	0x00000004		/* interrupt handler (separate from all other) */
#define CS_FUNCTION 	0x00000008		/* enter/leave functions */
#define CS_WAVE_WRITE 	0x00000010		/* write information for wave */
#define CS_WAVE_READ 	0x00000020		/* read information for wave */
#define CS_MIDI_WRITE 	0x00000040		/* write information for midi */
#define CS_MIDI_READ 	0x00000080		/* read information for midi */
#define CS_MPU401_WRITE 0x00000100		/* write information for mpu401 */
#define CS_MPU401_READ 	0x00000200		/* read information for mpu401 */
#define CS_OPEN		0x00000400		/* all open functions in the driver */
#define CS_RELEASE	0x00000800		/* all release functions in the driver */
#define CS_PARMS	0x00001000		/* functional and operational parameters */
#define CS_IOCTL	0x00002000		/* ioctl (non-mixer) */
#define CS_PM		0x00004000		/* PM */
#define CS_TMP		0x10000000		/* tmp debug mask bit */

#define CS_IOCTL_CMD_SUSPEND	0x1	// suspend
#define CS_IOCTL_CMD_RESUME	0x2	// resume

#if CSDEBUG
static unsigned long cs_debuglevel = 1;			/* levels range from 1-9 */
module_param(cs_debuglevel, ulong, 0644);
static unsigned long cs_debugmask = CS_INIT | CS_ERROR;	/* use CS_DBGOUT with various mask values */
module_param(cs_debugmask, ulong, 0644);
#endif
static unsigned long hercules_egpio_disable;  /* if non-zero set all EGPIO to 0 */
module_param(hercules_egpio_disable, ulong, 0);
static unsigned long initdelay = 700;  /* PM delay in millisecs */
module_param(initdelay, ulong, 0);
static unsigned long powerdown = -1;  /* turn on/off powerdown processing in driver */
module_param(powerdown, ulong, 0);
#define DMABUF_DEFAULTORDER 3
static unsigned long defaultorder = DMABUF_DEFAULTORDER;
module_param(defaultorder, ulong, 0);

static int external_amp;
module_param(external_amp, bool, 0);
static int thinkpad;
module_param(thinkpad, bool, 0);

/*
* set the powerdown module parm to 0 to disable all 
* powerdown. also set thinkpad to 1 to disable powerdown, 
* but also to enable the clkrun functionality.
*/
static unsigned cs_powerdown = 1;
static unsigned cs_laptop_wait = 1;

/* An instance of the 4610 channel */
struct cs_channel 
{
	int used;
	int num;
	void *state;
};

#define CS46XX_MAJOR_VERSION "1"
#define CS46XX_MINOR_VERSION "28"

#ifdef __ia64__
#define CS46XX_ARCH	     	"64"	//architecture key
#else
#define CS46XX_ARCH	     	"32"	//architecture key
#endif

static struct list_head cs46xx_devs = { &cs46xx_devs, &cs46xx_devs };

/* magic numbers to protect our data structures */
#define CS_CARD_MAGIC		0x43525553 /* "CRUS" */
#define CS_STATE_MAGIC		0x4c4f4749 /* "LOGI" */
#define NR_HW_CH		3

/* maxinum number of AC97 codecs connected, AC97 2.0 defined 4 */
#define NR_AC97		2

static const unsigned sample_size[] = { 1, 2, 2, 4 };
static const unsigned sample_shift[] = { 0, 1, 1, 2 };

/* "software" or virtual channel, an instance of opened /dev/dsp */
struct cs_state {
	unsigned int magic;
	struct cs_card *card;	/* Card info */

	/* single open lock mechanism, only used for recording */
	struct mutex open_mutex;
	wait_queue_head_t open_wait;

	/* file mode */
	mode_t open_mode;

	/* virtual channel number */
	int virt;
	
	struct dmabuf {
		/* wave sample stuff */
		unsigned int rate;
		unsigned char fmt, enable;

		/* hardware channel */
		struct cs_channel *channel;
		int pringbuf;		/* Software ring slot */
		void *pbuf;		/* 4K hardware DMA buffer */

		/* OSS buffer management stuff */
		void *rawbuf;
		dma_addr_t dma_handle;
		unsigned buforder;
		unsigned numfrag;
		unsigned fragshift;
		unsigned divisor;
		unsigned type;
		void *tmpbuff;			/* tmp buffer for sample conversions */
		dma_addr_t dmaaddr;
		dma_addr_t dmaaddr_tmpbuff;
		unsigned buforder_tmpbuff;	/* Log base 2 of size in bytes.. */

		/* our buffer acts like a circular ring */
		unsigned hwptr;		/* where dma last started, updated by update_ptr */
		unsigned swptr;		/* where driver last clear/filled, updated by read/write */
		int count;		/* bytes to be comsumed or been generated by dma machine */
		unsigned total_bytes;	/* total bytes dmaed by hardware */
		unsigned blocks;	/* total blocks */

		unsigned error;		/* number of over/underruns */
		unsigned underrun;	/* underrun pending before next write has occurred */
		wait_queue_head_t wait;	/* put process on wait queue when no more space in buffer */

		/* redundant, but makes calculations easier */
		unsigned fragsize;
		unsigned dmasize;
		unsigned fragsamples;

		/* OSS stuff */
		unsigned mapped:1;
		unsigned ready:1;
		unsigned endcleared:1;
		unsigned SGok:1;
		unsigned update_flag;
		unsigned ossfragshift;
		int ossmaxfrags;
		unsigned subdivision;
	} dmabuf;
	/* Guard against mmap/write/read races */
	struct mutex sem;
};

struct cs_card {
	struct cs_channel channel[2];
	unsigned int magic;

	/* We keep cs461x cards in a linked list */
	struct cs_card *next;

	/* The cs461x has a certain amount of cross channel interaction
	   so we use a single per card lock */
	spinlock_t lock;
	
	/* Keep AC97 sane */
	spinlock_t ac97_lock;

	/* mixer use count */
	atomic_t mixer_use_cnt;

	/* PCI device stuff */
	struct pci_dev *pci_dev;
	struct list_head list;

	unsigned int pctl, cctl;	/* Hardware DMA flag sets */

	/* soundcore stuff */
	int dev_audio;
	int dev_midi;

	/* structures for abstraction of hardware facilities, codecs, banks and channels*/
	struct ac97_codec *ac97_codec[NR_AC97];
	struct cs_state *states[2];

	u16 ac97_features;
	
	int amplifier;			/* Amplifier control */
	void (*amplifier_ctrl)(struct cs_card *, int);
	void (*amp_init)(struct cs_card *);
	
	int active;			/* Active clocking */
	void (*active_ctrl)(struct cs_card *, int);
	
	/* hardware resources */
	unsigned long ba0_addr;
	unsigned long ba1_addr;
	u32 irq;
	
	/* mappings */
	void __iomem *ba0;
	union
	{
		struct
		{
			u8 __iomem *data0;
			u8 __iomem *data1;
			u8 __iomem *pmem;
			u8 __iomem *reg;
		} name;
		u8 __iomem *idx[4];
	} ba1;
	
	/* Function support */
	struct cs_channel *(*alloc_pcm_channel)(struct cs_card *);
	struct cs_channel *(*alloc_rec_pcm_channel)(struct cs_card *);
	void (*free_pcm_channel)(struct cs_card *, int chan);

	/* /dev/midi stuff */
	struct {
		unsigned ird, iwr, icnt;
		unsigned ord, owr, ocnt;
		wait_queue_head_t open_wait;
		wait_queue_head_t iwait;
		wait_queue_head_t owait;
		spinlock_t lock;
		unsigned char ibuf[CS_MIDIINBUF];
		unsigned char obuf[CS_MIDIOUTBUF];
		mode_t open_mode;
		struct mutex open_mutex;
	} midi;
	struct cs46xx_pm pm;
};

static int cs_open_mixdev(struct inode *inode, struct file *file);
static int cs_release_mixdev(struct inode *inode, struct file *file);
static int cs_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd,
			unsigned long arg);
static int cs_hardware_init(struct cs_card *card);
static int cs46xx_powerup(struct cs_card *card, unsigned int type);
static int cs461x_powerdown(struct cs_card *card, unsigned int type, int suspendflag);
static void cs461x_clear_serial_FIFOs(struct cs_card *card, int type);
#ifdef CONFIG_PM
static int cs46xx_suspend_tbl(struct pci_dev *pcidev, pm_message_t state);
static int cs46xx_resume_tbl(struct pci_dev *pcidev);
#endif

#if CSDEBUG

/* DEBUG ROUTINES */

#define SOUND_MIXER_CS_GETDBGLEVEL 	_SIOWR('M',120, int)
#define SOUND_MIXER_CS_SETDBGLEVEL 	_SIOWR('M',121, int)
#define SOUND_MIXER_CS_GETDBGMASK 	_SIOWR('M',122, int)
#define SOUND_MIXER_CS_SETDBGMASK 	_SIOWR('M',123, int)
#define SOUND_MIXER_CS_APM	 	_SIOWR('M',124, int)

static void printioctl(unsigned int x)
{
    unsigned int i;
    unsigned char vidx;
	/* these values are incorrect for the ac97 driver, fix.
         * Index of mixtable1[] member is Device ID 
         * and must be <= SOUND_MIXER_NRDEVICES.
         * Value of array member is index into s->mix.vol[]
         */
        static const unsigned char mixtable1[SOUND_MIXER_NRDEVICES] = {
                [SOUND_MIXER_PCM]     = 1,   /* voice */
                [SOUND_MIXER_LINE1]   = 2,   /* AUX */
                [SOUND_MIXER_CD]      = 3,   /* CD */
                [SOUND_MIXER_LINE]    = 4,   /* Line */
                [SOUND_MIXER_SYNTH]   = 5,   /* FM */
                [SOUND_MIXER_MIC]     = 6,   /* Mic */
                [SOUND_MIXER_SPEAKER] = 7,   /* Speaker */
                [SOUND_MIXER_RECLEV]  = 8,   /* Recording level */
                [SOUND_MIXER_VOLUME]  = 9    /* Master Volume */
        };
        
    switch (x) {
	case SOUND_MIXER_CS_GETDBGMASK:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_GETDBGMASK: ") );
		break;
	case SOUND_MIXER_CS_GETDBGLEVEL:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_GETDBGLEVEL: ") );
		break;
	case SOUND_MIXER_CS_SETDBGMASK:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_SETDBGMASK: ") );
		break;
	case SOUND_MIXER_CS_SETDBGLEVEL:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_SETDBGLEVEL: ") );
		break;
        case OSS_GETVERSION:
		CS_DBGOUT(CS_IOCTL, 4, printk("OSS_GETVERSION: ") );
		break;
        case SNDCTL_DSP_SYNC:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SYNC: ") );
		break;
        case SNDCTL_DSP_SETDUPLEX:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETDUPLEX: ") );
		break;
        case SNDCTL_DSP_GETCAPS:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETCAPS: ") );
		break;
        case SNDCTL_DSP_RESET:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_RESET: ") );
		break;
        case SNDCTL_DSP_SPEED:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SPEED: ") );
		break;
        case SNDCTL_DSP_STEREO:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_STEREO: ") );
		break;
        case SNDCTL_DSP_CHANNELS:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_CHANNELS: ") );
		break;
        case SNDCTL_DSP_GETFMTS: 
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETFMTS: ") );
		break;
        case SNDCTL_DSP_SETFMT: 
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETFMT: ") );
		break;
        case SNDCTL_DSP_POST:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_POST: ") );
		break;
        case SNDCTL_DSP_GETTRIGGER:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETTRIGGER: ") );
		break;
        case SNDCTL_DSP_SETTRIGGER:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETTRIGGER: ") );
		break;
        case SNDCTL_DSP_GETOSPACE:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETOSPACE: ") );
		break;
        case SNDCTL_DSP_GETISPACE:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETISPACE: ") );
		break;
        case SNDCTL_DSP_NONBLOCK:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_NONBLOCK: ") );
		break;
        case SNDCTL_DSP_GETODELAY:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETODELAY: ") );
		break;
        case SNDCTL_DSP_GETIPTR:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETIPTR: ") );
		break;
        case SNDCTL_DSP_GETOPTR:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETOPTR: ") );
		break;
        case SNDCTL_DSP_GETBLKSIZE:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETBLKSIZE: ") );
		break;
        case SNDCTL_DSP_SETFRAGMENT:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETFRAGMENT: ") );
		break;
        case SNDCTL_DSP_SUBDIVIDE:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SUBDIVIDE: ") );
		break;
        case SOUND_PCM_READ_RATE:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_RATE: ") );
		break;
        case SOUND_PCM_READ_CHANNELS:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_CHANNELS: ") );
		break;
        case SOUND_PCM_READ_BITS:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_BITS: ") );
		break;
        case SOUND_PCM_WRITE_FILTER:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_WRITE_FILTER: ") );
		break;
        case SNDCTL_DSP_SETSYNCRO:
		CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETSYNCRO: ") );
		break;
        case SOUND_PCM_READ_FILTER:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_FILTER: ") );
		break;
        case SOUND_MIXER_PRIVATE1:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE1: ") );
		break;
        case SOUND_MIXER_PRIVATE2:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE2: ") );
		break;
        case SOUND_MIXER_PRIVATE3:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE3: ") );
		break;
        case SOUND_MIXER_PRIVATE4:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE4: ") );
		break;
        case SOUND_MIXER_PRIVATE5:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE5: ") );
		break;
        case SOUND_MIXER_INFO:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_INFO: ") );
		break;
        case SOUND_OLD_MIXER_INFO:
		CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_OLD_MIXER_INFO: ") );
		break;
	default:
		switch (_IOC_NR(x)) {
			case SOUND_MIXER_VOLUME:
				CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_VOLUME: ") );
				break;
			case SOUND_MIXER_SPEAKER:
				CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_SPEAKER: ") );
				break;
			case SOUND_MIXER_RECLEV:
				CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_RECLEV: ") );
				break;
			case SOUND_MIXER_MIC:
				CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_MIC: ") );
				break;
			case SOUND_MIXER_SYNTH:
				CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_SYNTH: ") );
				break;
			case SOUND_MIXER_RECSRC: 
				CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_RECSRC: ") );
				break;
			case SOUND_MIXER_DEVMASK:
				CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_DEVMASK: ") );
				break;
			case SOUND_MIXER_RECMASK:
				CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_RECMASK: ") );
				break;
			case SOUND_MIXER_STEREODEVS: 
				CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_STEREODEVS: ") );
				break;
			case SOUND_MIXER_CAPS:
				CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CAPS:") );
				break;
			default:
				i = _IOC_NR(x);
				if (i >= SOUND_MIXER_NRDEVICES || !(vidx = mixtable1[i])) {
					CS_DBGOUT(CS_IOCTL, 4, printk("UNKNOWN IOCTL: 0x%.8x NR=%d ",x,i) );
				} else {
					CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_IOCTL AC9x: 0x%.8x NR=%d ",
							x,i));
				}
				break;
		}
    }
    CS_DBGOUT(CS_IOCTL, 4, printk("command = 0x%x IOC_NR=%d\n",x, _IOC_NR(x)) );
}
#endif

/*
 *  common I/O routines
 */

static void cs461x_poke(struct cs_card *codec, unsigned long reg, unsigned int val)
{
	writel(val, codec->ba1.idx[(reg >> 16) & 3] + (reg & 0xffff));
}

static unsigned int cs461x_peek(struct cs_card *codec, unsigned long reg)
{
	return readl(codec->ba1.idx[(reg >> 16) & 3] + (reg & 0xffff));
}

static void cs461x_pokeBA0(struct cs_card *codec, unsigned long reg, unsigned int val)
{
	writel(val, codec->ba0 + reg);
}

static unsigned int cs461x_peekBA0(struct cs_card *codec, unsigned long reg)
{
	return readl(codec->ba0 + reg);
}


static u16 cs_ac97_get(struct ac97_codec *dev, u8 reg);
static void cs_ac97_set(struct ac97_codec *dev, u8 reg, u16 data);

static struct cs_channel *cs_alloc_pcm_channel(struct cs_card *card)
{
	if (card->channel[1].used == 1)
		return NULL;
	card->channel[1].used = 1;
	card->channel[1].num = 1;
	return &card->channel[1];
}

static struct cs_channel *cs_alloc_rec_pcm_channel(struct cs_card *card)
{
	if (card->channel[0].used == 1)
		return NULL;
	card->channel[0].used = 1;
	card->channel[0].num = 0;
	return &card->channel[0];
}

static void cs_free_pcm_channel(struct cs_card *card, int channel)
{
	card->channel[channel].state = NULL;
	card->channel[channel].used = 0;
}

/*
 * setup a divisor value to help with conversion from
 * 16bit Stereo, down to 8bit stereo/mono or 16bit mono.
 * assign a divisor of 1 if using 16bit Stereo as that is
 * the only format that the static image will capture.
 */
static void cs_set_divisor(struct dmabuf *dmabuf)
{
	if (dmabuf->type == CS_TYPE_DAC)
		dmabuf->divisor = 1;
	else if (!(dmabuf->fmt & CS_FMT_STEREO) &&
	    (dmabuf->fmt & CS_FMT_16BIT))
		dmabuf->divisor = 2;
	else if ((dmabuf->fmt & CS_FMT_STEREO) &&
	    !(dmabuf->fmt & CS_FMT_16BIT))
		dmabuf->divisor = 2;
	else if (!(dmabuf->fmt & CS_FMT_STEREO) &&
	    !(dmabuf->fmt & CS_FMT_16BIT))
		dmabuf->divisor = 4;
	else
		dmabuf->divisor = 1;

	CS_DBGOUT(CS_PARMS | CS_FUNCTION, 8, printk(
		"cs46xx: cs_set_divisor()- %s %d\n",
			(dmabuf->type == CS_TYPE_ADC) ? "ADC" : "DAC", 
			dmabuf->divisor) );
}

/*
* mute some of the more prevalent registers to avoid popping.
*/
static void cs_mute(struct cs_card *card, int state) 
{
	struct ac97_codec *dev = card->ac97_codec[0];

	CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO "cs46xx: cs_mute()+ %s\n",
		(state == CS_TRUE) ? "Muting" : "UnMuting"));

	if (state == CS_TRUE) {
	/*
	* fix pops when powering up on thinkpads
	*/
		card->pm.u32AC97_master_volume = (u32)cs_ac97_get( dev, 
				(u8)BA0_AC97_MASTER_VOLUME); 
		card->pm.u32AC97_headphone_volume = (u32)cs_ac97_get(dev, 
				(u8)BA0_AC97_HEADPHONE_VOLUME); 
		card->pm.u32AC97_master_volume_mono = (u32)cs_ac97_get(dev, 
				(u8)BA0_AC97_MASTER_VOLUME_MONO); 
		card->pm.u32AC97_pcm_out_volume = (u32)cs_ac97_get(dev, 
				(u8)BA0_AC97_PCM_OUT_VOLUME);
			
		cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME, 0x8000);
		cs_ac97_set(dev, (u8)BA0_AC97_HEADPHONE_VOLUME, 0x8000);
		cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME_MONO, 0x8000);
		cs_ac97_set(dev, (u8)BA0_AC97_PCM_OUT_VOLUME, 0x8000);
	} else {
		cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME, card->pm.u32AC97_master_volume);
		cs_ac97_set(dev, (u8)BA0_AC97_HEADPHONE_VOLUME, card->pm.u32AC97_headphone_volume);
		cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME_MONO, card->pm.u32AC97_master_volume_mono);
		cs_ac97_set(dev, (u8)BA0_AC97_PCM_OUT_VOLUME, card->pm.u32AC97_pcm_out_volume);
	}
	CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO "cs46xx: cs_mute()-\n"));
}

/* set playback sample rate */
static unsigned int cs_set_dac_rate(struct cs_state * state, unsigned int rate)
{	
	struct dmabuf *dmabuf = &state->dmabuf;
	unsigned int tmp1, tmp2;
	unsigned int phiIncr;
	unsigned int correctionPerGOF, correctionPerSec;
	unsigned long flags;

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_dac_rate()+ %d\n",rate) );

	/*
	 *  Compute the values used to drive the actual sample rate conversion.
	 *  The following formulas are being computed, using inline assembly
	 *  since we need to use 64 bit arithmetic to compute the values:
	 *
	 *  phiIncr = floor((Fs,in * 2^26) / Fs,out)
	 *  correctionPerGOF = floor((Fs,in * 2^26 - Fs,out * phiIncr) /
         *                                   GOF_PER_SEC)
         *  ulCorrectionPerSec = Fs,in * 2^26 - Fs,out * phiIncr -M
         *                       GOF_PER_SEC * correctionPerGOF
	 *
	 *  i.e.
	 *
	 *  phiIncr:other = dividend:remainder((Fs,in * 2^26) / Fs,out)
	 *  correctionPerGOF:correctionPerSec =
	 *      dividend:remainder(ulOther / GOF_PER_SEC)
	 */
	tmp1 = rate << 16;
	phiIncr = tmp1 / 48000;
	tmp1 -= phiIncr * 48000;
	tmp1 <<= 10;
	phiIncr <<= 10;
	tmp2 = tmp1 / 48000;
	phiIncr += tmp2;
	tmp1 -= tmp2 * 48000;
	correctionPerGOF = tmp1 / GOF_PER_SEC;
	tmp1 -= correctionPerGOF * GOF_PER_SEC;
	correctionPerSec = tmp1;

	/*
	 *  Fill in the SampleRateConverter control block.
	 */
	spin_lock_irqsave(&state->card->lock, flags);
	cs461x_poke(state->card, BA1_PSRC,
	  ((correctionPerSec << 16) & 0xFFFF0000) | (correctionPerGOF & 0xFFFF));
	cs461x_poke(state->card, BA1_PPI, phiIncr);
	spin_unlock_irqrestore(&state->card->lock, flags);
	dmabuf->rate = rate;
	
	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_dac_rate()- %d\n",rate) );
	return rate;
}

/* set recording sample rate */
static unsigned int cs_set_adc_rate(struct cs_state *state, unsigned int rate)
{
	struct dmabuf *dmabuf = &state->dmabuf;
	struct cs_card *card = state->card;
	unsigned int phiIncr, coeffIncr, tmp1, tmp2;
	unsigned int correctionPerGOF, correctionPerSec, initialDelay;
	unsigned int frameGroupLength, cnt;
	unsigned long flags;
	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_adc_rate()+ %d\n",rate) );

	/*
	 *  We can only decimate by up to a factor of 1/9th the hardware rate.
	 *  Correct the value if an attempt is made to stray outside that limit.
	 */
	if ((rate * 9) < 48000)
		rate = 48000 / 9;

	/*
	 *  We can not capture at at rate greater than the Input Rate (48000).
	 *  Return an error if an attempt is made to stray outside that limit.
	 */
	if (rate > 48000)
		rate = 48000;

	/*
	 *  Compute the values used to drive the actual sample rate conversion.
	 *  The following formulas are being computed, using inline assembly
	 *  since we need to use 64 bit arithmetic to compute the values:
	 *
	 *     coeffIncr = -floor((Fs,out * 2^23) / Fs,in)
	 *     phiIncr = floor((Fs,in * 2^26) / Fs,out)
	 *     correctionPerGOF = floor((Fs,in * 2^26 - Fs,out * phiIncr) /
	 *                                GOF_PER_SEC)
	 *     correctionPerSec = Fs,in * 2^26 - Fs,out * phiIncr -
	 *                          GOF_PER_SEC * correctionPerGOF
	 *     initialDelay = ceil((24 * Fs,in) / Fs,out)
	 *
	 * i.e.
	 *
	 *     coeffIncr = neg(dividend((Fs,out * 2^23) / Fs,in))
	 *     phiIncr:ulOther = dividend:remainder((Fs,in * 2^26) / Fs,out)
	 *     correctionPerGOF:correctionPerSec =
	 * 	    dividend:remainder(ulOther / GOF_PER_SEC)
	 *     initialDelay = dividend(((24 * Fs,in) + Fs,out - 1) / Fs,out)
	 */
	tmp1 = rate << 16;
	coeffIncr = tmp1 / 48000;
	tmp1 -= coeffIncr * 48000;
	tmp1 <<= 7;
	coeffIncr <<= 7;
	coeffIncr += tmp1 / 48000;
	coeffIncr ^= 0xFFFFFFFF;
	coeffIncr++;
	tmp1 = 48000 << 16;
	phiIncr = tmp1 / rate;
	tmp1 -= phiIncr * rate;
	tmp1 <<= 10;
	phiIncr <<= 10;
	tmp2 = tmp1 / rate;
	phiIncr += tmp2;
	tmp1 -= tmp2 * rate;
	correctionPerGOF = tmp1 / GOF_PER_SEC;
	tmp1 -= correctionPerGOF * GOF_PER_SEC;
	correctionPerSec = tmp1;
	initialDelay = ((48000 * 24) + rate - 1) / rate;

	/*
	 *  Fill in the VariDecimate control block.
	 */
	spin_lock_irqsave(&card->lock, flags);
	cs461x_poke(card, BA1_CSRC,
		((correctionPerSec << 16) & 0xFFFF0000) | (correctionPerGOF & 0xFFFF));
	cs461x_poke(card, BA1_CCI, coeffIncr);
	cs461x_poke(card, BA1_CD,
		(((BA1_VARIDEC_BUF_1 + (initialDelay << 2)) << 16) & 0xFFFF0000) | 0x80);
	cs461x_poke(card, BA1_CPI, phiIncr);
	spin_unlock_irqrestore(&card->lock, flags);

	/*
	 *  Figure out the frame group length for the write back task.  Basically,
	 *  this is just the factors of 24000 (2^6*3*5^3) that are not present in
	 *  the output sample rate.
	 */
	frameGroupLength = 1;
	for (cnt = 2; cnt <= 64; cnt *= 2) {
		if (((rate / cnt) * cnt) != rate)
			frameGroupLength *= 2;
	}
	if (((rate / 3) * 3) != rate) {
		frameGroupLength *= 3;
	}
	for (cnt = 5; cnt <= 125; cnt *= 5) {
		if (((rate / cnt) * cnt) != rate) 
			frameGroupLength *= 5;
        }

	/*
	 * Fill in the WriteBack control block.
	 */
	spin_lock_irqsave(&card->lock, flags);
	cs461x_poke(card, BA1_CFG1, frameGroupLength);
	cs461x_poke(card, BA1_CFG2, (0x00800000 | frameGroupLength));
	cs461x_poke(card, BA1_CCST, 0x0000FFFF);
	cs461x_poke(card, BA1_CSPB, ((65536 * rate) / 24000));
	cs461x_poke(card, (BA1_CSPB + 4), 0x0000FFFF);
	spin_unlock_irqrestore(&card->lock, flags);
	dmabuf->rate = rate;
	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_adc_rate()- %d\n",rate) );
	return rate;
}

/* prepare channel attributes for playback */ 
static void cs_play_setup(struct cs_state *state)
{
	struct dmabuf *dmabuf = &state->dmabuf;
	struct cs_card *card = state->card;
        unsigned int tmp, Count, playFormat;

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_play_setup()+\n") );
        cs461x_poke(card, BA1_PVOL, 0x80008000);
        if (!dmabuf->SGok)
               cs461x_poke(card, BA1_PBA, virt_to_bus(dmabuf->pbuf));
    
        Count = 4;                                                          
        playFormat=cs461x_peek(card, BA1_PFIE);                             
        if ((dmabuf->fmt & CS_FMT_STEREO)) {                                
                playFormat &= ~DMA_RQ_C2_AC_MONO_TO_STEREO;                 
                Count *= 2;                                                 
        } else
                playFormat |= DMA_RQ_C2_AC_MONO_TO_STEREO;                  
                                                                            
        if ((dmabuf->fmt & CS_FMT_16BIT)) {                                 
                playFormat &= ~(DMA_RQ_C2_AC_8_TO_16_BIT                    
                           | DMA_RQ_C2_AC_SIGNED_CONVERT);                  
                Count *= 2;                                                 
        } else
                playFormat |= (DMA_RQ_C2_AC_8_TO_16_BIT                     
                           | DMA_RQ_C2_AC_SIGNED_CONVERT);                  
                                                                            
        cs461x_poke(card, BA1_PFIE, playFormat);                            
                                                                            
        tmp = cs461x_peek(card, BA1_PDTC);                                  
        tmp &= 0xfffffe00;                                                  
        cs461x_poke(card, BA1_PDTC, tmp | --Count);                         

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_play_setup()-\n") );
}

static struct InitStruct
{
    u32 off;
    u32 val;
} InitArray[] = { {0x00000040, 0x3fc0000f},
                  {0x0000004c, 0x04800000},

                  {0x000000b3, 0x00000780},
                  {0x000000b7, 0x00000000},
                  {0x000000bc, 0x07800000},

                  {0x000000cd, 0x00800000},
                };

/*
 * "SetCaptureSPValues()" -- Initialize record task values before each
 * 	capture startup.  
 */
static void SetCaptureSPValues(struct cs_card *card)
{
	unsigned i, offset;
	CS_DBGOUT(CS_FUNCTION, 8, printk("cs46xx: SetCaptureSPValues()+\n") );
	for (i = 0; i < sizeof(InitArray) / sizeof(struct InitStruct); i++) {
		offset = InitArray[i].off*4; /* 8bit to 32bit offset value */
		cs461x_poke(card, offset, InitArray[i].val );
	}
	CS_DBGOUT(CS_FUNCTION, 8, printk("cs46xx: SetCaptureSPValues()-\n") );
}

/* prepare channel attributes for recording */
static void cs_rec_setup(struct cs_state *state)
{
	struct cs_card *card = state->card;
	struct dmabuf *dmabuf = &state->dmabuf;

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_rec_setup()+\n"));
	SetCaptureSPValues(card);

	/*
	 * set the attenuation to 0dB 
	 */
	cs461x_poke(card, BA1_CVOL, 0x80008000);

	/*
	 * set the physical address of the capture buffer into the SP
	 */
	cs461x_poke(card, BA1_CBA, virt_to_bus(dmabuf->rawbuf));

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_rec_setup()-\n") );
}


/* get current playback/recording dma buffer pointer (byte offset from LBA),
   called with spinlock held! */
   
static inline unsigned cs_get_dma_addr(struct cs_state *state)
{
	struct dmabuf *dmabuf = &state->dmabuf;
	u32 offset;
	
	if ( (!(dmabuf->enable & DAC_RUNNING)) &&
	     (!(dmabuf->enable & ADC_RUNNING) ) )
	{
		CS_DBGOUT(CS_ERROR, 2, printk(
			"cs46xx: ERROR cs_get_dma_addr(): not enabled \n") );
		return 0;
	}
		
	/*
	 * granularity is byte boundary, good part.
	 */
	if (dmabuf->enable & DAC_RUNNING)
		offset = cs461x_peek(state->card, BA1_PBA);                                  
	else /* ADC_RUNNING must be set */
		offset = cs461x_peek(state->card, BA1_CBA);                                  

	CS_DBGOUT(CS_PARMS | CS_FUNCTION, 9, 
		printk("cs46xx: cs_get_dma_addr() %d\n",offset) );
	offset = (u32)bus_to_virt((unsigned long)offset) - (u32)dmabuf->rawbuf;
	CS_DBGOUT(CS_PARMS | CS_FUNCTION, 8, 
		printk("cs46xx: cs_get_dma_addr()- %d\n",offset) );
	return offset;
}

static void resync_dma_ptrs(struct cs_state *state)
{
	struct dmabuf *dmabuf;
	
	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: resync_dma_ptrs()+ \n") );
	if (state) {
		dmabuf = &state->dmabuf;
		dmabuf->hwptr=dmabuf->swptr = 0;
		dmabuf->pringbuf = 0;
	}
	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: resync_dma_ptrs()- \n") );
}
	
/* Stop recording (lock held) */
static inline void __stop_adc(struct cs_state *state)
{
	struct dmabuf *dmabuf = &state->dmabuf;
	struct cs_card *card = state->card;
	unsigned int tmp;
	
	dmabuf->enable &= ~ADC_RUNNING;
	
	tmp = cs461x_peek(card, BA1_CCTL);
	tmp &= 0xFFFF0000;
	cs461x_poke(card, BA1_CCTL, tmp );
}

static void stop_adc(struct cs_state *state)
{
	unsigned long flags;

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_adc()+ \n") );
	spin_lock_irqsave(&state->card->lock, flags);
	__stop_adc(state);
	spin_unlock_irqrestore(&state->card->lock, flags);
	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_adc()- \n") );
}

static void start_adc(struct cs_state *state)
{
	struct dmabuf *dmabuf = &state->dmabuf;
	struct cs_card *card = state->card;
	unsigned long flags;
	unsigned int tmp;

	spin_lock_irqsave(&card->lock, flags);
	if (!(dmabuf->enable & ADC_RUNNING) && 
	     ((dmabuf->mapped || dmabuf->count < (signed)dmabuf->dmasize) 
	       && dmabuf->ready) && 
	       ((card->pm.flags & CS46XX_PM_IDLE) || 
	        (card->pm.flags & CS46XX_PM_RESUMED)) )
	{
		dmabuf->enable |= ADC_RUNNING;
		cs_set_divisor(dmabuf);
		tmp = cs461x_peek(card, BA1_CCTL);
		tmp &= 0xFFFF0000;
		tmp |= card->cctl;
		CS_DBGOUT(CS_FUNCTION, 2, printk(
			"cs46xx: start_adc() poke 0x%x \n",tmp) );
		cs461x_poke(card, BA1_CCTL, tmp);
	}
	spin_unlock_irqrestore(&card->lock, flags);
}

/* stop playback (lock held) */
static inline void __stop_dac(struct cs_state *state)
{
	struct dmabuf *dmabuf = &state->dmabuf;
	struct cs_card *card = state->card;
	unsigned int tmp;

	dmabuf->enable &= ~DAC_RUNNING;
	
	tmp=cs461x_peek(card, BA1_PCTL);
	tmp&=0xFFFF;
	cs461x_poke(card, BA1_PCTL, tmp);
}

static void stop_dac(struct cs_state *state)
{
	unsigned long flags;

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_dac()+ \n") );
	spin_lock_irqsave(&state->card->lock, flags);
	__stop_dac(state);
	spin_unlock_irqrestore(&state->card->lock, flags);
	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_dac()- \n") );
}	

static void start_dac(struct cs_state *state)
{
	struct dmabuf *dmabuf = &state->dmabuf;
	struct cs_card *card = state->card;
	unsigned long flags;
	int tmp;

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: start_dac()+ \n") );
	spin_lock_irqsave(&card->lock, flags);
	if (!(dmabuf->enable & DAC_RUNNING) && 
	    ((dmabuf->mapped || dmabuf->count > 0) && dmabuf->ready) &&
	       ((card->pm.flags & CS46XX_PM_IDLE) || 
	        (card->pm.flags & CS46XX_PM_RESUMED)) )
	{
		dmabuf->enable |= DAC_RUNNING;
		tmp = cs461x_peek(card, BA1_PCTL);
		tmp &= 0xFFFF;
		tmp |= card->pctl;
		CS_DBGOUT(CS_PARMS, 6, printk(
		    "cs46xx: start_dac() poke card=%p tmp=0x%.08x addr=%p \n",
		    card, (unsigned)tmp, 
		    card->ba1.idx[(BA1_PCTL >> 16) & 3]+(BA1_PCTL&0xffff) ) );
		cs461x_poke(card, BA1_PCTL, tmp);
	}
	spin_unlock_irqrestore(&card->lock, flags);
	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: start_dac()- \n") );
}

#define DMABUF_MINORDER 1

/*
 * allocate DMA buffer, playback and recording buffers are separate.
 */
static int alloc_dmabuf(struct cs_state *state)
{

	struct cs_card *card=state->card;
	struct dmabuf *dmabuf = &state->dmabuf;
	void *rawbuf = NULL;
	void *tmpbuff = NULL;
	int order;
	struct page *map, *mapend;
	unsigned long df;
	
	dmabuf->ready  = dmabuf->mapped = 0;
	dmabuf->SGok = 0;
/*
* check for order within limits, but do not overwrite value.
*/
	if ((defaultorder > 1) && (defaultorder < 12))
		df = defaultorder;
	else
		df = 2;	

	for (order = df; order >= DMABUF_MINORDER; order--)
		if ((rawbuf = (void *)pci_alloc_consistent(
			card->pci_dev, PAGE_SIZE << order, &dmabuf->dmaaddr)))
			    break;
	if (!rawbuf) {
		CS_DBGOUT(CS_ERROR, 1, printk(KERN_ERR
			"cs46xx: alloc_dmabuf(): unable to allocate rawbuf\n"));
		return -ENOMEM;
	}
	dmabuf->buforder = order;
	dmabuf->rawbuf = rawbuf;
	// Now mark the pages as reserved; otherwise the 
	// remap_pfn_range() in cs46xx_mmap doesn't work.
	// 1. get index to last page in mem_map array for rawbuf.
	mapend = virt_to_page(dmabuf->rawbuf + 
		(PAGE_SIZE << dmabuf->buforder) - 1);

	// 2. mark each physical page in range as 'reserved'.
	for (map = virt_to_page(dmabuf->rawbuf); map <= mapend; map++)
		cs4x_mem_map_reserve(map);

	CS_DBGOUT(CS_PARMS, 9, printk("cs46xx: alloc_dmabuf(): allocated %ld (order = %d) bytes at %p\n",
	       PAGE_SIZE << order, order, rawbuf) );

/*
*  only allocate the conversion buffer for the ADC
*/
	if (dmabuf->type == CS_TYPE_DAC) {
		dmabuf->tmpbuff = NULL;
		dmabuf->buforder_tmpbuff = 0;
		return 0;
	}
/*
 * now the temp buffer for 16/8 conversions
 */

	tmpbuff = (void *) pci_alloc_consistent(
		card->pci_dev, PAGE_SIZE << order, &dmabuf->dmaaddr_tmpbuff);

	if (!tmpbuff)
		return -ENOMEM;
	CS_DBGOUT(CS_PARMS, 9, printk("cs46xx: allocated %ld (order = %d) bytes at %p\n",
	       PAGE_SIZE << order, order, tmpbuff) );

	dmabuf->tmpbuff = tmpbuff;
	dmabuf->buforder_tmpbuff = order;
	
	// Now mark the pages as reserved; otherwise the 
	// remap_pfn_range() in cs46xx_mmap doesn't work.
	// 1. get index to last page in mem_map array for rawbuf.
	mapend = virt_to_page(dmabuf->tmpbuff + 
		(PAGE_SIZE << dmabuf->buforder_tmpbuff) - 1);

	// 2. mark each physical page in range as 'reserved'.
	for (map = virt_to_page(dmabuf->tmpbuff); map <= mapend; map++)
		cs4x_mem_map_reserve(map);
	return 0;
}

/* free DMA buffer */
static void dealloc_dmabuf(struct cs_state *state)
{
	struct dmabuf *dmabuf = &state->dmabuf;
	struct page *map, *mapend;

	if (dmabuf->rawbuf) {
		// Undo prog_dmabuf()'s marking the pages as reserved 
		mapend = virt_to_page(dmabuf->rawbuf + 
				(PAGE_SIZE << dmabuf->buforder) - 1);
		for (map = virt_to_page(dmabuf->rawbuf); map <= mapend; map++)
			cs4x_mem_map_unreserve(map);
		free_dmabuf(state->card, dmabuf);
	}

	if (dmabuf->tmpbuff) {
		// Undo prog_dmabuf()'s marking the pages as reserved 
		mapend = virt_to_page(dmabuf->tmpbuff +
				(PAGE_SIZE << dmabuf->buforder_tmpbuff) - 1);
		for (map = virt_to_page(dmabuf->tmpbuff); map <= mapend; map++)
			cs4x_mem_map_unreserve(map);
		free_dmabuf2(state->card, dmabuf);
	}

	dmabuf->rawbuf = NULL;
	dmabuf->tmpbuff = NULL;
	dmabuf->mapped = dmabuf->ready = 0;
	dmabuf->SGok = 0;
}

static int __prog_dmabuf(struct cs_state *state)
{
        struct dmabuf *dmabuf = &state->dmabuf;
        unsigned long flags;
        unsigned long allocated_pages, allocated_bytes;                     
        unsigned long tmp1, tmp2, fmt=0;                                           
        unsigned long *ptmp = (unsigned long *) dmabuf->pbuf;               
        unsigned long SGarray[9], nSGpages=0;                               
        int ret;

	CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()+ \n"));
/*
 * check for CAPTURE and use only non-sg for initial release
 */
	if (dmabuf->type == CS_TYPE_ADC) {
		CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf() ADC\n"));
		/* 
		 * add in non-sg support for capture.
		 */
		spin_lock_irqsave(&state->card->lock, flags);
	/* add code to reset the rawbuf memory. TRW */
		resync_dma_ptrs(state);
		dmabuf->total_bytes = dmabuf->blocks = 0;
		dmabuf->count = dmabuf->error = dmabuf->underrun = 0;

		dmabuf->SGok = 0;                                                   

		spin_unlock_irqrestore(&state->card->lock, flags);

		/* allocate DMA buffer if not allocated yet */
		if (!dmabuf->rawbuf || !dmabuf->tmpbuff)
			if ((ret = alloc_dmabuf(state)))
				return ret; 
	/*
	 * static image only supports 16Bit signed, stereo - hard code fmt
	 */
		fmt = CS_FMT_16BIT | CS_FMT_STEREO;

		dmabuf->numfrag = 2;                                        
		dmabuf->fragsize = 2048;                                    
		dmabuf->fragsamples = 2048 >> sample_shift[fmt];    
		dmabuf->dmasize = 4096;                                     
		dmabuf->fragshift = 11;                                     

		memset(dmabuf->rawbuf, (fmt & CS_FMT_16BIT) ? 0 : 0x80,
		       dmabuf->dmasize);
        	memset(dmabuf->tmpbuff, (fmt & CS_FMT_16BIT) ? 0 : 0x80, 
			PAGE_SIZE<<dmabuf->buforder_tmpbuff);      

		/*
		 *      Now set up the ring
		 */

		spin_lock_irqsave(&state->card->lock, flags);
		cs_rec_setup(state);
		spin_unlock_irqrestore(&state->card->lock, flags);

		/* set the ready flag for the dma buffer */
		dmabuf->ready = 1;

		CS_DBGOUT(CS_PARMS, 4, printk(
			"cs46xx: prog_dmabuf(): CAPTURE rate=%d fmt=0x%x numfrag=%d "
			"fragsize=%d dmasize=%d\n",
			    dmabuf->rate, dmabuf->fmt, dmabuf->numfrag,
			    dmabuf->fragsize, dmabuf->dmasize) );

		CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()- 0 \n"));
		return 0;
	} else if (dmabuf->type == CS_TYPE_DAC) {
	/*
	 * Must be DAC
	 */
		CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf() DAC\n"));
		spin_lock_irqsave(&state->card->lock, flags);
		resync_dma_ptrs(state);
		dmabuf->total_bytes = dmabuf->blocks = 0;
		dmabuf->count = dmabuf->error = dmabuf->underrun = 0;

		dmabuf->SGok = 0;                                                   

		spin_unlock_irqrestore(&state->card->lock, flags);

		/* allocate DMA buffer if not allocated yet */
		if (!dmabuf->rawbuf)
			if ((ret = alloc_dmabuf(state)))
				return ret;

		allocated_pages = 1 << dmabuf->buforder;                            
		allocated_bytes = allocated_pages*PAGE_SIZE;                        
										    
		if (allocated_pages < 2) {
			CS_DBGOUT(CS_FUNCTION, 4, printk(
			    "cs46xx: prog_dmabuf() Error: allocated_pages too small (%d)\n",
				(unsigned)allocated_pages));
			return -ENOMEM;
		}
										    
		/* Use all the pages allocated, fragsize 4k. */
		/* Use 'pbuf' for S/G page map table. */
		dmabuf->SGok = 1;           /* Use S/G. */

		nSGpages = allocated_bytes/4096;    /* S/G pages always 4k. */
										    
		     /* Set up S/G variables. */
		*ptmp = virt_to_bus(dmabuf->rawbuf);                                
		*(ptmp + 1) = 0x00000008;
		for (tmp1 = 1; tmp1 < nSGpages; tmp1++) {
			*(ptmp + 2 * tmp1) = virt_to_bus((dmabuf->rawbuf) + 4096 * tmp1);
			if (tmp1 == nSGpages - 1)
				tmp2 = 0xbfff0000;
			else                                                        
				tmp2 = 0x80000000 + 8 * (tmp1 + 1);
			*(ptmp + 2 * tmp1 + 1) = tmp2;
		}                                                                   
		SGarray[0] = 0x82c0200d;                                            
		SGarray[1] = 0xffff0000;                                            
		SGarray[2] = *ptmp;                                                 
		SGarray[3] = 0x00010600;                                            
		SGarray[4] = *(ptmp+2);                                             
		SGarray[5] = 0x80000010;                                            
		SGarray[6] = *ptmp;
		SGarray[7] = *(ptmp+2);
		SGarray[8] = (virt_to_bus(dmabuf->pbuf) & 0xffff000) | 0x10;

		if (dmabuf->SGok) {
			dmabuf->numfrag = nSGpages;
			dmabuf->fragsize = 4096;
			dmabuf->fragsamples = 4096 >> sample_shift[dmabuf->fmt];
			dmabuf->fragshift = 12;
			dmabuf->dmasize = dmabuf->numfrag * 4096;
		} else {
			SGarray[0] = 0xf2c0000f;                                    
			SGarray[1] = 0x00000200;                                    
			SGarray[2] = 0;                                             
			SGarray[3] = 0x00010600;                                    
			SGarray[4]=SGarray[5]=SGarray[6]=SGarray[7]=SGarray[8] = 0; 
			dmabuf->numfrag = 2;                                        
			dmabuf->fragsize = 2048;                                    
			dmabuf->fragsamples = 2048 >> sample_shift[dmabuf->fmt];    
			dmabuf->dmasize = 4096;                                     
			dmabuf->fragshift = 11;                                     
		}
		for (tmp1 = 0; tmp1 < sizeof(SGarray) / 4; tmp1++)
			cs461x_poke(state->card, BA1_PDTC+tmp1 * 4, SGarray[tmp1]);

		memset(dmabuf->rawbuf, (dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80,
		       dmabuf->dmasize);

		/*
		 *      Now set up the ring
		 */

		spin_lock_irqsave(&state->card->lock, flags);
		cs_play_setup(state);
		spin_unlock_irqrestore(&state->card->lock, flags);

		/* set the ready flag for the dma buffer */
		dmabuf->ready = 1;

		CS_DBGOUT(CS_PARMS, 4, printk(
			"cs46xx: prog_dmabuf(): PLAYBACK rate=%d fmt=0x%x numfrag=%d "
			"fragsize=%d dmasize=%d\n",
			    dmabuf->rate, dmabuf->fmt, dmabuf->numfrag,
			    dmabuf->fragsize, dmabuf->dmasize) );

		CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()- \n"));
		return 0;
	} else {
		CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()- Invalid Type %d\n",
			dmabuf->type));
	}
	return 1;
}

static int prog_dmabuf(struct cs_state *state)
{
	int ret;
	
	mutex_lock(&state->sem);
	ret = __prog_dmabuf(state);
	mutex_unlock(&state->sem);
	
	return ret;
}

static void cs_clear_tail(struct cs_state *state)
{
}

static int drain_dac(struct cs_state *state, int nonblock)
{
	DECLARE_WAITQUEUE(wait, current);
	struct dmabuf *dmabuf = &state->dmabuf;
	struct cs_card *card=state->card;
	unsigned long flags;
	unsigned long tmo;
	int count;

	CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()+ \n"));
	if (dmabuf->mapped || !dmabuf->ready)
	{
		CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()- 0, not ready\n"));
		return 0;
	}

	add_wait_queue(&dmabuf->wait, &wait);
	for (;;) {
		/* It seems that we have to set the current state to TASK_INTERRUPTIBLE
		   every time to make the process really go to sleep */
		current->state = TASK_INTERRUPTIBLE;

		spin_lock_irqsave(&state->card->lock, flags);
		count = dmabuf->count;
		spin_unlock_irqrestore(&state->card->lock, flags);

		if (count <= 0)
			break;

		if (signal_pending(current))
			break;

		if (nonblock) {
			remove_wait_queue(&dmabuf->wait, &wait);
			current->state = TASK_RUNNING;
			return -EBUSY;
		}

		tmo = (dmabuf->dmasize * HZ) / dmabuf->rate;
		tmo >>= sample_shift[dmabuf->fmt];
		tmo += (2048*HZ)/dmabuf->rate;
		
		if (!schedule_timeout(tmo ? tmo : 1) && tmo){
			printk(KERN_ERR "cs46xx: drain_dac, dma timeout? %d\n", count);
			break;
		}
	}
	remove_wait_queue(&dmabuf->wait, &wait);
	current->state = TASK_RUNNING;
	if (signal_pending(current)) {
		CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()- -ERESTARTSYS\n"));
		/*
		* set to silence and let that clear the fifos.
		*/
		cs461x_clear_serial_FIFOs(card, CS_TYPE_DAC);
		return -ERESTARTSYS;
	}

	CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()- 0\n"));
	return 0;
}


/* update buffer manangement pointers, especially, dmabuf->count and dmabuf->hwptr */
static void cs_update_ptr(struct cs_card *card, int wake)
{
	struct cs_state *state;
	struct dmabuf *dmabuf;
	unsigned hwptr;
	int diff;

	/* error handling and process wake up for ADC */
	state = card->states[0];
	if (state) {
		dmabuf = &state->dmabuf;
		if (dmabuf->enable & ADC_RUNNING) {
			/* update hardware pointer */
			hwptr = cs_get_dma_addr(state);

			diff = (dmabuf->dmasize + hwptr - dmabuf->hwptr) % dmabuf->dmasize;
			CS_DBGOUT(CS_PARMS, 9, printk(
				"cs46xx: cs_update_ptr()+ ADC hwptr=%d diff=%d\n", 
				hwptr,diff) );
			dmabuf->hwptr = hwptr;
			dmabuf->total_bytes += diff;
			dmabuf->count += diff;
			if (dmabuf->count > dmabuf->dmasize)
				dmabuf->count = dmabuf->dmasize;

			if (dmabuf->mapped) {
				if (wake && dmabuf->count >= (signed)dmabuf->fragsize)
					wake_up(&dmabuf->wait);
			} else {
				if (wake && dmabuf->count > 0)
					wake_up(&dmabuf->wait);
			}
		}
	}

/*
 * Now the DAC
 */
	state = card->states[1];
	if (state) {
		dmabuf = &state->dmabuf;
		/* error handling and process wake up for DAC */
		if (dmabuf->enable & DAC_RUNNING) {
			/* update hardware pointer */
			hwptr = cs_get_dma_addr(state);

			diff = (dmabuf->dmasize + hwptr - dmabuf->hwptr) % dmabuf->dmasize;
			CS_DBGOUT(CS_PARMS, 9, printk(
				"cs46xx: cs_update_ptr()+ DAC hwptr=%d diff=%d\n", 
				hwptr,diff) );
			dmabuf->hwptr = hwptr;
			dmabuf->total_bytes += diff;
			if (dmabuf->mapped) {
				dmabuf->count += diff;
				if (wake && dmabuf->count >= (signed)dmabuf->fragsize)
					wake_up(&dmabuf->wait);
				/*
				 * other drivers use fragsize, but don't see any sense
				 * in that, since dmasize is the buffer asked for
				 * via mmap.
				 */
				if (dmabuf->count > dmabuf->dmasize)
					dmabuf->count &= dmabuf->dmasize-1;
			} else {
				dmabuf->count -= diff;
				/*
				 * backfill with silence and clear out the last 
				 * "diff" number of bytes.
				 */
				if (hwptr >= diff) {
					memset(dmabuf->rawbuf + hwptr - diff, 
						(dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80, diff);
				} else {
					memset(dmabuf->rawbuf, 
						(dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80,
						(unsigned)hwptr);
					memset((char *)dmabuf->rawbuf + 
							dmabuf->dmasize + hwptr - diff,
						(dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80, 
						diff - hwptr); 
				}

				if (dmabuf->count < 0 || dmabuf->count > dmabuf->dmasize) {
					CS_DBGOUT(CS_ERROR, 2, printk(KERN_INFO
					  "cs46xx: ERROR DAC count<0 or count > dmasize (%d)\n",
					  	dmabuf->count));
					/* 
					* buffer underrun or buffer overrun, reset the
					* count of bytes written back to 0.
					*/
					if (dmabuf->count < 0)
						dmabuf->underrun = 1;
					dmabuf->count = 0;
					dmabuf->error++;
				}
				if (wake && dmabuf->count < (signed)dmabuf->dmasize / 2)
					wake_up(&dmabuf->wait);
			}
		}
	}
}


/* hold spinlock for the following! */
static void cs_handle_midi(struct cs_card *card)
{
        unsigned char ch;
        int wake;
        unsigned temp1;

        wake = 0;
        while (!(cs461x_peekBA0(card,  BA0_MIDSR) & MIDSR_RBE)) {
                ch = cs461x_peekBA0(card, BA0_MIDRP);
                if (card->midi.icnt < CS_MIDIINBUF) {
                        card->midi.ibuf[card->midi.iwr] = ch;
                        card->midi.iwr = (card->midi.iwr + 1) % CS_MIDIINBUF;
                        card->midi.icnt++;
                }
                wake = 1;
        }
        if (wake)
                wake_up(&card->midi.iwait);
        wake = 0;
        while (!(cs461x_peekBA0(card,  BA0_MIDSR) & MIDSR_TBF) && card->midi.ocnt > 0) {
                temp1 = ( card->midi.obuf[card->midi.ord] ) & 0x000000ff;
                cs461x_pokeBA0(card, BA0_MIDWP,temp1);
                card->midi.ord = (card->midi.ord + 1) % CS_MIDIOUTBUF;
                card->midi.ocnt--;
                if (card->midi.ocnt < CS_MIDIOUTBUF-16)
                        wake = 1;
        }
        if (wake)
                wake_up(&card->midi.owait);
}

static irqreturn_t cs_interrupt(int irq, void *dev_id)
{
	struct cs_card *card = (struct cs_card *)dev_id;
	/* Single channel card */
	struct cs_state *recstate = card->channel[0].state;
	struct cs_state *playstate = card->channel[1].state;
	u32 status;

	CS_DBGOUT(CS_INTERRUPT, 9, printk("cs46xx: cs_interrupt()+ \n"));

	spin_lock(&card->lock);

	status = cs461x_peekBA0(card, BA0_HISR);
	
	if ((status & 0x7fffffff) == 0) {
		cs461x_pokeBA0(card, BA0_HICR, HICR_CHGM|HICR_IEV);
		spin_unlock(&card->lock);
		return IRQ_HANDLED;	/* Might be IRQ_NONE.. */
	}
	
	/*
	 * check for playback or capture interrupt only
	 */
	if (((status & HISR_VC0) && playstate && playstate->dmabuf.ready) ||
	    (((status & HISR_VC1) && recstate && recstate->dmabuf.ready))) {
		CS_DBGOUT(CS_INTERRUPT, 8, printk(
			"cs46xx: cs_interrupt() interrupt bit(s) set (0x%x)\n",status));
		cs_update_ptr(card, CS_TRUE);
	}

        if (status & HISR_MIDI)
                cs_handle_midi(card);
	
 	/* clear 'em */
	cs461x_pokeBA0(card, BA0_HICR, HICR_CHGM|HICR_IEV);
	spin_unlock(&card->lock);
	CS_DBGOUT(CS_INTERRUPT, 9, printk("cs46xx: cs_interrupt()- \n"));
	return IRQ_HANDLED;
}


/**********************************************************************/

static ssize_t cs_midi_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
{
        struct cs_card *card = file->private_data;
        ssize_t ret;
        unsigned long flags;
        unsigned ptr;
        int cnt;

        if (!access_ok(VERIFY_WRITE, buffer, count))
                return -EFAULT;
        ret = 0;
        while (count > 0) {
                spin_lock_irqsave(&card->lock, flags);
                ptr = card->midi.ird;
                cnt = CS_MIDIINBUF - ptr;
                if (card->midi.icnt < cnt)
                        cnt = card->midi.icnt;
                spin_unlock_irqrestore(&card->lock, flags);
                if (cnt > count)
                        cnt = count;
                if (cnt <= 0) {
                        if (file->f_flags & O_NONBLOCK)
                                return ret ? ret : -EAGAIN;
                        interruptible_sleep_on(&card->midi.iwait);
                        if (signal_pending(current))
                                return ret ? ret : -ERESTARTSYS;
                        continue;
                }
                if (copy_to_user(buffer, card->midi.ibuf + ptr, cnt))
                        return ret ? ret : -EFAULT;
                ptr = (ptr + cnt) % CS_MIDIINBUF;
                spin_lock_irqsave(&card->lock, flags);
                card->midi.ird = ptr;
                card->midi.icnt -= cnt;
                spin_unlock_irqrestore(&card->lock, flags);
                count -= cnt;
                buffer += cnt;
                ret += cnt;
        }
        return ret;
}


static ssize_t cs_midi_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
{
        struct cs_card *card = file->private_data;
        ssize_t ret;
        unsigned long flags;
        unsigned ptr;
        int cnt;

        if (!access_ok(VERIFY_READ, buffer, count))
                return -EFAULT;
        ret = 0;
        while (count > 0) {
                spin_lock_irqsave(&card->lock, flags);
                ptr = card->midi.owr;
                cnt = CS_MIDIOUTBUF - ptr;
                if (card->midi.ocnt + cnt > CS_MIDIOUTBUF)
                        cnt = CS_MIDIOUTBUF - card->midi.ocnt;
                if (cnt <= 0)
                        cs_handle_midi(card);
                spin_unlock_irqrestore(&card->lock, flags);
                if (cnt > count)
                        cnt = count;
                if (cnt <= 0) {
                        if (file->f_flags & O_NONBLOCK)
                                return ret ? ret : -EAGAIN;
                        interruptible_sleep_on(&card->midi.owait);
                        if (signal_pending(current))
                                return ret ? ret : -ERESTARTSYS;
                        continue;
                }
                if (copy_from_user(card->midi.obuf + ptr, buffer, cnt))
                        return ret ? ret : -EFAULT;
                ptr = (ptr + cnt) % CS_MIDIOUTBUF;
                spin_lock_irqsave(&card->lock, flags);
                card->midi.owr = ptr;
                card->midi.ocnt += cnt;
                spin_unlock_irqrestore(&card->lock, flags);
                count -= cnt;
                buffer += cnt;
                ret += cnt;
                spin_lock_irqsave(&card->lock, flags);
                cs_handle_midi(card);
                spin_unlock_irqrestore(&card->lock, flags);
        }
        return ret;
}


static unsigned int cs_midi_poll(struct file *file, struct poll_table_struct *wait)
{
        struct cs_card *card = file->private_data;
        unsigned long flags;
        unsigned int mask = 0;

        if (file->f_flags & FMODE_WRITE)
                poll_wait(file, &card->midi.owait, wait);
        if (file->f_flags & FMODE_READ)
                poll_wait(file, &card->midi.iwait, wait);
        spin_lock_irqsave(&card->lock, flags);
        if (file->f_flags & FMODE_READ) {
                if (card->midi.icnt > 0)
                        mask |= POLLIN | POLLRDNORM;
        }
        if (file->f_flags & FMODE_WRITE) {
                if (card->midi.ocnt < CS_MIDIOUTBUF)
                        mask |= POLLOUT | POLLWRNORM;
        }
        spin_unlock_irqrestore(&card->lock, flags);
        return mask;
}


static int cs_midi_open(struct inode *inode, struct file *file)
{
        unsigned int minor = iminor(inode);
        struct cs_card *card = NULL;
        unsigned long flags;
	struct list_head *entry;

	list_for_each(entry, &cs46xx_devs) {
		card = list_entry(entry, struct cs_card, list);
		if (card->dev_midi == minor)
			break;
	}

	if (entry == &cs46xx_devs)
		return -ENODEV;
	if (!card) {
		CS_DBGOUT(CS_FUNCTION | CS_OPEN, 2, printk(KERN_INFO
			"cs46xx: cs46xx_midi_open(): Error - unable to find card struct\n"));
		return -ENODEV;
	}

        file->private_data = card;
        /* wait for device to become free */
        mutex_lock(&card->midi.open_mutex);
        while (card->midi.open_mode & file->f_mode) {
                if (file->f_flags & O_NONBLOCK) {
                        mutex_unlock(&card->midi.open_mutex);
                        return -EBUSY;
                }
                mutex_unlock(&card->midi.open_mutex);
                interruptible_sleep_on(&card->midi.open_wait);
                if (signal_pending(current))
                        return -ERESTARTSYS;
                mutex_lock(&card->midi.open_mutex);
        }
        spin_lock_irqsave(&card->midi.lock, flags);
        if (!(card->midi.open_mode & (FMODE_READ | FMODE_WRITE))) {
                card->midi.ird = card->midi.iwr = card->midi.icnt = 0;
                card->midi.ord = card->midi.owr = card->midi.ocnt = 0;
                card->midi.ird = card->midi.iwr = card->midi.icnt = 0;
                cs461x_pokeBA0(card, BA0_MIDCR, 0x0000000f);            /* Enable xmit, rcv. */
                cs461x_pokeBA0(card, BA0_HICR, HICR_IEV | HICR_CHGM);   /* Enable interrupts */
        }
        if (file->f_mode & FMODE_READ)
                card->midi.ird = card->midi.iwr = card->midi.icnt = 0;
        if (file->f_mode & FMODE_WRITE)
                card->midi.ord = card->midi.owr = card->midi.ocnt = 0;
        spin_unlock_irqrestore(&card->midi.lock, flags);
        card->midi.open_mode |= (file->f_mode & (FMODE_READ | FMODE_WRITE));
        mutex_unlock(&card->midi.open_mutex);
        return 0;
}


static int cs_midi_release(struct inode *inode, struct file *file)
{
        struct cs_card *card = file->private_data;
        DECLARE_WAITQUEUE(wait, current);
        unsigned long flags;
        unsigned count, tmo;

        if (file->f_mode & FMODE_WRITE) {
                current->state = TASK_INTERRUPTIBLE;
                add_wait_queue(&card->midi.owait, &wait);
                for (;;) {
                        spin_lock_irqsave(&card->midi.lock, flags);
                        count = card->midi.ocnt;
                        spin_unlock_irqrestore(&card->midi.lock, flags);
                        if (count <= 0)
                                break;
                        if (signal_pending(current))
                                break;
                        if (file->f_flags & O_NONBLOCK)
                        	break;
                        tmo = (count * HZ) / 3100;
                        if (!schedule_timeout(tmo ? : 1) && tmo)
                                printk(KERN_DEBUG "cs46xx: midi timed out??\n");
                }
                remove_wait_queue(&card->midi.owait, &wait);
                current->state = TASK_RUNNING;
        }
        mutex_lock(&card->midi.open_mutex);
        card->midi.open_mode &= (~(file->f_mode & (FMODE_READ | FMODE_WRITE)));
        mutex_unlock(&card->midi.open_mutex);
        wake_up(&card->midi.open_wait);
        return 0;
}

/*
 *   Midi file operations struct.
 */
static /*const*/ struct file_operations cs_midi_fops = {
	CS_OWNER	CS_THIS_MODULE
	.llseek		= no_llseek,
	.read		= cs_midi_read,
	.write		= cs_midi_write,
	.poll		= cs_midi_poll,
	.open		= cs_midi_open,
	.release	= cs_midi_release,
};

/*
 *
 * CopySamples copies 16-bit stereo signed samples from the source to the
 * destination, possibly converting down to unsigned 8-bit and/or mono.
 * count specifies the number of output bytes to write.
 *
 *  Arguments:
 *
 *  dst             - Pointer to a destination buffer.
 *  src             - Pointer to a source buffer
 *  count           - The number of bytes to copy into the destination buffer.
 *  fmt             - CS_FMT_16BIT and/or CS_FMT_STEREO bits
 *  dmabuf          - pointer to the dma buffer structure
 *
 * NOTES: only call this routine if the output desired is not 16 Signed Stereo
 * 	
 *
 */
static void CopySamples(char *dst, char *src, int count, unsigned fmt, 
		struct dmabuf *dmabuf)
{
    s32 s32AudioSample;
    s16 *psSrc = (s16 *)src;
    s16 *psDst = (s16 *)dst;
    u8 *pucDst = (u8 *)dst;

    CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO "cs46xx: CopySamples()+ ") );
    CS_DBGOUT(CS_WAVE_READ, 8, printk(KERN_INFO
	" dst=%p src=%p count=%d fmt=0x%x\n",
	dst,src,count,fmt) );

    /*
     * See if the data should be output as 8-bit unsigned stereo.
     */
    if ((fmt & CS_FMT_STEREO) && !(fmt & CS_FMT_16BIT)) {
        /*
         * Convert each 16-bit signed stereo sample to 8-bit unsigned 
	 * stereo using rounding.
         */
        psSrc = (s16 *)src;
	count = count / 2;
        while (count--)
            *(pucDst++) = (u8)(((s16)(*psSrc++) + (s16)0x8000) >> 8);
    }
    /*
     * See if the data should be output at 8-bit unsigned mono.
     */
    else if (!(fmt & CS_FMT_STEREO) && !(fmt & CS_FMT_16BIT)) {
        /*
         * Convert each 16-bit signed stereo sample to 8-bit unsigned 
	 * mono using averaging and rounding.
         */
        psSrc = (s16 *)src;
	count = count / 2;
        while (count--) {
	    s32AudioSample = ((*psSrc) + (*(psSrc + 1))) / 2 + (s32)0x80;
	    if (s32AudioSample > 0x7fff)
	    	s32AudioSample = 0x7fff;
            *(pucDst++) = (u8)(((s16)s32AudioSample + (s16)0x8000) >> 8);
	    psSrc += 2;
        }
    }
    /*
     * See if the data should be output at 16-bit signed mono.
     */
    else if (!(fmt & CS_FMT_STEREO) && (fmt & CS_FMT_16BIT)) {
        /*
         * Convert each 16-bit signed stereo sample to 16-bit signed 
	 * mono using averaging.
         */
        psSrc = (s16 *)src;
	count = count / 2;
        while (count--) {
            *(psDst++) = (s16)((*psSrc) + (*(psSrc + 1))) / 2;
	    psSrc += 2;
        }
    }
}

/*
 * cs_copy_to_user()
 * replacement for the standard copy_to_user, to allow for a conversion from
 * 16 bit to 8 bit and from stereo to mono, if the record conversion is active.  
 * The current CS46xx/CS4280 static image only records in 16bit unsigned Stereo, 
 * so we convert from any of the other format combinations.
 */
static unsigned cs_copy_to_user(
	struct cs_state *s, 
	void __user *dest, 
	void *hwsrc, 
	unsigned cnt, 
	unsigned *copied)
{
	struct dmabuf *dmabuf = &s->dmabuf;
	void *src = hwsrc;  /* default to the standard destination buffer addr */

	CS_DBGOUT(CS_FUNCTION, 6, printk(KERN_INFO 
		"cs_copy_to_user()+ fmt=0x%x cnt=%d dest=%p\n",
		dmabuf->fmt,(unsigned)cnt,dest) );

	if (cnt > dmabuf->dmasize)
		cnt = dmabuf->dmasize;
	if (!cnt) {
		*copied = 0;
		return 0;
	}
	if (dmabuf->divisor != 1) {
		if (!dmabuf->tmpbuff) {
			*copied = cnt / dmabuf->divisor;
			return 0;
		}

		CopySamples((char *)dmabuf->tmpbuff, (char *)hwsrc, cnt, 
			dmabuf->fmt, dmabuf);
		src = dmabuf->tmpbuff;
		cnt = cnt/dmabuf->divisor;
	}
        if (copy_to_user(dest, src, cnt)) {
		CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_ERR 
			"cs46xx: cs_copy_to_user()- fault dest=%p src=%p cnt=%d\n",
				dest,src,cnt));
		*copied = 0;
		return -EFAULT;
	}
	*copied = cnt;
	CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO 
		"cs46xx: cs_copy_to_user()- copied bytes is %d \n",cnt));
	return 0;
}

/* in this loop, dmabuf.count signifies the amount of data that is waiting to be copied to
   the user's buffer.  it is filled by the dma machine and drained by this loop. */
static ssize_t cs_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
{
	struct cs_card *card = file->private_data;
	struct cs_state *state;
	DECLARE_WAITQUEUE(wait, current);
	struct dmabuf *dmabuf;
	ssize_t ret = 0;
	unsigned long flags;
	unsigned swptr;
	int cnt;
	unsigned copied = 0;

	CS_DBGOUT(CS_WAVE_READ | CS_FUNCTION, 4, 
		printk("cs46xx: cs_read()+ %zd\n",count) );
	state = card->states[0];
	if (!state)
		return -ENODEV;
	dmabuf = &state->dmabuf;

	if (dmabuf->mapped)
		return -ENXIO;
	if (!access_ok(VERIFY_WRITE, buffer, count))
		return -EFAULT;
	
	mutex_lock(&state->sem);
	if (!dmabuf->ready && (ret = __prog_dmabuf(state)))
		goto out2;

	add_wait_queue(&state->dmabuf.wait, &wait);
	while (count > 0) {
		while (!(card->pm.flags & CS46XX_PM_IDLE)) {
			schedule();
			if (signal_pending(current)) {
				if (!ret)
					ret = -ERESTARTSYS;
				goto out;
			}
		}
		spin_lock_irqsave(&state->card->lock, flags);
		swptr = dmabuf->swptr;
		cnt = dmabuf->dmasize - swptr;
		if (dmabuf->count < cnt)
			cnt = dmabuf->count;
		if (cnt <= 0)
			__set_current_state(TASK_INTERRUPTIBLE);
		spin_unlock_irqrestore(&state->card->lock, flags);

		if (cnt > (count * dmabuf->divisor))
			cnt = count * dmabuf->divisor;
		if (cnt <= 0) {
			/* buffer is empty, start the dma machine and wait for data to be
			   recorded */
			start_adc(state);
			if (file->f_flags & O_NONBLOCK) {
				if (!ret)
					ret = -EAGAIN;
				goto out;
 			}
			mutex_unlock(&state->sem);
			schedule();
			if (signal_pending(current)) {
				if (!ret)
					ret = -ERESTARTSYS;
				goto out;
			}
			mutex_lock(&state->sem);
			if (dmabuf->mapped) {
				if (!ret)
					ret = -ENXIO;
				goto out;
			}
 			continue;
		}

		CS_DBGOUT(CS_WAVE_READ, 2, printk(KERN_INFO 
			"_read() copy_to cnt=%d count=%zd ", cnt,count) );
		CS_DBGOUT(CS_WAVE_READ, 8, printk(KERN_INFO 
			" .dmasize=%d .count=%d buffer=%p ret=%zd\n",
			dmabuf->dmasize,dmabuf->count,buffer,ret));

                if (cs_copy_to_user(state, buffer, 
			(char *)dmabuf->rawbuf + swptr, cnt, &copied)) {
			if (!ret)
				ret = -EFAULT;
			goto out;
		}
                swptr = (swptr + cnt) % dmabuf->dmasize;
                spin_lock_irqsave(&card->lock, flags);
                dmabuf->swptr = swptr;
                dmabuf->count -= cnt;
                spin_unlock_irqrestore(&card->lock, flags);
                count -= copied;
                buffer += copied;
                ret += copied;
                start_adc(state);
	}
out:
	remove_wait_queue(&state->dmabuf.wait, &wait);
out2:
	mutex_unlock(&state->sem);
	set_current_state(TASK_RUNNING);
	CS_DBGOUT(CS_WAVE_READ | CS_FUNCTION, 4, 
		printk("cs46xx: cs_read()- %zd\n",ret) );
	return ret;
}

/* in this loop, dmabuf.count signifies the amount of data that is waiting to be dma to
   the soundcard.  it is drained by the dma machine and filled by this loop. */
static ssize_t cs_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
{
	struct cs_card *card = file->private_data;
	struct cs_state *state;
	DECLARE_WAITQUEUE(wait, current);
	struct dmabuf *dmabuf;
	ssize_t ret;
	unsigned long flags;
	unsigned swptr;
	int cnt;

	CS_DBGOUT(CS_WAVE_WRITE | CS_FUNCTION, 4,
		printk("cs46xx: cs_write called, count = %zd\n", count) );
	state = card->states[1];
	if (!state)
		return -ENODEV;
	if (!access_ok(VERIFY_READ, buffer, count))
		return -EFAULT;
	dmabuf = &state->dmabuf;

	mutex_lock(&state->sem);
	if (dmabuf->mapped) {
		ret = -ENXIO;
		goto out;
	}

	if (!dmabuf->ready && (ret = __prog_dmabuf(state)))
		goto out;
	add_wait_queue(&state->dmabuf.wait, &wait);
	ret = 0;
/*
* Start the loop to read from the user's buffer and write to the dma buffer.
* check for PM events and underrun/overrun in the loop.
*/
	while (count > 0) {
		while (!(card->pm.flags & CS46XX_PM_IDLE)) {
			schedule();
			if (signal_pending(current)) {
				if (!ret)
					ret = -ERESTARTSYS;
				goto out;
			}
		}
		spin_lock_irqsave(&state->card->lock, flags);
		if (dmabuf->count < 0) {
			/* buffer underrun, we are recovering from sleep_on_timeout,
			   resync hwptr and swptr */
			dmabuf->count = 0;
			dmabuf->swptr = dmabuf->hwptr;
		}
		if (dmabuf->underrun) {
			dmabuf->underrun = 0;
			dmabuf->hwptr = cs_get_dma_addr(state);
			dmabuf->swptr = dmabuf->hwptr;
		}

		swptr = dmabuf->swptr;
		cnt = dmabuf->dmasize - swptr;
		if (dmabuf->count + cnt > dmabuf->dmasize)
			cnt = dmabuf->dmasize - dmabuf->count;
		if (cnt <= 0)
			__set_current_state(TASK_INTERRUPTIBLE);
		spin_unlock_irqrestore(&state->card->lock, flags);

		if (cnt > count)
			cnt = count;
		if (cnt <= 0) {
			/* buffer is full, start the dma machine and wait for data to be
			   played */
			start_dac(state);
			if (file->f_flags & O_NONBLOCK) {
				if (!ret)
					ret = -EAGAIN;
				goto out;
 			}
			mutex_unlock(&state->sem);
			schedule();
 			if (signal_pending(current)) {
				if (!ret)
					ret = -ERESTARTSYS;
				goto out;
 			}
			mutex_lock(&state->sem);
			if (dmabuf->mapped) {
				if (!ret)
					ret = -ENXIO;
				goto out;
			}
 			continue;
 		}
		if (copy_from_user(dmabuf->rawbuf + swptr, buffer, cnt)) {
			if (!ret)
				ret = -EFAULT;
			goto out;
		}
		spin_lock_irqsave(&state->card->lock, flags);
		swptr = (swptr + cnt) % dmabuf->dmasize;
		dmabuf->swptr = swptr;
		dmabuf->count += cnt;
		if (dmabuf->count > dmabuf->dmasize) {
			CS_DBGOUT(CS_WAVE_WRITE | CS_ERROR, 2, printk(
			    "cs46xx: cs_write() d->count > dmasize - resetting\n"));
			dmabuf->count = dmabuf->dmasize;
		}
		dmabuf->endcleared = 0;
		spin_unlock_irqrestore(&state->card->lock, flags);

		count -= cnt;
		buffer += cnt;
		ret += cnt;
		start_dac(state);
	}
out:
	mutex_unlock(&state->sem);
	remove_wait_queue(&state->dmabuf.wait, &wait);
	set_current_state(TASK_RUNNING);

	CS_DBGOUT(CS_WAVE_WRITE | CS_FUNCTION, 2, 
		printk("cs46xx: cs_write()- ret=%zd\n", ret));
	return ret;
}

static unsigned int cs_poll(struct file *file, struct poll_table_struct *wait)
{
	struct cs_card *card = file->private_data;
	struct dmabuf *dmabuf;
	struct cs_state *state;
	unsigned long flags;
	unsigned int mask = 0;

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_poll()+ \n"));
	if (!(file->f_mode & (FMODE_WRITE | FMODE_READ))) {
		return -EINVAL;
	}
	if (file->f_mode & FMODE_WRITE) {
		state = card->states[1];
		if (state) {
			dmabuf = &state->dmabuf;
			poll_wait(file, &dmabuf->wait, wait);
		}
	}
	if (file->f_mode & FMODE_READ) {
		state = card->states[0];
		if (state) {
			dmabuf = &state->dmabuf;
			poll_wait(file, &dmabuf->wait, wait);
		}
	}

	spin_lock_irqsave(&card->lock, flags);
	cs_update_ptr(card, CS_FALSE);
	if (file->f_mode & FMODE_READ) {
		state = card->states[0];
		if (state) {
			dmabuf = &state->dmabuf;
			if (dmabuf->count >= (signed)dmabuf->fragsize)
				mask |= POLLIN | POLLRDNORM;
		}
	}
	if (file->f_mode & FMODE_WRITE) {
		state = card->states[1];
		if (state) {
			dmabuf = &state->dmabuf;
			if (dmabuf->mapped) {
				if (dmabuf->count >= (signed)dmabuf->fragsize)
				    mask |= POLLOUT | POLLWRNORM;
			} else {
				if ((signed)dmabuf->dmasize >= dmabuf->count 
					+ (signed)dmabuf->fragsize)
				    mask |= POLLOUT | POLLWRNORM;
			}
		}
	}
	spin_unlock_irqrestore(&card->lock, flags);

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_poll()- (0x%x) \n",
		mask));
	return mask;
}

/*
 *	We let users mmap the ring buffer. Its not the real DMA buffer but
 *	that side of the code is hidden in the IRQ handling. We do a software
 *	emulation of DMA from a 64K or so buffer into a 2K FIFO. 
 *	(the hardware probably deserves a moan here but Crystal send me nice
 *	toys ;)).
 */
 
static int cs_mmap(struct file *file, struct vm_area_struct *vma)
{
	struct cs_card *card = file->private_data;
	struct cs_state *state;
	struct dmabuf *dmabuf;
	int ret = 0;
	unsigned long size;

	CS_DBGOUT(CS_FUNCTION | CS_PARMS, 2, printk("cs46xx: cs_mmap()+ file=%p %s %s\n", 
		file, vma->vm_flags & VM_WRITE ? "VM_WRITE" : "",
		vma->vm_flags & VM_READ ? "VM_READ" : "") );

	if (vma->vm_flags & VM_WRITE) {
		state = card->states[1];
		if (state) {
			CS_DBGOUT(CS_OPEN, 2, printk(
			  "cs46xx: cs_mmap() VM_WRITE - state TRUE prog_dmabuf DAC\n") );
			if ((ret = prog_dmabuf(state)) != 0)
				return ret;
		}
	} else if (vma->vm_flags & VM_READ) {
		state = card->states[0];
		if (state) {
			CS_DBGOUT(CS_OPEN, 2, printk(
			  "cs46xx: cs_mmap() VM_READ - state TRUE prog_dmabuf ADC\n") );
			if ((ret = prog_dmabuf(state)) != 0)
				return ret;
		}
	} else {
		CS_DBGOUT(CS_ERROR, 2, printk(
		  "cs46xx: cs_mmap() return -EINVAL\n") );
		return -EINVAL;
	}

/*
 * For now ONLY support playback, but seems like the only way to use
 * mmap() is to open an FD with RDWR, just read or just write access
 * does not function, get an error back from the kernel.
 * Also, QuakeIII opens with RDWR!  So, there must be something
 * to needing read/write access mapping.  So, allow read/write but 
 * use the DAC only.
 */
	state = card->states[1];  
	if (!state) {
		ret = -EINVAL;
		goto out;
	}

	mutex_lock(&state->sem);
	dmabuf = &state->dmabuf;
	if (cs4x_pgoff(vma) != 0) {
		ret = -EINVAL;
		goto out;
	}
	size = vma->vm_end - vma->vm_start;

	CS_DBGOUT(CS_PARMS, 2, printk("cs46xx: cs_mmap(): size=%d\n",(unsigned)size) );

	if (size > (PAGE_SIZE << dmabuf->buforder)) {
		ret = -EINVAL;
		goto out;
	}
	if (remap_pfn_range(vma, vma->vm_start,
			     virt_to_phys(dmabuf->rawbuf) >> PAGE_SHIFT,
			     size, vma->vm_page_prot)) {
		ret = -EAGAIN;
		goto out;
	}
	dmabuf->mapped = 1;

	CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_mmap()-\n") );
out:
	mutex_unlock(&state->sem);
	return ret;	
}

static int cs_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
{
	struct cs_card *card = file->private_data;
	struct cs_state *state;
	struct dmabuf *dmabuf = NULL;
	unsigned long flags;
	audio_buf_info abinfo;
	count_info cinfo;
	int val, valsave, ret;
	int mapped = 0;
	void __user *argp = (void __user *)arg;
	int __user *p = argp;

	state = card->states[0];
	if (state) {
		dmabuf = &state->dmabuf;
		mapped = (file->f_mode & FMODE_READ) && dmabuf->mapped;
	}
	state = card->states[1];
	if (state) {
		dmabuf = &state->dmabuf;
		mapped |= (file->f_mode & FMODE_WRITE) && dmabuf->mapped;
	}
		
#if CSDEBUG
	printioctl(cmd);
#endif

	switch (cmd) {
	case OSS_GETVERSION:
		return put_user(SOUND_VERSION, p);
	case SNDCTL_DSP_RESET:
		/* FIXME: spin_lock ? */
		if (file->f_mode & FMODE_WRITE) {
			state = card->states[1];
			if (state) {
				dmabuf = &state->dmabuf;
				stop_dac(state);
				synchronize_irq(card->irq);
				dmabuf->ready = 0;
				resync_dma_ptrs(state);
				dmabuf->swptr = dmabuf->hwptr = 0;
				dmabuf->count = dmabuf->total_bytes = 0;
				dmabuf->blocks = 0;
				dmabuf->SGok = 0;
			}
		}
		if (file->f_mode & FMODE_READ) {
			state = card->states[0];
			if (state) {
				dmabuf = &state->dmabuf;
				stop_adc(state);
				synchronize_irq(card->irq);
				resync_dma_ptrs(state);
				dmabuf->ready = 0;
				dmabuf->swptr = dmabuf->hwptr = 0;
				dmabuf->count = dmabuf->total_bytes = 0;
				dmabuf->blocks = 0;
				dmabuf->SGok = 0;
			}
		}
		CS_DBGOUT(CS_IOCTL, 2, printk("cs46xx: DSP_RESET()-\n") );
		return 0;
	case SNDCTL_DSP_SYNC:
		if (file->f_mode & FMODE_WRITE)
			return drain_dac(state, file->f_flags & O_NONBLOCK);
		return 0;
	case SNDCTL_DSP_SPEED: /* set sample rate */
		if (get_user(val, p))
			return -EFAULT;
		if (val >= 0) {
			if (file->f_mode & FMODE_READ) {
				state = card->states[0];
				if (state) {
					dmabuf = &state->dmabuf;
					stop_adc(state);
					dmabuf->ready = 0;
					dmabuf->SGok = 0;
					cs_set_adc_rate(state, val);
					cs_set_divisor(dmabuf);
				}
			}
			if (file->f_mode & FMODE_WRITE) {
				state = card->states[1];
				if (state) {
					dmabuf = &state->dmabuf;
					stop_dac(state);
					dmabuf->ready = 0;
					dmabuf->SGok = 0;
					cs_set_dac_rate(state, val);
					cs_set_divisor(dmabuf);
				}
			}
			CS_DBGOUT(CS_IOCTL | CS_PARMS, 4, printk(
			    "cs46xx: cs_ioctl() DSP_SPEED %s %s %d\n",
				file->f_mode & FMODE_WRITE ? "DAC" : "",
				file->f_mode & FMODE_READ ? "ADC" : "",
				dmabuf->rate ) );
			return put_user(dmabuf->rate, p);
		}
		return put_user(0, p);
	case SNDCTL_DSP_STEREO: /* set stereo or mono channel */
		if (get_user(val, p))
			return -EFAULT;
		if (file->f_mode & FMODE_WRITE) {
			state = card->states[1];
			if (state) {
				dmabuf = &state->dmabuf;
				stop_dac(state);
				dmabuf->ready = 0;
				dmabuf->SGok = 0;
				if (val)
					dmabuf->fmt |= CS_FMT_STEREO;
				else
					dmabuf->fmt &= ~CS_FMT_STEREO;
				cs_set_divisor(dmabuf);
				CS_DBGOUT(CS_IOCTL | CS_PARMS, 4, printk(
				    "cs46xx: DSP_STEREO() DAC %s\n",
				    (dmabuf->fmt & CS_FMT_STEREO) ?
					"STEREO":"MONO") );
			}
		}
		if (file->f_mode & FMODE_READ) {
			state = card->states[0];
			if (state) {
				dmabuf = &state->dmabuf;
				stop_adc(state);
				dmabuf->ready = 0;
				dmabuf->SGok = 0;
				if (val)
					dmabuf->fmt |= CS_FMT_STEREO;
				else
					dmabuf->fmt &= ~CS_FMT_STEREO;
				cs_set_divisor(dmabuf);
				CS_DBGOUT(CS_IOCTL | CS_PARMS, 4, printk(
				    "cs46xx: DSP_STEREO() ADC %s\n",
				    (dmabuf->fmt & CS_FMT_STEREO) ?
					"STEREO":"MONO") );
			}
		}
		return 0;
	case SNDCTL_DSP_GETBLKSIZE:
		if (file->f_mode & FMODE_WRITE) {
			state = card->states[1];
			if (state) {
				dmabuf = &state->dmabuf;
				if ((val = prog_dmabuf(state)))
					return val;
				return put_user(dmabuf->fragsize, p);
			}
		}
		if (file->f_mode & FMODE_READ) {
			state = card->states[0];
			if (state) {
				dmabuf = &state->dmabuf;
				if ((val = prog_dmabuf(state)))
					return val;
				return put_user(dmabuf->fragsize/dmabuf->divisor, 
						p);
			}
		}
		return put_user(0, p);
	case SNDCTL_DSP_GETFMTS: /* Returns a mask of supported sample format*/
		return put_user(AFMT_S16_LE | AFMT_U8, p);
	case SNDCTL_DSP_SETFMT: /* Select sample format */
		if (get_user(val, p))
			return -EFAULT;
		CS_DBGOUT(CS_IOCTL | CS_PARMS, 4, printk(
		    "cs46xx: cs_ioctl() DSP_SETFMT %s %s %s %s\n",
			file->f_mode & FMODE_WRITE ? "DAC" : "",
			file->f_mode & FMODE_READ ? "ADC" : "",
			val == AFMT_S16_LE ? "16Bit Signed" : "",
			val == AFMT_U8 ? "8Bit Unsigned" : "") );
		valsave = val;
		if (val != AFMT_QUERY) {
			if (val==AFMT_S16_LE || val==AFMT_U8) {
				if (file->f_mode & FMODE_WRITE) {
					state = card->states[1];
					if (state) {
						dmabuf = &state->dmabuf;
						stop_dac(state);
						dmabuf->ready = 0;
						dmabuf->SGok = 0;
						if (val == AFMT_S16_LE)
							dmabuf->fmt |= CS_FMT_16BIT;
						else
							dmabuf->fmt &= ~CS_FMT_16BIT;
						cs_set_divisor(dmabuf);
						if ((ret = prog_dmabuf(state)))
							return ret;
					}
				}
				if (file->f_mode & FMODE_READ) {
					val = valsave;
					state = card->states[0];
					if (state) {
						dmabuf = &state->dmabuf;
						stop_adc(state);
						dmabuf->ready = 0;
						dmabuf->SGok = 0;
						if (val == AFMT_S16_LE)
							dmabuf->fmt |= CS_FMT_16BIT;
						else
							dmabuf->fmt &= ~CS_FMT_16BIT;
						cs_set_divisor(dmabuf);
						if ((ret = prog_dmabuf(state)))
							return ret;
					}
				}
			} else {
				CS_DBGOUT(CS_IOCTL | CS_ERROR, 2, printk(
				    "cs46xx: DSP_SETFMT() Unsupported format (0x%x)\n",
					valsave) );
			}
		} else {
			if (file->f_mode & FMODE_WRITE) {
				state = card->states[1];
				if (state)
					dmabuf = &state->dmabuf;
			} else if (file->f_mode & FMODE_READ) {
				state = card->states[0];
				if (state)
					dmabuf = &state->dmabuf;
			}
		}
		if (dmabuf) {
			if (dmabuf->fmt & CS_FMT_16BIT)
				return put_user(AFMT_S16_LE, p);
			else
				return put_user(AFMT_U8, p);
		}
		return put_user(0, p);
	case SNDCTL_DSP_CHANNELS:
		if (get_user(val, p))
			return -EFAULT;
		if (val != 0) {
			if (file->f_mode & FMODE_WRITE) {
				state = card->states[1];
				if (state) {
					dmabuf = &state->dmabuf;
					stop_dac(state);
					dmabuf->ready = 0;
					dmabuf->SGok = 0;
					if (val > 1)
						dmabuf->fmt |= CS_FMT_STEREO;
					else
						dmabuf->fmt &= ~CS_FMT_STEREO;
					cs_set_divisor(dmabuf);
					if (prog_dmabuf(state))
						return 0;
				}
			}
			if (file->f_mode & FMODE_READ) {
				state = card->states[0];
				if (state) {
					dmabuf = &state->dmabuf;
					stop_adc(state);
					dmabuf->ready = 0;
					dmabuf->SGok = 0;
					if (val > 1)
						dmabuf->fmt |= CS_FMT_STEREO;
					else
						dmabuf->fmt &= ~CS_FMT_STEREO;
					cs_set_divisor(dmabuf);
					if (prog_dmabuf(state))
						return 0;
				}
			}
		}
		return put_user((dmabuf->fmt & CS_FMT_STEREO) ? 2 : 1,
				p);
	case SNDCTL_DSP_POST:
		/*
		 * There will be a longer than normal pause in the data.
		 * so... do nothing, because there is nothing that we can do.
		 */
		return 0;
	case SNDCTL_DSP_SUBDIVIDE:
		if (file->f_mode & FMODE_WRITE) {
			state = card->states[1];
			if (state) {
				dmabuf = &state->dmabuf;
				if (dmabuf->subdivision)
					return -EINVAL;
				if (get_user(val, p))
					return -EFAULT;
				if (val != 1 && val != 2)
					return -EINVAL;
				dmabuf->subdivision = val;
			}
		}
		if (file->f_mode & FMODE_READ) {
			state = card->states[0];
			if (state) {
				dmabuf = &state->dmabuf;
				if (dmabuf->subdivision)
					return -EINVAL;
				if (get_user(val, p))
					return -EFAULT;
				if (val != 1 && val != 2)
					return -EINVAL;
				dmabuf->subdivision = val;
			}
		}
		return 0;
	case SNDCTL_DSP_SETFRAGMENT:
		if (get_user(val, p))
			return -EFAULT;
		if (file->f_mode & FMODE_WRITE) {
			state = card->states[1];
			if (state) {
				dmabuf = &state->dmabuf;
				dmabuf->ossfragshift = val & 0xffff;
				dmabuf->ossmaxfrags = (val >> 16) & 0xffff;
			}
		}
		if (file->f_mode & FMODE_READ) {
			state = card->states[0];
			if (state) {
				dmabuf = &state->dmabuf;
				dmabuf->ossfragshift = val & 0xffff;
				dmabuf->ossmaxfrags = (val >> 16) & 0xffff;
			}
		}
		return 0;
	case SNDCTL_DSP_GETOSPACE:
		if (!(file->f_mode & FMODE_WRITE))
			return -EINVAL;
		state = card->states[1];
		if (state) {
			dmabuf = &state->dmabuf;
			spin_lock_irqsave(&state->card->lock, flags);
			cs_update_ptr(card, CS_TRUE);
			abinfo.fragsize = dmabuf->fragsize;
			abinfo.fragstotal = dmabuf->numfrag;
		/*
		 * for mmap we always have total space available
		 */
			if (dmabuf->mapped)
				abinfo.bytes = dmabuf->dmasize;
			else
				abinfo.bytes = dmabuf->dmasize - dmabuf->count;

			abinfo.fragments = abinfo.bytes >> dmabuf->fragshift;
			spin_unlock_irqrestore(&state->card->lock, flags);
			return copy_to_user(argp, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
		}
		return -ENODEV;
	case SNDCTL_DSP_GETISPACE:
		if (!(file->f_mode & FMODE_READ))
			return -EINVAL;
		state = card->states[0];
		if (state) {
			dmabuf = &state->dmabuf;
			spin_lock_irqsave(&state->card->lock, flags);
			cs_update_ptr(card, CS_TRUE);
			abinfo.fragsize = dmabuf->fragsize/dmabuf->divisor;
			abinfo.bytes = dmabuf->count/dmabuf->divisor;
			abinfo.fragstotal = dmabuf->numfrag;
			abinfo.fragments = abinfo.bytes >> dmabuf->fragshift;
			spin_unlock_irqrestore(&state->card->lock, flags);
			return copy_to_user(argp, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
		}
		return -ENODEV;
	case SNDCTL_DSP_NONBLOCK:
		file->f_flags |= O_NONBLOCK;
		return 0;
	case SNDCTL_DSP_GETCAPS:
		return put_user(DSP_CAP_REALTIME|DSP_CAP_TRIGGER|DSP_CAP_MMAP,
			    p);
	case SNDCTL_DSP_GETTRIGGER:
		val = 0;
		CS_DBGOUT(CS_IOCTL, 2, printk("cs46xx: DSP_GETTRIGGER()+\n") );
		if (file->f_mode & FMODE_WRITE) {
			state = card->states[1];
			if (state) {
				dmabuf = &state->dmabuf;
				if (dmabuf->enable & DAC_RUNNING)
					val |= PCM_ENABLE_INPUT;
			}
		}
		if (file->f_mode & FMODE_READ) {
			if (state) {
				state = card->states[0];
				dmabuf = &state->dmabuf;
				if (dmabuf->enable & ADC_RUNNING)
					val |= PCM_ENABLE_OUTPUT;
			}
		}
		CS_DBGOUT(CS_IOCTL, 2, printk("cs46xx: DSP_GETTRIGGER()- val=0x%x\n",val) );
		return put_user(val, p);
	case SNDCTL_DSP_SETTRIGGER:
		if (get_user(val, p))
			return -EFAULT;
		if (file->f_mode & FMODE_READ) {
			state = card->states[0];
			if (state) {
				dmabuf = &state->dmabuf;
				if (val & PCM_ENABLE_INPUT) {
					if (!dmabuf->ready && (ret = prog_dmabuf(state)))
						return ret;
					start_adc(state);
				} else
					stop_adc(state);
			}
		}
		if (file->f_mode & FMODE_WRITE) {
			state = card->states[1];
			if (state) {
				dmabuf = &state->dmabuf;
				if (val & PCM_ENABLE_OUTPUT) {
					if (!dmabuf->ready && (ret = prog_dmabuf(state)))
						return ret;
					start_dac(state);
				} else
					stop_dac(state);
			}
		}
		return 0;
	case SNDCTL_DSP_GETIPTR:
		if (!(file->f_mode & FMODE_READ))
			return -EINVAL;
		state = card->states[0];
		if (state) {
			dmabuf = &state->dmabuf;
			spin_lock_irqsave(&state->card->lock, flags);
			cs_update_ptr(card, CS_TRUE);
			cinfo.bytes = dmabuf->total_bytes/dmabuf->divisor;
			cinfo.blocks = dmabuf->count/dmabuf->divisor >> dmabuf->fragshift;
			cinfo.ptr = dmabuf->hwptr/dmabuf->divisor;
			spin_unlock_irqrestore(&state->card->lock, flags);
			if (copy_to_user(argp, &cinfo, sizeof(cinfo)))
				return -EFAULT;
			return 0;
		}
		return -ENODEV;
	case SNDCTL_DSP_GETOPTR:
		if (!(file->f_mode & FMODE_WRITE))
			return -EINVAL;
		state = card->states[1];
		if (state) {
			dmabuf = &state->dmabuf;
			spin_lock_irqsave(&state->card->lock, flags);
			cs_update_ptr(card, CS_TRUE);
			cinfo.bytes = dmabuf->total_bytes;
			if (dmabuf->mapped) {
				cinfo.blocks = (cinfo.bytes >> dmabuf->fragshift) 
							- dmabuf->blocks;
				CS_DBGOUT(CS_PARMS, 8, 
					printk("total_bytes=%d blocks=%d dmabuf->blocks=%d\n", 
					cinfo.bytes,cinfo.blocks,dmabuf->blocks) );
				dmabuf->blocks = cinfo.bytes >> dmabuf->fragshift;
			} else {
				cinfo.blocks = dmabuf->count >> dmabuf->fragshift;
			}
			cinfo.ptr = dmabuf->hwptr;

			CS_DBGOUT(CS_PARMS, 4, printk(
			    "cs46xx: GETOPTR bytes=%d blocks=%d ptr=%d\n",
				cinfo.bytes,cinfo.blocks,cinfo.ptr) );
			spin_unlock_irqrestore(&state->card->lock, flags);
			if (copy_to_user(argp, &cinfo, sizeof(cinfo)))
				return -EFAULT;
			return 0;
		}
		return -ENODEV;
	case SNDCTL_DSP_SETDUPLEX:
		return 0;
	case SNDCTL_DSP_GETODELAY:
		if (!(file->f_mode & FMODE_WRITE))
			return -EINVAL;
		state = card->states[1];
		if (state) {
			dmabuf = &state->dmabuf;
			spin_lock_irqsave(&state->card->lock, flags);
			cs_update_ptr(card, CS_TRUE);
			val = dmabuf->count;
			spin_unlock_irqrestore(&state->card->lock, flags);
		} else
			val = 0;
		return put_user(val, p);
	case SOUND_PCM_READ_RATE:
		if (file->f_mode & FMODE_READ)
			state = card->states[0];
		else 
			state = card->states[1];
		if (state) {
			dmabuf = &state->dmabuf;
			return put_user(dmabuf->rate, p);
		}
		return put_user(0, p);
	case SOUND_PCM_READ_CHANNELS:
		if (file->f_mode & FMODE_READ)
			state = card->states[0];
		else 
			state = card->states[1];
		if (state) {
			dmabuf = &state->dmabuf;
			return put_user((dmabuf->fmt & CS_FMT_STEREO) ? 2 : 1,
				p);
		}
		return put_user(0, p);
	case SOUND_PCM_READ_BITS:
		if (file->f_mode & FMODE_READ)
			state = card->states[0];
		else 
			state = card->states[1];
		if (state) {
			dmabuf = &state->dmabuf;
			return put_user((dmabuf->fmt & CS_FMT_16BIT) ? 
			  	AFMT_S16_LE : AFMT_U8, p);

		}
		return put_user(0, p);
	case SNDCTL_DSP_MAPINBUF:
	case SNDCTL_DSP_MAPOUTBUF:
	case SNDCTL_DSP_SETSYNCRO:
	case SOUND_PCM_WRITE_FILTER:
	case SOUND_PCM_READ_FILTER:
		return -EINVAL;
	}
	return -EINVAL;
}


/*
 *	AMP control - null AMP
 */
 
static void amp_none(struct cs_card *card, int change)
{	
}

/*
 *	Crystal EAPD mode
 */
 
static void amp_voyetra(struct cs_card *card, int change)
{
	/* Manage the EAPD bit on the Crystal 4297 
	   and the Analog AD1885 */
	   
	int old = card->amplifier;
	
	card->amplifier+=change;
	if (card->amplifier && !old) {
		/* Turn the EAPD amp on */
		cs_ac97_set(card->ac97_codec[0],  AC97_POWER_CONTROL, 
			cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) |
				0x8000);
	} else if(old && !card->amplifier) {
		/* Turn the EAPD amp off */
		cs_ac97_set(card->ac97_codec[0],  AC97_POWER_CONTROL, 
			cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) &
				~0x8000);
	}
}

		       
/*
 *	Game Theatre XP card - EGPIO[2] is used to enable the external amp.
 */
 
static void amp_hercules(struct cs_card *card, int change)
{
	int old = card->amplifier;
	if (!card) {
		CS_DBGOUT(CS_ERROR, 2, printk(KERN_INFO 
			"cs46xx: amp_hercules() called before initialized.\n"));
		return;
	}
	card->amplifier+=change;
	if ((card->amplifier && !old) && !(hercules_egpio_disable)) {
		CS_DBGOUT(CS_PARMS, 4, printk(KERN_INFO 
			"cs46xx: amp_hercules() external amp enabled\n"));
		cs461x_pokeBA0(card, BA0_EGPIODR, 
			EGPIODR_GPOE2);     /* enable EGPIO2 output */
		cs461x_pokeBA0(card, BA0_EGPIOPTR, 
			EGPIOPTR_GPPT2);   /* open-drain on output */
	} else if (old && !card->amplifier) {
		CS_DBGOUT(CS_PARMS, 4, printk(KERN_INFO 
			"cs46xx: amp_hercules() external amp disabled\n"));
		cs461x_pokeBA0(card, BA0_EGPIODR, 0); /* disable */
		cs461x_pokeBA0(card, BA0_EGPIOPTR, 0); /* disable */
	}
}

/*
 *	Handle the CLKRUN on a thinkpad. We must disable CLKRUN support
 *	whenever we need to beat on the chip.
 *
 *	The original idea and code for this hack comes from David Kaiser at
 *	Linuxcare. Perhaps one day Crystal will document their chips well
 *	enough to make them useful.
 */
 
static void clkrun_hack(struct cs_card *card, int change)
{
	struct pci_dev *acpi_dev;
	u16 control;
	u8 pp;
	unsigned long port;
	int old = card->active;
	
	card->active+=change;
	
	acpi_dev = pci_get_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_3, NULL);
	if (acpi_dev == NULL)
		return;		/* Not a thinkpad thats for sure */

	/* Find the control port */		
	pci_read_config_byte(acpi_dev, 0x41, &pp);
	port = pp << 8;

	/* Read ACPI port */	
	control = inw(port + 0x10);

	/* Flip CLKRUN off while running */
	if (!card->active && old) {
		CS_DBGOUT(CS_PARMS , 9, printk( KERN_INFO
			"cs46xx: clkrun() enable clkrun - change=%d active=%d\n",
				change,card->active));
		outw(control|0x2000, port+0x10);
	} else {
	/*
	* sometimes on a resume the bit is set, so always reset the bit.
	*/
		CS_DBGOUT(CS_PARMS , 9, printk( KERN_INFO
			"cs46xx: clkrun() disable clkrun - change=%d active=%d\n",
				change,card->active));
		outw(control&~0x2000, port+0x10);
	}
	pci_dev_put(acpi_dev);
}

	
static int cs_open(struct inode *inode, struct file *file)
{
	struct cs_card *card = file->private_data;
	struct cs_state *state = NULL;
	struct dmabuf *dmabuf = NULL;
	struct list_head *entry;
        unsigned int minor = iminor(inode);
	int ret = 0;
	unsigned int tmp;

	CS_DBGOUT(CS_OPEN | CS_FUNCTION, 2, printk("cs46xx: cs_open()+ file=%p %s %s\n",
		file, file->f_mode & FMODE_WRITE ? "FMODE_WRITE" : "",
		file->f_mode & FMODE_READ ? "FMODE_READ" : "") );

	list_for_each(entry, &cs46xx_devs) {
		card = list_entry(entry, struct cs_card, list);

		if (!((card->dev_audio ^ minor) & ~0xf))
			break;
	}
	if (entry == &cs46xx_devs)
		return -ENODEV;
	if (!card) {
		CS_DBGOUT(CS_FUNCTION | CS_OPEN, 2, printk(KERN_INFO
			"cs46xx: cs_open(): Error - unable to find audio card struct\n"));
		return -ENODEV;
	}

	/*
	 * hardcode state[0] for capture, [1] for playback
	 */
	if (file->f_mode & FMODE_READ) {
		CS_DBGOUT(CS_WAVE_READ, 2, printk("cs46xx: cs_open() FMODE_READ\n") );
		if (card->states[0] == NULL) {
			state = card->states[0] =
				kmalloc(sizeof(struct cs_state), GFP_KERNEL);
			if (state == NULL)
				return -ENOMEM;
			memset(state, 0, sizeof(struct cs_state));
			mutex_init(&state->sem);
			dmabuf = &state->dmabuf;
			dmabuf->pbuf = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
			if (dmabuf->pbuf == NULL) {
				kfree(state);
				card->states[0] = NULL;
				return -ENOMEM;
			}
		} else {
			state = card->states[0];
			if (state->open_mode & FMODE_READ)
				return -EBUSY;
		}
		dmabuf->channel = card->alloc_rec_pcm_channel(card);
			
		if (dmabuf->channel == NULL) {
			kfree(card->states[0]);
			card->states[0] = NULL;
			return -ENODEV;
		}

		/* Now turn on external AMP if needed */
		state->card = card;
		state->card->active_ctrl(state->card, 1);
		state->card->amplifier_ctrl(state->card, 1);
		
		if ((tmp = cs46xx_powerup(card, CS_POWER_ADC))) {
			CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
				"cs46xx: cs46xx_powerup of ADC failed (0x%x)\n", tmp));
			return -EIO;
		}

		dmabuf->channel->state = state;
		/* initialize the virtual channel */
		state->virt = 0;
		state->magic = CS_STATE_MAGIC;
		init_waitqueue_head(&dmabuf->wait);
		mutex_init(&state->open_mutex);
		file->private_data = card;

		mutex_lock(&state->open_mutex);

		/* set default sample format. According to OSS Programmer's Guide  /dev/dsp
		   should be default to unsigned 8-bits, mono, with sample rate 8kHz and
		   /dev/dspW will accept 16-bits sample */

		/* Default input is 8bit mono */
		dmabuf->fmt &= ~CS_FMT_MASK;
		dmabuf->type = CS_TYPE_ADC;
		dmabuf->ossfragshift = 0;
		dmabuf->ossmaxfrags  = 0;
		dmabuf->subdivision  = 0;
		cs_set_adc_rate(state, 8000);
		cs_set_divisor(dmabuf);

		state->open_mode |= FMODE_READ;
		mutex_unlock(&state->open_mutex);
	}
	if (file->f_mode & FMODE_WRITE) {
		CS_DBGOUT(CS_OPEN, 2, printk("cs46xx: cs_open() FMODE_WRITE\n") );
		if (card->states[1] == NULL) {
			state = card->states[1] =
				kmalloc(sizeof(struct cs_state), GFP_KERNEL);
			if (state == NULL)
				return -ENOMEM;
			memset(state, 0, sizeof(struct cs_state));
			mutex_init(&state->sem);
			dmabuf = &state->dmabuf;
			dmabuf->pbuf = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
			if (dmabuf->pbuf == NULL) {
				kfree(state);
				card->states[1] = NULL;
				return -ENOMEM;
			}
		} else {
			state = card->states[1];
			if (state->open_mode & FMODE_WRITE)
				return -EBUSY;
		}
		dmabuf->channel = card->alloc_pcm_channel(card);
			
		if (dmabuf->channel == NULL) {
			kfree(card->states[1]);
			card->states[1] = NULL;
			return -ENODEV;
		}

		/* Now turn on external AMP if needed */
		state->card = card;
		state->card->active_ctrl(state->card, 1);
		state->card->amplifier_ctrl(state->card, 1);

		if ((tmp = cs46xx_powerup(card, CS_POWER_DAC))) {
			CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
				"cs46xx: cs46xx_powerup of DAC failed (0x%x)\n", tmp));
			return -EIO;
		}
		
		dmabuf->channel->state = state;
		/* initialize the virtual channel */
		state->virt = 1;
		state->magic = CS_STATE_MAGIC;
		init_waitqueue_head(&dmabuf->wait);
		mutex_init(&state->open_mutex);
		file->private_data = card;

		mutex_lock(&state->open_mutex);

		/* set default sample format. According to OSS Programmer's Guide  /dev/dsp
		   should be default to unsigned 8-bits, mono, with sample rate 8kHz and
		   /dev/dspW will accept 16-bits sample */

		/* Default output is 8bit mono. */
		dmabuf->fmt &= ~CS_FMT_MASK;
		dmabuf->type = CS_TYPE_DAC;
		dmabuf->ossfragshift = 0;
		dmabuf->ossmaxfrags  = 0;
		dmabuf->subdivision  = 0;
		cs_set_dac_rate(state, 8000);
		cs_set_divisor(dmabuf);

		state->open_mode |= FMODE_WRITE;
		mutex_unlock(&state->open_mutex);
		if ((ret = prog_dmabuf(state)))
			return ret;
	}
	CS_DBGOUT(CS_OPEN | CS_FUNCTION, 2, printk("cs46xx: cs_open()- 0\n"));
	return nonseekable_open(inode, file);
}

static int cs_release(struct inode *inode, struct file *file)
{
	struct cs_card *card = file->private_data;
	struct dmabuf *dmabuf;
	struct cs_state *state;
	unsigned int tmp;
	CS_DBGOUT(CS_RELEASE | CS_FUNCTION, 2, printk("cs46xx: cs_release()+ file=%p %s %s\n",
		file, file->f_mode & FMODE_WRITE ? "FMODE_WRITE" : "",
		file->f_mode & FMODE_READ ? "FMODE_READ" : ""));

	if (!(file->f_mode & (FMODE_WRITE | FMODE_READ)))
		return -EINVAL;
	state = card->states[1];
	if (state) {
		if ((state->open_mode & FMODE_WRITE) & (file->f_mode & FMODE_WRITE)) {
			CS_DBGOUT(CS_RELEASE, 2, printk("cs46xx: cs_release() FMODE_WRITE\n"));
			dmabuf = &state->dmabuf;
			cs_clear_tail(state);
			drain_dac(state, file->f_flags & O_NONBLOCK);
			/* stop DMA state machine and free DMA buffers/channels */
			mutex_lock(&state->open_mutex);
			stop_dac(state);
			dealloc_dmabuf(state);
			state->card->free_pcm_channel(state->card, dmabuf->channel->num);
			free_page((unsigned long)state->dmabuf.pbuf);

			/* we're covered by the open_mutex */
			mutex_unlock(&state->open_mutex);
			state->card->states[state->virt] = NULL;
			state->open_mode &= (~file->f_mode) & (FMODE_READ|FMODE_WRITE);

			if ((tmp = cs461x_powerdown(card, CS_POWER_DAC, CS_FALSE))) {
				CS_DBGOUT(CS_ERROR, 1, printk(KERN_INFO 
					"cs46xx: cs_release_mixdev() powerdown DAC failure (0x%x)\n",tmp) );
			}

			/* Now turn off external AMP if needed */
			state->card->amplifier_ctrl(state->card, -1);
			state->card->active_ctrl(state->card, -1);
			kfree(state);
		}
	}

	state = card->states[0];
	if (state) {
		if ((state->open_mode & FMODE_READ) & (file->f_mode & FMODE_READ)) {
			CS_DBGOUT(CS_RELEASE, 2, printk("cs46xx: cs_release() FMODE_READ\n"));
			dmabuf = &state->dmabuf;
			mutex_lock(&state->open_mutex);
			stop_adc(state);
			dealloc_dmabuf(state);
			state->card->free_pcm_channel(state->card, dmabuf->channel->num);
			free_page((unsigned long)state->dmabuf.pbuf);

			/* we're covered by the open_mutex */
			mutex_unlock(&state->open_mutex);
			state->card->states[state->virt] = NULL;
			state->open_mode &= (~file->f_mode) & (FMODE_READ|FMODE_WRITE);

			if ((tmp = cs461x_powerdown(card, CS_POWER_ADC, CS_FALSE))) {
				CS_DBGOUT(CS_ERROR, 1, printk(KERN_INFO 
					"cs46xx: cs_release_mixdev() powerdown ADC failure (0x%x)\n",tmp) );
			}

			/* Now turn off external AMP if needed */
			state->card->amplifier_ctrl(state->card, -1);
			state->card->active_ctrl(state->card, -1);
			kfree(state);
		}
	}

	CS_DBGOUT(CS_FUNCTION | CS_RELEASE, 2, printk("cs46xx: cs_release()- 0\n"));
	return 0;
}

static void printpm(struct cs_card *s)
{
	CS_DBGOUT(CS_PM, 9, printk("pm struct:\n"));
	CS_DBGOUT(CS_PM, 9, printk("flags:0x%x u32CLKCR1_SAVE: 0%x u32SSPMValue: 0x%x\n",
		(unsigned)s->pm.flags,s->pm.u32CLKCR1_SAVE,s->pm.u32SSPMValue));
	CS_DBGOUT(CS_PM, 9, printk("u32PPLVCvalue: 0x%x u32PPRVCvalue: 0x%x\n",
		s->pm.u32PPLVCvalue,s->pm.u32PPRVCvalue));
	CS_DBGOUT(CS_PM, 9, printk("u32FMLVCvalue: 0x%x u32FMRVCvalue: 0x%x\n",
		s->pm.u32FMLVCvalue,s->pm.u32FMRVCvalue));
	CS_DBGOUT(CS_PM, 9, printk("u32GPIORvalue: 0x%x u32JSCTLvalue: 0x%x\n",
		s->pm.u32GPIORvalue,s->pm.u32JSCTLvalue));
	CS_DBGOUT(CS_PM, 9, printk("u32SSCR: 0x%x u32SRCSA: 0x%x\n",
		s->pm.u32SSCR,s->pm.u32SRCSA));
	CS_DBGOUT(CS_PM, 9, printk("u32DacASR: 0x%x u32AdcASR: 0x%x\n",
		s->pm.u32DacASR,s->pm.u32AdcASR));
	CS_DBGOUT(CS_PM, 9, printk("u32DacSR: 0x%x u32AdcSR: 0x%x\n",
		s->pm.u32DacSR,s->pm.u32AdcSR));
	CS_DBGOUT(CS_PM, 9, printk("u32MIDCR_Save: 0x%x\n",
		s->pm.u32MIDCR_Save));
	CS_DBGOUT(CS_PM, 9, printk("u32AC97_powerdown: 0x%x _general_purpose 0x%x\n",
		s->pm.u32AC97_powerdown,s->pm.u32AC97_general_purpose));
	CS_DBGOUT(CS_PM, 9, printk("u32AC97_master_volume: 0x%x\n",
		s->pm.u32AC97_master_volume));
	CS_DBGOUT(CS_PM, 9, printk("u32AC97_headphone_volume: 0x%x\n",
		s->pm.u32AC97_headphone_volume));
	CS_DBGOUT(CS_PM, 9, printk("u32AC97_master_volume_mono: 0x%x\n",
		s->pm.u32AC97_master_volume_mono));
	CS_DBGOUT(CS_PM, 9, printk("u32AC97_pcm_out_volume: 0x%x\n",
		s->pm.u32AC97_pcm_out_volume));
	CS_DBGOUT(CS_PM, 9, printk("dmabuf_swptr_play: 0x%x dmabuf_count_play: %d\n",
		s->pm.dmabuf_swptr_play,s->pm.dmabuf_count_play));
	CS_DBGOUT(CS_PM, 9, printk("dmabuf_swptr_capture: 0x%x dmabuf_count_capture: %d\n",
		s->pm.dmabuf_swptr_capture,s->pm.dmabuf_count_capture));

}

/****************************************************************************
*
*  Suspend - save the ac97 regs, mute the outputs and power down the part.  
*
****************************************************************************/
static void cs46xx_ac97_suspend(struct cs_card *card)
{
	int Count,i;
	struct ac97_codec *dev=card->ac97_codec[0];
	unsigned int tmp;

	CS_DBGOUT(CS_PM, 9, printk("cs46xx: cs46xx_ac97_suspend()+\n"));

	if (card->states[1]) {
		stop_dac(card->states[1]);
		resync_dma_ptrs(card->states[1]);
	}
	if (card->states[0]) {
		stop_adc(card->states[0]);