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