Linux Audio

Check our new training course

Embedded Linux Audio

Check our new training course
with Creative Commons CC-BY-SA
lecture materials

Bootlin logo

Elixir Cross Referencer

Loading...
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
/*
 *  linux/sound/oss/dmasound/dmasound_core.c
 *
 *
 *  OSS/Free compatible Atari TT/Falcon and Amiga DMA sound driver for
 *  Linux/m68k
 *  Extended to support Power Macintosh for Linux/ppc by Paul Mackerras
 *
 *  (c) 1995 by Michael Schlueter & Michael Marte
 *
 *  Michael Schlueter (michael@duck.syd.de) did the basic structure of the VFS
 *  interface and the u-law to signed byte conversion.
 *
 *  Michael Marte (marte@informatik.uni-muenchen.de) did the sound queue,
 *  /dev/mixer, /dev/sndstat and complemented the VFS interface. He would like
 *  to thank:
 *    - Michael Schlueter for initial ideas and documentation on the MFP and
 *	the DMA sound hardware.
 *    - Therapy? for their CD 'Troublegum' which really made me rock.
 *
 *  /dev/sndstat is based on code by Hannu Savolainen, the author of the
 *  VoxWare family of drivers.
 *
 *  This file is subject to the terms and conditions of the GNU General Public
 *  License.  See the file COPYING in the main directory of this archive
 *  for more details.
 *
 *  History:
 *
 *	1995/8/25	First release
 *
 *	1995/9/02	Roman Hodek:
 *			  - Fixed atari_stram_alloc() call, the timer
 *			    programming and several race conditions
 *	1995/9/14	Roman Hodek:
 *			  - After some discussion with Michael Schlueter,
 *			    revised the interrupt disabling
 *			  - Slightly speeded up U8->S8 translation by using
 *			    long operations where possible
 *			  - Added 4:3 interpolation for /dev/audio
 *
 *	1995/9/20	Torsten Scherer:
 *			  - Fixed a bug in sq_write and changed /dev/audio
 *			    converting to play at 12517Hz instead of 6258Hz.
 *
 *	1995/9/23	Torsten Scherer:
 *			  - Changed sq_interrupt() and sq_play() to pre-program
 *			    the DMA for another frame while there's still one
 *			    running. This allows the IRQ response to be
 *			    arbitrarily delayed and playing will still continue.
 *
 *	1995/10/14	Guenther Kelleter, Torsten Scherer:
 *			  - Better support for Falcon audio (the Falcon doesn't
 *			    raise an IRQ at the end of a frame, but at the
 *			    beginning instead!). uses 'if (codec_dma)' in lots
 *			    of places to simply switch between Falcon and TT
 *			    code.
 *
 *	1995/11/06	Torsten Scherer:
 *			  - Started introducing a hardware abstraction scheme
 *			    (may perhaps also serve for Amigas?)
 *			  - Can now play samples at almost all frequencies by
 *			    means of a more generalized expand routine
 *			  - Takes a good deal of care to cut data only at
 *			    sample sizes
 *			  - Buffer size is now a kernel runtime option
 *			  - Implemented fsync() & several minor improvements
 *			Guenther Kelleter:
 *			  - Useful hints and bug fixes
 *			  - Cross-checked it for Falcons
 *
 *	1996/3/9	Geert Uytterhoeven:
 *			  - Support added for Amiga, A-law, 16-bit little
 *			    endian.
 *			  - Unification to drivers/sound/dmasound.c.
 *
 *	1996/4/6	Martin Mitchell:
 *			  - Updated to 1.3 kernel.
 *
 *	1996/6/13       Topi Kanerva:
 *			  - Fixed things that were broken (mainly the amiga
 *			    14-bit routines)
 *			  - /dev/sndstat shows now the real hardware frequency
 *			  - The lowpass filter is disabled by default now
 *
 *	1996/9/25	Geert Uytterhoeven:
 *			  - Modularization
 *
 *	1998/6/10	Andreas Schwab:
 *			  - Converted to use sound_core
 *
 *	1999/12/28	Richard Zidlicky:
 *			  - Added support for Q40
 *
 *	2000/2/27	Geert Uytterhoeven:
 *			  - Clean up and split the code into 4 parts:
 *			      o dmasound_core: machine-independent code
 *			      o dmasound_atari: Atari TT and Falcon support
 *			      o dmasound_awacs: Apple PowerMac support
 *			      o dmasound_paula: Amiga support
 *
 *	2000/3/25	Geert Uytterhoeven:
 *			  - Integration of dmasound_q40
 *			  - Small clean ups
 *
 *	2001/01/26 [1.0] Iain Sandoe
 *			  - make /dev/sndstat show revision & edition info.
 *			  - since dmasound.mach.sq_setup() can fail on pmac
 *			    its type has been changed to int and the returns
 *			    are checked.
 *		   [1.1]  - stop missing translations from being called.
 *	2001/02/08 [1.2]  - remove unused translation tables & move machine-
 *			    specific tables to low-level.
 *			  - return correct info. for SNDCTL_DSP_GETFMTS.
 *		   [1.3]  - implement SNDCTL_DSP_GETCAPS fully.
 *		   [1.4]  - make /dev/sndstat text length usage deterministic.
 *			  - make /dev/sndstat call to low-level
 *			    dmasound.mach.state_info() pass max space to ll driver.
 *			  - tidy startup banners and output info.
 *		   [1.5]  - tidy up a little (removed some unused #defines in
 *			    dmasound.h)
 *			  - fix up HAS_RECORD conditionalisation.
 *			  - add record code in places it is missing...
 *			  - change buf-sizes to bytes to allow < 1kb for pmac
 *			    if user param entry is < 256 the value is taken to
 *			    be in kb > 256 is taken to be in bytes.
 *			  - make default buff/frag params conditional on
 *			    machine to allow smaller values for pmac.
 *			  - made the ioctls, read & write comply with the OSS
 *			    rules on setting params.
 *			  - added parsing of _setup() params for record.
 *	2001/04/04 [1.6]  - fix bug where sample rates higher than maximum were
 *			    being reported as OK.
 *			  - fix open() to return -EBUSY as per OSS doc. when
 *			    audio is in use - this is independent of O_NOBLOCK.
 *			  - fix bug where SNDCTL_DSP_POST was blocking.
 */

 /* Record capability notes 30/01/2001:
  * At present these observations apply only to pmac LL driver (the only one
  * that can do record, at present).  However, if other LL drivers for machines
  * with record are added they may apply.
  *
  * The fragment parameters for the record and play channels are separate.
  * However, if the driver is opened O_RDWR there is no way (in the current OSS
  * API) to specify their values independently for the record and playback
  * channels.  Since the only common factor between the input & output is the
  * sample rate (on pmac) it should be possible to open /dev/dspX O_WRONLY and
  * /dev/dspY O_RDONLY.  The input & output channels could then have different
  * characteristics (other than the first that sets sample rate claiming the
  * right to set it for ever).  As it stands, the format, channels, number of
  * bits & sample rate are assumed to be common.  In the future perhaps these
  * should be the responsibility of the LL driver - and then if a card really
  * does not share items between record & playback they can be specified
  * separately.
*/

/* Thread-safeness of shared_resources notes: 31/01/2001
 * If the user opens O_RDWR and then splits record & play between two threads
 * both of which inherit the fd - and then starts changing things from both
 * - we will have difficulty telling.
 *
 * It's bad application coding - but ...
 * TODO: think about how to sort this out... without bogging everything down in
 * semaphores.
 *
 * Similarly, the OSS spec says "all changes to parameters must be between
 * open() and the first read() or write(). - and a bit later on (by
 * implication) "between SNDCTL_DSP_RESET and the first read() or write() after
 * it".  If the app is multi-threaded and this rule is broken between threads
 * we will have trouble spotting it - and the fault will be rather obscure :-(
 *
 * We will try and put out at least a kmsg if we see it happen... but I think
 * it will be quite hard to trap it with an -EXXX return... because we can't
 * see the fault until after the damage is done.
*/

#include <linux/module.h>
#include <linux/slab.h>
#include <linux/sound.h>
#include <linux/init.h>
#include <linux/soundcard.h>
#include <linux/poll.h>
#include <linux/smp_lock.h>

#include <asm/uaccess.h>

#include "dmasound.h"

#define DMASOUND_CORE_REVISION 1
#define DMASOUND_CORE_EDITION 6

    /*
     *  Declarations
     */

int dmasound_catchRadius = 0;
module_param(dmasound_catchRadius, int, 0);

static unsigned int numWriteBufs = DEFAULT_N_BUFFERS;
module_param(numWriteBufs, int, 0);
static unsigned int writeBufSize = DEFAULT_BUFF_SIZE ;	/* in bytes */
module_param(writeBufSize, int, 0);

MODULE_LICENSE("GPL");

#ifdef MODULE
static int sq_unit = -1;
static int mixer_unit = -1;
static int state_unit = -1;
static int irq_installed;
#endif /* MODULE */

/* control over who can modify resources shared between play/record */
static mode_t shared_resource_owner;
static int shared_resources_initialised;

    /*
     *  Mid level stuff
     */

struct sound_settings dmasound = { .lock = SPIN_LOCK_UNLOCKED };

static inline void sound_silence(void)
{
	dmasound.mach.silence(); /* _MUST_ stop DMA */
}

static inline int sound_set_format(int format)
{
	return dmasound.mach.setFormat(format);
}


static int sound_set_speed(int speed)
{
	if (speed < 0)
		return dmasound.soft.speed;

	/* trap out-of-range speed settings.
	   at present we allow (arbitrarily) low rates - using soft
	   up-conversion - but we can't allow > max because there is
	   no soft down-conversion.
	*/
	if (dmasound.mach.max_dsp_speed &&
	   (speed > dmasound.mach.max_dsp_speed))
		speed = dmasound.mach.max_dsp_speed ;

	dmasound.soft.speed = speed;

	if (dmasound.minDev == SND_DEV_DSP)
		dmasound.dsp.speed = dmasound.soft.speed;

	return dmasound.soft.speed;
}

static int sound_set_stereo(int stereo)
{
	if (stereo < 0)
		return dmasound.soft.stereo;

	stereo = !!stereo;    /* should be 0 or 1 now */

	dmasound.soft.stereo = stereo;
	if (dmasound.minDev == SND_DEV_DSP)
		dmasound.dsp.stereo = stereo;

	return stereo;
}

static ssize_t sound_copy_translate(TRANS *trans, const u_char __user *userPtr,
				    size_t userCount, u_char frame[],
				    ssize_t *frameUsed, ssize_t frameLeft)
{
	ssize_t (*ct_func)(const u_char __user *, size_t, u_char *, ssize_t *, ssize_t);

	switch (dmasound.soft.format) {
	    case AFMT_MU_LAW:
		ct_func = trans->ct_ulaw;
		break;
	    case AFMT_A_LAW:
		ct_func = trans->ct_alaw;
		break;
	    case AFMT_S8:
		ct_func = trans->ct_s8;
		break;
	    case AFMT_U8:
		ct_func = trans->ct_u8;
		break;
	    case AFMT_S16_BE:
		ct_func = trans->ct_s16be;
		break;
	    case AFMT_U16_BE:
		ct_func = trans->ct_u16be;
		break;
	    case AFMT_S16_LE:
		ct_func = trans->ct_s16le;
		break;
	    case AFMT_U16_LE:
		ct_func = trans->ct_u16le;
		break;
	    default:
		return 0;
	}
	/* if the user has requested a non-existent translation don't try
	   to call it but just return 0 bytes moved
	*/
	if (ct_func)
		return ct_func(userPtr, userCount, frame, frameUsed, frameLeft);
	return 0;
}

    /*
     *  /dev/mixer abstraction
     */

static struct {
    int busy;
    int modify_counter;
} mixer;

static int mixer_open(struct inode *inode, struct file *file)
{
	if (!try_module_get(dmasound.mach.owner))
		return -ENODEV;
	mixer.busy = 1;
	return 0;
}

static int mixer_release(struct inode *inode, struct file *file)
{
	lock_kernel();
	mixer.busy = 0;
	module_put(dmasound.mach.owner);
	unlock_kernel();
	return 0;
}
static int mixer_ioctl(struct inode *inode, struct file *file, u_int cmd,
		       u_long arg)
{
	if (_SIOC_DIR(cmd) & _SIOC_WRITE)
	    mixer.modify_counter++;
	switch (cmd) {
	    case OSS_GETVERSION:
		return IOCTL_OUT(arg, SOUND_VERSION);
	    case SOUND_MIXER_INFO:
		{
		    mixer_info info;
		    memset(&info, 0, sizeof(info));
		    strlcpy(info.id, dmasound.mach.name2, sizeof(info.id));
		    strlcpy(info.name, dmasound.mach.name2, sizeof(info.name));
		    info.modify_counter = mixer.modify_counter;
		    if (copy_to_user((void __user *)arg, &info, sizeof(info)))
			    return -EFAULT;
		    return 0;
		}
	}
	if (dmasound.mach.mixer_ioctl)
	    return dmasound.mach.mixer_ioctl(cmd, arg);
	return -EINVAL;
}

static const struct file_operations mixer_fops =
{
	.owner		= THIS_MODULE,
	.llseek		= no_llseek,
	.ioctl		= mixer_ioctl,
	.open		= mixer_open,
	.release	= mixer_release,
};

static void mixer_init(void)
{
#ifndef MODULE
	int mixer_unit;
#endif
	mixer_unit = register_sound_mixer(&mixer_fops, -1);
	if (mixer_unit < 0)
		return;

	mixer.busy = 0;
	dmasound.treble = 0;
	dmasound.bass = 0;
	if (dmasound.mach.mixer_init)
	    dmasound.mach.mixer_init();
}


    /*
     *  Sound queue stuff, the heart of the driver
     */

struct sound_queue dmasound_write_sq;
static void sq_reset_output(void) ;

static int sq_allocate_buffers(struct sound_queue *sq, int num, int size)
{
	int i;

	if (sq->buffers)
		return 0;
	sq->numBufs = num;
	sq->bufSize = size;
	sq->buffers = kmalloc (num * sizeof(char *), GFP_KERNEL);
	if (!sq->buffers)
		return -ENOMEM;
	for (i = 0; i < num; i++) {
		sq->buffers[i] = dmasound.mach.dma_alloc(size, GFP_KERNEL);
		if (!sq->buffers[i]) {
			while (i--)
				dmasound.mach.dma_free(sq->buffers[i], size);
			kfree(sq->buffers);
			sq->buffers = NULL;
			return -ENOMEM;
		}
	}
	return 0;
}

static void sq_release_buffers(struct sound_queue *sq)
{
	int i;

	if (sq->buffers) {
		for (i = 0; i < sq->numBufs; i++)
			dmasound.mach.dma_free(sq->buffers[i], sq->bufSize);
		kfree(sq->buffers);
		sq->buffers = NULL;
	}
}


static int sq_setup(struct sound_queue *sq)
{
	int (*setup_func)(void) = NULL;
	int hard_frame ;

	if (sq->locked) { /* are we already set? - and not changeable */
#ifdef DEBUG_DMASOUND
printk("dmasound_core: tried to sq_setup a locked queue\n") ;
#endif
		return -EINVAL ;
	}
	sq->locked = 1 ; /* don't think we have a race prob. here _check_ */

	/* make sure that the parameters are set up
	   This should have been done already...
	*/

	dmasound.mach.init();

	/* OK.  If the user has set fragment parameters explicitly, then we
	   should leave them alone... as long as they are valid.
	   Invalid user fragment params can occur if we allow the whole buffer
	   to be used when the user requests the fragments sizes (with no soft
	   x-lation) and then the user subsequently sets a soft x-lation that
	   requires increased internal buffering.

	   Othwerwise (if the user did not set them) OSS says that we should
	   select frag params on the basis of 0.5 s output & 0.1 s input
	   latency. (TODO.  For now we will copy in the defaults.)
	*/

	if (sq->user_frags <= 0) {
		sq->max_count = sq->numBufs ;
		sq->max_active = sq->numBufs ;
		sq->block_size = sq->bufSize;
		/* set up the user info */
		sq->user_frags = sq->numBufs ;
		sq->user_frag_size = sq->bufSize ;
		sq->user_frag_size *=
			(dmasound.soft.size * (dmasound.soft.stereo+1) ) ;
		sq->user_frag_size /=
			(dmasound.hard.size * (dmasound.hard.stereo+1) ) ;
	} else {
		/* work out requested block size */
		sq->block_size = sq->user_frag_size ;
		sq->block_size *=
			(dmasound.hard.size * (dmasound.hard.stereo+1) ) ;
		sq->block_size /=
			(dmasound.soft.size * (dmasound.soft.stereo+1) ) ;
		/* the user wants to write frag-size chunks */
		sq->block_size *= dmasound.hard.speed ;
		sq->block_size /= dmasound.soft.speed ;
		/* this only works for size values which are powers of 2 */
		hard_frame =
			(dmasound.hard.size * (dmasound.hard.stereo+1))/8 ;
		sq->block_size +=  (hard_frame - 1) ;
		sq->block_size &= ~(hard_frame - 1) ; /* make sure we are aligned */
		/* let's just check for obvious mistakes */
		if ( sq->block_size <= 0 || sq->block_size > sq->bufSize) {
#ifdef DEBUG_DMASOUND
printk("dmasound_core: invalid frag size (user set %d)\n", sq->user_frag_size) ;
#endif
			sq->block_size = sq->bufSize ;
		}
		if ( sq->user_frags <= sq->numBufs ) {
			sq->max_count = sq->user_frags ;
			/* if user has set max_active - then use it */
			sq->max_active = (sq->max_active <= sq->max_count) ?
				sq->max_active : sq->max_count ;
		} else {
#ifdef DEBUG_DMASOUND
printk("dmasound_core: invalid frag count (user set %d)\n", sq->user_frags) ;
#endif
			sq->max_count =
			sq->max_active = sq->numBufs ;
		}
	}
	sq->front = sq->count = sq->rear_size = 0;
	sq->syncing = 0;
	sq->active = 0;

	if (sq == &write_sq) {
	    sq->rear = -1;
	    setup_func = dmasound.mach.write_sq_setup;
	}
	if (setup_func)
	    return setup_func();
	return 0 ;
}

static inline void sq_play(void)
{
	dmasound.mach.play();
}

static ssize_t sq_write(struct file *file, const char __user *src, size_t uLeft,
			loff_t *ppos)
{
	ssize_t uWritten = 0;
	u_char *dest;
	ssize_t uUsed = 0, bUsed, bLeft;
	unsigned long flags ;

	/* ++TeSche: Is something like this necessary?
	 * Hey, that's an honest question! Or does any other part of the
	 * filesystem already checks this situation? I really don't know.
	 */
	if (uLeft == 0)
		return 0;

	/* implement any changes we have made to the soft/hard params.
	   this is not satisfactory really, all we have done up to now is to
	   say what we would like - there hasn't been any real checking of capability
	*/

	if (shared_resources_initialised == 0) {
		dmasound.mach.init() ;
		shared_resources_initialised = 1 ;
	}

	/* set up the sq if it is not already done. This may seem a dumb place
	   to do it - but it is what OSS requires.  It means that write() can
	   return memory allocation errors.  To avoid this possibility use the
	   GETBLKSIZE or GETOSPACE ioctls (after you've fiddled with all the
	   params you want to change) - these ioctls also force the setup.
	*/

	if (write_sq.locked == 0) {
		if ((uWritten = sq_setup(&write_sq)) < 0) return uWritten ;
		uWritten = 0 ;
	}

/* FIXME: I think that this may be the wrong behaviour when we get strapped
	for time and the cpu is close to being (or actually) behind in sending data.
	- because we've lost the time that the N samples, already in the buffer,
	would have given us to get here with the next lot from the user.
*/
	/* The interrupt doesn't start to play the last, incomplete frame.
	 * Thus we can append to it without disabling the interrupts! (Note
	 * also that write_sq.rear isn't affected by the interrupt.)
	 */

	/* as of 1.6 this behaviour changes if SNDCTL_DSP_POST has been issued:
	   this will mimic the behaviour of syncing and allow the sq_play() to
	   queue a partial fragment.  Since sq_play() may/will be called from
	   the IRQ handler - at least on Pmac we have to deal with it.
	   The strategy - possibly not optimum - is to kill _POST status if we
	   get here.  This seems, at least, reasonable - in the sense that POST
	   is supposed to indicate that we might not write before the queue
	   is drained - and if we get here in time then it does not apply.
	*/

	spin_lock_irqsave(&dmasound.lock, flags);
	write_sq.syncing &= ~2 ; /* take out POST status */
	spin_unlock_irqrestore(&dmasound.lock, flags);

	if (write_sq.count > 0 &&
	    (bLeft = write_sq.block_size-write_sq.rear_size) > 0) {
		dest = write_sq.buffers[write_sq.rear];
		bUsed = write_sq.rear_size;
		uUsed = sound_copy_translate(dmasound.trans_write, src, uLeft,
					     dest, &bUsed, bLeft);
		if (uUsed <= 0)
			return uUsed;
		src += uUsed;
		uWritten += uUsed;
		uLeft = (uUsed <= uLeft) ? (uLeft - uUsed) : 0 ; /* paranoia */
		write_sq.rear_size = bUsed;
	}

	while (uLeft) {
		while (write_sq.count >= write_sq.max_active) {
			sq_play();
			if (write_sq.open_mode & O_NONBLOCK)
				return uWritten > 0 ? uWritten : -EAGAIN;
			SLEEP(write_sq.action_queue);
			if (signal_pending(current))
				return uWritten > 0 ? uWritten : -EINTR;
		}

		/* Here, we can avoid disabling the interrupt by first
		 * copying and translating the data, and then updating
		 * the write_sq variables. Until this is done, the interrupt
		 * won't see the new frame and we can work on it
		 * undisturbed.
		 */

		dest = write_sq.buffers[(write_sq.rear+1) % write_sq.max_count];
		bUsed = 0;
		bLeft = write_sq.block_size;
		uUsed = sound_copy_translate(dmasound.trans_write, src, uLeft,
					     dest, &bUsed, bLeft);
		if (uUsed <= 0)
			break;
		src += uUsed;
		uWritten += uUsed;
		uLeft = (uUsed <= uLeft) ? (uLeft - uUsed) : 0 ; /* paranoia */
		if (bUsed) {
			write_sq.rear = (write_sq.rear+1) % write_sq.max_count;
			write_sq.rear_size = bUsed;
			write_sq.count++;
		}
	} /* uUsed may have been 0 */

	sq_play();

	return uUsed < 0? uUsed: uWritten;
}

static unsigned int sq_poll(struct file *file, struct poll_table_struct *wait)
{
	unsigned int mask = 0;
	int retVal;
	
	if (write_sq.locked == 0) {
		if ((retVal = sq_setup(&write_sq)) < 0)
			return retVal;
		return 0;
	}
	if (file->f_mode & FMODE_WRITE )
		poll_wait(file, &write_sq.action_queue, wait);
	if (file->f_mode & FMODE_WRITE)
		if (write_sq.count < write_sq.max_active || write_sq.block_size - write_sq.rear_size > 0)
			mask |= POLLOUT | POLLWRNORM;
	return mask;

}

static inline void sq_init_waitqueue(struct sound_queue *sq)
{
	init_waitqueue_head(&sq->action_queue);
	init_waitqueue_head(&sq->open_queue);
	init_waitqueue_head(&sq->sync_queue);
	sq->busy = 0;
}

#if 0 /* blocking open() */
static inline void sq_wake_up(struct sound_queue *sq, struct file *file,
			      mode_t mode)
{
	if (file->f_mode & mode) {
		sq->busy = 0; /* CHECK: IS THIS OK??? */
		WAKE_UP(sq->open_queue);
	}
}
#endif

static int sq_open2(struct sound_queue *sq, struct file *file, mode_t mode,
		    int numbufs, int bufsize)
{
	int rc = 0;

	if (file->f_mode & mode) {
		if (sq->busy) {
#if 0 /* blocking open() */
			rc = -EBUSY;
			if (file->f_flags & O_NONBLOCK)
				return rc;
			rc = -EINTR;
			while (sq->busy) {
				SLEEP(sq->open_queue);
				if (signal_pending(current))
					return rc;
			}
			rc = 0;
#else
			/* OSS manual says we will return EBUSY regardless
			   of O_NOBLOCK.
			*/
			return -EBUSY ;
#endif
		}
		sq->busy = 1; /* Let's play spot-the-race-condition */

		/* allocate the default number & size of buffers.
		   (i.e. specified in _setup() or as module params)
		   can't be changed at the moment - but _could_ be perhaps
		   in the setfragments ioctl.
		*/
		if (( rc = sq_allocate_buffers(sq, numbufs, bufsize))) {
#if 0 /* blocking open() */
			sq_wake_up(sq, file, mode);
#else
			sq->busy = 0 ;
#endif
			return rc;
		}

		sq->open_mode = file->f_mode;
	}
	return rc;
}

#define write_sq_init_waitqueue()	sq_init_waitqueue(&write_sq)
#if 0 /* blocking open() */
#define write_sq_wake_up(file)		sq_wake_up(&write_sq, file, FMODE_WRITE)
#endif
#define write_sq_release_buffers()	sq_release_buffers(&write_sq)
#define write_sq_open(file)	\
	sq_open2(&write_sq, file, FMODE_WRITE, numWriteBufs, writeBufSize )

static int sq_open(struct inode *inode, struct file *file)
{
	int rc;

	if (!try_module_get(dmasound.mach.owner))
		return -ENODEV;

	rc = write_sq_open(file); /* checks the f_mode */
	if (rc)
		goto out;
	if (file->f_mode & FMODE_READ) {
		/* TODO: if O_RDWR, release any resources grabbed by write part */
		rc = -ENXIO ; /* I think this is what is required by open(2) */
		goto out;
	}

	if (dmasound.mach.sq_open)
	    dmasound.mach.sq_open(file->f_mode);

	/* CHECK whether this is sensible - in the case that dsp0 could be opened
	  O_RDONLY and dsp1 could be opened O_WRONLY
	*/

	dmasound.minDev = iminor(inode) & 0x0f;

	/* OK. - we should make some attempt at consistency. At least the H'ware
	   options should be set with a valid mode.  We will make it that the LL
	   driver must supply defaults for hard & soft params.
	*/

	if (shared_resource_owner == 0) {
		/* you can make this AFMT_U8/mono/8K if you want to mimic old
		   OSS behaviour - while we still have soft translations ;-) */
		dmasound.soft = dmasound.mach.default_soft ;
		dmasound.dsp = dmasound.mach.default_soft ;
		dmasound.hard = dmasound.mach.default_hard ;
	}

#ifndef DMASOUND_STRICT_OSS_COMPLIANCE
	/* none of the current LL drivers can actually do this "native" at the moment
	   OSS does not really require us to supply /dev/audio if we can't do it.
	*/
	if (dmasound.minDev == SND_DEV_AUDIO) {
		sound_set_speed(8000);
		sound_set_stereo(0);
		sound_set_format(AFMT_MU_LAW);
	}
#endif

	return 0;
 out:
	module_put(dmasound.mach.owner);
	return rc;
}

static void sq_reset_output(void)
{
	sound_silence(); /* this _must_ stop DMA, we might be about to lose the buffers */
	write_sq.active = 0;
	write_sq.count = 0;
	write_sq.rear_size = 0;
	/* write_sq.front = (write_sq.rear+1) % write_sq.max_count;*/
	write_sq.front = 0 ;
	write_sq.rear = -1 ; /* same as for set-up */

	/* OK - we can unlock the parameters and fragment settings */
	write_sq.locked = 0 ;
	write_sq.user_frags = 0 ;
	write_sq.user_frag_size = 0 ;
}

static void sq_reset(void)
{
	sq_reset_output() ;
	/* we could consider resetting the shared_resources_owner here... but I
	   think it is probably still rather non-obvious to application writer
	*/

	/* we release everything else though */
	shared_resources_initialised = 0 ;
}

static int sq_fsync(struct file *filp, struct dentry *dentry)
{
	int rc = 0;
	int timeout = 5;

	write_sq.syncing |= 1;
	sq_play();	/* there may be an incomplete frame waiting */

	while (write_sq.active) {
		SLEEP(write_sq.sync_queue);
		if (signal_pending(current)) {
			/* While waiting for audio output to drain, an
			 * interrupt occurred.  Stop audio output immediately
			 * and clear the queue. */
			sq_reset_output();
			rc = -EINTR;
			break;
		}
		if (!--timeout) {
			printk(KERN_WARNING "dmasound: Timeout draining output\n");
			sq_reset_output();
			rc = -EIO;
			break;
		}
	}

	/* flag no sync regardless of whether we had a DSP_POST or not */
	write_sq.syncing = 0 ;
	return rc;
}

static int sq_release(struct inode *inode, struct file *file)
{
	int rc = 0;

	lock_kernel();

	if (file->f_mode & FMODE_WRITE) {
		if (write_sq.busy)
			rc = sq_fsync(file, file->f_path.dentry);

		sq_reset_output() ; /* make sure dma is stopped and all is quiet */
		write_sq_release_buffers();
		write_sq.busy = 0;
	}

	if (file->f_mode & shared_resource_owner) { /* it's us that has them */
		shared_resource_owner = 0 ;
		shared_resources_initialised = 0 ;
		dmasound.hard = dmasound.mach.default_hard ;
	}

	module_put(dmasound.mach.owner);

#if 0 /* blocking open() */
	/* Wake up a process waiting for the queue being released.
	 * Note: There may be several processes waiting for a call
	 * to open() returning. */

	/* Iain: hmm I don't understand this next comment ... */
	/* There is probably a DOS atack here. They change the mode flag. */
	/* XXX add check here,*/
	read_sq_wake_up(file); /* checks f_mode */
	write_sq_wake_up(file); /* checks f_mode */
#endif /* blocking open() */

	unlock_kernel();

	return rc;
}

/* here we see if we have a right to modify format, channels, size and so on
   if no-one else has claimed it already then we do...

   TODO: We might change this to mask O_RDWR such that only one or the other channel
   is the owner - if we have problems.
*/

static int shared_resources_are_mine(mode_t md)
{
	if (shared_resource_owner)
		return (shared_resource_owner & md ) ;
	else {
		shared_resource_owner = md ;
		return 1 ;
	}
}

/* if either queue is locked we must deny the right to change shared params
*/

static int queues_are_quiescent(void)
{
	if (write_sq.locked)
		return 0 ;
	return 1 ;
}

/* check and set a queue's fragments per user's wishes...
   we will check against the pre-defined literals and the actual sizes.
   This is a bit fraught - because soft translations can mess with our
   buffer requirements *after* this call - OSS says "call setfrags first"
*/

/* It is possible to replace all the -EINVAL returns with an override that
   just puts the allowable value in.  This may be what many OSS apps require
*/

static int set_queue_frags(struct sound_queue *sq, int bufs, int size)
{
	if (sq->locked) {
#ifdef DEBUG_DMASOUND
printk("dmasound_core: tried to set_queue_frags on a locked queue\n") ;
#endif
		return -EINVAL ;
	}

	if ((size < MIN_FRAG_SIZE) || (size > MAX_FRAG_SIZE))
		return -EINVAL ;
	size = (1<<size) ; /* now in bytes */
	if (size > sq->bufSize)
		return -EINVAL ; /* this might still not work */

	if (bufs <= 0)
		return -EINVAL ;
	if (bufs > sq->numBufs) /* the user is allowed say "don't care" with 0x7fff */
		bufs = sq->numBufs ;

	/* there is, currently, no way to specify max_active separately
	   from max_count.  This could be a LL driver issue - I guess
	   if there is a requirement for these values to be different then
	  we will have to pass that info. up to this level.
	*/
	sq->user_frags =
	sq->max_active = bufs ;
	sq->user_frag_size = size ;

	return 0 ;
}

static int sq_ioctl(struct inode *inode, struct file *file, u_int cmd,
		    u_long arg)
{
	int val, result;
	u_long fmt;
	int data;
	int size, nbufs;
	audio_buf_info info;

	switch (cmd) {
	case SNDCTL_DSP_RESET:
		sq_reset();
		return 0;
		break ;
	case SNDCTL_DSP_GETFMTS:
		fmt = dmasound.mach.hardware_afmts ; /* this is what OSS says.. */
		return IOCTL_OUT(arg, fmt);
		break ;
	case SNDCTL_DSP_GETBLKSIZE:
		/* this should tell the caller about bytes that the app can
		   read/write - the app doesn't care about our internal buffers.
		   We force sq_setup() here as per OSS 1.1 (which should
		   compute the values necessary).
		   Since there is no mechanism to specify read/write separately, for
		   fds opened O_RDWR, the write_sq values will, arbitrarily, overwrite
		   the read_sq ones.
		*/
		size = 0 ;
		if (file->f_mode & FMODE_WRITE) {
			if ( !write_sq.locked )
				sq_setup(&write_sq) ;
			size = write_sq.user_frag_size ;
		}
		return IOCTL_OUT(arg, size);
		break ;
	case SNDCTL_DSP_POST:
		/* all we are going to do is to tell the LL that any
		   partial frags can be queued for output.
		   The LL will have to clear this flag when last output
		   is queued.
		*/
		write_sq.syncing |= 0x2 ;
		sq_play() ;
		return 0 ;
	case SNDCTL_DSP_SYNC:
		/* This call, effectively, has the same behaviour as SNDCTL_DSP_RESET
		   except that it waits for output to finish before resetting
		   everything - read, however, is killed imediately.
		*/
		result = 0 ;
		if (file->f_mode & FMODE_WRITE) {
			result = sq_fsync(file, file->f_path.dentry);
			sq_reset_output() ;
		}
		/* if we are the shared resource owner then release them */
		if (file->f_mode & shared_resource_owner)
			shared_resources_initialised = 0 ;
		return result ;
		break ;
	case SOUND_PCM_READ_RATE:
		return IOCTL_OUT(arg, dmasound.soft.speed);
	case SNDCTL_DSP_SPEED:
		/* changing this on the fly will have weird effects on the sound.
		   Where there are rate conversions implemented in soft form - it
		   will cause the _ctx_xxx() functions to be substituted.
		   However, there doesn't appear to be any reason to dis-allow it from
		   a driver pov.
		*/
		if (shared_resources_are_mine(file->f_mode)) {
			IOCTL_IN(arg, data);
			data = sound_set_speed(data) ;
			shared_resources_initialised = 0 ;
			return IOCTL_OUT(arg, data);
		} else
			return -EINVAL ;
		break ;
	/* OSS says these next 4 actions are undefined when the device is
	   busy/active - we will just return -EINVAL.
	   To be allowed to change one - (a) you have to own the right
	    (b) the queue(s) must be quiescent
	*/
	case SNDCTL_DSP_STEREO:
		if (shared_resources_are_mine(file->f_mode) &&
		    queues_are_quiescent()) {
			IOCTL_IN(arg, data);
			shared_resources_initialised = 0 ;
			return IOCTL_OUT(arg, sound_set_stereo(data));
		} else
			return -EINVAL ;
		break ;
	case SOUND_PCM_WRITE_CHANNELS:
		if (shared_resources_are_mine(file->f_mode) &&
		    queues_are_quiescent()) {
			IOCTL_IN(arg, data);
			/* the user might ask for 20 channels, we will return 1 or 2 */
			shared_resources_initialised = 0 ;
			return IOCTL_OUT(arg, sound_set_stereo(data-1)+1);
		} else
			return -EINVAL ;
		break ;
	case SNDCTL_DSP_SETFMT:
		if (shared_resources_are_mine(file->f_mode) &&
		    queues_are_quiescent()) {
		    	int format;
			IOCTL_IN(arg, data);
			shared_resources_initialised = 0 ;
			format = sound_set_format(data);
			result = IOCTL_OUT(arg, format);
			if (result < 0)
				return result;
			if (format != data && data != AFMT_QUERY)
				return -EINVAL;
			return 0;
		} else
			return -EINVAL ;
	case SNDCTL_DSP_SUBDIVIDE:
		return -EINVAL ;
	case SNDCTL_DSP_SETFRAGMENT:
		/* we can do this independently for the two queues - with the
		   proviso that for fds opened O_RDWR we cannot separate the
		   actions and both queues will be set per the last call.
		   NOTE: this does *NOT* actually set the queue up - merely
		   registers our intentions.
		*/
		IOCTL_IN(arg, data);
		result = 0 ;
		nbufs = (data >> 16) & 0x7fff ; /* 0x7fff is 'use maximum' */
		size = data & 0xffff;
		if (file->f_mode & FMODE_WRITE) {
			result = set_queue_frags(&write_sq, nbufs, size) ;
			if (result)
				return result ;
		}
		/* NOTE: this return value is irrelevant - OSS specifically says that
		   the value is 'random' and that the user _must_ check the actual
		   frags values using SNDCTL_DSP_GETBLKSIZE or similar */
		return IOCTL_OUT(arg, data);
		break ;
	case SNDCTL_DSP_GETOSPACE:
		/*
		*/
		if (file->f_mode & FMODE_WRITE) {
			if ( !write_sq.locked )
				sq_setup(&write_sq) ;
			info.fragments = write_sq.max_active - write_sq.count;
			info.fragstotal = write_sq.max_active;
			info.fragsize = write_sq.user_frag_size;
			info.bytes = info.fragments * info.fragsize;
			if (copy_to_user((void __user *)arg, &info, sizeof(info)))
				return -EFAULT;
			return 0;
		} else
			return -EINVAL ;
		break ;
	case SNDCTL_DSP_GETCAPS:
		val = dmasound.mach.capabilities & 0xffffff00;
		return IOCTL_OUT(arg,val);

	default:
		return mixer_ioctl(inode, file, cmd, arg);
	}
	return -EINVAL;
}

static const struct file_operations sq_fops =
{
	.owner		= THIS_MODULE,
	.llseek		= no_llseek,
	.write		= sq_write,
	.poll		= sq_poll,
	.ioctl		= sq_ioctl,
	.open		= sq_open,
	.release	= sq_release,
};

static int sq_init(void)
{
	const struct file_operations *fops = &sq_fops;
#ifndef MODULE
	int sq_unit;
#endif

	sq_unit = register_sound_dsp(fops, -1);
	if (sq_unit < 0) {
		printk(KERN_ERR "dmasound_core: couldn't register fops\n") ;
		return sq_unit ;
	}

	write_sq_init_waitqueue();

	/* These parameters will be restored for every clean open()
	 * in the case of multiple open()s (e.g. dsp0 & dsp1) they
	 * will be set so long as the shared resources have no owner.
	 */

	if (shared_resource_owner == 0) {
		dmasound.soft = dmasound.mach.default_soft ;
		dmasound.hard = dmasound.mach.default_hard ;
		dmasound.dsp = dmasound.mach.default_soft ;
		shared_resources_initialised = 0 ;
	}
	return 0 ;
}


    /*
     *  /dev/sndstat
     */

/* we allow more space for record-enabled because there are extra output lines.
   the number here must include the amount we are prepared to give to the low-level
   driver.
*/

#define STAT_BUFF_LEN 768

/* this is how much space we will allow the low-level driver to use
   in the stat buffer.  Currently, 2 * (80 character line + <NL>).
   We do not police this (it is up to the ll driver to be honest).
*/

#define LOW_LEVEL_STAT_ALLOC 162

static struct {
    int busy;
    char buf[STAT_BUFF_LEN];	/* state.buf should not overflow! */
    int len, ptr;
} state;

/* publish this function for use by low-level code, if required */

static char *get_afmt_string(int afmt)
{
        switch(afmt) {
            case AFMT_MU_LAW:
                return "mu-law";
                break;
            case AFMT_A_LAW:
                return "A-law";
                break;
            case AFMT_U8:
                return "unsigned 8 bit";
                break;
            case AFMT_S8:
                return "signed 8 bit";
                break;
            case AFMT_S16_BE:
                return "signed 16 bit BE";
                break;
            case AFMT_U16_BE:
                return "unsigned 16 bit BE";
                break;
            case AFMT_S16_LE:
                return "signed 16 bit LE";
                break;
            case AFMT_U16_LE:
                return "unsigned 16 bit LE";
                break;
	    case 0:
		return "format not set" ;
		break ;
            default:
                break ;
        }
        return "ERROR: Unsupported AFMT_XXXX code" ;
}

static int state_open(struct inode *inode, struct file *file)
{
	char *buffer = state.buf;
	int len = 0;

	if (state.busy)
		return -EBUSY;

	if (!try_module_get(dmasound.mach.owner))
		return -ENODEV;
	state.ptr = 0;
	state.busy = 1;

	len += sprintf(buffer+len, "%sDMA sound driver rev %03d :\n",
		dmasound.mach.name, (DMASOUND_CORE_REVISION<<4) +
		((dmasound.mach.version>>8) & 0x0f));
	len += sprintf(buffer+len,
		"Core driver edition %02d.%02d : %s driver edition %02d.%02d\n",
		DMASOUND_CORE_REVISION, DMASOUND_CORE_EDITION, dmasound.mach.name2,
		(dmasound.mach.version >> 8), (dmasound.mach.version & 0xff)) ;

	/* call the low-level module to fill in any stat info. that it has
	   if present.  Maximum buffer usage is specified.
	*/

	if (dmasound.mach.state_info)
		len += dmasound.mach.state_info(buffer+len,
			(size_t) LOW_LEVEL_STAT_ALLOC) ;

	/* make usage of the state buffer as deterministic as poss.
	   exceptional conditions could cause overrun - and this is flagged as
	   a kernel error.
	*/

	/* formats and settings */

	len += sprintf(buffer+len,"\t\t === Formats & settings ===\n") ;
	len += sprintf(buffer+len,"Parameter %20s%20s\n","soft","hard") ;
	len += sprintf(buffer+len,"Format   :%20s%20s\n",
		get_afmt_string(dmasound.soft.format),
		get_afmt_string(dmasound.hard.format));

	len += sprintf(buffer+len,"Samp Rate:%14d s/sec%14d s/sec\n",
		       dmasound.soft.speed, dmasound.hard.speed);

	len += sprintf(buffer+len,"Channels :%20s%20s\n",
		       dmasound.soft.stereo ? "stereo" : "mono",
		       dmasound.hard.stereo ? "stereo" : "mono" );

	/* sound queue status */

	len += sprintf(buffer+len,"\t\t === Sound Queue status ===\n");
	len += sprintf(buffer+len,"Allocated:%8s%6s\n","Buffers","Size") ;
	len += sprintf(buffer+len,"%9s:%8d%6d\n",
		"write", write_sq.numBufs, write_sq.bufSize) ;
	len += sprintf(buffer+len,
		"Current  : MaxFrg FragSiz MaxAct Frnt Rear "
		"Cnt RrSize A B S L  xruns\n") ;
	len += sprintf(buffer+len,"%9s:%7d%8d%7d%5d%5d%4d%7d%2d%2d%2d%2d%7d\n",
		"write", write_sq.max_count, write_sq.block_size,
		write_sq.max_active, write_sq.front, write_sq.rear,
		write_sq.count, write_sq.rear_size, write_sq.active,
		write_sq.busy, write_sq.syncing, write_sq.locked, write_sq.xruns) ;
#ifdef DEBUG_DMASOUND
printk("dmasound: stat buffer used %d bytes\n", len) ;
#endif

	if (len >= STAT_BUFF_LEN)
		printk(KERN_ERR "dmasound_core: stat buffer overflowed!\n");

	state.len = len;
	return 0;
}

static int state_release(struct inode *inode, struct file *file)
{
	lock_kernel();
	state.busy = 0;
	module_put(dmasound.mach.owner);
	unlock_kernel();
	return 0;
}

static ssize_t state_read(struct file *file, char __user *buf, size_t count,
			  loff_t *ppos)
{
	int n = state.len - state.ptr;
	if (n > count)
		n = count;
	if (n <= 0)
		return 0;
	if (copy_to_user(buf, &state.buf[state.ptr], n))
		return -EFAULT;
	state.ptr += n;
	return n;
}

static const struct file_operations state_fops = {
	.owner		= THIS_MODULE,
	.llseek		= no_llseek,
	.read		= state_read,
	.open		= state_open,
	.release	= state_release,
};

static int state_init(void)
{
#ifndef MODULE
	int state_unit;
#endif
	state_unit = register_sound_special(&state_fops, SND_DEV_STATUS);
	if (state_unit < 0)
		return state_unit ;
	state.busy = 0;
	return 0 ;
}


    /*
     *  Config & Setup
     *
     *  This function is called by _one_ chipset-specific driver
     */

int dmasound_init(void)
{
	int res ;
#ifdef MODULE
	if (irq_installed)
		return -EBUSY;
#endif

	/* Set up sound queue, /dev/audio and /dev/dsp. */

	/* Set default settings. */
	if ((res = sq_init()) < 0)
		return res ;

	/* Set up /dev/sndstat. */
	if ((res = state_init()) < 0)
		return res ;

	/* Set up /dev/mixer. */
	mixer_init();

	if (!dmasound.mach.irqinit()) {
		printk(KERN_ERR "DMA sound driver: Interrupt initialization failed\n");
		return -ENODEV;
	}
#ifdef MODULE
	irq_installed = 1;
#endif

	printk(KERN_INFO "%s DMA sound driver rev %03d installed\n",
		dmasound.mach.name, (DMASOUND_CORE_REVISION<<4) +
		((dmasound.mach.version>>8) & 0x0f));
	printk(KERN_INFO
		"Core driver edition %02d.%02d : %s driver edition %02d.%02d\n",
		DMASOUND_CORE_REVISION, DMASOUND_CORE_EDITION, dmasound.mach.name2,
		(dmasound.mach.version >> 8), (dmasound.mach.version & 0xff)) ;
	printk(KERN_INFO "Write will use %4d fragments of %7d bytes as default\n",
		numWriteBufs, writeBufSize) ;
	return 0;
}

#ifdef MODULE

void dmasound_deinit(void)
{
	if (irq_installed) {
		sound_silence();
		dmasound.mach.irqcleanup();
		irq_installed = 0;
	}

	write_sq_release_buffers();

	if (mixer_unit >= 0)
		unregister_sound_mixer(mixer_unit);
	if (state_unit >= 0)
		unregister_sound_special(state_unit);
	if (sq_unit >= 0)
		unregister_sound_dsp(sq_unit);
}

#else /* !MODULE */

static int dmasound_setup(char *str)
{
	int ints[6], size;

	str = get_options(str, ARRAY_SIZE(ints), ints);

	/* check the bootstrap parameter for "dmasound=" */

	/* FIXME: other than in the most naive of cases there is no sense in these
	 *	  buffers being other than powers of two.  This is not checked yet.
	 */

	switch (ints[0]) {
	case 3:
		if ((ints[3] < 0) || (ints[3] > MAX_CATCH_RADIUS))
			printk("dmasound_setup: invalid catch radius, using default = %d\n", catchRadius);
		else
			catchRadius = ints[3];
		/* fall through */
	case 2:
		if (ints[1] < MIN_BUFFERS)
			printk("dmasound_setup: invalid number of buffers, using default = %d\n", numWriteBufs);
		else
			numWriteBufs = ints[1];
		/* fall through */
	case 1:
		if ((size = ints[2]) < 256) /* check for small buffer specs */
			size <<= 10 ;
                if (size < MIN_BUFSIZE || size > MAX_BUFSIZE)
                        printk("dmasound_setup: invalid write buffer size, using default = %d\n", writeBufSize);
                else
                        writeBufSize = size;
	case 0:
		break;
	default:
		printk("dmasound_setup: invalid number of arguments\n");
		return 0;
	}
	return 1;
}

__setup("dmasound=", dmasound_setup);

#endif /* !MODULE */

    /*
     *  Conversion tables
     */

#ifdef HAS_8BIT_TABLES
/* 8 bit mu-law */

char dmasound_ulaw2dma8[] = {
	-126,	-122,	-118,	-114,	-110,	-106,	-102,	-98,
	-94,	-90,	-86,	-82,	-78,	-74,	-70,	-66,
	-63,	-61,	-59,	-57,	-55,	-53,	-51,	-49,
	-47,	-45,	-43,	-41,	-39,	-37,	-35,	-33,
	-31,	-30,	-29,	-28,	-27,	-26,	-25,	-24,
	-23,	-22,	-21,	-20,	-19,	-18,	-17,	-16,
	-16,	-15,	-15,	-14,	-14,	-13,	-13,	-12,
	-12,	-11,	-11,	-10,	-10,	-9,	-9,	-8,
	-8,	-8,	-7,	-7,	-7,	-7,	-6,	-6,
	-6,	-6,	-5,	-5,	-5,	-5,	-4,	-4,
	-4,	-4,	-4,	-4,	-3,	-3,	-3,	-3,
	-3,	-3,	-3,	-3,	-2,	-2,	-2,	-2,
	-2,	-2,	-2,	-2,	-2,	-2,	-2,	-2,
	-1,	-1,	-1,	-1,	-1,	-1,	-1,	-1,
	-1,	-1,	-1,	-1,	-1,	-1,	-1,	-1,
	-1,	-1,	-1,	-1,	-1,	-1,	-1,	0,
	125,	121,	117,	113,	109,	105,	101,	97,
	93,	89,	85,	81,	77,	73,	69,	65,
	62,	60,	58,	56,	54,	52,	50,	48,
	46,	44,	42,	40,	38,	36,	34,	32,
	30,	29,	28,	27,	26,	25,	24,	23,
	22,	21,	20,	19,	18,	17,	16,	15,
	15,	14,	14,	13,	13,	12,	12,	11,
	11,	10,	10,	9,	9,	8,	8,	7,
	7,	7,	6,	6,	6,	6,	5,	5,
	5,	5,	4,	4,	4,	4,	3,	3,
	3,	3,	3,	3,	2,	2,	2,	2,
	2,	2,	2,	2,	1,	1,	1,	1,
	1,	1,	1,	1,	1,	1,	1,	1,
	0,	0,	0,	0,	0,	0,	0,	0,
	0,	0,	0,	0,	0,	0,	0,	0,
	0,	0,	0,	0,	0,	0,	0,	0
};

/* 8 bit A-law */

char dmasound_alaw2dma8[] = {
	-22,	-21,	-24,	-23,	-18,	-17,	-20,	-19,
	-30,	-29,	-32,	-31,	-26,	-25,	-28,	-27,
	-11,	-11,	-12,	-12,	-9,	-9,	-10,	-10,
	-15,	-15,	-16,	-16,	-13,	-13,	-14,	-14,
	-86,	-82,	-94,	-90,	-70,	-66,	-78,	-74,
	-118,	-114,	-126,	-122,	-102,	-98,	-110,	-106,
	-43,	-41,	-47,	-45,	-35,	-33,	-39,	-37,
	-59,	-57,	-63,	-61,	-51,	-49,	-55,	-53,
	-2,	-2,	-2,	-2,	-2,	-2,	-2,	-2,
	-2,	-2,	-2,	-2,	-2,	-2,	-2,	-2,
	-1,	-1,	-1,	-1,	-1,	-1,	-1,	-1,
	-1,	-1,	-1,	-1,	-1,	-1,	-1,	-1,
	-6,	-6,	-6,	-6,	-5,	-5,	-5,	-5,
	-8,	-8,	-8,	-8,	-7,	-7,	-7,	-7,
	-3,	-3,	-3,	-3,	-3,	-3,	-3,	-3,
	-4,	-4,	-4,	-4,	-4,	-4,	-4,	-4,
	21,	20,	23,	22,	17,	16,	19,	18,
	29,	28,	31,	30,	25,	24,	27,	26,
	10,	10,	11,	11,	8,	8,	9,	9,
	14,	14,	15,	15,	12,	12,	13,	13,
	86,	82,	94,	90,	70,	66,	78,	74,
	118,	114,	126,	122,	102,	98,	110,	106,
	43,	41,	47,	45,	35,	33,	39,	37,
	59,	57,	63,	61,	51,	49,	55,	53,
	1,	1,	1,	1,	1,	1,	1,	1,
	1,	1,	1,	1,	1,	1,	1,	1,
	0,	0,	0,	0,	0,	0,	0,	0,
	0,	0,	0,	0,	0,	0,	0,	0,
	5,	5,	5,	5,	4,	4,	4,	4,
	7,	7,	7,	7,	6,	6,	6,	6,
	2,	2,	2,	2,	2,	2,	2,	2,
	3,	3,	3,	3,	3,	3,	3,	3
};
#endif /* HAS_8BIT_TABLES */

    /*
     *  Visible symbols for modules
     */

EXPORT_SYMBOL(dmasound);
EXPORT_SYMBOL(dmasound_init);
#ifdef MODULE
EXPORT_SYMBOL(dmasound_deinit);
#endif
EXPORT_SYMBOL(dmasound_write_sq);
EXPORT_SYMBOL(dmasound_catchRadius);
#ifdef HAS_8BIT_TABLES
EXPORT_SYMBOL(dmasound_ulaw2dma8);
EXPORT_SYMBOL(dmasound_alaw2dma8);
#endif