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