xref: /freebsd/sys/dev/speaker/spkr.c (revision 6780ab54325a71e7e70112b11657973edde8655e)
1 /*
2  * spkr.c -- device driver for console speaker
3  *
4  * v1.4 by Eric S. Raymond (esr@snark.thyrsus.com) Aug 1993
5  * modified for FreeBSD by Andrew A. Chernov <ache@astral.msk.su>
6  * modified for PC98 by Kakefuda
7  *
8  * $FreeBSD$
9  */
10 
11 #include <sys/param.h>
12 #include <sys/systm.h>
13 #include <sys/bus.h>
14 #include <sys/kernel.h>
15 #include <sys/module.h>
16 #include <sys/uio.h>
17 #include <sys/conf.h>
18 #include <sys/ctype.h>
19 #include <sys/malloc.h>
20 #include <isa/isavar.h>
21 #ifdef PC98
22 #include <pc98/pc98/pc98.h>
23 #else
24 #include <i386/isa/isa.h>
25 #endif
26 #include <i386/isa/timerreg.h>
27 #include <machine/clock.h>
28 #include <machine/speaker.h>
29 
30 static	d_open_t	spkropen;
31 static	d_close_t	spkrclose;
32 static	d_write_t	spkrwrite;
33 static	d_ioctl_t	spkrioctl;
34 
35 #define CDEV_MAJOR 26
36 static struct cdevsw spkr_cdevsw = {
37 	/* open */	spkropen,
38 	/* close */	spkrclose,
39 	/* read */	noread,
40 	/* write */	spkrwrite,
41 	/* ioctl */	spkrioctl,
42 	/* poll */	nopoll,
43 	/* mmap */	nommap,
44 	/* strategy */	nostrategy,
45 	/* name */	"spkr",
46 	/* maj */	CDEV_MAJOR,
47 	/* dump */	nodump,
48 	/* psize */	nopsize,
49 	/* flags */	0,
50 };
51 
52 static MALLOC_DEFINE(M_SPKR, "spkr", "Speaker buffer");
53 
54 /**************** MACHINE DEPENDENT PART STARTS HERE *************************
55  *
56  * This section defines a function tone() which causes a tone of given
57  * frequency and duration from the ISA console speaker.
58  * Another function endtone() is defined to force sound off, and there is
59  * also a rest() entry point to do pauses.
60  *
61  * Audible sound is generated using the Programmable Interval Timer (PIT) and
62  * Programmable Peripheral Interface (PPI) attached to the ISA speaker. The
63  * PPI controls whether sound is passed through at all; the PIT's channel 2 is
64  * used to generate clicks (a square wave) of whatever frequency is desired.
65  */
66 
67 /*
68  * XXX PPI control values should be in a header and used in clock.c.
69  */
70 #ifdef PC98
71 #define	PPI_SPKR	0x08	/* turn these PPI bits on to pass sound */
72 #define	PIT_COUNT	0x3fdb	/* PIT count address */
73 
74 #define	SPEAKER_ON	outb(IO_PPI, inb(IO_PPI) & ~PPI_SPKR)
75 #define	SPEAKER_OFF	outb(IO_PPI, inb(IO_PPI) | PPI_SPKR)
76 #define	TIMER_ACQUIRE	acquire_timer1(TIMER_SEL1 | TIMER_SQWAVE | TIMER_16BIT)
77 #define	TIMER_RELEASE	release_timer1()
78 #define	SPEAKER_WRITE(val)	{ \
79 					outb(PIT_COUNT, (val & 0xff)); \
80 					outb(PIT_COUNT, (val >> 8)); \
81 				}
82 #else
83 #define PPI_SPKR	0x03	/* turn these PPI bits on to pass sound */
84 
85 #define	SPEAKER_ON	outb(IO_PPI, inb(IO_PPI) | PPI_SPKR)
86 #define	SPEAKER_OFF	outb(IO_PPI, inb(IO_PPI) & ~PPI_SPKR)
87 #define	TIMER_ACQUIRE	acquire_timer2(TIMER_SEL2 | TIMER_SQWAVE | TIMER_16BIT)
88 #define	TIMER_RELEASE	release_timer2()
89 #define	SPEAKER_WRITE(val)	{ \
90 					outb(TIMER_CNTR2, (val & 0xff)); \
91     					outb(TIMER_CNTR2, (val >> 8)); \
92 				}
93 #endif
94 
95 #define SPKRPRI PSOCK
96 static char endtone, endrest;
97 
98 static void tone(unsigned int thz, unsigned int ticks);
99 static void rest(int ticks);
100 static void playinit(void);
101 static void playtone(int pitch, int value, int sustain);
102 static void playstring(char *cp, size_t slen);
103 
104 /* emit tone of frequency thz for given number of ticks */
105 static void
106 tone(thz, ticks)
107 	unsigned int thz, ticks;
108 {
109     unsigned int divisor;
110     int sps;
111 
112     if (thz <= 0)
113 	return;
114 
115     divisor = timer_freq / thz;
116 
117 #ifdef DEBUG
118     (void) printf("tone: thz=%d ticks=%d\n", thz, ticks);
119 #endif /* DEBUG */
120 
121     /* set timer to generate clicks at given frequency in Hertz */
122     sps = splclock();
123 
124     if (TIMER_ACQUIRE) {
125 	/* enter list of waiting procs ??? */
126 	splx(sps);
127 	return;
128     }
129     splx(sps);
130     disable_intr();
131     SPEAKER_WRITE(divisor);
132     enable_intr();
133 
134     /* turn the speaker on */
135     SPEAKER_ON;
136 
137     /*
138      * Set timeout to endtone function, then give up the timeslice.
139      * This is so other processes can execute while the tone is being
140      * emitted.
141      */
142     if (ticks > 0)
143 	tsleep((caddr_t)&endtone, SPKRPRI | PCATCH, "spkrtn", ticks);
144     SPEAKER_OFF;
145     sps = splclock();
146     TIMER_RELEASE;
147     splx(sps);
148 }
149 
150 /* rest for given number of ticks */
151 static void
152 rest(ticks)
153 	int	ticks;
154 {
155     /*
156      * Set timeout to endrest function, then give up the timeslice.
157      * This is so other processes can execute while the rest is being
158      * waited out.
159      */
160 #ifdef DEBUG
161     (void) printf("rest: %d\n", ticks);
162 #endif /* DEBUG */
163     if (ticks > 0)
164 	tsleep((caddr_t)&endrest, SPKRPRI | PCATCH, "spkrrs", ticks);
165 }
166 
167 /**************** PLAY STRING INTERPRETER BEGINS HERE **********************
168  *
169  * Play string interpretation is modelled on IBM BASIC 2.0's PLAY statement;
170  * M[LNS] are missing; the ~ synonym and the _ slur mark and the octave-
171  * tracking facility are added.
172  * Requires tone(), rest(), and endtone(). String play is not interruptible
173  * except possibly at physical block boundaries.
174  */
175 
176 typedef int	bool;
177 #define TRUE	1
178 #define FALSE	0
179 
180 #define dtoi(c)		((c) - '0')
181 
182 static int octave;	/* currently selected octave */
183 static int whole;	/* whole-note time at current tempo, in ticks */
184 static int value;	/* whole divisor for note time, quarter note = 1 */
185 static int fill;	/* controls spacing of notes */
186 static bool octtrack;	/* octave-tracking on? */
187 static bool octprefix;	/* override current octave-tracking state? */
188 
189 /*
190  * Magic number avoidance...
191  */
192 #define SECS_PER_MIN	60	/* seconds per minute */
193 #define WHOLE_NOTE	4	/* quarter notes per whole note */
194 #define MIN_VALUE	64	/* the most we can divide a note by */
195 #define DFLT_VALUE	4	/* default value (quarter-note) */
196 #define FILLTIME	8	/* for articulation, break note in parts */
197 #define STACCATO	6	/* 6/8 = 3/4 of note is filled */
198 #define NORMAL		7	/* 7/8ths of note interval is filled */
199 #define LEGATO		8	/* all of note interval is filled */
200 #define DFLT_OCTAVE	4	/* default octave */
201 #define MIN_TEMPO	32	/* minimum tempo */
202 #define DFLT_TEMPO	120	/* default tempo */
203 #define MAX_TEMPO	255	/* max tempo */
204 #define NUM_MULT	3	/* numerator of dot multiplier */
205 #define DENOM_MULT	2	/* denominator of dot multiplier */
206 
207 /* letter to half-tone:  A   B  C  D  E  F  G */
208 static int notetab[8] = {9, 11, 0, 2, 4, 5, 7};
209 
210 /*
211  * This is the American Standard A440 Equal-Tempered scale with frequencies
212  * rounded to nearest integer. Thank Goddess for the good ol' CRC Handbook...
213  * our octave 0 is standard octave 2.
214  */
215 #define OCTAVE_NOTES	12	/* semitones per octave */
216 static int pitchtab[] =
217 {
218 /*        C     C#    D     D#    E     F     F#    G     G#    A     A#    B*/
219 /* 0 */   65,   69,   73,   78,   82,   87,   93,   98,  103,  110,  117,  123,
220 /* 1 */  131,  139,  147,  156,  165,  175,  185,  196,  208,  220,  233,  247,
221 /* 2 */  262,  277,  294,  311,  330,  349,  370,  392,  415,  440,  466,  494,
222 /* 3 */  523,  554,  587,  622,  659,  698,  740,  784,  831,  880,  932,  988,
223 /* 4 */ 1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1975,
224 /* 5 */ 2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951,
225 /* 6 */ 4186, 4435, 4698, 4978, 5274, 5588, 5920, 6272, 6644, 7040, 7459, 7902,
226 };
227 
228 static void
229 playinit()
230 {
231     octave = DFLT_OCTAVE;
232     whole = (hz * SECS_PER_MIN * WHOLE_NOTE) / DFLT_TEMPO;
233     fill = NORMAL;
234     value = DFLT_VALUE;
235     octtrack = FALSE;
236     octprefix = TRUE;	/* act as though there was an initial O(n) */
237 }
238 
239 /* play tone of proper duration for current rhythm signature */
240 static void
241 playtone(pitch, value, sustain)
242 	int	pitch, value, sustain;
243 {
244     register int	sound, silence, snum = 1, sdenom = 1;
245 
246     /* this weirdness avoids floating-point arithmetic */
247     for (; sustain; sustain--)
248     {
249 	/* See the BUGS section in the man page for discussion */
250 	snum *= NUM_MULT;
251 	sdenom *= DENOM_MULT;
252     }
253 
254     if (value == 0 || sdenom == 0)
255 	return;
256 
257     if (pitch == -1)
258 	rest(whole * snum / (value * sdenom));
259     else
260     {
261 	sound = (whole * snum) / (value * sdenom)
262 		- (whole * (FILLTIME - fill)) / (value * FILLTIME);
263 	silence = whole * (FILLTIME-fill) * snum / (FILLTIME * value * sdenom);
264 
265 #ifdef DEBUG
266 	(void) printf("playtone: pitch %d for %d ticks, rest for %d ticks\n",
267 			pitch, sound, silence);
268 #endif /* DEBUG */
269 
270 	tone(pitchtab[pitch], sound);
271 	if (fill != LEGATO)
272 	    rest(silence);
273     }
274 }
275 
276 /* interpret and play an item from a notation string */
277 static void
278 playstring(cp, slen)
279 	char	*cp;
280 	size_t	slen;
281 {
282     int		pitch, oldfill, lastpitch = OCTAVE_NOTES * DFLT_OCTAVE;
283 
284 #define GETNUM(cp, v)	for(v=0; isdigit(cp[1]) && slen > 0; ) \
285 				{v = v * 10 + (*++cp - '0'); slen--;}
286     for (; slen--; cp++)
287     {
288 	int		sustain, timeval, tempo;
289 	register char	c = toupper(*cp);
290 
291 #ifdef DEBUG
292 	(void) printf("playstring: %c (%x)\n", c, c);
293 #endif /* DEBUG */
294 
295 	switch (c)
296 	{
297 	case 'A':  case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
298 
299 	    /* compute pitch */
300 	    pitch = notetab[c - 'A'] + octave * OCTAVE_NOTES;
301 
302 	    /* this may be followed by an accidental sign */
303 	    if (cp[1] == '#' || cp[1] == '+')
304 	    {
305 		++pitch;
306 		++cp;
307 		slen--;
308 	    }
309 	    else if (cp[1] == '-')
310 	    {
311 		--pitch;
312 		++cp;
313 		slen--;
314 	    }
315 
316 	    /*
317 	     * If octave-tracking mode is on, and there has been no octave-
318 	     * setting prefix, find the version of the current letter note
319 	     * closest to the last regardless of octave.
320 	     */
321 	    if (octtrack && !octprefix)
322 	    {
323 		if (abs(pitch-lastpitch) > abs(pitch+OCTAVE_NOTES-lastpitch))
324 		{
325 		    ++octave;
326 		    pitch += OCTAVE_NOTES;
327 		}
328 
329 		if (abs(pitch-lastpitch) > abs((pitch-OCTAVE_NOTES)-lastpitch))
330 		{
331 		    --octave;
332 		    pitch -= OCTAVE_NOTES;
333 		}
334 	    }
335 	    octprefix = FALSE;
336 	    lastpitch = pitch;
337 
338 	    /* ...which may in turn be followed by an override time value */
339 	    GETNUM(cp, timeval);
340 	    if (timeval <= 0 || timeval > MIN_VALUE)
341 		timeval = value;
342 
343 	    /* ...and/or sustain dots */
344 	    for (sustain = 0; cp[1] == '.'; cp++)
345 	    {
346 		slen--;
347 		sustain++;
348 	    }
349 
350 	    /* ...and/or a slur mark */
351 	    oldfill = fill;
352 	    if (cp[1] == '_')
353 	    {
354 		fill = LEGATO;
355 		++cp;
356 		slen--;
357 	    }
358 
359 	    /* time to emit the actual tone */
360 	    playtone(pitch, timeval, sustain);
361 
362 	    fill = oldfill;
363 	    break;
364 
365 	case 'O':
366 	    if (cp[1] == 'N' || cp[1] == 'n')
367 	    {
368 		octprefix = octtrack = FALSE;
369 		++cp;
370 		slen--;
371 	    }
372 	    else if (cp[1] == 'L' || cp[1] == 'l')
373 	    {
374 		octtrack = TRUE;
375 		++cp;
376 		slen--;
377 	    }
378 	    else
379 	    {
380 		GETNUM(cp, octave);
381 		if (octave >= sizeof(pitchtab) / sizeof(pitchtab[0]) / OCTAVE_NOTES)
382 		    octave = DFLT_OCTAVE;
383 		octprefix = TRUE;
384 	    }
385 	    break;
386 
387 	case '>':
388 	    if (octave < sizeof(pitchtab) / sizeof(pitchtab[0]) / OCTAVE_NOTES - 1)
389 		octave++;
390 	    octprefix = TRUE;
391 	    break;
392 
393 	case '<':
394 	    if (octave > 0)
395 		octave--;
396 	    octprefix = TRUE;
397 	    break;
398 
399 	case 'N':
400 	    GETNUM(cp, pitch);
401 	    for (sustain = 0; cp[1] == '.'; cp++)
402 	    {
403 		slen--;
404 		sustain++;
405 	    }
406 	    oldfill = fill;
407 	    if (cp[1] == '_')
408 	    {
409 		fill = LEGATO;
410 		++cp;
411 		slen--;
412 	    }
413 	    playtone(pitch - 1, value, sustain);
414 	    fill = oldfill;
415 	    break;
416 
417 	case 'L':
418 	    GETNUM(cp, value);
419 	    if (value <= 0 || value > MIN_VALUE)
420 		value = DFLT_VALUE;
421 	    break;
422 
423 	case 'P':
424 	case '~':
425 	    /* this may be followed by an override time value */
426 	    GETNUM(cp, timeval);
427 	    if (timeval <= 0 || timeval > MIN_VALUE)
428 		timeval = value;
429 	    for (sustain = 0; cp[1] == '.'; cp++)
430 	    {
431 		slen--;
432 		sustain++;
433 	    }
434 	    playtone(-1, timeval, sustain);
435 	    break;
436 
437 	case 'T':
438 	    GETNUM(cp, tempo);
439 	    if (tempo < MIN_TEMPO || tempo > MAX_TEMPO)
440 		tempo = DFLT_TEMPO;
441 	    whole = (hz * SECS_PER_MIN * WHOLE_NOTE) / tempo;
442 	    break;
443 
444 	case 'M':
445 	    if (cp[1] == 'N' || cp[1] == 'n')
446 	    {
447 		fill = NORMAL;
448 		++cp;
449 		slen--;
450 	    }
451 	    else if (cp[1] == 'L' || cp[1] == 'l')
452 	    {
453 		fill = LEGATO;
454 		++cp;
455 		slen--;
456 	    }
457 	    else if (cp[1] == 'S' || cp[1] == 's')
458 	    {
459 		fill = STACCATO;
460 		++cp;
461 		slen--;
462 	    }
463 	    break;
464 	}
465     }
466 }
467 
468 /******************* UNIX DRIVER HOOKS BEGIN HERE **************************
469  *
470  * This section implements driver hooks to run playstring() and the tone(),
471  * endtone(), and rest() functions defined above.
472  */
473 
474 static int spkr_active = FALSE; /* exclusion flag */
475 static char *spkr_inbuf;  /* incoming buf */
476 
477 static int
478 spkropen(dev, flags, fmt, td)
479 	dev_t		dev;
480 	int		flags;
481 	int		fmt;
482 	struct thread	*td;
483 {
484 #ifdef DEBUG
485     (void) printf("spkropen: entering with dev = %s\n", devtoname(dev));
486 #endif /* DEBUG */
487 
488     if (minor(dev) != 0)
489 	return(ENXIO);
490     else if (spkr_active)
491 	return(EBUSY);
492     else
493     {
494 #ifdef DEBUG
495 	(void) printf("spkropen: about to perform play initialization\n");
496 #endif /* DEBUG */
497 	playinit();
498 	spkr_inbuf = malloc(DEV_BSIZE, M_SPKR, 0);
499 	spkr_active = TRUE;
500 	return(0);
501     }
502 }
503 
504 static int
505 spkrwrite(dev, uio, ioflag)
506 	dev_t		dev;
507 	struct uio	*uio;
508 	int		ioflag;
509 {
510 #ifdef DEBUG
511     printf("spkrwrite: entering with dev = %s, count = %d\n",
512 		devtoname(dev), uio->uio_resid);
513 #endif /* DEBUG */
514 
515     if (minor(dev) != 0)
516 	return(ENXIO);
517     else if (uio->uio_resid > (DEV_BSIZE - 1))     /* prevent system crashes */
518 	return(E2BIG);
519     else
520     {
521 	unsigned n;
522 	char *cp;
523 	int error;
524 
525 	n = uio->uio_resid;
526 	cp = spkr_inbuf;
527 	error = uiomove(cp, n, uio);
528 	if (!error) {
529 		cp[n] = '\0';
530 		playstring(cp, n);
531 	}
532 	return(error);
533     }
534 }
535 
536 static int
537 spkrclose(dev, flags, fmt, td)
538 	dev_t		dev;
539 	int		flags;
540 	int		fmt;
541 	struct thread	*td;
542 {
543 #ifdef DEBUG
544     (void) printf("spkrclose: entering with dev = %s\n", devtoname(dev));
545 #endif /* DEBUG */
546 
547     if (minor(dev) != 0)
548 	return(ENXIO);
549     else
550     {
551 	wakeup((caddr_t)&endtone);
552 	wakeup((caddr_t)&endrest);
553 	free(spkr_inbuf, M_SPKR);
554 	spkr_active = FALSE;
555 	return(0);
556     }
557 }
558 
559 static int
560 spkrioctl(dev, cmd, cmdarg, flags, td)
561 	dev_t		dev;
562 	unsigned long	cmd;
563 	caddr_t		cmdarg;
564 	int		flags;
565 	struct thread	*td;
566 {
567 #ifdef DEBUG
568     (void) printf("spkrioctl: entering with dev = %s, cmd = %lx\n",
569     	devtoname(dev), cmd);
570 #endif /* DEBUG */
571 
572     if (minor(dev) != 0)
573 	return(ENXIO);
574     else if (cmd == SPKRTONE)
575     {
576 	tone_t	*tp = (tone_t *)cmdarg;
577 
578 	if (tp->frequency == 0)
579 	    rest(tp->duration);
580 	else
581 	    tone(tp->frequency, tp->duration);
582 	return 0;
583     }
584     else if (cmd == SPKRTUNE)
585     {
586 	tone_t  *tp = (tone_t *)(*(caddr_t *)cmdarg);
587 	tone_t ttp;
588 	int error;
589 
590 	for (; ; tp++) {
591 	    error = copyin(tp, &ttp, sizeof(tone_t));
592 	    if (error)
593 		    return(error);
594 	    if (ttp.duration == 0)
595 		    break;
596 	    if (ttp.frequency == 0)
597 		 rest(ttp.duration);
598 	    else
599 		 tone(ttp.frequency, ttp.duration);
600 	}
601 	return(0);
602     }
603     return(EINVAL);
604 }
605 
606 /*
607  * Install placeholder to claim the resources owned by the
608  * AT tone generator.
609  */
610 static struct isa_pnp_id speaker_ids[] = {
611 #ifndef PC98
612 	{ 0x0008d041 /* PNP0800 */, "PC speaker" },
613 #endif
614 	{ 0 }
615 };
616 
617 static dev_t speaker_dev;
618 
619 static int
620 speaker_probe(device_t dev)
621 {
622 	int	error;
623 
624 	error = ISA_PNP_PROBE(device_get_parent(dev), dev, speaker_ids);
625 
626 	/* PnP match */
627 	if (error == 0)
628 		return (0);
629 
630 	/* No match */
631 	if (error == ENXIO)
632 		return (ENXIO);
633 
634 	/* Not configured by hints. */
635 	if (strncmp(device_get_name(dev), "speaker", 9))
636 		return (ENXIO);
637 
638 	device_set_desc(dev, "PC speaker");
639 
640 	return (0);
641 }
642 
643 static int
644 speaker_attach(device_t dev)
645 {
646 
647 	if (speaker_dev) {
648 		device_printf(dev, "Already attached!\n");
649 		return (ENXIO);
650 	}
651 
652 	speaker_dev = make_dev(&spkr_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600,
653 	    "speaker");
654 	return (0);
655 }
656 
657 static int
658 speaker_detach(device_t dev)
659 {
660 	destroy_dev(speaker_dev);
661 	return (0);
662 }
663 
664 static device_method_t speaker_methods[] = {
665 	/* Device interface */
666 	DEVMETHOD(device_probe,		speaker_probe),
667 	DEVMETHOD(device_attach,	speaker_attach),
668 	DEVMETHOD(device_detach,	speaker_detach),
669 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
670 	DEVMETHOD(device_suspend,	bus_generic_suspend),
671 	DEVMETHOD(device_resume,	bus_generic_resume),
672 	{ 0, 0 }
673 };
674 
675 static driver_t speaker_driver = {
676 	"speaker",
677 	speaker_methods,
678 	1,		/* no softc */
679 };
680 
681 static devclass_t speaker_devclass;
682 
683 DRIVER_MODULE(speaker, isa, speaker_driver, speaker_devclass, 0, 0);
684 #ifndef PC98
685 DRIVER_MODULE(speaker, acpi, speaker_driver, speaker_devclass, 0, 0);
686 #endif
687 
688 /* spkr.c ends here */
689