spkr.c revision 82555
1256904Sray/*
2256904Sray * spkr.c -- device driver for console speaker
3256904Sray *
4256904Sray * v1.4 by Eric S. Raymond (esr@snark.thyrsus.com) Aug 1993
5256904Sray * modified for FreeBSD by Andrew A. Chernov <ache@astral.msk.su>
6256904Sray *
7256904Sray * $FreeBSD: head/sys/dev/speaker/spkr.c 82555 2001-08-30 09:17:03Z msmith $
8256904Sray */
9256904Sray
10256904Sray#include <sys/param.h>
11256904Sray#include <sys/systm.h>
12256904Sray#include <sys/bus.h>
13256904Sray#include <sys/kernel.h>
14256904Sray#include <sys/module.h>
15256904Sray#include <sys/uio.h>
16256904Sray#include <sys/conf.h>
17256904Sray#include <sys/ctype.h>
18256904Sray#include <sys/malloc.h>
19256904Sray#include <isa/isavar.h>
20256904Sray#include <i386/isa/isa.h>
21256904Sray#include <i386/isa/timerreg.h>
22256904Sray#include <machine/clock.h>
23256904Sray#include <machine/speaker.h>
24256904Sray
25256904Sraystatic	d_open_t	spkropen;
26256904Sraystatic	d_close_t	spkrclose;
27256904Sraystatic	d_write_t	spkrwrite;
28256904Sraystatic	d_ioctl_t	spkrioctl;
29256904Sray
30256904Sray#define CDEV_MAJOR 26
31256904Sraystatic struct cdevsw spkr_cdevsw = {
32256904Sray	/* open */	spkropen,
33256904Sray	/* close */	spkrclose,
34256904Sray	/* read */	noread,
35256904Sray	/* write */	spkrwrite,
36256904Sray	/* ioctl */	spkrioctl,
37256904Sray	/* poll */	nopoll,
38256904Sray	/* mmap */	nommap,
39256904Sray	/* strategy */	nostrategy,
40256904Sray	/* name */	"spkr",
41256904Sray	/* maj */	CDEV_MAJOR,
42256904Sray	/* dump */	nodump,
43256904Sray	/* psize */	nopsize,
44256904Sray	/* flags */	0,
45256904Sray};
46256904Sray
47256904Sraystatic MALLOC_DEFINE(M_SPKR, "spkr", "Speaker buffer");
48256904Sray
49256904Sray/**************** MACHINE DEPENDENT PART STARTS HERE *************************
50256904Sray *
51256904Sray * This section defines a function tone() which causes a tone of given
52257725Sray * frequency and duration from the ISA console speaker.
53256904Sray * Another function endtone() is defined to force sound off, and there is
54256904Sray * also a rest() entry point to do pauses.
55256904Sray *
56256904Sray * Audible sound is generated using the Programmable Interval Timer (PIT) and
57256904Sray * Programmable Peripheral Interface (PPI) attached to the ISA speaker. The
58256904Sray * PPI controls whether sound is passed through at all; the PIT's channel 2 is
59256904Sray * used to generate clicks (a square wave) of whatever frequency is desired.
60256904Sray */
61257725Sray
62256904Sray/*
63256904Sray * PPI control values.
64256904Sray * XXX should be in a header and used in clock.c.
65256904Sray */
66256904Sray#define PPI_SPKR	0x03	/* turn these PPI bits on to pass sound */
67256904Sray
68256904Sray#define SPKRPRI PSOCK
69256904Sraystatic char endtone, endrest;
70256904Sray
71256904Sraystatic void tone __P((unsigned int thz, unsigned int ticks));
72256904Sraystatic void rest __P((int ticks));
73256904Sraystatic void playinit __P((void));
74256904Sraystatic void playtone __P((int pitch, int value, int sustain));
75256904Sraystatic int abs __P((int n));
76256904Sraystatic void playstring __P((char *cp, size_t slen));
77256904Sray
78256904Sray/* emit tone of frequency thz for given number of ticks */
79256904Sraystatic void
80256904Sraytone(thz, ticks)
81256904Sray	unsigned int thz, ticks;
82256904Sray{
83256904Sray    unsigned int divisor;
84256904Sray    int sps;
85256904Sray
86256904Sray    if (thz <= 0)
87256904Sray	return;
88256904Sray
89257013Sray    divisor = timer_freq / thz;
90257013Sray
91256904Sray#ifdef DEBUG
92256904Sray    (void) printf("tone: thz=%d ticks=%d\n", thz, ticks);
93256904Sray#endif /* DEBUG */
94257725Sray
95256904Sray    /* set timer to generate clicks at given frequency in Hertz */
96256904Sray    sps = splclock();
97256904Sray
98256904Sray    if (acquire_timer2(TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT)) {
99256904Sray	/* enter list of waiting procs ??? */
100256904Sray	splx(sps);
101256904Sray	return;
102256904Sray    }
103256904Sray    splx(sps);
104256904Sray    disable_intr();
105256904Sray    outb(TIMER_CNTR2, (divisor & 0xff));	/* send lo byte */
106256904Sray    outb(TIMER_CNTR2, (divisor >> 8));	/* send hi byte */
107256904Sray    enable_intr();
108256904Sray
109256904Sray    /* turn the speaker on */
110256904Sray    outb(IO_PPI, inb(IO_PPI) | PPI_SPKR);
111256904Sray
112256904Sray    /*
113256904Sray     * Set timeout to endtone function, then give up the timeslice.
114256904Sray     * This is so other processes can execute while the tone is being
115256904Sray     * emitted.
116256904Sray     */
117256904Sray    if (ticks > 0)
118256904Sray	tsleep((caddr_t)&endtone, SPKRPRI | PCATCH, "spkrtn", ticks);
119256904Sray    outb(IO_PPI, inb(IO_PPI) & ~PPI_SPKR);
120256904Sray    sps = splclock();
121256904Sray    release_timer2();
122256904Sray    splx(sps);
123256904Sray}
124256904Sray
125256904Sray/* rest for given number of ticks */
126256904Sraystatic void
127256904Srayrest(ticks)
128256904Sray	int	ticks;
129256904Sray{
130256904Sray    /*
131256904Sray     * Set timeout to endrest function, then give up the timeslice.
132256904Sray     * This is so other processes can execute while the rest is being
133256904Sray     * waited out.
134256904Sray     */
135256904Sray#ifdef DEBUG
136256904Sray    (void) printf("rest: %d\n", ticks);
137256904Sray#endif /* DEBUG */
138256904Sray    if (ticks > 0)
139256904Sray	tsleep((caddr_t)&endrest, SPKRPRI | PCATCH, "spkrrs", ticks);
140256904Sray}
141256904Sray
142256904Sray/**************** PLAY STRING INTERPRETER BEGINS HERE **********************
143256904Sray *
144256904Sray * Play string interpretation is modelled on IBM BASIC 2.0's PLAY statement;
145256904Sray * M[LNS] are missing; the ~ synonym and the _ slur mark and the octave-
146257725Sray * tracking facility are added.
147256904Sray * Requires tone(), rest(), and endtone(). String play is not interruptible
148256904Sray * except possibly at physical block boundaries.
149256904Sray */
150256904Sray
151256904Sraytypedef int	bool;
152256904Sray#define TRUE	1
153256904Sray#define FALSE	0
154256904Sray
155256904Sray#define dtoi(c)		((c) - '0')
156256904Sray
157256904Sraystatic int octave;	/* currently selected octave */
158256904Sraystatic int whole;	/* whole-note time at current tempo, in ticks */
159256904Sraystatic int value;	/* whole divisor for note time, quarter note = 1 */
160256904Sraystatic int fill;	/* controls spacing of notes */
161256904Sraystatic bool octtrack;	/* octave-tracking on? */
162256904Sraystatic bool octprefix;	/* override current octave-tracking state? */
163256904Sray
164256904Sray/*
165256904Sray * Magic number avoidance...
166256904Sray */
167256904Sray#define SECS_PER_MIN	60	/* seconds per minute */
168256904Sray#define WHOLE_NOTE	4	/* quarter notes per whole note */
169256904Sray#define MIN_VALUE	64	/* the most we can divide a note by */
170256904Sray#define DFLT_VALUE	4	/* default value (quarter-note) */
171256904Sray#define FILLTIME	8	/* for articulation, break note in parts */
172256904Sray#define STACCATO	6	/* 6/8 = 3/4 of note is filled */
173256904Sray#define NORMAL		7	/* 7/8ths of note interval is filled */
174256904Sray#define LEGATO		8	/* all of note interval is filled */
175256904Sray#define DFLT_OCTAVE	4	/* default octave */
176256904Sray#define MIN_TEMPO	32	/* minimum tempo */
177256904Sray#define DFLT_TEMPO	120	/* default tempo */
178256904Sray#define MAX_TEMPO	255	/* max tempo */
179256904Sray#define NUM_MULT	3	/* numerator of dot multiplier */
180257725Sray#define DENOM_MULT	2	/* denominator of dot multiplier */
181256904Sray
182256904Sray/* letter to half-tone:  A   B  C  D  E  F  G */
183256904Sraystatic int notetab[8] = {9, 11, 0, 2, 4, 5, 7};
184256904Sray
185256904Sray/*
186256904Sray * This is the American Standard A440 Equal-Tempered scale with frequencies
187256904Sray * rounded to nearest integer. Thank Goddess for the good ol' CRC Handbook...
188256904Sray * our octave 0 is standard octave 2.
189256904Sray */
190256904Sray#define OCTAVE_NOTES	12	/* semitones per octave */
191256904Sraystatic int pitchtab[] =
192256904Sray{
193256904Sray/*        C     C#    D     D#    E     F     F#    G     G#    A     A#    B*/
194256904Sray/* 0 */   65,   69,   73,   78,   82,   87,   93,   98,  103,  110,  117,  123,
195256904Sray/* 1 */  131,  139,  147,  156,  165,  175,  185,  196,  208,  220,  233,  247,
196256904Sray/* 2 */  262,  277,  294,  311,  330,  349,  370,  392,  415,  440,  466,  494,
197256904Sray/* 3 */  523,  554,  587,  622,  659,  698,  740,  784,  831,  880,  932,  988,
198256904Sray/* 4 */ 1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1975,
199256904Sray/* 5 */ 2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951,
200256904Sray/* 6 */ 4186, 4435, 4698, 4978, 5274, 5588, 5920, 6272, 6644, 7040, 7459, 7902,
201256904Sray};
202256904Sray
203256904Sraystatic void
204256904Srayplayinit()
205256904Sray{
206256904Sray    octave = DFLT_OCTAVE;
207256904Sray    whole = (hz * SECS_PER_MIN * WHOLE_NOTE) / DFLT_TEMPO;
208256904Sray    fill = NORMAL;
209256904Sray    value = DFLT_VALUE;
210256904Sray    octtrack = FALSE;
211257725Sray    octprefix = TRUE;	/* act as though there was an initial O(n) */
212256904Sray}
213256904Sray
214/* play tone of proper duration for current rhythm signature */
215static void
216playtone(pitch, value, sustain)
217	int	pitch, value, sustain;
218{
219    register int	sound, silence, snum = 1, sdenom = 1;
220
221    /* this weirdness avoids floating-point arithmetic */
222    for (; sustain; sustain--)
223    {
224	/* See the BUGS section in the man page for discussion */
225	snum *= NUM_MULT;
226	sdenom *= DENOM_MULT;
227    }
228
229    if (value == 0 || sdenom == 0)
230	return;
231
232    if (pitch == -1)
233	rest(whole * snum / (value * sdenom));
234    else
235    {
236	sound = (whole * snum) / (value * sdenom)
237		- (whole * (FILLTIME - fill)) / (value * FILLTIME);
238	silence = whole * (FILLTIME-fill) * snum / (FILLTIME * value * sdenom);
239
240#ifdef DEBUG
241	(void) printf("playtone: pitch %d for %d ticks, rest for %d ticks\n",
242			pitch, sound, silence);
243#endif /* DEBUG */
244
245	tone(pitchtab[pitch], sound);
246	if (fill != LEGATO)
247	    rest(silence);
248    }
249}
250
251static int
252abs(n)
253	int n;
254{
255    if (n < 0)
256	return(-n);
257    else
258	return(n);
259}
260
261/* interpret and play an item from a notation string */
262static void
263playstring(cp, slen)
264	char	*cp;
265	size_t	slen;
266{
267    int		pitch, oldfill, lastpitch = OCTAVE_NOTES * DFLT_OCTAVE;
268
269#define GETNUM(cp, v)	for(v=0; isdigit(cp[1]) && slen > 0; ) \
270				{v = v * 10 + (*++cp - '0'); slen--;}
271    for (; slen--; cp++)
272    {
273	int		sustain, timeval, tempo;
274	register char	c = toupper(*cp);
275
276#ifdef DEBUG
277	(void) printf("playstring: %c (%x)\n", c, c);
278#endif /* DEBUG */
279
280	switch (c)
281	{
282	case 'A':  case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
283
284	    /* compute pitch */
285	    pitch = notetab[c - 'A'] + octave * OCTAVE_NOTES;
286
287	    /* this may be followed by an accidental sign */
288	    if (cp[1] == '#' || cp[1] == '+')
289	    {
290		++pitch;
291		++cp;
292		slen--;
293	    }
294	    else if (cp[1] == '-')
295	    {
296		--pitch;
297		++cp;
298		slen--;
299	    }
300
301	    /*
302	     * If octave-tracking mode is on, and there has been no octave-
303	     * setting prefix, find the version of the current letter note
304	     * closest to the last regardless of octave.
305	     */
306	    if (octtrack && !octprefix)
307	    {
308		if (abs(pitch-lastpitch) > abs(pitch+OCTAVE_NOTES-lastpitch))
309		{
310		    ++octave;
311		    pitch += OCTAVE_NOTES;
312		}
313
314		if (abs(pitch-lastpitch) > abs((pitch-OCTAVE_NOTES)-lastpitch))
315		{
316		    --octave;
317		    pitch -= OCTAVE_NOTES;
318		}
319	    }
320	    octprefix = FALSE;
321	    lastpitch = pitch;
322
323	    /* ...which may in turn be followed by an override time value */
324	    GETNUM(cp, timeval);
325	    if (timeval <= 0 || timeval > MIN_VALUE)
326		timeval = value;
327
328	    /* ...and/or sustain dots */
329	    for (sustain = 0; cp[1] == '.'; cp++)
330	    {
331		slen--;
332		sustain++;
333	    }
334
335	    /* ...and/or a slur mark */
336	    oldfill = fill;
337	    if (cp[1] == '_')
338	    {
339		fill = LEGATO;
340		++cp;
341		slen--;
342	    }
343
344	    /* time to emit the actual tone */
345	    playtone(pitch, timeval, sustain);
346
347	    fill = oldfill;
348	    break;
349
350	case 'O':
351	    if (cp[1] == 'N' || cp[1] == 'n')
352	    {
353		octprefix = octtrack = FALSE;
354		++cp;
355		slen--;
356	    }
357	    else if (cp[1] == 'L' || cp[1] == 'l')
358	    {
359		octtrack = TRUE;
360		++cp;
361		slen--;
362	    }
363	    else
364	    {
365		GETNUM(cp, octave);
366		if (octave >= sizeof(pitchtab) / sizeof(pitchtab[0]) / OCTAVE_NOTES)
367		    octave = DFLT_OCTAVE;
368		octprefix = TRUE;
369	    }
370	    break;
371
372	case '>':
373	    if (octave < sizeof(pitchtab) / sizeof(pitchtab[0]) / OCTAVE_NOTES - 1)
374		octave++;
375	    octprefix = TRUE;
376	    break;
377
378	case '<':
379	    if (octave > 0)
380		octave--;
381	    octprefix = TRUE;
382	    break;
383
384	case 'N':
385	    GETNUM(cp, pitch);
386	    for (sustain = 0; cp[1] == '.'; cp++)
387	    {
388		slen--;
389		sustain++;
390	    }
391	    oldfill = fill;
392	    if (cp[1] == '_')
393	    {
394		fill = LEGATO;
395		++cp;
396		slen--;
397	    }
398	    playtone(pitch - 1, value, sustain);
399	    fill = oldfill;
400	    break;
401
402	case 'L':
403	    GETNUM(cp, value);
404	    if (value <= 0 || value > MIN_VALUE)
405		value = DFLT_VALUE;
406	    break;
407
408	case 'P':
409	case '~':
410	    /* this may be followed by an override time value */
411	    GETNUM(cp, timeval);
412	    if (timeval <= 0 || timeval > MIN_VALUE)
413		timeval = value;
414	    for (sustain = 0; cp[1] == '.'; cp++)
415	    {
416		slen--;
417		sustain++;
418	    }
419	    playtone(-1, timeval, sustain);
420	    break;
421
422	case 'T':
423	    GETNUM(cp, tempo);
424	    if (tempo < MIN_TEMPO || tempo > MAX_TEMPO)
425		tempo = DFLT_TEMPO;
426	    whole = (hz * SECS_PER_MIN * WHOLE_NOTE) / tempo;
427	    break;
428
429	case 'M':
430	    if (cp[1] == 'N' || cp[1] == 'n')
431	    {
432		fill = NORMAL;
433		++cp;
434		slen--;
435	    }
436	    else if (cp[1] == 'L' || cp[1] == 'l')
437	    {
438		fill = LEGATO;
439		++cp;
440		slen--;
441	    }
442	    else if (cp[1] == 'S' || cp[1] == 's')
443	    {
444		fill = STACCATO;
445		++cp;
446		slen--;
447	    }
448	    break;
449	}
450    }
451}
452
453/******************* UNIX DRIVER HOOKS BEGIN HERE **************************
454 *
455 * This section implements driver hooks to run playstring() and the tone(),
456 * endtone(), and rest() functions defined above.
457 */
458
459static int spkr_active = FALSE; /* exclusion flag */
460static char *spkr_inbuf;  /* incoming buf */
461
462int
463spkropen(dev, flags, fmt, p)
464	dev_t		dev;
465	int		flags;
466	int		fmt;
467	struct proc	*p;
468{
469#ifdef DEBUG
470    (void) printf("spkropen: entering with dev = %s\n", devtoname(dev));
471#endif /* DEBUG */
472
473    if (minor(dev) != 0)
474	return(ENXIO);
475    else if (spkr_active)
476	return(EBUSY);
477    else
478    {
479#ifdef DEBUG
480	(void) printf("spkropen: about to perform play initialization\n");
481#endif /* DEBUG */
482	playinit();
483	spkr_inbuf = malloc(DEV_BSIZE, M_SPKR, M_WAITOK);
484	spkr_active = TRUE;
485	return(0);
486    }
487}
488
489int
490spkrwrite(dev, uio, ioflag)
491	dev_t		dev;
492	struct uio	*uio;
493	int		ioflag;
494{
495#ifdef DEBUG
496    printf("spkrwrite: entering with dev = %s, count = %d\n",
497		devtoname(dev), uio->uio_resid);
498#endif /* DEBUG */
499
500    if (minor(dev) != 0)
501	return(ENXIO);
502    else if (uio->uio_resid > (DEV_BSIZE - 1))     /* prevent system crashes */
503	return(E2BIG);
504    else
505    {
506	unsigned n;
507	char *cp;
508	int error;
509
510	n = uio->uio_resid;
511	cp = spkr_inbuf;
512	error = uiomove(cp, n, uio);
513	if (!error) {
514		cp[n] = '\0';
515		playstring(cp, n);
516	}
517	return(error);
518    }
519}
520
521int
522spkrclose(dev, flags, fmt, p)
523	dev_t		dev;
524	int		flags;
525	int		fmt;
526	struct proc	*p;
527{
528#ifdef DEBUG
529    (void) printf("spkrclose: entering with dev = %s\n", devtoname(dev));
530#endif /* DEBUG */
531
532    if (minor(dev) != 0)
533	return(ENXIO);
534    else
535    {
536	wakeup((caddr_t)&endtone);
537	wakeup((caddr_t)&endrest);
538	free(spkr_inbuf, M_SPKR);
539	spkr_active = FALSE;
540	return(0);
541    }
542}
543
544int
545spkrioctl(dev, cmd, cmdarg, flags, p)
546	dev_t		dev;
547	unsigned long	cmd;
548	caddr_t		cmdarg;
549	int		flags;
550	struct proc	*p;
551{
552#ifdef DEBUG
553    (void) printf("spkrioctl: entering with dev = %s, cmd = %lx\n",
554    	devtoname(dev), cmd);
555#endif /* DEBUG */
556
557    if (minor(dev) != 0)
558	return(ENXIO);
559    else if (cmd == SPKRTONE)
560    {
561	tone_t	*tp = (tone_t *)cmdarg;
562
563	if (tp->frequency == 0)
564	    rest(tp->duration);
565	else
566	    tone(tp->frequency, tp->duration);
567	return 0;
568    }
569    else if (cmd == SPKRTUNE)
570    {
571	tone_t  *tp = (tone_t *)(*(caddr_t *)cmdarg);
572	tone_t ttp;
573	int error;
574
575	for (; ; tp++) {
576	    error = copyin(tp, &ttp, sizeof(tone_t));
577	    if (error)
578		    return(error);
579	    if (ttp.duration == 0)
580		    break;
581	    if (ttp.frequency == 0)
582		 rest(ttp.duration);
583	    else
584		 tone(ttp.frequency, ttp.duration);
585	}
586	return(0);
587    }
588    return(EINVAL);
589}
590
591static void
592spkr_drvinit(void *unused)
593{
594	make_dev(&spkr_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "speaker");
595}
596
597SYSINIT(spkrdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,spkr_drvinit,NULL)
598
599/*
600 * Install placeholder to claim the resources owned by the
601 * AT tone generator.
602 */
603static struct isa_pnp_id atspeaker_ids[] = {
604	{ 0x0008d041 /* PNP0800 */, "AT speaker" },
605	{ 0 }
606};
607
608static int
609atspeaker_probe(device_t dev)
610{
611	return(ISA_PNP_PROBE(device_get_parent(dev), dev, atspeaker_ids));
612}
613
614static int
615atspeaker_attach(device_t dev)
616{
617	return(0);
618}
619
620static device_method_t atspeaker_methods[] = {
621	/* Device interface */
622	DEVMETHOD(device_probe,		atspeaker_probe),
623	DEVMETHOD(device_attach,	atspeaker_attach),
624	DEVMETHOD(device_detach,	bus_generic_detach),
625	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
626	DEVMETHOD(device_suspend,	bus_generic_suspend),
627	DEVMETHOD(device_resume,	bus_generic_resume),
628	{ 0, 0 }
629};
630
631static driver_t atspeaker_driver = {
632	"atspeaker",
633	atspeaker_methods,
634	1,		/* no softc */
635};
636
637static devclass_t atspeaker_devclass;
638
639DRIVER_MODULE(atspeaker, isa, atspeaker_driver, atspeaker_devclass, 0, 0);
640DRIVER_MODULE(atspeaker, acpi, atspeaker_driver, atspeaker_devclass, 0, 0);
641
642/* spkr.c ends here */
643