xref: /freebsd/sys/dev/sound/pcm/channel.c (revision 23f282aa31e9b6fceacd449020e936e98d6f2298)
1 /*
2  * Copyright (c) 1999 Cameron Grant <gandalf@vilnya.demon.co.uk>
3  * Portions Copyright by Luigi Rizzo - 1997-99
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD$
28  */
29 
30 #include <dev/sound/pcm/sound.h>
31 
32 #define MIN_CHUNK_SIZE 		256	/* for uiomove etc. */
33 #define	DMA_ALIGN_THRESHOLD	4
34 #define	DMA_ALIGN_MASK		(~(DMA_ALIGN_THRESHOLD - 1))
35 
36 #define ISA_DMA(b) (((b)->chan >= 0 && (b)->chan != 4 && (b)->chan < 8))
37 #define CANCHANGE(c) (!(c)->buffer.dl)
38 /*
39 #define DEB(x) x
40 */
41 static void buf_clear(snd_dbuf *b, u_int32_t fmt, int length);
42 static void chn_dmaupdate(pcm_channel *c);
43 static void chn_wrintr(pcm_channel *c);
44 static void chn_rdintr(pcm_channel *c);
45 /*
46  * SOUND OUTPUT
47 
48 We use a circular buffer to store samples directed to the DAC.
49 The buffer is split into two variable-size regions, each identified
50 by an offset in the buffer (rp,fp) and a length (rl,fl):
51 
52       0          rp,rl        fp,fl    bufsize
53       |__________>____________>________|
54 	  FREE   d   READY    w FREE
55 
56   READY: data written from the process and ready to be sent to the DAC;
57   FREE: free part of the buffer.
58 
59 Both regions can wrap around the end of the buffer.  At initialization,
60 READY is empty, FREE takes all the available space, and dma is
61 idle.  dl contains the length of the current DMA transfer, dl=0
62 means that the dma is idle.
63 
64 The two boundaries (rp,fp) in the buffers are advanced by DMA [d]
65 and write() [w] operations. The first portion of the READY region
66 is used for DMA transfers. The transfer is started at rp and with
67 chunks of length dl. During DMA operations, dsp_wr_dmaupdate()
68 updates rp, rl and fl tracking the ISA DMA engine as the transfer
69 makes progress.
70 When a new block is written, fp advances and rl,fl are updated
71 accordingly.
72 
73 The code works as follows: the user write routine dsp_write_body()
74 fills up the READY region with new data (reclaiming space from the
75 FREE region) and starts the write DMA engine if inactive.  When a
76 DMA transfer is complete, an interrupt causes dsp_wrintr() to be
77 called which extends the FREE region and possibly starts the next
78 transfer.
79 
80 In some cases, the code tries to track the current status of DMA
81 operations by calling dsp_wr_dmaupdate() which changes rp, rl and fl.
82 
83 The system tries to make all DMA transfers use the same size,
84 play_blocksize or rec_blocksize. The size is either selected by
85 the user, or computed by the system to correspond to about .25s of
86 audio. The blocksize must be within a range which is currently:
87 
88 	min(5ms, 40 bytes) ... 1/2 buffer size.
89 
90 When there aren't enough data (write) or space (read), a transfer
91 is started with a reduced size.
92 
93 To reduce problems in case of overruns, the routine which fills up
94 the buffer should initialize (e.g. by repeating the last value) a
95 reasonably long area after the last block so that no noise is
96 produced on overruns.
97 
98   *
99   */
100 
101 
102 /* XXX  this is broken: in the event a bounce buffer is used, data never
103  * gets copied in or out of the real buffer.  fix requires mods to isa_dma.c
104  * and possibly fixes to other autodma mode clients
105  */
106 static void
107 chn_isadmabounce(pcm_channel *c)
108 {
109 	if (ISA_DMA(&c->buffer)) {
110 		/* tell isa_dma to bounce data in/out */
111     	} else KASSERT(1, ("chn_isadmabounce called on invalid channel"));
112 }
113 
114 static int
115 chn_polltrigger(pcm_channel *c)
116 {
117 	snd_dbuf *bs = &c->buffer2nd;
118 	unsigned lim = (c->flags & CHN_F_HAS_SIZE)? c->blocksize2nd : 0;
119 	int trig = 0;
120 
121 	lim = 0;
122 	if (c->flags & CHN_F_MAPPED)
123 		trig = ((bs->int_count > bs->prev_int_count) || bs->first_poll);
124 	else
125 		trig = (((c->direction == PCMDIR_PLAY)? bs->fl : bs->rl) > lim);
126 	return trig;
127 }
128 
129 static int
130 chn_pollreset(pcm_channel *c)
131 {
132 	snd_dbuf *bs = &c->buffer2nd;
133 
134 	if (c->flags & CHN_F_MAPPED) bs->prev_int_count = bs->int_count;
135 	bs->first_poll = 0;
136 	return 1;
137 }
138 
139 /*
140  * chn_dmadone() updates pointers and wakes up any process waiting
141  * on a select(). Must be called at spltty().
142  */
143 static void
144 chn_dmadone(pcm_channel *c)
145 {
146 	snd_dbuf *b = &c->buffer;
147 
148 	if (c->direction == PCMDIR_PLAY)
149 		chn_checkunderflow(c);
150 	else
151 		chn_dmaupdate(c);
152 	if (ISA_DMA(b)) chn_isadmabounce(c); /* sync bounce buffer */
153 	b->int_count++;
154 }
155 
156 /*
157  * chn_dmawakeup() wakes up any process sleeping. Separated from
158  * chn_dmadone() so that wakeup occurs only when feed from a
159  * secondary buffer to a DMA buffer takes place. Must be called
160  * at spltty().
161  */
162 static void
163 chn_dmawakeup(pcm_channel *c)
164 {
165 	snd_dbuf *b = &c->buffer;
166 
167 	wakeup(b);
168 }
169 
170 /*
171  * chn_dmaupdate() tracks the status of a dma transfer,
172  * updating pointers. It must be called at spltty().
173  *
174  * NOTE: when we are using auto dma in the device, rl might become
175  * negative.
176  */
177 DEB (static int chn_updatecount=0);
178 
179 static void
180 chn_dmaupdate(pcm_channel *c)
181 {
182 	snd_dbuf *b = &c->buffer;
183 	int delta, hwptr;
184 	DEB (int b_rl=b->rl; int b_fl=b->fl; int b_rp=b->rp; int b_fp=b->fp);
185 
186 	hwptr = chn_getptr(c);
187 	if (c->direction == PCMDIR_PLAY) {
188 		delta = (b->bufsize + hwptr - b->rp) % b->bufsize;
189 		b->rp = hwptr;
190 		b->rl -= delta;
191 		b->fl += delta;
192 
193 		if (b->rl < 0) {
194 			DEB(printf("OUCH!(%d) rl %d(%d) delta %d bufsize %d hwptr %d rp %d(%d)\n", chn_updatecount++, b->rl, b_rl, delta, b->bufsize, hwptr, b->rp, b_rp));
195 		}
196 	} else {
197 		delta = (b->bufsize + hwptr - b->fp) % b->bufsize;
198 		b->fp = hwptr;
199 		b->rl += delta;
200 		b->fl -= delta;
201 		if (b->fl < 0) {
202 			DEB(printf("OUCH!(%d) fl %d(%d) delta %d bufsize %d hwptr %d fp %d(%d)\n", chn_updatecount++, b->fl, b_fl, delta, b->bufsize, hwptr, b->fp, b_fp));
203 		}
204 	}
205 	b->total += delta;
206 }
207 
208 /*
209  * Check channel for underflow occured. Reset DMA buffer in case of
210  * underflow, so that new data can go into the buffer. It must be
211  * called at spltty().
212  */
213 void
214 chn_checkunderflow(pcm_channel *c)
215 {
216     	snd_dbuf *b = &c->buffer;
217 
218 	if (b->underflow) {
219 		DEB(printf("Clear underflow condition\n"));
220 		/*
221 		 * The DMA keeps running even after underflow occurs.
222 		 * Hence the value returned by chn_getptr() here soon
223 		 * gets a lag when we get back to chn_write(). Although
224 		 * there are no easy and precise methods to figure out
225 		 * the lag, a quarter of b->bufsize would be a fair
226 		 * choice, provided that a DMA interrupt generates upon
227 		 * each transfer of a half b->bufsize.
228 		 */
229 		b->rp = chn_getptr(c);
230 		b->fp = (b->rp + b->bufsize / 4) % b->bufsize;
231 		b->rl = b->bufsize / 4;
232 		b->fl = b->bufsize - b->rl;
233 	  	b->underflow = 0;
234 	} else {
235 		chn_dmaupdate(c);
236 	}
237 }
238 
239 /*
240  * Feeds new data to the write dma buffer. Can be called in the bottom half.
241  * Hence must be called at spltty.
242  */
243 int
244 chn_wrfeed(pcm_channel *c)
245 {
246     	snd_dbuf *b = &c->buffer;
247     	snd_dbuf *bs = &c->buffer2nd;
248 	int a, l, lacc;
249 
250 	/* ensure we always have a whole number of samples */
251 	a = (1 << c->align) - 1;
252 	lacc = 0;
253     	if (c->flags & CHN_F_MAPPED) {
254 		bs->rl = min(c->blocksize, b->fl);
255 		bs->fl = 0;
256 		a = 0;
257 	}
258 	/*
259 	printf("b: [rl: %d, rp %d, fl %d, fp %d]; bs: [rl: %d, rp %d, fl %d, fp %d]\n",
260 		b->rl, b->rp, b->fl, b->fp, bs->rl, bs->rp, bs->fl, bs->fp);
261 	*/
262 	/* Don't allow write unaligned data */
263 	while (bs->rl > a && b->fl > a) {
264 		/* ensure we always have a whole number of samples */
265 		l = min(min(bs->rl, bs->bufsize - bs->rp), min(b->fl, b->bufsize - b->fp)) & ~a;
266 		if (l == 0)
267 			return lacc;
268 		/* Move the samples, update the markers and pointers. */
269 		bcopy(bs->buf + bs->rp, b->buf + b->fp, l);
270 		bs->fl += l;
271 		bs->rl -= l;
272 		bs->rp = (bs->rp + l) % bs->bufsize;
273 		b->rl += l;
274 		b->fl -= l;
275 		b->fp = (b->fp + l) % b->bufsize;
276 		/* Clear the new space in the secondary buffer. */
277 		buf_clear(bs, c->hwfmt, l);
278 		/* Accumulate the total bytes of the moved samples. */
279 		lacc += l;
280 		/* A feed to the DMA buffer is equivalent to an interrupt. */
281 		bs->total += l;
282     		if (c->flags & CHN_F_MAPPED) {
283 			if (bs->total - bs->prev_total >= c->blocksize2nd) {
284 				bs->prev_total = bs->total;
285 				bs->int_count++;
286 				c->blocks++;
287 			}
288 		} else
289 			bs->int_count++;
290 		if (bs->sel.si_pid && chn_polltrigger(c)) selwakeup(&bs->sel);
291 	}
292 
293 	return lacc;
294 }
295 
296 /* Feeds new data to the secondary write buffer. */
297 static int
298 chn_wrfeed2nd(pcm_channel *c, struct uio *buf)
299 {
300     	snd_dbuf *bs = &c->buffer2nd;
301 	int l, w, wacc;
302 
303 	/* The DMA buffer may have some space. */
304 	while (chn_wrfeed(c) > 0);
305 
306 	/* ensure we always have a whole number of samples */
307 	wacc = 0;
308 	while (buf->uio_resid > 0 && bs->fl > 0) {
309 		/*
310 		 * The size of the data to move here does not have to be
311 		 * aligned. We take care of it upon moving the data to a
312 		 * DMA buffer.
313 		 */
314 		l = min(bs->fl, bs->bufsize - bs->fp);
315 		/* Move the samples, update the markers and pointers. */
316 		w = c->feeder->feed(c->feeder, c, bs->buf + bs->fp, l, buf);
317 		if (w == 0) panic("no feed");
318 		bs->rl += w;
319 		bs->fl -= w;
320 		bs->fp = (bs->fp + w) % bs->bufsize;
321 		/* Accumulate the total bytes of the moved samples. */
322 		bs->total += w;
323 		wacc += w;
324 
325 		/* If any pcm data gets moved, push it to the DMA buffer. */
326 		if (w > 0)
327 			while (chn_wrfeed(c) > 0);
328 	}
329 
330 	return wacc;
331 }
332 
333 /*
334  * Write interrupt routine. Can be called from other places (e.g.
335  * to start a paused transfer), but with interrupts disabled.
336  */
337 static void
338 chn_wrintr(pcm_channel *c)
339 {
340     	snd_dbuf *b = &c->buffer;
341     	int start, l;
342 
343     	if (b->underflow && !(c->flags & CHN_F_MAPPED)) {
344 /*		printf("underflow return\n");
345 */		return; /* nothing new happened */
346 	}
347 	if (b->dl) chn_dmadone(c);
348 
349     	/*
350 	 * start another dma operation only if have ready data in the buffer,
351 	 * there is no pending abort, have a full-duplex device, or have a
352 	 * half duplex device and there is no pending op on the other side.
353 	 *
354 	 * Force transfers to be aligned to a boundary of 4, which is
355 	 * needed when doing stereo and 16-bit.
356 	 */
357 
358 	/*
359 	 * Prepare new space of at least c->blocksize in the DMA
360 	 * buffer for mmap.
361 	 */
362 	/*
363     	if (c->flags & CHN_F_MAPPED && b->fl < c->blocksize) {
364 		dl = c->blocksize - b->fl;
365 		b->fl += dl;
366 		b->rl -= dl;
367 		b->rp = (b->rp + dl) % b->bufsize;
368 		buf_clear(b, c->hwfmt, dl);
369 	}
370 	*/
371 	/* Check underflow and update the pointers. */
372 	chn_checkunderflow(c);
373 
374 	/*
375 	 * Fill up the DMA buffer, followed by waking up the top half.
376 	 * If some of the pcm data in uio are still left, the top half
377 	 * goes to sleep by itself.
378 	 */
379 	if (c->flags & CHN_F_MAPPED)
380 		chn_wrfeed(c);
381 	else {
382 		while (chn_wrfeed(c) > 0);
383 		buf_clear(b, c->hwfmt, b->fl);
384 	}
385 	chn_dmawakeup(c);
386     	if (c->flags & CHN_F_MAPPED)
387 		start = c->flags & CHN_F_TRIGGERED;
388 	else {
389 /*		printf("%d >= %d && !(%x & %x)\n", b->rl, DMA_ALIGN_THRESHOLD, c->flags, CHN_F_ABORTING | CHN_F_CLOSING);
390 */		start = (b->rl >= DMA_ALIGN_THRESHOLD && !(c->flags & CHN_F_ABORTING));
391 	}
392     	if (start & !(c->flags & CHN_F_NOTRIGGER)) {
393 		chn_dmaupdate(c);
394 		if (c->flags & CHN_F_MAPPED) l = c->blocksize;
395 		else l = min(b->rl, c->blocksize) & DMA_ALIGN_MASK;
396 		/*
397 	 	 * check if we need to reprogram the DMA on the sound card.
398 	 	 * This happens if the size has changed from zero
399 	 	 */
400 		if (b->dl == 0) {
401 			/* Start DMA operation */
402 	    		b->dl = c->blocksize; /* record new transfer size */
403 	    		chn_trigger(c, PCMTRIG_START);
404 		}
405  		/*
406  		 * Emulate writing by DMA, i.e. transfer the pcm data from
407  		 * the emulated-DMA buffer to the device itself.
408  		 */
409  		chn_trigger(c, PCMTRIG_EMLDMAWR);
410 		if (b->dl != l) {
411 			DEB(printf("near underflow %d, %d, %d\n", l, b->dl, b->fl));
412 			/*
413 			 * we are near to underflow condition, so to prevent
414 			 * audio 'clicks' clear next b->fl bytes
415 			 */
416 			buf_clear(b, c->hwfmt, b->fl);
417 		}
418     	} else {
419 		/* cannot start a new dma transfer */
420 		DEB(printf("underflow, flags 0x%08x rp %d rl %d\n", c->flags, b->rp, b->rl));
421 		if (b->dl) { /* DMA was active */
422 			b->underflow = 1; /* set underflow flag */
423 			buf_clear(b, c->hwfmt, b->bufsize);
424 		}
425     	}
426 }
427 
428 /*
429  * user write routine
430  *
431  * advance the boundary between READY and FREE, fill the space with
432  * uiomove(), and possibly start DMA. Do the above until the transfer
433  * is complete.
434  *
435  * To minimize latency in case a pending DMA transfer is about to end,
436  * we do the transfer in pieces of increasing sizes, extending the
437  * READY area at every checkpoint. In the (necessary) assumption that
438  * memory bandwidth is larger than the rate at which the dma consumes
439  * data, we reduce the latency to something proportional to the length
440  * of the first piece, while keeping the overhead low and being able
441  * to feed the DMA with large blocks.
442  */
443 
444 int
445 chn_write(pcm_channel *c, struct uio *buf)
446 {
447 	int 		ret = 0, timeout, res, newsize;
448 	long		s;
449 	snd_dbuf       *b = &c->buffer;
450 	snd_dbuf       *bs = &c->buffer2nd;
451 
452 	if (c->flags & CHN_F_WRITING) {
453 		/* This shouldn't happen and is actually silly
454 		 * - will never wake up, just timeout; why not sleep on b?
455 		 */
456 	       	tsleep(&s, PZERO, "pcmwrW", hz);
457 		return EBUSY;
458 	}
459 	c->flags |= CHN_F_WRITING;
460 	c->flags &= ~CHN_F_ABORTING;
461 	s = spltty();
462 
463 	/*
464 	 * XXX Certain applications attempt to write larger size
465 	 * of pcm data than c->blocksize2nd without blocking,
466 	 * resulting partial write. Expand the block size so that
467 	 * the write operation avoids blocking.
468 	 */
469 	if ((c->flags & CHN_F_NBIO) && buf->uio_resid > c->blocksize2nd) {
470 		DEB(printf("pcm warning: broken app, nbio and tried to write %d bytes with fragsz %d\n",
471 			buf->uio_resid, c->blocksize2nd));
472 		newsize = 16;
473 		while (newsize < min(buf->uio_resid, CHN_2NDBUFMAXSIZE / 2))
474 			newsize <<= 1;
475 		chn_setblocksize(c, c->fragments, newsize);
476 		DEB(printf("pcm warning: frags reset to %d x %d\n", c->fragments, c->blocksize2nd));
477 	}
478 
479 	/* Store the initial size in the uio. */
480 	res = buf->uio_resid;
481 
482 	/*
483 	 * Fill up the secondary and DMA buffer.
484 	 * chn_wrfeed*() takes care of the alignment.
485 	 */
486 
487 	/* Check for underflow before writing into the buffers. */
488 	chn_checkunderflow(c);
489   	while (chn_wrfeed2nd(c, buf) > 0);
490    	if (c->flags & CHN_F_NBIO && buf->uio_resid > 0)
491 		ret = EAGAIN;
492 
493 	/* Start playing if not yet. */
494 	if ((bs->rl || b->rl) && !b->dl)
495 		chn_intr(c);
496 
497 	if (ret == 0) {
498 		/* Wait until all samples are played in blocking mode. */
499    		while (buf->uio_resid > 0) {
500 			/* Check for underflow before writing into the buffers. */
501 			chn_checkunderflow(c);
502 			/* Fill up the buffers with new pcm data. */
503   			while (chn_wrfeed2nd(c, buf) > 0);
504 
505 			/* Start playing if necessary. */
506   			if ((bs->rl || b->rl) && !b->dl)
507 				chn_intr(c);
508 
509 			/* Have we finished to feed the secondary buffer? */
510 			if (buf->uio_resid == 0)
511 				break;
512 
513 			/* Wait for new free space to write new pcm samples. */
514 			splx(s);
515 			timeout = 1; /*(buf->uio_resid >= b->dl)? hz / 20 : 1; */
516    			ret = tsleep(b, PRIBIO | PCATCH, "pcmwr", timeout);
517    			s = spltty();
518  			/* if (ret == EINTR) chn_abort(c); */
519  			if (ret == EINTR || ret == ERESTART)
520 				break;
521  		}
522 	} else
523 		ret = 0;
524 	c->flags &= ~CHN_F_WRITING;
525    	splx(s);
526 	return ret;
527 }
528 
529 /*
530  * SOUND INPUT
531  *
532 
533 The input part is similar to the output one, with a circular buffer
534 split in two regions, and boundaries advancing because of read() calls
535 [r] or dma operation [d].  At initialization, as for the write
536 routine, READY is empty, and FREE takes all the space.
537 
538       0          rp,rl        fp,fl    bufsize
539       |__________>____________>________|
540 	  FREE   r   READY    d  FREE
541 
542 Operation is as follows: upon user read (dsp_read_body()) a DMA read
543 is started if not already active (marked by b->dl > 0),
544 then as soon as data are available in the READY region they are
545 transferred to the user buffer, thus advancing the boundary between FREE
546 and READY. Upon interrupts, caused by a completion of a DMA transfer,
547 the READY region is extended and possibly a new transfer is started.
548 
549 When necessary, dsp_rd_dmaupdate() is called to advance fp (and update
550 rl,fl accordingly). Upon user reads, rp is advanced and rl,fl are
551 updated accordingly.
552 
553 The rules to choose the size of the new DMA area are similar to
554 the other case, with a preferred constant transfer size equal to
555 rec_blocksize, and fallback to smaller sizes if no space is available.
556 
557  */
558 
559 /*
560  * Feed new data from the read buffer. Can be called in the bottom half.
561  * Hence must be called at spltty.
562  */
563 int
564 chn_rdfeed(pcm_channel *c)
565 {
566     	snd_dbuf *b = &c->buffer;
567     	snd_dbuf *bs = &c->buffer2nd;
568 	int l, lacc;
569 
570 	/* ensure we always have a whole number of samples */
571 	lacc = 0;
572 	while (bs->fl >= DMA_ALIGN_THRESHOLD && b->rl >= DMA_ALIGN_THRESHOLD) {
573 		l = min(min(bs->fl, bs->bufsize - bs->fp), min(b->rl, b->bufsize - b->rp)) & DMA_ALIGN_MASK;
574 		/* Move the samples, update the markers and pointers. */
575 		bcopy(b->buf + b->rp, bs->buf + bs->fp, l);
576 		bs->fl -= l;
577 		bs->rl += l;
578 		bs->fp = (bs->fp + l) % bs->bufsize;
579 		b->rl -= l;
580 		b->fl += l;
581 		b->rp = (b->rp + l) % b->bufsize;
582 		/* Clear the new space in the DMA buffer. */
583 		buf_clear(b, c->hwfmt, l);
584 		/* Accumulate the total bytes of the moved samples. */
585 		lacc += l;
586 		/* A feed from the DMA buffer is equivalent to an interrupt. */
587 		bs->int_count++;
588 		if (bs->sel.si_pid && chn_polltrigger(c)) selwakeup(&bs->sel);
589 	}
590 
591 	return lacc;
592 }
593 
594 /* Feeds new data from the secondary read buffer. */
595 static int
596 chn_rdfeed2nd(pcm_channel *c, struct uio *buf)
597 {
598     	snd_dbuf *bs = &c->buffer2nd;
599 	int l, w, wacc;
600 
601 	/* The DMA buffer may have pcm data. */
602 	while(chn_rdfeed(c) > 0);
603 
604 	/* ensure we always have a whole number of samples */
605 	wacc = 0;
606 	while (buf->uio_resid > 0 && bs->rl > 0) {
607 		/*
608 		 * The size of the data to move here does not have to be
609 		 * aligned. We take care of it upon moving the data to a
610 		 * DMA buffer.
611 		 */
612 		l = min(bs->rl, bs->bufsize - bs->rp);
613 		/* Move the samples, update the markers and pointers. */
614 		w = c->feeder->feed(c->feeder, c, bs->buf + bs->rp, l, buf);
615 		if (w == 0) panic("no feed");
616 		bs->fl += w;
617 		bs->rl -= w;
618 		bs->rp = (bs->rp + w) % bs->bufsize;
619 		/* Clear the new space in the secondary buffer. */
620 		buf_clear(bs, c->hwfmt, l);
621 		/* Accumulate the total bytes of the moved samples. */
622 		bs->total += w;
623 		wacc += w;
624 
625 		/* If any pcm data gets moved, suck up the DMA buffer. */
626 		if (w > 0)
627 			while (chn_rdfeed(c) > 0);
628 	}
629 
630 	return wacc;
631 }
632 
633 /* read interrupt routine. Must be called with interrupts blocked. */
634 static void
635 chn_rdintr(pcm_channel *c)
636 {
637     	snd_dbuf *b = &c->buffer;
638     	snd_dbuf *bs = &c->buffer2nd;
639     	int start, dl;
640 
641     	if (b->dl) chn_dmadone(c);
642 
643     	DEB(printf("rdintr: start dl %d, rp:rl %d:%d, fp:fl %d:%d\n",
644 		b->dl, b->rp, b->rl, b->fp, b->fl));
645     	/* Restart if have enough free space to absorb overruns */
646 
647 	/*
648 	 * Prepare new space of at least c->blocksize in the secondary
649 	 * buffer for mmap.
650 	 */
651     	if (c->flags & CHN_F_MAPPED && bs->fl < c->blocksize) {
652 		dl = c->blocksize - bs->fl;
653 		bs->fl += dl;
654 		bs->rl -= dl;
655 		bs->rp = (bs->rp + dl) % bs->bufsize;
656 		buf_clear(bs, c->hwfmt, dl);
657 	}
658 
659 	/* Update the pointers. */
660 	chn_dmaupdate(c);
661 
662 	/*
663 	 * Suck up the DMA buffer, followed by waking up the top half.
664 	 * If some of the pcm data in the secondary buffer are still left,
665 	 * the top half goes to sleep by itself.
666 	 */
667 	while(chn_rdfeed(c) > 0);
668 	chn_dmawakeup(c);
669     	if (c->flags & CHN_F_MAPPED)
670 		start = c->flags & CHN_F_TRIGGERED;
671     	else
672 		start = (b->fl > 0x200 && !(c->flags & CHN_F_ABORTING));
673     	if (start) {
674 		int l = min(b->fl - 0x100, c->blocksize);
675 		if (c->flags & CHN_F_MAPPED) l = c->blocksize;
676 		l &= DMA_ALIGN_MASK ; /* realign sizes */
677 
678 		DEB(printf("rdintr: dl %d -> %d\n", b->dl, l);)
679 		if (l != b->dl) {
680 	    		/* size has changed. Stop and restart */
681 	    		if (b->dl) {
682 	    			chn_trigger(c, PCMTRIG_STOP);
683 				chn_dmaupdate(c);
684 				l = min(b->fl - 0x100, c->blocksize);
685 				l &= DMA_ALIGN_MASK ; /* realign sizes */
686 	    		}
687 	    		b->dl = l;
688 	    		chn_trigger(c, PCMTRIG_START);
689 		}
690     	} else {
691 		if (b->dl) { /* was active */
692 	    		b->dl = 0;
693 	    		chn_trigger(c, PCMTRIG_STOP);
694 	    		chn_dmaupdate(c);
695 		}
696     	}
697 }
698 
699 /*
700  * body of user-read routine
701  *
702  * Start DMA if not active; wait for READY not empty.
703  * Transfer data from READY region using uiomove(), advance boundary
704  * between FREE and READY. Repeat until transfer is complete.
705  *
706  * To avoid excessive latency in freeing up space for the DMA
707  * engine, transfers are done in blocks of increasing size, so that
708  * the latency is proportional to the size of the smallest block, but
709  * we have a low overhead and are able to feed the dma engine with
710  * large blocks.
711  *
712  * NOTE: in the current version, read will not return more than
713  * blocksize bytes at once (unless more are already available), to
714  * avoid that requests using very large buffers block for too long.
715  */
716 
717 int
718 chn_read(pcm_channel *c, struct uio *buf)
719 {
720 	int		ret = 0, timeout, limit, res;
721 	long		s;
722 	snd_dbuf       *b = &c->buffer;
723 	snd_dbuf       *bs = &c->buffer2nd;
724 
725 	if (c->flags & CHN_F_READING) {
726 		/* This shouldn't happen and is actually silly */
727 		tsleep(&s, PZERO, "pcmrdR", hz);
728 		return (EBUSY);
729 	}
730 
731   	s = spltty();
732 
733 	/* Store the initial size in the uio. */
734 	res = buf->uio_resid;
735 
736 	c->flags |= CHN_F_READING;
737 	c->flags &= ~CHN_F_ABORTING;
738 	limit = buf->uio_resid - c->blocksize;
739 	if (limit < 0) limit = 0;
740 
741 	/* Update the pointers and suck up the DMA and secondary buffers. */
742 	chn_dmaupdate(c);
743  	while (chn_rdfeed2nd(c, buf) > 0);
744 
745 	/* Start capturing if not yet. */
746   	if ((!bs->rl || !b->rl) && !b->dl) chn_intr(c);
747 
748   	if (!(c->flags & CHN_F_NBIO)) {
749   		/* Wait until all samples are captured. */
750   		while (buf->uio_resid > 0) {
751 			/* Suck up the DMA and secondary buffers. */
752 			chn_dmaupdate(c);
753  			while (chn_rdfeed2nd(c, buf) > 0);
754 
755 			/* Start capturing if necessary. */
756  			if ((!bs->rl || !b->rl) && !b->dl) chn_intr(c);
757 
758 			/* Have we finished to feed the uio? */
759 			if (buf->uio_resid == 0)
760 				break;
761 
762 			/* Wait for new pcm samples. */
763 			splx(s);
764 			timeout = (buf->uio_resid - limit >= b->dl)? hz / 20 : 1;
765   			ret = tsleep(b, PRIBIO | PCATCH, "pcmrd", timeout);
766   			s = spltty();
767 			if (ret == EINTR) chn_abort(c);
768 			if (ret == EINTR || ret == ERESTART) break;
769 		}
770 	} else {
771 		/* If no pcm data was read on nonblocking, return EAGAIN. */
772 		if (buf->uio_resid == res)
773 			ret = EAGAIN;
774 	}
775 	c->flags &= ~CHN_F_READING;
776   	splx(s);
777 	return ret;
778 }
779 
780 void
781 chn_intr(pcm_channel *c)
782 {
783 	if (c->flags & CHN_F_INIT)
784 		chn_reinit(c);
785 	if (c->direction == PCMDIR_PLAY)
786 		chn_wrintr(c);
787 	else
788 		chn_rdintr(c);
789 }
790 
791 static void
792 chn_dma_setmap(void *arg, bus_dma_segment_t *segs, int nseg, int error)
793 {
794 	snd_dbuf *b = (snd_dbuf *)arg;
795 
796 	if (bootverbose) {
797 		printf("pcm: setmap %lx, %lx; ", (unsigned long)segs->ds_addr,
798 		       (unsigned long)segs->ds_len);
799 		printf("%p -> %lx\n", b->buf, (unsigned long)vtophys(b->buf));
800 	}
801 }
802 
803 /*
804  * Allocate memory for DMA buffer. If the device do not perform DMA transfer,
805  * the drvier can call malloc(9) by its own.
806  */
807 int
808 chn_allocbuf(snd_dbuf *b, bus_dma_tag_t parent_dmat)
809 {
810 	if (bus_dmamem_alloc(parent_dmat, (void **)&b->buf,
811 			     BUS_DMA_NOWAIT, &b->dmamap)) return -1;
812 	if (bus_dmamap_load(parent_dmat, b->dmamap, b->buf,
813 			    b->bufsize, chn_dma_setmap, b, 0)) return -1;
814 	return 0;
815 }
816 
817 static void
818 buf_clear(snd_dbuf *b, u_int32_t fmt, int length)
819 {
820 	int i;
821 	u_int16_t data, *p;
822 
823 	/* rely on length & DMA_ALIGN_MASK == 0 */
824 	length &= DMA_ALIGN_MASK;
825 	if (length == 0)
826 		return;
827 
828 	if (fmt & AFMT_SIGNED)
829 		data = 0x00;
830 	else
831 		data = 0x80;
832 
833 	if (fmt & AFMT_16BIT)
834 		data <<= 8;
835 	else
836 		data |= data << 8;
837 
838 	if (fmt & AFMT_BIGENDIAN)
839 		data = ((data >> 8) & 0x00ff) | ((data << 8) & 0xff00);
840 
841 	i = b->fp;
842 	p = (u_int16_t *)(b->buf + b->fp);
843 	while (length > 0) {
844 		*p++ = data;
845 		length -= 2;
846 		i += 2;
847 		if (i >= b->bufsize) {
848 			p = (u_int16_t *)b->buf;
849 			i = 0;
850 		}
851 	}
852 }
853 
854 void
855 chn_resetbuf(pcm_channel *c)
856 {
857 	snd_dbuf *b = &c->buffer;
858 	snd_dbuf *bs = &c->buffer2nd;
859 
860 	c->blocks = 0;
861 	b->sample_size = 1;
862 	b->sample_size <<= (c->hwfmt & AFMT_STEREO)? 1 : 0;
863 	b->sample_size <<= (c->hwfmt & AFMT_16BIT)? 1 : 0;
864 
865 	b->rp = b->fp = 0;
866 	b->dl = b->rl = 0;
867 	b->fl = b->bufsize;
868 	b->prev_total = b->total = 0;
869 	b->prev_int_count = b->int_count = 0;
870 	b->first_poll = 1;
871 	b->underflow = 0;
872 	if (b->buf && b->bufsize > 0)
873 		buf_clear(b, c->hwfmt, b->bufsize);
874 
875 	bs->rp = bs->fp = 0;
876 	bs->dl = bs->rl = 0;
877 	bs->fl = bs->bufsize;
878 	bs->prev_total = bs->total = 0;
879 	b->prev_int_count = b->int_count = 0;
880 	b->first_poll = 1;
881 	b->underflow = 0;
882 	if (bs->buf && bs->bufsize > 0)
883 		buf_clear(bs, c->hwfmt, bs->bufsize);
884 }
885 
886 void
887 buf_isadma(snd_dbuf *b, int go)
888 {
889 	if (ISA_DMA(b)) {
890 		switch (go) {
891 		case PCMTRIG_START:
892 			DEB(printf("buf 0x%p ISA DMA started\n", b));
893 			isa_dmastart(b->dir | ISADMA_RAW, b->buf,
894 					b->bufsize, b->chan);
895 			break;
896 		case PCMTRIG_STOP:
897 		case PCMTRIG_ABORT:
898 			DEB(printf("buf 0x%p ISA DMA stopped\n", b));
899 			isa_dmastop(b->chan);
900 			isa_dmadone(b->dir | ISADMA_RAW, b->buf, b->bufsize,
901 				    b->chan);
902 			break;
903 		}
904     	} else KASSERT(1, ("buf_isadma called on invalid channel"));
905 }
906 
907 int
908 buf_isadmaptr(snd_dbuf *b)
909 {
910 	if (ISA_DMA(b)) {
911 		int i = b->dl? isa_dmastatus(b->chan) : b->bufsize;
912 		if (i < 0) i = 0;
913 		return b->bufsize - i;
914     	} else KASSERT(1, ("buf_isadmaptr called on invalid channel"));
915 	return -1;
916 }
917 
918 /*
919  * chn_sync waits until the space in the given channel goes above
920  * a threshold. The threshold is checked against fl or rl respectively.
921  * Assume that the condition can become true, do not check here...
922  */
923 int
924 chn_sync(pcm_channel *c, int threshold)
925 {
926     	u_long s, rdy;
927     	int ret;
928     	snd_dbuf *b = &c->buffer;
929     	snd_dbuf *bs = &c->buffer2nd;
930 
931     	for (;;) {
932 		s = spltty();
933 		chn_checkunderflow(c);
934 		while (chn_wrfeed(c) > 0);
935 		rdy = (c->direction == PCMDIR_PLAY)? bs->fl : bs->rl;
936 		if (rdy <= threshold) {
937 	    		ret = tsleep((caddr_t)b, PRIBIO | PCATCH, "pcmsyn", 1);
938 	    		splx(s);
939 	    		if (ret == ERESTART || ret == EINTR) {
940 				DEB(printf("chn_sync: tsleep returns %d\n", ret));
941 				return -1;
942 	    		}
943 		} else break;
944     	}
945     	splx(s);
946     	return 0;
947 }
948 
949 int
950 chn_poll(pcm_channel *c, int ev, struct proc *p)
951 {
952 	snd_dbuf *b = &c->buffer;
953 	snd_dbuf *bs = &c->buffer2nd;
954 	u_long s;
955 	int ret;
956 
957 	s = spltty();
958     	if (!(c->flags & CHN_F_MAPPED)) {
959 		if (c->direction == PCMDIR_PLAY) {
960 			/* Fill up the DMA buffer. */
961 			chn_checkunderflow(c);
962 			while (chn_wrfeed(c) > 0);
963 		} else {
964 			/* Suck up the DMA buffer. */
965 			chn_dmaupdate(c);
966 			while (chn_rdfeed(c) > 0);
967 		}
968 		if (!b->dl)
969 			chn_intr(c);
970 	}
971 	ret = 0;
972 	if (chn_polltrigger(c) && chn_pollreset(c))
973 		ret = ev;
974 	else
975 		selrecord(p, &bs->sel);
976 	splx(s);
977 	return ret;
978 }
979 
980 /*
981  * chn_abort is a non-blocking function which aborts a pending
982  * DMA transfer and flushes the buffers.
983  * It returns the number of bytes that have not been transferred.
984  */
985 int
986 chn_abort(pcm_channel *c)
987 {
988     	int missing = 0, cnt = 0;
989     	snd_dbuf *b = &c->buffer;
990     	snd_dbuf *bs = &c->buffer2nd;
991 
992 	if (!b->dl) return 0;
993 	c->flags |= CHN_F_ABORTING;
994 	while (!b->underflow && (b->dl > 0) && (cnt < 20)) {
995 		tsleep((caddr_t)b, PRIBIO, "pcmabr", hz / 20);
996 		cnt++;
997 	}
998 	chn_trigger(c, PCMTRIG_ABORT);
999 	b->dl = 0;
1000 	if (c->direction == PCMDIR_PLAY)
1001 		chn_checkunderflow(c);
1002 	else
1003 		chn_dmaupdate(c);
1004     	missing = bs->rl;
1005     	return missing;
1006 }
1007 
1008 /*
1009  * this routine tries to flush the dma transfer. It is called
1010  * on a close. We immediately abort any read DMA
1011  * operation, and then wait for the play buffer to drain.
1012  */
1013 
1014 int
1015 chn_flush(pcm_channel *c)
1016 {
1017     	int ret, count = 50, s;
1018     	snd_dbuf *b = &c->buffer;
1019 
1020     	DEB(printf("chn_flush c->flags 0x%08x\n", c->flags));
1021     	c->flags |= CHN_F_CLOSING;
1022 	c->flags &= ~CHN_F_TRIGGERED;
1023     	if (c->direction == PCMDIR_REC)
1024 		chn_abort(c);
1025     	else if (b->dl) {
1026 		while ((b->rl > 0) && !b->underflow && (count-- > 0)) {
1027 			/* still pending output data. */
1028 			ret = tsleep((caddr_t)b, PRIBIO | PCATCH, "pcmflu", hz / 10);
1029 			s = spltty();
1030 			chn_dmaupdate(c);
1031 			splx(s);
1032 			DEB(printf("chn_flush: now rl = %d, fl = %d\n", b->rl, b->fl));
1033 			if (ret == EINTR || ret == ERESTART) {
1034 	    			DEB(printf("chn_flush: tsleep returns %d\n", ret));
1035 	    			return ret;
1036 			}
1037     		}
1038 	}
1039 	if (count == 0)
1040 		DEB(printf("chn_flush: timeout flushing dbuf_out, cnt 0x%x flags 0x%x\n", b->rl, c->flags));
1041     	c->flags &= ~CHN_F_CLOSING;
1042     	if (c->direction == PCMDIR_PLAY && b->dl) chn_abort(c);
1043     	return 0;
1044 }
1045 
1046 int
1047 chn_reset(pcm_channel *c, u_int32_t fmt)
1048 {
1049 	int r;
1050 
1051 	chn_abort(c);
1052 	c->flags &= CHN_F_RESET;
1053 	r = chn_setblocksize(c, CHN_2NDBUFBLKNUM, CHN_2NDBUFBLKSIZE);
1054 	if (r)
1055 		return r;
1056 	if (fmt) {
1057 		c->format = fmt;
1058 		c->speed = DSP_DEFAULT_SPEED;
1059 		c->volume = (100 << 8) | 100;
1060 	}
1061 	chn_resetbuf(c);
1062 	c->flags |= CHN_F_INIT;
1063 	return 0;
1064 }
1065 
1066 int
1067 chn_reinit(pcm_channel *c)
1068 {
1069 	if ((c->flags & CHN_F_INIT) && CANCHANGE(c)) {
1070 		chn_setformat(c, c->format);
1071 		chn_setspeed(c, c->speed);
1072 		chn_setvolume(c, (c->volume >> 8) & 0xff, c->volume & 0xff);
1073 		c->flags &= ~CHN_F_INIT;
1074 		return 1;
1075 	}
1076 	return 0;
1077 }
1078 
1079 int
1080 chn_init(pcm_channel *c, void *devinfo, int dir)
1081 {
1082 	snd_dbuf       *bs = &c->buffer2nd;
1083 
1084 	/* Initialize the hardware and DMA buffer first. */
1085 	c->flags = 0;
1086 	c->feeder = &feeder_root;
1087 	c->buffer.chan = -1;
1088 	c->devinfo = c->init(devinfo, &c->buffer, c, dir);
1089 	if (c->devinfo == NULL || c->buffer.bufsize == 0)
1090 		return 1;
1091 	chn_setdir(c, dir);
1092 
1093 	/* And the secondary buffer. */
1094 	bs->buf = NULL;
1095 	bs->bufsize = 0;
1096 	return 0;
1097 }
1098 
1099 int
1100 chn_setdir(pcm_channel *c, int dir)
1101 {
1102 	int r;
1103 
1104 	c->direction = dir;
1105 	r = c->setdir(c->devinfo, c->direction);
1106 	if (!r && ISA_DMA(&c->buffer))
1107 		c->buffer.dir = (dir == PCMDIR_PLAY)? ISADMA_WRITE : ISADMA_READ;
1108 	return r;
1109 }
1110 
1111 int
1112 chn_setvolume(pcm_channel *c, int left, int right)
1113 {
1114 	/* could add a feeder for volume changing if channel returns -1 */
1115 	if (CANCHANGE(c)) {
1116 		return -1;
1117 	}
1118 	c->volume = (left << 8) | right;
1119 	c->flags |= CHN_F_INIT;
1120 	return 0;
1121 }
1122 
1123 int
1124 chn_setspeed(pcm_channel *c, int speed)
1125 {
1126 	/* could add a feeder for rate conversion */
1127 	if (CANCHANGE(c)) {
1128 		c->speed = c->setspeed(c->devinfo, speed);
1129 		return c->speed;
1130 	}
1131 	c->speed = speed;
1132 	c->flags |= CHN_F_INIT;
1133 	return 0;
1134 }
1135 
1136 int
1137 chn_setformat(pcm_channel *c, u_int32_t fmt)
1138 {
1139 	if (CANCHANGE(c)) {
1140 		c->hwfmt = c->format = fmt;
1141 		c->hwfmt = chn_feedchain(c);
1142 		chn_resetbuf(c);
1143 		c->setformat(c->devinfo, c->hwfmt);
1144 		return fmt;
1145 	}
1146 	c->format = fmt;
1147 	c->flags |= CHN_F_INIT;
1148 	return 0;
1149 }
1150 
1151 int
1152 chn_setblocksize(pcm_channel *c, int blkcnt, int blksz)
1153 {
1154 	snd_dbuf *bs = &c->buffer2nd;
1155 	int s, bufsz;
1156 
1157 	if (c->fragments == blkcnt && c->blocksize2nd == blksz)
1158 		return 0;
1159     	if (c->flags & CHN_F_MAPPED) {
1160 		DEB(printf("chn_setblocksize: can't work on mapped channel"));
1161 		return EINVAL;
1162 	}
1163 	c->flags &= ~CHN_F_HAS_SIZE;
1164 	if (blksz >= 2)
1165 		c->flags |= CHN_F_HAS_SIZE;
1166 	/* let us specify blksz without setting CHN_F_HAS_SIZE */
1167 	if (blksz < 0)
1168 		blksz = -blksz;
1169 	/* default to blksz = ~0.25s */
1170 	if (blksz < 16)
1171 		blksz = (c->buffer.sample_size * c->speed) >> 2;
1172 
1173 	if (blkcnt * blksz > CHN_2NDBUFMAXSIZE)
1174 		blkcnt = CHN_2NDBUFMAXSIZE / blksz;
1175 	bufsz = blkcnt * blksz;
1176 
1177 	s = spltty();
1178 	if (bs->buf != NULL)
1179 		free(bs->buf, M_DEVBUF);
1180 	bs->buf = malloc(bufsz, M_DEVBUF, M_WAITOK);
1181 	if (bs->buf == NULL) {
1182       		splx(s);
1183 		DEB(printf("chn_setblocksize: out of memory."));
1184 		return ENOSPC;
1185 	}
1186 	bs->bufsize = bufsz;
1187 	bs->rl = bs->rp = bs->fp = 0;
1188 	bs->fl = bs->bufsize;
1189 	buf_clear(bs, c->hwfmt, bs->bufsize);
1190 	c->fragments = blkcnt;
1191 	c->blocksize2nd = blksz;
1192 	RANGE(blksz, 16, c->buffer.bufsize / 2);
1193 	c->blocksize = c->setblocksize(c->devinfo, blksz);
1194 	splx(s);
1195 
1196 	return 0;
1197 }
1198 
1199 int
1200 chn_trigger(pcm_channel *c, int go)
1201 {
1202 	return c->trigger(c->devinfo, go);
1203 }
1204 
1205 int
1206 chn_getptr(pcm_channel *c)
1207 {
1208 	int hwptr;
1209 	int a = (1 << c->align) - 1;
1210 	snd_dbuf *b = &c->buffer;
1211 
1212 	hwptr = b->dl? c->getptr(c->devinfo) : 0;
1213 	/* don't allow unaligned values in the hwa ptr */
1214 	hwptr &= ~a ; /* Apply channel align mask */
1215 	hwptr &= DMA_ALIGN_MASK; /* Apply DMA align mask */
1216 	return hwptr;
1217 }
1218 
1219 pcmchan_caps *
1220 chn_getcaps(pcm_channel *c)
1221 {
1222 	return c->getcaps(c->devinfo);
1223 }
1224