xref: /linux/sound/drivers/aloop.c (revision 8770bd8f91749dfd05714447dfbd511147cb9576)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Loopback soundcard
4  *
5  *  Original code:
6  *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
7  *
8  *  More accurate positioning and full-duplex support:
9  *  Copyright (c) Ahmet İnan <ainan at mathematik.uni-freiburg.de>
10  *
11  *  Major (almost complete) rewrite:
12  *  Copyright (c) by Takashi Iwai <tiwai@suse.de>
13  *
14  *  A next major update in 2010 (separate timers for playback and capture):
15  *  Copyright (c) Jaroslav Kysela <perex@perex.cz>
16  */
17 
18 #include <linux/init.h>
19 #include <linux/jiffies.h>
20 #include <linux/slab.h>
21 #include <linux/string.h>
22 #include <linux/time.h>
23 #include <linux/wait.h>
24 #include <linux/module.h>
25 #include <linux/platform_device.h>
26 #include <sound/core.h>
27 #include <sound/control.h>
28 #include <sound/pcm.h>
29 #include <sound/pcm_params.h>
30 #include <sound/info.h>
31 #include <sound/initval.h>
32 #include <sound/timer.h>
33 
34 MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
35 MODULE_DESCRIPTION("A loopback soundcard");
36 MODULE_LICENSE("GPL");
37 
38 #define MAX_PCM_SUBSTREAMS	8
39 
40 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;	/* Index 0-MAX */
41 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;	/* ID for this card */
42 static bool enable[SNDRV_CARDS] = {1, [1 ... (SNDRV_CARDS - 1)] = 0};
43 static int pcm_substreams[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 8};
44 static int pcm_notify[SNDRV_CARDS];
45 static char *timer_source[SNDRV_CARDS];
46 
47 module_param_array(index, int, NULL, 0444);
48 MODULE_PARM_DESC(index, "Index value for loopback soundcard.");
49 module_param_array(id, charp, NULL, 0444);
50 MODULE_PARM_DESC(id, "ID string for loopback soundcard.");
51 module_param_array(enable, bool, NULL, 0444);
52 MODULE_PARM_DESC(enable, "Enable this loopback soundcard.");
53 module_param_array(pcm_substreams, int, NULL, 0444);
54 MODULE_PARM_DESC(pcm_substreams, "PCM substreams # (1-8) for loopback driver.");
55 module_param_array(pcm_notify, int, NULL, 0444);
56 MODULE_PARM_DESC(pcm_notify, "Break capture when PCM format/rate/channels changes.");
57 module_param_array(timer_source, charp, NULL, 0444);
58 MODULE_PARM_DESC(timer_source, "Sound card name or number and device/subdevice number of timer to be used. Empty string for jiffies timer [default].");
59 
60 #define NO_PITCH 100000
61 
62 #define CABLE_VALID_PLAYBACK	BIT(SNDRV_PCM_STREAM_PLAYBACK)
63 #define CABLE_VALID_CAPTURE	BIT(SNDRV_PCM_STREAM_CAPTURE)
64 #define CABLE_VALID_BOTH	(CABLE_VALID_PLAYBACK | CABLE_VALID_CAPTURE)
65 
66 struct loopback_cable;
67 struct loopback_pcm;
68 
69 struct loopback_ops {
70 	/* optional
71 	 * call in loopback->cable_lock
72 	 */
73 	int (*open)(struct loopback_pcm *dpcm);
74 	/* required
75 	 * call in cable->lock
76 	 */
77 	int (*start)(struct loopback_pcm *dpcm);
78 	/* required
79 	 * call in cable->lock
80 	 */
81 	int (*stop)(struct loopback_pcm *dpcm);
82 	/* optional */
83 	int (*stop_sync)(struct loopback_pcm *dpcm);
84 	/* optional */
85 	int (*close_substream)(struct loopback_pcm *dpcm);
86 	/* optional
87 	 * call in loopback->cable_lock
88 	 */
89 	int (*close_cable)(struct loopback_pcm *dpcm);
90 	/* optional
91 	 * call in cable->lock
92 	 */
93 	unsigned int (*pos_update)(struct loopback_cable *cable);
94 	/* optional */
95 	void (*dpcm_info)(struct loopback_pcm *dpcm,
96 			  struct snd_info_buffer *buffer);
97 };
98 
99 struct loopback_cable {
100 	spinlock_t lock;
101 	struct loopback_pcm *streams[2];
102 	struct snd_pcm_hardware hw;
103 	/* flags */
104 	unsigned int valid;
105 	unsigned int running;
106 	unsigned int pause;
107 	/* timer specific */
108 	const struct loopback_ops *ops;
109 	/* If sound timer is used */
110 	struct {
111 		int stream;
112 		struct snd_timer_id id;
113 		struct work_struct event_work;
114 		struct snd_timer_instance *instance;
115 	} snd_timer;
116 };
117 
118 struct loopback_setup {
119 	unsigned int notify: 1;
120 	unsigned int rate_shift;
121 	snd_pcm_format_t format;
122 	unsigned int rate;
123 	snd_pcm_access_t access;
124 	unsigned int channels;
125 	struct snd_ctl_elem_id active_id;
126 	struct snd_ctl_elem_id format_id;
127 	struct snd_ctl_elem_id rate_id;
128 	struct snd_ctl_elem_id channels_id;
129 	struct snd_ctl_elem_id access_id;
130 };
131 
132 struct loopback {
133 	struct snd_card *card;
134 	struct mutex cable_lock;
135 	struct loopback_cable *cables[MAX_PCM_SUBSTREAMS][2];
136 	struct snd_pcm *pcm[2];
137 	struct loopback_setup setup[MAX_PCM_SUBSTREAMS][2];
138 	const char *timer_source;
139 };
140 
141 struct loopback_pcm {
142 	struct loopback *loopback;
143 	struct snd_pcm_substream *substream;
144 	struct loopback_cable *cable;
145 	unsigned int pcm_buffer_size;
146 	unsigned int buf_pos;	/* position in buffer */
147 	unsigned int silent_size;
148 	/* PCM parameters */
149 	unsigned int pcm_period_size;
150 	unsigned int pcm_bps;		/* bytes per second */
151 	unsigned int pcm_salign;	/* bytes per sample * channels */
152 	unsigned int pcm_rate_shift;	/* rate shift value */
153 	/* flags */
154 	unsigned int period_update_pending :1;
155 	/* timer stuff */
156 	unsigned int irq_pos;		/* fractional IRQ position in jiffies
157 					 * ticks
158 					 */
159 	unsigned int period_size_frac;	/* period size in jiffies ticks */
160 	unsigned int last_drift;
161 	unsigned long last_jiffies;
162 	/* If jiffies timer is used */
163 	struct timer_list timer;
164 
165 	/* size of per channel buffer in case of non-interleaved access */
166 	unsigned int channel_buf_n;
167 };
168 
169 static struct platform_device *devices[SNDRV_CARDS];
170 
byte_pos(struct loopback_pcm * dpcm,unsigned int x)171 static inline unsigned int byte_pos(struct loopback_pcm *dpcm, unsigned int x)
172 {
173 	if (dpcm->pcm_rate_shift == NO_PITCH) {
174 		x /= HZ;
175 	} else {
176 		x = div_u64(NO_PITCH * (unsigned long long)x,
177 			    HZ * (unsigned long long)dpcm->pcm_rate_shift);
178 	}
179 	return x - (x % dpcm->pcm_salign);
180 }
181 
frac_pos(struct loopback_pcm * dpcm,unsigned int x)182 static inline unsigned int frac_pos(struct loopback_pcm *dpcm, unsigned int x)
183 {
184 	if (dpcm->pcm_rate_shift == NO_PITCH) {	/* no pitch */
185 		return x * HZ;
186 	} else {
187 		x = div_u64(dpcm->pcm_rate_shift * (unsigned long long)x * HZ,
188 			    NO_PITCH);
189 	}
190 	return x;
191 }
192 
get_setup(struct loopback_pcm * dpcm)193 static inline struct loopback_setup *get_setup(struct loopback_pcm *dpcm)
194 {
195 	int device = dpcm->substream->pstr->pcm->device;
196 
197 	if (dpcm->substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
198 		device ^= 1;
199 	return &dpcm->loopback->setup[dpcm->substream->number][device];
200 }
201 
get_notify(struct loopback_pcm * dpcm)202 static inline unsigned int get_notify(struct loopback_pcm *dpcm)
203 {
204 	return get_setup(dpcm)->notify;
205 }
206 
get_rate_shift(struct loopback_pcm * dpcm)207 static inline unsigned int get_rate_shift(struct loopback_pcm *dpcm)
208 {
209 	return get_setup(dpcm)->rate_shift;
210 }
211 
212 /* call in cable->lock */
loopback_jiffies_timer_start(struct loopback_pcm * dpcm)213 static int loopback_jiffies_timer_start(struct loopback_pcm *dpcm)
214 {
215 	unsigned long tick;
216 	unsigned int rate_shift = get_rate_shift(dpcm);
217 
218 	if (rate_shift != dpcm->pcm_rate_shift) {
219 		dpcm->pcm_rate_shift = rate_shift;
220 		dpcm->period_size_frac = frac_pos(dpcm, dpcm->pcm_period_size);
221 	}
222 	if (dpcm->period_size_frac <= dpcm->irq_pos) {
223 		dpcm->irq_pos %= dpcm->period_size_frac;
224 		dpcm->period_update_pending = 1;
225 	}
226 	tick = dpcm->period_size_frac - dpcm->irq_pos;
227 	tick = DIV_ROUND_UP(tick, dpcm->pcm_bps);
228 	mod_timer(&dpcm->timer, jiffies + tick);
229 
230 	return 0;
231 }
232 
233 /* call in cable->lock */
loopback_snd_timer_start(struct loopback_pcm * dpcm)234 static int loopback_snd_timer_start(struct loopback_pcm *dpcm)
235 {
236 	struct loopback_cable *cable = dpcm->cable;
237 	int err;
238 
239 	/* Loopback device has to use same period as timer card. Therefore
240 	 * wake up for each snd_pcm_period_elapsed() call of timer card.
241 	 */
242 	err = snd_timer_start(cable->snd_timer.instance, 1);
243 	if (err < 0) {
244 		/* do not report error if trying to start but already
245 		 * running. For example called by opposite substream
246 		 * of the same cable
247 		 */
248 		if (err == -EBUSY)
249 			return 0;
250 
251 		pcm_err(dpcm->substream->pcm,
252 			"snd_timer_start(%d,%d,%d) failed with %d",
253 			cable->snd_timer.id.card,
254 			cable->snd_timer.id.device,
255 			cable->snd_timer.id.subdevice,
256 			err);
257 	}
258 
259 	return err;
260 }
261 
262 /* call in cable->lock */
loopback_jiffies_timer_stop(struct loopback_pcm * dpcm)263 static inline int loopback_jiffies_timer_stop(struct loopback_pcm *dpcm)
264 {
265 	timer_delete(&dpcm->timer);
266 	dpcm->timer.expires = 0;
267 
268 	return 0;
269 }
270 
271 /* call in cable->lock */
loopback_snd_timer_stop(struct loopback_pcm * dpcm)272 static int loopback_snd_timer_stop(struct loopback_pcm *dpcm)
273 {
274 	struct loopback_cable *cable = dpcm->cable;
275 	int err;
276 
277 	/* only stop if both devices (playback and capture) are not running */
278 	if (cable->running ^ cable->pause)
279 		return 0;
280 
281 	err = snd_timer_stop(cable->snd_timer.instance);
282 	if (err < 0) {
283 		pcm_err(dpcm->substream->pcm,
284 			"snd_timer_stop(%d,%d,%d) failed with %d",
285 			cable->snd_timer.id.card,
286 			cable->snd_timer.id.device,
287 			cable->snd_timer.id.subdevice,
288 			err);
289 	}
290 
291 	return err;
292 }
293 
loopback_jiffies_timer_stop_sync(struct loopback_pcm * dpcm)294 static inline int loopback_jiffies_timer_stop_sync(struct loopback_pcm *dpcm)
295 {
296 	timer_delete_sync(&dpcm->timer);
297 
298 	return 0;
299 }
300 
301 /* call in loopback->cable_lock */
loopback_snd_timer_close_cable(struct loopback_pcm * dpcm)302 static int loopback_snd_timer_close_cable(struct loopback_pcm *dpcm)
303 {
304 	struct loopback_cable *cable = dpcm->cable;
305 
306 	/* snd_timer was not opened */
307 	if (!cable->snd_timer.instance)
308 		return 0;
309 
310 	/* will only be called from free_cable() when other stream was
311 	 * already closed. Other stream cannot be reopened as long as
312 	 * loopback->cable_lock is locked. Therefore no need to lock
313 	 * cable->lock;
314 	 */
315 	snd_timer_close(cable->snd_timer.instance);
316 
317 	/* wait till drain work has finished if requested */
318 	cancel_work_sync(&cable->snd_timer.event_work);
319 
320 	snd_timer_instance_free(cable->snd_timer.instance);
321 	memset(&cable->snd_timer, 0, sizeof(cable->snd_timer));
322 
323 	return 0;
324 }
325 
is_access_interleaved(snd_pcm_access_t access)326 static bool is_access_interleaved(snd_pcm_access_t access)
327 {
328 	switch (access) {
329 	case SNDRV_PCM_ACCESS_MMAP_INTERLEAVED:
330 	case SNDRV_PCM_ACCESS_RW_INTERLEAVED:
331 		return true;
332 	default:
333 		return false;
334 	}
335 };
336 
loopback_check_format(struct loopback_cable * cable,int stream)337 static int loopback_check_format(struct loopback_cable *cable, int stream)
338 {
339 	struct loopback_pcm *dpcm_play, *dpcm_capt;
340 	struct snd_pcm_runtime *runtime, *cruntime;
341 	struct loopback_setup *setup;
342 	struct snd_card *card;
343 	bool stop_capture = false;
344 	int check;
345 
346 	scoped_guard(spinlock_irqsave, &cable->lock) {
347 		dpcm_play = cable->streams[SNDRV_PCM_STREAM_PLAYBACK];
348 		dpcm_capt = cable->streams[SNDRV_PCM_STREAM_CAPTURE];
349 
350 		if (cable->valid != CABLE_VALID_BOTH) {
351 			if (stream == SNDRV_PCM_STREAM_CAPTURE || !dpcm_play)
352 				return 0;
353 		} else {
354 			if (!dpcm_play || !dpcm_capt)
355 				return -EIO;
356 			runtime = dpcm_play->substream->runtime;
357 			cruntime = dpcm_capt->substream->runtime;
358 			if (!runtime || !cruntime)
359 				return -EIO;
360 			check = runtime->format != cruntime->format ||
361 			runtime->rate != cruntime->rate ||
362 			runtime->channels != cruntime->channels ||
363 			is_access_interleaved(runtime->access) !=
364 			is_access_interleaved(cruntime->access);
365 			if (!check)
366 				return 0;
367 			if (stream == SNDRV_PCM_STREAM_CAPTURE)
368 				return -EIO;
369 			else if (cruntime->state == SNDRV_PCM_STATE_RUNNING)
370 				stop_capture = true;
371 		}
372 
373 		setup = get_setup(dpcm_play);
374 		card = dpcm_play->loopback->card;
375 		runtime = dpcm_play->substream->runtime;
376 		if (setup->format != runtime->format) {
377 			snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
378 							&setup->format_id);
379 			setup->format = runtime->format;
380 		}
381 		if (setup->rate != runtime->rate) {
382 			snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
383 							&setup->rate_id);
384 			setup->rate = runtime->rate;
385 		}
386 		if (setup->channels != runtime->channels) {
387 			snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
388 							&setup->channels_id);
389 			setup->channels = runtime->channels;
390 		}
391 		if (is_access_interleaved(setup->access) !=
392 		    is_access_interleaved(runtime->access)) {
393 			snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
394 							&setup->access_id);
395 			setup->access = runtime->access;
396 		}
397 	}
398 
399 	if (stop_capture)
400 		snd_pcm_stop(dpcm_capt->substream, SNDRV_PCM_STATE_DRAINING);
401 
402 	return 0;
403 }
404 
loopback_active_notify(struct loopback_pcm * dpcm)405 static void loopback_active_notify(struct loopback_pcm *dpcm)
406 {
407 	snd_ctl_notify(dpcm->loopback->card,
408 		       SNDRV_CTL_EVENT_MASK_VALUE,
409 		       &get_setup(dpcm)->active_id);
410 }
411 
loopback_trigger(struct snd_pcm_substream * substream,int cmd)412 static int loopback_trigger(struct snd_pcm_substream *substream, int cmd)
413 {
414 	struct snd_pcm_runtime *runtime = substream->runtime;
415 	struct loopback_pcm *dpcm = runtime->private_data;
416 	struct loopback_cable *cable = dpcm->cable;
417 	int err = 0, stream = 1 << substream->stream;
418 
419 	switch (cmd) {
420 	case SNDRV_PCM_TRIGGER_START:
421 		err = loopback_check_format(cable, substream->stream);
422 		if (err < 0)
423 			return err;
424 		dpcm->last_jiffies = jiffies;
425 		dpcm->pcm_rate_shift = 0;
426 		dpcm->last_drift = 0;
427 		scoped_guard(spinlock, &cable->lock) {
428 			cable->running |= stream;
429 			cable->pause &= ~stream;
430 			err = cable->ops->start(dpcm);
431 		}
432 		if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
433 			loopback_active_notify(dpcm);
434 		break;
435 	case SNDRV_PCM_TRIGGER_STOP:
436 		scoped_guard(spinlock, &cable->lock) {
437 			cable->running &= ~stream;
438 			cable->pause &= ~stream;
439 			err = cable->ops->stop(dpcm);
440 		}
441 		if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
442 			loopback_active_notify(dpcm);
443 		break;
444 	case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
445 	case SNDRV_PCM_TRIGGER_SUSPEND:
446 		scoped_guard(spinlock, &cable->lock) {
447 			cable->pause |= stream;
448 			err = cable->ops->stop(dpcm);
449 		}
450 		if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
451 			loopback_active_notify(dpcm);
452 		break;
453 	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
454 	case SNDRV_PCM_TRIGGER_RESUME:
455 		scoped_guard(spinlock, &cable->lock) {
456 			dpcm->last_jiffies = jiffies;
457 			cable->pause &= ~stream;
458 			err = cable->ops->start(dpcm);
459 		}
460 		if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
461 			loopback_active_notify(dpcm);
462 		break;
463 	default:
464 		return -EINVAL;
465 	}
466 	return err;
467 }
468 
params_change(struct snd_pcm_substream * substream)469 static void params_change(struct snd_pcm_substream *substream)
470 {
471 	struct snd_pcm_runtime *runtime = substream->runtime;
472 	struct loopback_pcm *dpcm = runtime->private_data;
473 	struct loopback_cable *cable = dpcm->cable;
474 
475 	cable->hw.formats = pcm_format_to_bits(runtime->format);
476 	cable->hw.rate_min = runtime->rate;
477 	cable->hw.rate_max = runtime->rate;
478 	cable->hw.channels_min = runtime->channels;
479 	cable->hw.channels_max = runtime->channels;
480 
481 	if (cable->snd_timer.instance) {
482 		cable->hw.period_bytes_min =
483 				frames_to_bytes(runtime, runtime->period_size);
484 		cable->hw.period_bytes_max = cable->hw.period_bytes_min;
485 	}
486 
487 }
488 
loopback_prepare(struct snd_pcm_substream * substream)489 static int loopback_prepare(struct snd_pcm_substream *substream)
490 {
491 	struct snd_pcm_runtime *runtime = substream->runtime;
492 	struct loopback_pcm *dpcm = runtime->private_data;
493 	struct loopback_cable *cable = dpcm->cable;
494 	int err, bps, salign;
495 
496 	if (cable->ops->stop_sync) {
497 		err = cable->ops->stop_sync(dpcm);
498 		if (err < 0)
499 			return err;
500 	}
501 
502 	salign = (snd_pcm_format_physical_width(runtime->format) *
503 						runtime->channels) / 8;
504 	bps = salign * runtime->rate;
505 	if (bps <= 0 || salign <= 0)
506 		return -EINVAL;
507 
508 	dpcm->buf_pos = 0;
509 	dpcm->pcm_buffer_size = frames_to_bytes(runtime, runtime->buffer_size);
510 	dpcm->channel_buf_n = dpcm->pcm_buffer_size / runtime->channels;
511 	if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) {
512 		/* clear capture buffer */
513 		dpcm->silent_size = dpcm->pcm_buffer_size;
514 		snd_pcm_format_set_silence(runtime->format, runtime->dma_area,
515 					   runtime->buffer_size * runtime->channels);
516 	}
517 
518 	dpcm->irq_pos = 0;
519 	dpcm->period_update_pending = 0;
520 	dpcm->pcm_bps = bps;
521 	dpcm->pcm_salign = salign;
522 	dpcm->pcm_period_size = frames_to_bytes(runtime, runtime->period_size);
523 
524 	guard(mutex)(&dpcm->loopback->cable_lock);
525 	if (!(cable->valid & ~(1 << substream->stream)) ||
526             (get_setup(dpcm)->notify &&
527 	     substream->stream == SNDRV_PCM_STREAM_PLAYBACK))
528 		params_change(substream);
529 	cable->valid |= 1 << substream->stream;
530 
531 	return 0;
532 }
533 
clear_capture_buf(struct loopback_pcm * dpcm,unsigned int bytes)534 static void clear_capture_buf(struct loopback_pcm *dpcm, unsigned int bytes)
535 {
536 	struct snd_pcm_runtime *runtime = dpcm->substream->runtime;
537 	char *dst = runtime->dma_area;
538 	unsigned int dst_off = dpcm->buf_pos;
539 
540 	if (dpcm->silent_size >= dpcm->pcm_buffer_size)
541 		return;
542 	if (dpcm->silent_size + bytes > dpcm->pcm_buffer_size)
543 		bytes = dpcm->pcm_buffer_size - dpcm->silent_size;
544 
545 	for (;;) {
546 		unsigned int size = bytes;
547 		if (dst_off + size > dpcm->pcm_buffer_size)
548 			size = dpcm->pcm_buffer_size - dst_off;
549 		snd_pcm_format_set_silence(runtime->format, dst + dst_off,
550 					   bytes_to_frames(runtime, size) *
551 					   	runtime->channels);
552 		dpcm->silent_size += size;
553 		bytes -= size;
554 		if (!bytes)
555 			break;
556 		dst_off = 0;
557 	}
558 }
559 
copy_play_buf_part_n(struct loopback_pcm * play,struct loopback_pcm * capt,unsigned int size,unsigned int src_off,unsigned int dst_off)560 static void copy_play_buf_part_n(struct loopback_pcm *play, struct loopback_pcm *capt,
561 				 unsigned int size, unsigned int src_off, unsigned int dst_off)
562 {
563 	unsigned int channels = capt->substream->runtime->channels;
564 	unsigned int size_p_ch = size / channels;
565 	unsigned int src_off_ch = src_off / channels;
566 	unsigned int dst_off_ch = dst_off / channels;
567 	int i;
568 
569 	for (i = 0; i < channels; i++) {
570 		memcpy(capt->substream->runtime->dma_area + capt->channel_buf_n * i + dst_off_ch,
571 		       play->substream->runtime->dma_area + play->channel_buf_n * i + src_off_ch,
572 		       size_p_ch);
573 	}
574 }
575 
copy_play_buf(struct loopback_pcm * play,struct loopback_pcm * capt,unsigned int bytes)576 static void copy_play_buf(struct loopback_pcm *play,
577 			  struct loopback_pcm *capt,
578 			  unsigned int bytes)
579 {
580 	struct snd_pcm_runtime *runtime = play->substream->runtime;
581 	char *src = runtime->dma_area;
582 	char *dst = capt->substream->runtime->dma_area;
583 	unsigned int src_off = play->buf_pos;
584 	unsigned int dst_off = capt->buf_pos;
585 	unsigned int clear_bytes = 0;
586 
587 	/* check if playback is draining, trim the capture copy size
588 	 * when our pointer is at the end of playback ring buffer */
589 	if (runtime->state == SNDRV_PCM_STATE_DRAINING &&
590 	    snd_pcm_playback_hw_avail(runtime) < runtime->buffer_size) {
591 	    	snd_pcm_uframes_t appl_ptr, appl_ptr1, diff;
592 		appl_ptr = appl_ptr1 = runtime->control->appl_ptr;
593 		appl_ptr1 -= appl_ptr1 % runtime->buffer_size;
594 		appl_ptr1 += play->buf_pos / play->pcm_salign;
595 		if (appl_ptr < appl_ptr1)
596 			appl_ptr1 -= runtime->buffer_size;
597 		diff = (appl_ptr - appl_ptr1) * play->pcm_salign;
598 		if (diff < bytes) {
599 			clear_bytes = bytes - diff;
600 			bytes = diff;
601 		}
602 	}
603 
604 	for (;;) {
605 		unsigned int size = bytes;
606 		if (src_off + size > play->pcm_buffer_size)
607 			size = play->pcm_buffer_size - src_off;
608 		if (dst_off + size > capt->pcm_buffer_size)
609 			size = capt->pcm_buffer_size - dst_off;
610 		if (!is_access_interleaved(runtime->access))
611 			copy_play_buf_part_n(play, capt, size, src_off, dst_off);
612 		else
613 			memcpy(dst + dst_off, src + src_off, size);
614 		capt->silent_size = 0;
615 		bytes -= size;
616 		if (!bytes)
617 			break;
618 		src_off = (src_off + size) % play->pcm_buffer_size;
619 		dst_off = (dst_off + size) % capt->pcm_buffer_size;
620 	}
621 
622 	if (clear_bytes > 0) {
623 		clear_capture_buf(capt, clear_bytes);
624 		capt->silent_size = 0;
625 	}
626 }
627 
bytepos_delta(struct loopback_pcm * dpcm,unsigned int jiffies_delta)628 static inline unsigned int bytepos_delta(struct loopback_pcm *dpcm,
629 					 unsigned int jiffies_delta)
630 {
631 	unsigned long last_pos;
632 	unsigned int delta;
633 
634 	last_pos = byte_pos(dpcm, dpcm->irq_pos);
635 	dpcm->irq_pos += jiffies_delta * dpcm->pcm_bps;
636 	delta = byte_pos(dpcm, dpcm->irq_pos) - last_pos;
637 	if (delta >= dpcm->last_drift)
638 		delta -= dpcm->last_drift;
639 	dpcm->last_drift = 0;
640 	if (dpcm->irq_pos >= dpcm->period_size_frac) {
641 		dpcm->irq_pos %= dpcm->period_size_frac;
642 		dpcm->period_update_pending = 1;
643 	}
644 	return delta;
645 }
646 
bytepos_finish(struct loopback_pcm * dpcm,unsigned int delta)647 static inline void bytepos_finish(struct loopback_pcm *dpcm,
648 				  unsigned int delta)
649 {
650 	dpcm->buf_pos += delta;
651 	dpcm->buf_pos %= dpcm->pcm_buffer_size;
652 }
653 
654 /* call in cable->lock */
loopback_jiffies_timer_pos_update(struct loopback_cable * cable)655 static unsigned int loopback_jiffies_timer_pos_update
656 		(struct loopback_cable *cable)
657 {
658 	struct loopback_pcm *dpcm_play =
659 			cable->streams[SNDRV_PCM_STREAM_PLAYBACK];
660 	struct loopback_pcm *dpcm_capt =
661 			cable->streams[SNDRV_PCM_STREAM_CAPTURE];
662 	unsigned long delta_play = 0, delta_capt = 0, cur_jiffies;
663 	unsigned int running, count1, count2;
664 
665 	cur_jiffies = jiffies;
666 	running = cable->running ^ cable->pause;
667 	if (running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) {
668 		delta_play = cur_jiffies - dpcm_play->last_jiffies;
669 		dpcm_play->last_jiffies += delta_play;
670 	}
671 
672 	if (running & (1 << SNDRV_PCM_STREAM_CAPTURE)) {
673 		delta_capt = cur_jiffies - dpcm_capt->last_jiffies;
674 		dpcm_capt->last_jiffies += delta_capt;
675 	}
676 
677 	if (delta_play == 0 && delta_capt == 0)
678 		goto unlock;
679 
680 	if (delta_play > delta_capt) {
681 		count1 = bytepos_delta(dpcm_play, delta_play - delta_capt);
682 		bytepos_finish(dpcm_play, count1);
683 		delta_play = delta_capt;
684 	} else if (delta_play < delta_capt) {
685 		count1 = bytepos_delta(dpcm_capt, delta_capt - delta_play);
686 		clear_capture_buf(dpcm_capt, count1);
687 		bytepos_finish(dpcm_capt, count1);
688 		delta_capt = delta_play;
689 	}
690 
691 	if (delta_play == 0 && delta_capt == 0)
692 		goto unlock;
693 
694 	/* note delta_capt == delta_play at this moment */
695 	count1 = bytepos_delta(dpcm_play, delta_play);
696 	count2 = bytepos_delta(dpcm_capt, delta_capt);
697 	if (count1 < count2) {
698 		dpcm_capt->last_drift = count2 - count1;
699 		count1 = count2;
700 	} else if (count1 > count2) {
701 		dpcm_play->last_drift = count1 - count2;
702 	}
703 	copy_play_buf(dpcm_play, dpcm_capt, count1);
704 	bytepos_finish(dpcm_play, count1);
705 	bytepos_finish(dpcm_capt, count1);
706  unlock:
707 	return running;
708 }
709 
loopback_jiffies_timer_function(struct timer_list * t)710 static void loopback_jiffies_timer_function(struct timer_list *t)
711 {
712 	struct loopback_pcm *dpcm = timer_container_of(dpcm, t, timer);
713 	bool period_elapsed = false;
714 
715 	scoped_guard(spinlock_irqsave, &dpcm->cable->lock) {
716 		if (loopback_jiffies_timer_pos_update(dpcm->cable) &
717 		    (1 << dpcm->substream->stream)) {
718 			loopback_jiffies_timer_start(dpcm);
719 			if (dpcm->period_update_pending) {
720 				dpcm->period_update_pending = 0;
721 				period_elapsed = true;
722 				break;
723 			}
724 		}
725 	}
726 
727 	if (period_elapsed)
728 		snd_pcm_period_elapsed(dpcm->substream);
729 }
730 
731 /* call in cable->lock */
loopback_snd_timer_check_resolution(struct snd_pcm_runtime * runtime,unsigned long resolution)732 static int loopback_snd_timer_check_resolution(struct snd_pcm_runtime *runtime,
733 					       unsigned long resolution)
734 {
735 	if (resolution != runtime->timer_resolution) {
736 		struct loopback_pcm *dpcm = runtime->private_data;
737 		struct loopback_cable *cable = dpcm->cable;
738 		/* Worst case estimation of possible values for resolution
739 		 * resolution <= (512 * 1024) frames / 8kHz in nsec
740 		 * resolution <= 65.536.000.000 nsec
741 		 *
742 		 * period_size <= 65.536.000.000 nsec / 1000nsec/usec * 192kHz +
743 		 *  500.000
744 		 * period_size <= 12.582.912.000.000  <64bit
745 		 *  / 1.000.000 usec/sec
746 		 */
747 		snd_pcm_uframes_t period_size_usec =
748 				resolution / 1000 * runtime->rate;
749 		/* round to nearest sample rate */
750 		snd_pcm_uframes_t period_size =
751 				(period_size_usec + 500 * 1000) / (1000 * 1000);
752 
753 		pcm_err(dpcm->substream->pcm,
754 			"Period size (%lu frames) of loopback device is not corresponding to timer resolution (%lu nsec = %lu frames) of card timer %d,%d,%d. Use period size of %lu frames for loopback device.",
755 			runtime->period_size, resolution, period_size,
756 			cable->snd_timer.id.card,
757 			cable->snd_timer.id.device,
758 			cable->snd_timer.id.subdevice,
759 			period_size);
760 		return -EINVAL;
761 	}
762 	return 0;
763 }
764 
loopback_snd_timer_period_elapsed(struct loopback_cable * cable,int event,unsigned long resolution)765 static void loopback_snd_timer_period_elapsed(struct loopback_cable *cable,
766 					      int event,
767 					      unsigned long resolution)
768 {
769 	struct loopback_pcm *dpcm_play, *dpcm_capt;
770 	struct snd_pcm_substream *substream_play, *substream_capt;
771 	struct snd_pcm_runtime *valid_runtime;
772 	unsigned int running, elapsed_bytes;
773 	bool xrun = false;
774 
775 	scoped_guard(spinlock_irqsave, &cable->lock) {
776 		running = cable->running ^ cable->pause;
777 		/* no need to do anything if no stream is running */
778 		if (!running)
779 			return;
780 
781 		dpcm_play = cable->streams[SNDRV_PCM_STREAM_PLAYBACK];
782 		dpcm_capt = cable->streams[SNDRV_PCM_STREAM_CAPTURE];
783 
784 		if (event == SNDRV_TIMER_EVENT_MSTOP) {
785 			if (!dpcm_play ||
786 			    dpcm_play->substream->runtime->state !=
787 			    SNDRV_PCM_STATE_DRAINING)
788 				return;
789 		}
790 
791 		substream_play = (running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) ?
792 			dpcm_play->substream : NULL;
793 		substream_capt = (running & (1 << SNDRV_PCM_STREAM_CAPTURE)) ?
794 			dpcm_capt->substream : NULL;
795 		valid_runtime = (running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) ?
796 			dpcm_play->substream->runtime :
797 			dpcm_capt->substream->runtime;
798 
799 		/* resolution is only valid for SNDRV_TIMER_EVENT_TICK events */
800 		if (event == SNDRV_TIMER_EVENT_TICK) {
801 			/* The hardware rules guarantee that playback and capture period
802 			 * are the same. Therefore only one device has to be checked
803 			 * here.
804 			 */
805 			if (loopback_snd_timer_check_resolution(valid_runtime,
806 								resolution) < 0) {
807 				xrun = true;
808 				break;
809 			}
810 		}
811 
812 		elapsed_bytes = frames_to_bytes(valid_runtime,
813 						valid_runtime->period_size);
814 		/* The same timer interrupt is used for playback and capture device */
815 		if ((running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) &&
816 		    (running & (1 << SNDRV_PCM_STREAM_CAPTURE))) {
817 			copy_play_buf(dpcm_play, dpcm_capt, elapsed_bytes);
818 			bytepos_finish(dpcm_play, elapsed_bytes);
819 			bytepos_finish(dpcm_capt, elapsed_bytes);
820 		} else if (running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) {
821 			bytepos_finish(dpcm_play, elapsed_bytes);
822 		} else if (running & (1 << SNDRV_PCM_STREAM_CAPTURE)) {
823 			clear_capture_buf(dpcm_capt, elapsed_bytes);
824 			bytepos_finish(dpcm_capt, elapsed_bytes);
825 		}
826 	}
827 
828 	if (xrun) {
829 		if (substream_play)
830 			snd_pcm_stop_xrun(substream_play);
831 		if (substream_capt)
832 			snd_pcm_stop_xrun(substream_capt);
833 		return;
834 	}
835 
836 	if (substream_play)
837 		snd_pcm_period_elapsed(substream_play);
838 	if (substream_capt)
839 		snd_pcm_period_elapsed(substream_capt);
840 }
841 
loopback_snd_timer_function(struct snd_timer_instance * timeri,unsigned long resolution,unsigned long ticks)842 static void loopback_snd_timer_function(struct snd_timer_instance *timeri,
843 					unsigned long resolution,
844 					unsigned long ticks)
845 {
846 	struct loopback_cable *cable = timeri->callback_data;
847 
848 	loopback_snd_timer_period_elapsed(cable, SNDRV_TIMER_EVENT_TICK,
849 					  resolution);
850 }
851 
loopback_snd_timer_work(struct work_struct * work)852 static void loopback_snd_timer_work(struct work_struct *work)
853 {
854 	struct loopback_cable *cable;
855 
856 	cable = container_of(work, struct loopback_cable, snd_timer.event_work);
857 	loopback_snd_timer_period_elapsed(cable, SNDRV_TIMER_EVENT_MSTOP, 0);
858 }
859 
loopback_snd_timer_event(struct snd_timer_instance * timeri,int event,struct timespec64 * tstamp,unsigned long resolution)860 static void loopback_snd_timer_event(struct snd_timer_instance *timeri,
861 				     int event,
862 				     struct timespec64 *tstamp,
863 				     unsigned long resolution)
864 {
865 	/* Do not lock cable->lock here because timer->lock is already hold.
866 	 * There are other functions which first lock cable->lock and than
867 	 * timer->lock e.g.
868 	 * loopback_trigger()
869 	 * spin_lock(&cable->lock)
870 	 * loopback_snd_timer_start()
871 	 * snd_timer_start()
872 	 * spin_lock(&timer->lock)
873 	 * Therefore when using the oposit order of locks here it could result
874 	 * in a deadlock.
875 	 */
876 
877 	if (event == SNDRV_TIMER_EVENT_MSTOP) {
878 		struct loopback_cable *cable = timeri->callback_data;
879 
880 		/* sound card of the timer was stopped. Therefore there will not
881 		 * be any further timer callbacks. Due to this forward audio
882 		 * data from here if in draining state. When still in running
883 		 * state the streaming will be aborted by the usual timeout. It
884 		 * should not be aborted here because may be the timer sound
885 		 * card does only a recovery and the timer is back soon.
886 		 * This work triggers loopback_snd_timer_work()
887 		 */
888 		schedule_work(&cable->snd_timer.event_work);
889 	}
890 }
891 
loopback_jiffies_timer_dpcm_info(struct loopback_pcm * dpcm,struct snd_info_buffer * buffer)892 static void loopback_jiffies_timer_dpcm_info(struct loopback_pcm *dpcm,
893 					     struct snd_info_buffer *buffer)
894 {
895 	snd_iprintf(buffer, "    update_pending:\t%u\n",
896 		    dpcm->period_update_pending);
897 	snd_iprintf(buffer, "    irq_pos:\t\t%u\n", dpcm->irq_pos);
898 	snd_iprintf(buffer, "    period_frac:\t%u\n", dpcm->period_size_frac);
899 	snd_iprintf(buffer, "    last_jiffies:\t%lu (%lu)\n",
900 		    dpcm->last_jiffies, jiffies);
901 	snd_iprintf(buffer, "    timer_expires:\t%lu\n", dpcm->timer.expires);
902 }
903 
loopback_snd_timer_dpcm_info(struct loopback_pcm * dpcm,struct snd_info_buffer * buffer)904 static void loopback_snd_timer_dpcm_info(struct loopback_pcm *dpcm,
905 					 struct snd_info_buffer *buffer)
906 {
907 	struct loopback_cable *cable = dpcm->cable;
908 
909 	snd_iprintf(buffer, "    sound timer:\thw:%d,%d,%d\n",
910 		    cable->snd_timer.id.card,
911 		    cable->snd_timer.id.device,
912 		    cable->snd_timer.id.subdevice);
913 	snd_iprintf(buffer, "    timer open:\t\t%s\n",
914 		    snd_pcm_direction_name(cable->snd_timer.stream));
915 }
916 
loopback_pointer(struct snd_pcm_substream * substream)917 static snd_pcm_uframes_t loopback_pointer(struct snd_pcm_substream *substream)
918 {
919 	struct snd_pcm_runtime *runtime = substream->runtime;
920 	struct loopback_pcm *dpcm = runtime->private_data;
921 	snd_pcm_uframes_t pos;
922 
923 	guard(spinlock)(&dpcm->cable->lock);
924 	if (dpcm->cable->ops->pos_update)
925 		dpcm->cable->ops->pos_update(dpcm->cable);
926 	pos = dpcm->buf_pos;
927 	return bytes_to_frames(runtime, pos);
928 }
929 
930 static const struct snd_pcm_hardware loopback_pcm_hardware =
931 {
932 	.info =		(SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_MMAP |
933 			 SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_PAUSE |
934 			 SNDRV_PCM_INFO_RESUME | SNDRV_PCM_INFO_NONINTERLEAVED),
935 	.formats =	(SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE |
936 			 SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_BE |
937 			 SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S24_3BE |
938 			 SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE |
939 			 SNDRV_PCM_FMTBIT_FLOAT_LE | SNDRV_PCM_FMTBIT_FLOAT_BE |
940 			 SNDRV_PCM_FMTBIT_DSD_U8 |
941 			 SNDRV_PCM_FMTBIT_DSD_U16_LE | SNDRV_PCM_FMTBIT_DSD_U16_BE |
942 			 SNDRV_PCM_FMTBIT_DSD_U32_LE | SNDRV_PCM_FMTBIT_DSD_U32_BE),
943 	.rates =	SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_768000,
944 	.rate_min =		8000,
945 	.rate_max =		768000,
946 	.channels_min =		1,
947 	.channels_max =		32,
948 	.buffer_bytes_max =	2 * 1024 * 1024,
949 	.period_bytes_min =	64,
950 	/* note check overflow in frac_pos() using pcm_rate_shift before
951 	   changing period_bytes_max value */
952 	.period_bytes_max =	1024 * 1024,
953 	.periods_min =		1,
954 	.periods_max =		1024,
955 	.fifo_size =		0,
956 };
957 
loopback_runtime_free(struct snd_pcm_runtime * runtime)958 static void loopback_runtime_free(struct snd_pcm_runtime *runtime)
959 {
960 	struct loopback_pcm *dpcm = runtime->private_data;
961 	kfree(dpcm);
962 }
963 
loopback_hw_free(struct snd_pcm_substream * substream)964 static int loopback_hw_free(struct snd_pcm_substream *substream)
965 {
966 	struct snd_pcm_runtime *runtime = substream->runtime;
967 	struct loopback_pcm *dpcm = runtime->private_data;
968 	struct loopback_cable *cable = dpcm->cable;
969 
970 	guard(mutex)(&dpcm->loopback->cable_lock);
971 	cable->valid &= ~(1 << substream->stream);
972 	return 0;
973 }
974 
get_cable_index(struct snd_pcm_substream * substream)975 static unsigned int get_cable_index(struct snd_pcm_substream *substream)
976 {
977 	if (!substream->pcm->device)
978 		return substream->stream;
979 	else
980 		return !substream->stream;
981 }
982 
rule_format(struct snd_pcm_hw_params * params,struct snd_pcm_hw_rule * rule)983 static int rule_format(struct snd_pcm_hw_params *params,
984 		       struct snd_pcm_hw_rule *rule)
985 {
986 	struct loopback_pcm *dpcm = rule->private;
987 	struct loopback_cable *cable = dpcm->cable;
988 	struct snd_mask m;
989 
990 	snd_mask_none(&m);
991 	scoped_guard(mutex, &dpcm->loopback->cable_lock) {
992 		m.bits[0] = (u_int32_t)cable->hw.formats;
993 		m.bits[1] = (u_int32_t)(cable->hw.formats >> 32);
994 	}
995 	return snd_mask_refine(hw_param_mask(params, rule->var), &m);
996 }
997 
rule_rate(struct snd_pcm_hw_params * params,struct snd_pcm_hw_rule * rule)998 static int rule_rate(struct snd_pcm_hw_params *params,
999 		     struct snd_pcm_hw_rule *rule)
1000 {
1001 	struct loopback_pcm *dpcm = rule->private;
1002 	struct loopback_cable *cable = dpcm->cable;
1003 	struct snd_interval t;
1004 
1005 	scoped_guard(mutex, &dpcm->loopback->cable_lock) {
1006 		t.min = cable->hw.rate_min;
1007 		t.max = cable->hw.rate_max;
1008 	}
1009         t.openmin = t.openmax = 0;
1010         t.integer = 0;
1011 	return snd_interval_refine(hw_param_interval(params, rule->var), &t);
1012 }
1013 
rule_channels(struct snd_pcm_hw_params * params,struct snd_pcm_hw_rule * rule)1014 static int rule_channels(struct snd_pcm_hw_params *params,
1015 			 struct snd_pcm_hw_rule *rule)
1016 {
1017 	struct loopback_pcm *dpcm = rule->private;
1018 	struct loopback_cable *cable = dpcm->cable;
1019 	struct snd_interval t;
1020 
1021 	scoped_guard(mutex, &dpcm->loopback->cable_lock) {
1022 		t.min = cable->hw.channels_min;
1023 		t.max = cable->hw.channels_max;
1024 	}
1025         t.openmin = t.openmax = 0;
1026         t.integer = 0;
1027 	return snd_interval_refine(hw_param_interval(params, rule->var), &t);
1028 }
1029 
rule_period_bytes(struct snd_pcm_hw_params * params,struct snd_pcm_hw_rule * rule)1030 static int rule_period_bytes(struct snd_pcm_hw_params *params,
1031 			     struct snd_pcm_hw_rule *rule)
1032 {
1033 	struct loopback_pcm *dpcm = rule->private;
1034 	struct loopback_cable *cable = dpcm->cable;
1035 	struct snd_interval t;
1036 
1037 	scoped_guard(mutex, &dpcm->loopback->cable_lock) {
1038 		t.min = cable->hw.period_bytes_min;
1039 		t.max = cable->hw.period_bytes_max;
1040 	}
1041 	t.openmin = 0;
1042 	t.openmax = 0;
1043 	t.integer = 0;
1044 	return snd_interval_refine(hw_param_interval(params, rule->var), &t);
1045 }
1046 
free_cable(struct snd_pcm_substream * substream)1047 static void free_cable(struct snd_pcm_substream *substream)
1048 {
1049 	struct loopback *loopback = substream->private_data;
1050 	int dev = get_cable_index(substream);
1051 	struct loopback_cable *cable;
1052 
1053 	cable = loopback->cables[substream->number][dev];
1054 	if (!cable)
1055 		return;
1056 	if (cable->streams[!substream->stream]) {
1057 		/* other stream is still alive */
1058 		guard(spinlock_irq)(&cable->lock);
1059 		cable->streams[substream->stream] = NULL;
1060 	} else {
1061 		struct loopback_pcm *dpcm = substream->runtime->private_data;
1062 
1063 		if (cable->ops && cable->ops->close_cable && dpcm)
1064 			cable->ops->close_cable(dpcm);
1065 		/* free the cable */
1066 		loopback->cables[substream->number][dev] = NULL;
1067 		kfree(cable);
1068 	}
1069 }
1070 
loopback_jiffies_timer_open(struct loopback_pcm * dpcm)1071 static int loopback_jiffies_timer_open(struct loopback_pcm *dpcm)
1072 {
1073 	timer_setup(&dpcm->timer, loopback_jiffies_timer_function, 0);
1074 
1075 	return 0;
1076 }
1077 
1078 static const struct loopback_ops loopback_jiffies_timer_ops = {
1079 	.open = loopback_jiffies_timer_open,
1080 	.start = loopback_jiffies_timer_start,
1081 	.stop = loopback_jiffies_timer_stop,
1082 	.stop_sync = loopback_jiffies_timer_stop_sync,
1083 	.close_substream = loopback_jiffies_timer_stop_sync,
1084 	.pos_update = loopback_jiffies_timer_pos_update,
1085 	.dpcm_info = loopback_jiffies_timer_dpcm_info,
1086 };
1087 
loopback_parse_timer_id(const char * str,struct snd_timer_id * tid)1088 static int loopback_parse_timer_id(const char *str,
1089 				   struct snd_timer_id *tid)
1090 {
1091 	/* [<pref>:](<card name>|<card idx>)[{.,}<dev idx>[{.,}<subdev idx>]] */
1092 	const char * const sep_dev = ".,";
1093 	const char * const sep_pref = ":";
1094 	const char *name = str;
1095 	char *sep, save = '\0';
1096 	int card_idx = 0, dev = 0, subdev = 0;
1097 	int err;
1098 
1099 	sep = strpbrk(str, sep_pref);
1100 	if (sep)
1101 		name = sep + 1;
1102 	sep = strpbrk(name, sep_dev);
1103 	if (sep) {
1104 		save = *sep;
1105 		*sep = '\0';
1106 	}
1107 	err = kstrtoint(name, 0, &card_idx);
1108 	if (err == -EINVAL) {
1109 		/* Must be the name, not number */
1110 		for (card_idx = 0; card_idx < snd_ecards_limit; card_idx++) {
1111 			struct snd_card *card = snd_card_ref(card_idx);
1112 
1113 			if (card) {
1114 				if (!strcmp(card->id, name))
1115 					err = 0;
1116 				snd_card_unref(card);
1117 			}
1118 			if (!err)
1119 				break;
1120 		}
1121 	}
1122 	if (sep) {
1123 		*sep = save;
1124 		if (!err) {
1125 			char *sep2, save2 = '\0';
1126 
1127 			sep2 = strpbrk(sep + 1, sep_dev);
1128 			if (sep2) {
1129 				save2 = *sep2;
1130 				*sep2 = '\0';
1131 			}
1132 			err = kstrtoint(sep + 1, 0, &dev);
1133 			if (sep2) {
1134 				*sep2 = save2;
1135 				if (!err)
1136 					err = kstrtoint(sep2 + 1, 0, &subdev);
1137 			}
1138 		}
1139 	}
1140 	if (card_idx == -1)
1141 		tid->dev_class = SNDRV_TIMER_CLASS_GLOBAL;
1142 	if (!err && tid) {
1143 		tid->card = card_idx;
1144 		tid->device = dev;
1145 		tid->subdevice = subdev;
1146 	}
1147 	return err;
1148 }
1149 
1150 /* call in loopback->cable_lock */
loopback_snd_timer_open(struct loopback_pcm * dpcm)1151 static int loopback_snd_timer_open(struct loopback_pcm *dpcm)
1152 {
1153 	int err = 0;
1154 	struct snd_timer_id tid = {
1155 		.dev_class = SNDRV_TIMER_CLASS_PCM,
1156 		.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION,
1157 	};
1158 	struct snd_timer_instance *timeri;
1159 	struct loopback_cable *cable = dpcm->cable;
1160 
1161 	/* check if timer was already opened. It is only opened once
1162 	 * per playback and capture subdevice (aka cable).
1163 	 */
1164 	if (cable->snd_timer.instance)
1165 		goto exit;
1166 
1167 	err = loopback_parse_timer_id(dpcm->loopback->timer_source, &tid);
1168 	if (err < 0) {
1169 		pcm_err(dpcm->substream->pcm,
1170 			"Parsing timer source \'%s\' failed with %d",
1171 			dpcm->loopback->timer_source, err);
1172 		goto exit;
1173 	}
1174 
1175 	cable->snd_timer.stream = dpcm->substream->stream;
1176 	cable->snd_timer.id = tid;
1177 
1178 	timeri = snd_timer_instance_new(dpcm->loopback->card->id);
1179 	if (!timeri) {
1180 		err = -ENOMEM;
1181 		goto exit;
1182 	}
1183 	/* The callback has to be called from another work. If
1184 	 * SNDRV_TIMER_IFLG_FAST is specified it will be called from the
1185 	 * snd_pcm_period_elapsed() call of the selected sound card.
1186 	 * snd_pcm_period_elapsed() helds snd_pcm_stream_lock_irqsave().
1187 	 * Due to our callback loopback_snd_timer_function() also calls
1188 	 * snd_pcm_period_elapsed() which calls snd_pcm_stream_lock_irqsave().
1189 	 * This would end up in a dead lock.
1190 	 */
1191 	timeri->flags |= SNDRV_TIMER_IFLG_AUTO;
1192 	timeri->callback = loopback_snd_timer_function;
1193 	timeri->callback_data = (void *)cable;
1194 	timeri->ccallback = loopback_snd_timer_event;
1195 
1196 	/* initialise a work used for draining */
1197 	INIT_WORK(&cable->snd_timer.event_work, loopback_snd_timer_work);
1198 
1199 	/* The mutex loopback->cable_lock is kept locked.
1200 	 * Therefore snd_timer_open() cannot be called a second time
1201 	 * by the other device of the same cable.
1202 	 * Therefore the following issue cannot happen:
1203 	 * [proc1] Call loopback_timer_open() ->
1204 	 *	   Unlock cable->lock for snd_timer_close/open() call
1205 	 * [proc2] Call loopback_timer_open() -> snd_timer_open(),
1206 	 *	   snd_timer_start()
1207 	 * [proc1] Call snd_timer_open() and overwrite running timer
1208 	 *	   instance
1209 	 */
1210 	err = snd_timer_open(timeri, &cable->snd_timer.id, current->pid);
1211 	if (err < 0) {
1212 		pcm_err(dpcm->substream->pcm,
1213 			"snd_timer_open (%d,%d,%d) failed with %d",
1214 			cable->snd_timer.id.card,
1215 			cable->snd_timer.id.device,
1216 			cable->snd_timer.id.subdevice,
1217 			err);
1218 		snd_timer_instance_free(timeri);
1219 		goto exit;
1220 	}
1221 
1222 	cable->snd_timer.instance = timeri;
1223 
1224 exit:
1225 	return err;
1226 }
1227 
1228 /* stop_sync() is not required for sound timer because it does not need to be
1229  * restarted in loopback_prepare() on Xrun recovery
1230  */
1231 static const struct loopback_ops loopback_snd_timer_ops = {
1232 	.open = loopback_snd_timer_open,
1233 	.start = loopback_snd_timer_start,
1234 	.stop = loopback_snd_timer_stop,
1235 	.close_cable = loopback_snd_timer_close_cable,
1236 	.dpcm_info = loopback_snd_timer_dpcm_info,
1237 };
1238 
loopback_open(struct snd_pcm_substream * substream)1239 static int loopback_open(struct snd_pcm_substream *substream)
1240 {
1241 	struct snd_pcm_runtime *runtime = substream->runtime;
1242 	struct loopback *loopback = substream->private_data;
1243 	struct loopback_pcm *dpcm;
1244 	struct loopback_cable *cable = NULL;
1245 	int err = 0;
1246 	int dev = get_cable_index(substream);
1247 
1248 	guard(mutex)(&loopback->cable_lock);
1249 	dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
1250 	if (!dpcm)
1251 		return -ENOMEM;
1252 	dpcm->loopback = loopback;
1253 	dpcm->substream = substream;
1254 
1255 	cable = loopback->cables[substream->number][dev];
1256 	if (!cable) {
1257 		cable = kzalloc(sizeof(*cable), GFP_KERNEL);
1258 		if (!cable) {
1259 			err = -ENOMEM;
1260 			goto unlock;
1261 		}
1262 		spin_lock_init(&cable->lock);
1263 		cable->hw = loopback_pcm_hardware;
1264 		if (loopback->timer_source)
1265 			cable->ops = &loopback_snd_timer_ops;
1266 		else
1267 			cable->ops = &loopback_jiffies_timer_ops;
1268 		loopback->cables[substream->number][dev] = cable;
1269 	}
1270 	dpcm->cable = cable;
1271 	runtime->private_data = dpcm;
1272 
1273 	if (cable->ops->open) {
1274 		err = cable->ops->open(dpcm);
1275 		if (err < 0)
1276 			goto unlock;
1277 	}
1278 
1279 	snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
1280 
1281 	/* use dynamic rules based on actual runtime->hw values */
1282 	/* note that the default rules created in the PCM midlevel code */
1283 	/* are cached -> they do not reflect the actual state */
1284 	err = snd_pcm_hw_rule_add(runtime, 0,
1285 				  SNDRV_PCM_HW_PARAM_FORMAT,
1286 				  rule_format, dpcm,
1287 				  SNDRV_PCM_HW_PARAM_FORMAT, -1);
1288 	if (err < 0)
1289 		goto unlock;
1290 	err = snd_pcm_hw_rule_add(runtime, 0,
1291 				  SNDRV_PCM_HW_PARAM_RATE,
1292 				  rule_rate, dpcm,
1293 				  SNDRV_PCM_HW_PARAM_RATE, -1);
1294 	if (err < 0)
1295 		goto unlock;
1296 	err = snd_pcm_hw_rule_add(runtime, 0,
1297 				  SNDRV_PCM_HW_PARAM_CHANNELS,
1298 				  rule_channels, dpcm,
1299 				  SNDRV_PCM_HW_PARAM_CHANNELS, -1);
1300 	if (err < 0)
1301 		goto unlock;
1302 
1303 	/* In case of sound timer the period time of both devices of the same
1304 	 * loop has to be the same.
1305 	 * This rule only takes effect if a sound timer was chosen
1306 	 */
1307 	if (cable->snd_timer.instance) {
1308 		err = snd_pcm_hw_rule_add(runtime, 0,
1309 					  SNDRV_PCM_HW_PARAM_PERIOD_BYTES,
1310 					  rule_period_bytes, dpcm,
1311 					  SNDRV_PCM_HW_PARAM_PERIOD_BYTES, -1);
1312 		if (err < 0)
1313 			goto unlock;
1314 	}
1315 
1316 	/* loopback_runtime_free() has not to be called if kfree(dpcm) was
1317 	 * already called here. Otherwise it will end up with a double free.
1318 	 */
1319 	runtime->private_free = loopback_runtime_free;
1320 	if (get_notify(dpcm))
1321 		runtime->hw = loopback_pcm_hardware;
1322 	else
1323 		runtime->hw = cable->hw;
1324 
1325 	scoped_guard(spinlock_irq, &cable->lock) {
1326 		cable->streams[substream->stream] = dpcm;
1327 	}
1328 
1329  unlock:
1330 	if (err < 0) {
1331 		free_cable(substream);
1332 		kfree(dpcm);
1333 	}
1334 	return err;
1335 }
1336 
loopback_close(struct snd_pcm_substream * substream)1337 static int loopback_close(struct snd_pcm_substream *substream)
1338 {
1339 	struct loopback *loopback = substream->private_data;
1340 	struct loopback_pcm *dpcm = substream->runtime->private_data;
1341 	int err = 0;
1342 
1343 	if (dpcm->cable->ops->close_substream)
1344 		err = dpcm->cable->ops->close_substream(dpcm);
1345 	guard(mutex)(&loopback->cable_lock);
1346 	free_cable(substream);
1347 	return err;
1348 }
1349 
1350 static const struct snd_pcm_ops loopback_pcm_ops = {
1351 	.open =		loopback_open,
1352 	.close =	loopback_close,
1353 	.hw_free =	loopback_hw_free,
1354 	.prepare =	loopback_prepare,
1355 	.trigger =	loopback_trigger,
1356 	.pointer =	loopback_pointer,
1357 };
1358 
loopback_pcm_new(struct loopback * loopback,int device,int substreams)1359 static int loopback_pcm_new(struct loopback *loopback,
1360 			    int device, int substreams)
1361 {
1362 	struct snd_pcm *pcm;
1363 	int err;
1364 
1365 	err = snd_pcm_new(loopback->card, "Loopback PCM", device,
1366 			  substreams, substreams, &pcm);
1367 	if (err < 0)
1368 		return err;
1369 	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &loopback_pcm_ops);
1370 	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &loopback_pcm_ops);
1371 	snd_pcm_set_managed_buffer_all(pcm, SNDRV_DMA_TYPE_VMALLOC, NULL, 0, 0);
1372 
1373 	pcm->private_data = loopback;
1374 	pcm->info_flags = 0;
1375 	strscpy(pcm->name, "Loopback PCM");
1376 
1377 	loopback->pcm[device] = pcm;
1378 	return 0;
1379 }
1380 
loopback_rate_shift_info(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_info * uinfo)1381 static int loopback_rate_shift_info(struct snd_kcontrol *kcontrol,
1382 				    struct snd_ctl_elem_info *uinfo)
1383 {
1384 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1385 	uinfo->count = 1;
1386 	uinfo->value.integer.min = 80000;
1387 	uinfo->value.integer.max = 120000;
1388 	uinfo->value.integer.step = 1;
1389 	return 0;
1390 }
1391 
loopback_rate_shift_get(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_value * ucontrol)1392 static int loopback_rate_shift_get(struct snd_kcontrol *kcontrol,
1393 				   struct snd_ctl_elem_value *ucontrol)
1394 {
1395 	struct loopback *loopback = snd_kcontrol_chip(kcontrol);
1396 
1397 	guard(mutex)(&loopback->cable_lock);
1398 	ucontrol->value.integer.value[0] =
1399 		loopback->setup[kcontrol->id.subdevice]
1400 			       [kcontrol->id.device].rate_shift;
1401 	return 0;
1402 }
1403 
loopback_rate_shift_put(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_value * ucontrol)1404 static int loopback_rate_shift_put(struct snd_kcontrol *kcontrol,
1405 				   struct snd_ctl_elem_value *ucontrol)
1406 {
1407 	struct loopback *loopback = snd_kcontrol_chip(kcontrol);
1408 	unsigned int val;
1409 	int change = 0;
1410 
1411 	val = ucontrol->value.integer.value[0];
1412 	if (val < 80000)
1413 		val = 80000;
1414 	if (val > 120000)
1415 		val = 120000;
1416 	guard(mutex)(&loopback->cable_lock);
1417 	if (val != loopback->setup[kcontrol->id.subdevice]
1418 				  [kcontrol->id.device].rate_shift) {
1419 		loopback->setup[kcontrol->id.subdevice]
1420 			       [kcontrol->id.device].rate_shift = val;
1421 		change = 1;
1422 	}
1423 	return change;
1424 }
1425 
loopback_notify_get(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_value * ucontrol)1426 static int loopback_notify_get(struct snd_kcontrol *kcontrol,
1427 			       struct snd_ctl_elem_value *ucontrol)
1428 {
1429 	struct loopback *loopback = snd_kcontrol_chip(kcontrol);
1430 
1431 	guard(mutex)(&loopback->cable_lock);
1432 	ucontrol->value.integer.value[0] =
1433 		loopback->setup[kcontrol->id.subdevice]
1434 			       [kcontrol->id.device].notify;
1435 	return 0;
1436 }
1437 
loopback_notify_put(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_value * ucontrol)1438 static int loopback_notify_put(struct snd_kcontrol *kcontrol,
1439 			       struct snd_ctl_elem_value *ucontrol)
1440 {
1441 	struct loopback *loopback = snd_kcontrol_chip(kcontrol);
1442 	unsigned int val;
1443 	int change = 0;
1444 
1445 	val = ucontrol->value.integer.value[0] ? 1 : 0;
1446 	guard(mutex)(&loopback->cable_lock);
1447 	if (val != loopback->setup[kcontrol->id.subdevice]
1448 				[kcontrol->id.device].notify) {
1449 		loopback->setup[kcontrol->id.subdevice]
1450 			[kcontrol->id.device].notify = val;
1451 		change = 1;
1452 	}
1453 	return change;
1454 }
1455 
loopback_active_get(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_value * ucontrol)1456 static int loopback_active_get(struct snd_kcontrol *kcontrol,
1457 			       struct snd_ctl_elem_value *ucontrol)
1458 {
1459 	struct loopback *loopback = snd_kcontrol_chip(kcontrol);
1460 	struct loopback_cable *cable;
1461 
1462 	unsigned int val = 0;
1463 
1464 	guard(mutex)(&loopback->cable_lock);
1465 	cable = loopback->cables[kcontrol->id.subdevice][kcontrol->id.device ^ 1];
1466 	if (cable != NULL) {
1467 		unsigned int running = cable->running ^ cable->pause;
1468 
1469 		val = (running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) ? 1 : 0;
1470 	}
1471 	ucontrol->value.integer.value[0] = val;
1472 	return 0;
1473 }
1474 
loopback_format_info(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_info * uinfo)1475 static int loopback_format_info(struct snd_kcontrol *kcontrol,
1476 				struct snd_ctl_elem_info *uinfo)
1477 {
1478 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1479 	uinfo->count = 1;
1480 	uinfo->value.integer.min = 0;
1481 	uinfo->value.integer.max = (__force int)SNDRV_PCM_FORMAT_LAST;
1482 	uinfo->value.integer.step = 1;
1483 	return 0;
1484 }
1485 
loopback_format_get(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_value * ucontrol)1486 static int loopback_format_get(struct snd_kcontrol *kcontrol,
1487 			       struct snd_ctl_elem_value *ucontrol)
1488 {
1489 	struct loopback *loopback = snd_kcontrol_chip(kcontrol);
1490 
1491 	ucontrol->value.integer.value[0] =
1492 		(__force int)loopback->setup[kcontrol->id.subdevice]
1493 			       [kcontrol->id.device].format;
1494 	return 0;
1495 }
1496 
loopback_rate_info(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_info * uinfo)1497 static int loopback_rate_info(struct snd_kcontrol *kcontrol,
1498 			      struct snd_ctl_elem_info *uinfo)
1499 {
1500 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1501 	uinfo->count = 1;
1502 	uinfo->value.integer.min = 0;
1503 	uinfo->value.integer.max = 192000;
1504 	uinfo->value.integer.step = 1;
1505 	return 0;
1506 }
1507 
loopback_rate_get(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_value * ucontrol)1508 static int loopback_rate_get(struct snd_kcontrol *kcontrol,
1509 			     struct snd_ctl_elem_value *ucontrol)
1510 {
1511 	struct loopback *loopback = snd_kcontrol_chip(kcontrol);
1512 
1513 	guard(mutex)(&loopback->cable_lock);
1514 	ucontrol->value.integer.value[0] =
1515 		loopback->setup[kcontrol->id.subdevice]
1516 			       [kcontrol->id.device].rate;
1517 	return 0;
1518 }
1519 
loopback_channels_info(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_info * uinfo)1520 static int loopback_channels_info(struct snd_kcontrol *kcontrol,
1521 				  struct snd_ctl_elem_info *uinfo)
1522 {
1523 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1524 	uinfo->count = 1;
1525 	uinfo->value.integer.min = 1;
1526 	uinfo->value.integer.max = 1024;
1527 	uinfo->value.integer.step = 1;
1528 	return 0;
1529 }
1530 
loopback_channels_get(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_value * ucontrol)1531 static int loopback_channels_get(struct snd_kcontrol *kcontrol,
1532 				 struct snd_ctl_elem_value *ucontrol)
1533 {
1534 	struct loopback *loopback = snd_kcontrol_chip(kcontrol);
1535 
1536 	guard(mutex)(&loopback->cable_lock);
1537 	ucontrol->value.integer.value[0] =
1538 		loopback->setup[kcontrol->id.subdevice]
1539 			       [kcontrol->id.device].channels;
1540 	return 0;
1541 }
1542 
loopback_access_info(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_info * uinfo)1543 static int loopback_access_info(struct snd_kcontrol *kcontrol,
1544 				struct snd_ctl_elem_info *uinfo)
1545 {
1546 	const char * const texts[] = {"Interleaved", "Non-interleaved"};
1547 
1548 	return snd_ctl_enum_info(uinfo, 1, ARRAY_SIZE(texts), texts);
1549 }
1550 
loopback_access_get(struct snd_kcontrol * kcontrol,struct snd_ctl_elem_value * ucontrol)1551 static int loopback_access_get(struct snd_kcontrol *kcontrol,
1552 			       struct snd_ctl_elem_value *ucontrol)
1553 {
1554 	struct loopback *loopback = snd_kcontrol_chip(kcontrol);
1555 	snd_pcm_access_t access;
1556 
1557 	guard(mutex)(&loopback->cable_lock);
1558 	access = loopback->setup[kcontrol->id.subdevice][kcontrol->id.device].access;
1559 
1560 	ucontrol->value.enumerated.item[0] = !is_access_interleaved(access);
1561 
1562 	return 0;
1563 }
1564 
1565 static const struct snd_kcontrol_new loopback_controls[]  = {
1566 {
1567 	.iface =        SNDRV_CTL_ELEM_IFACE_PCM,
1568 	.name =         "PCM Rate Shift 100000",
1569 	.info =         loopback_rate_shift_info,
1570 	.get =          loopback_rate_shift_get,
1571 	.put =          loopback_rate_shift_put,
1572 },
1573 {
1574 	.iface =        SNDRV_CTL_ELEM_IFACE_PCM,
1575 	.name =         "PCM Notify",
1576 	.info =         snd_ctl_boolean_mono_info,
1577 	.get =          loopback_notify_get,
1578 	.put =          loopback_notify_put,
1579 },
1580 #define ACTIVE_IDX 2
1581 {
1582 	.access =	SNDRV_CTL_ELEM_ACCESS_READ,
1583 	.iface =        SNDRV_CTL_ELEM_IFACE_PCM,
1584 	.name =         "PCM Slave Active",
1585 	.info =         snd_ctl_boolean_mono_info,
1586 	.get =          loopback_active_get,
1587 },
1588 #define FORMAT_IDX 3
1589 {
1590 	.access =	SNDRV_CTL_ELEM_ACCESS_READ,
1591 	.iface =        SNDRV_CTL_ELEM_IFACE_PCM,
1592 	.name =         "PCM Slave Format",
1593 	.info =         loopback_format_info,
1594 	.get =          loopback_format_get
1595 },
1596 #define RATE_IDX 4
1597 {
1598 	.access =	SNDRV_CTL_ELEM_ACCESS_READ,
1599 	.iface =        SNDRV_CTL_ELEM_IFACE_PCM,
1600 	.name =         "PCM Slave Rate",
1601 	.info =         loopback_rate_info,
1602 	.get =          loopback_rate_get
1603 },
1604 #define CHANNELS_IDX 5
1605 {
1606 	.access =	SNDRV_CTL_ELEM_ACCESS_READ,
1607 	.iface =        SNDRV_CTL_ELEM_IFACE_PCM,
1608 	.name =         "PCM Slave Channels",
1609 	.info =         loopback_channels_info,
1610 	.get =          loopback_channels_get
1611 },
1612 #define ACCESS_IDX 6
1613 {
1614 	.access =	SNDRV_CTL_ELEM_ACCESS_READ,
1615 	.iface =	SNDRV_CTL_ELEM_IFACE_PCM,
1616 	.name =		"PCM Slave Access Mode",
1617 	.info =		loopback_access_info,
1618 	.get =		loopback_access_get,
1619 },
1620 };
1621 
loopback_mixer_new(struct loopback * loopback,int notify)1622 static int loopback_mixer_new(struct loopback *loopback, int notify)
1623 {
1624 	struct snd_card *card = loopback->card;
1625 	struct snd_pcm *pcm;
1626 	struct snd_kcontrol *kctl;
1627 	struct loopback_setup *setup;
1628 	int err, dev, substr, substr_count, idx;
1629 
1630 	strscpy(card->mixername, "Loopback Mixer");
1631 	for (dev = 0; dev < 2; dev++) {
1632 		pcm = loopback->pcm[dev];
1633 		substr_count =
1634 		    pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream_count;
1635 		for (substr = 0; substr < substr_count; substr++) {
1636 			setup = &loopback->setup[substr][dev];
1637 			setup->notify = notify;
1638 			setup->rate_shift = NO_PITCH;
1639 			setup->format = SNDRV_PCM_FORMAT_S16_LE;
1640 			setup->access = SNDRV_PCM_ACCESS_RW_INTERLEAVED;
1641 			setup->rate = 48000;
1642 			setup->channels = 2;
1643 			for (idx = 0; idx < ARRAY_SIZE(loopback_controls);
1644 									idx++) {
1645 				kctl = snd_ctl_new1(&loopback_controls[idx],
1646 						    loopback);
1647 				if (!kctl)
1648 					return -ENOMEM;
1649 				kctl->id.device = dev;
1650 				kctl->id.subdevice = substr;
1651 
1652 				/* Add the control before copying the id so that
1653 				 * the numid field of the id is set in the copy.
1654 				 */
1655 				err = snd_ctl_add(card, kctl);
1656 				if (err < 0)
1657 					return err;
1658 
1659 				switch (idx) {
1660 				case ACTIVE_IDX:
1661 					setup->active_id = kctl->id;
1662 					break;
1663 				case FORMAT_IDX:
1664 					setup->format_id = kctl->id;
1665 					break;
1666 				case RATE_IDX:
1667 					setup->rate_id = kctl->id;
1668 					break;
1669 				case CHANNELS_IDX:
1670 					setup->channels_id = kctl->id;
1671 					break;
1672 				case ACCESS_IDX:
1673 					setup->access_id = kctl->id;
1674 					break;
1675 				default:
1676 					break;
1677 				}
1678 			}
1679 		}
1680 	}
1681 	return 0;
1682 }
1683 
print_dpcm_info(struct snd_info_buffer * buffer,struct loopback_pcm * dpcm,const char * id)1684 static void print_dpcm_info(struct snd_info_buffer *buffer,
1685 			    struct loopback_pcm *dpcm,
1686 			    const char *id)
1687 {
1688 	snd_iprintf(buffer, "  %s\n", id);
1689 	if (dpcm == NULL) {
1690 		snd_iprintf(buffer, "    inactive\n");
1691 		return;
1692 	}
1693 	snd_iprintf(buffer, "    buffer_size:\t%u\n", dpcm->pcm_buffer_size);
1694 	snd_iprintf(buffer, "    buffer_pos:\t\t%u\n", dpcm->buf_pos);
1695 	snd_iprintf(buffer, "    silent_size:\t%u\n", dpcm->silent_size);
1696 	snd_iprintf(buffer, "    period_size:\t%u\n", dpcm->pcm_period_size);
1697 	snd_iprintf(buffer, "    bytes_per_sec:\t%u\n", dpcm->pcm_bps);
1698 	snd_iprintf(buffer, "    sample_align:\t%u\n", dpcm->pcm_salign);
1699 	snd_iprintf(buffer, "    rate_shift:\t\t%u\n", dpcm->pcm_rate_shift);
1700 	if (dpcm->cable->ops->dpcm_info)
1701 		dpcm->cable->ops->dpcm_info(dpcm, buffer);
1702 }
1703 
print_substream_info(struct snd_info_buffer * buffer,struct loopback * loopback,int sub,int num)1704 static void print_substream_info(struct snd_info_buffer *buffer,
1705 				 struct loopback *loopback,
1706 				 int sub,
1707 				 int num)
1708 {
1709 	struct loopback_cable *cable = loopback->cables[sub][num];
1710 
1711 	snd_iprintf(buffer, "Cable %i substream %i:\n", num, sub);
1712 	if (cable == NULL) {
1713 		snd_iprintf(buffer, "  inactive\n");
1714 		return;
1715 	}
1716 	snd_iprintf(buffer, "  valid: %u\n", cable->valid);
1717 	snd_iprintf(buffer, "  running: %u\n", cable->running);
1718 	snd_iprintf(buffer, "  pause: %u\n", cable->pause);
1719 	print_dpcm_info(buffer, cable->streams[0], "Playback");
1720 	print_dpcm_info(buffer, cable->streams[1], "Capture");
1721 }
1722 
print_cable_info(struct snd_info_entry * entry,struct snd_info_buffer * buffer)1723 static void print_cable_info(struct snd_info_entry *entry,
1724 			     struct snd_info_buffer *buffer)
1725 {
1726 	struct loopback *loopback = entry->private_data;
1727 	int sub, num;
1728 
1729 	guard(mutex)(&loopback->cable_lock);
1730 	num = entry->name[strlen(entry->name)-1];
1731 	num = num == '0' ? 0 : 1;
1732 	for (sub = 0; sub < MAX_PCM_SUBSTREAMS; sub++)
1733 		print_substream_info(buffer, loopback, sub, num);
1734 }
1735 
loopback_cable_proc_new(struct loopback * loopback,int cidx)1736 static int loopback_cable_proc_new(struct loopback *loopback, int cidx)
1737 {
1738 	char name[32];
1739 
1740 	snprintf(name, sizeof(name), "cable#%d", cidx);
1741 	return snd_card_ro_proc_new(loopback->card, name, loopback,
1742 				    print_cable_info);
1743 }
1744 
loopback_set_timer_source(struct loopback * loopback,const char * value)1745 static void loopback_set_timer_source(struct loopback *loopback,
1746 				      const char *value)
1747 {
1748 	if (loopback->timer_source) {
1749 		devm_kfree(loopback->card->dev, loopback->timer_source);
1750 		loopback->timer_source = NULL;
1751 	}
1752 	if (value && *value)
1753 		loopback->timer_source = devm_kstrdup(loopback->card->dev,
1754 						      value, GFP_KERNEL);
1755 }
1756 
print_timer_source_info(struct snd_info_entry * entry,struct snd_info_buffer * buffer)1757 static void print_timer_source_info(struct snd_info_entry *entry,
1758 				    struct snd_info_buffer *buffer)
1759 {
1760 	struct loopback *loopback = entry->private_data;
1761 
1762 	guard(mutex)(&loopback->cable_lock);
1763 	snd_iprintf(buffer, "%s\n",
1764 		    loopback->timer_source ? loopback->timer_source : "");
1765 }
1766 
change_timer_source_info(struct snd_info_entry * entry,struct snd_info_buffer * buffer)1767 static void change_timer_source_info(struct snd_info_entry *entry,
1768 				     struct snd_info_buffer *buffer)
1769 {
1770 	struct loopback *loopback = entry->private_data;
1771 	char line[64];
1772 
1773 	guard(mutex)(&loopback->cable_lock);
1774 	if (!snd_info_get_line(buffer, line, sizeof(line)))
1775 		loopback_set_timer_source(loopback, strim(line));
1776 }
1777 
loopback_timer_source_proc_new(struct loopback * loopback)1778 static int loopback_timer_source_proc_new(struct loopback *loopback)
1779 {
1780 	return snd_card_rw_proc_new(loopback->card, "timer_source", loopback,
1781 				    print_timer_source_info,
1782 				    change_timer_source_info);
1783 }
1784 
loopback_probe(struct platform_device * devptr)1785 static int loopback_probe(struct platform_device *devptr)
1786 {
1787 	struct snd_card *card;
1788 	struct loopback *loopback;
1789 	int dev = devptr->id;
1790 	int err;
1791 
1792 	err = snd_devm_card_new(&devptr->dev, index[dev], id[dev], THIS_MODULE,
1793 				sizeof(struct loopback), &card);
1794 	if (err < 0)
1795 		return err;
1796 	loopback = card->private_data;
1797 
1798 	if (pcm_substreams[dev] < 1)
1799 		pcm_substreams[dev] = 1;
1800 	if (pcm_substreams[dev] > MAX_PCM_SUBSTREAMS)
1801 		pcm_substreams[dev] = MAX_PCM_SUBSTREAMS;
1802 
1803 	loopback->card = card;
1804 	loopback_set_timer_source(loopback, timer_source[dev]);
1805 
1806 	mutex_init(&loopback->cable_lock);
1807 
1808 	err = loopback_pcm_new(loopback, 0, pcm_substreams[dev]);
1809 	if (err < 0)
1810 		return err;
1811 	err = loopback_pcm_new(loopback, 1, pcm_substreams[dev]);
1812 	if (err < 0)
1813 		return err;
1814 	err = loopback_mixer_new(loopback, pcm_notify[dev] ? 1 : 0);
1815 	if (err < 0)
1816 		return err;
1817 	loopback_cable_proc_new(loopback, 0);
1818 	loopback_cable_proc_new(loopback, 1);
1819 	loopback_timer_source_proc_new(loopback);
1820 	strscpy(card->driver, "Loopback");
1821 	strscpy(card->shortname, "Loopback");
1822 	sprintf(card->longname, "Loopback %i", dev + 1);
1823 	err = snd_card_register(card);
1824 	if (err < 0)
1825 		return err;
1826 	platform_set_drvdata(devptr, card);
1827 	return 0;
1828 }
1829 
loopback_suspend(struct device * pdev)1830 static int loopback_suspend(struct device *pdev)
1831 {
1832 	struct snd_card *card = dev_get_drvdata(pdev);
1833 
1834 	snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
1835 	return 0;
1836 }
1837 
loopback_resume(struct device * pdev)1838 static int loopback_resume(struct device *pdev)
1839 {
1840 	struct snd_card *card = dev_get_drvdata(pdev);
1841 
1842 	snd_power_change_state(card, SNDRV_CTL_POWER_D0);
1843 	return 0;
1844 }
1845 
1846 static DEFINE_SIMPLE_DEV_PM_OPS(loopback_pm, loopback_suspend, loopback_resume);
1847 
1848 #define SND_LOOPBACK_DRIVER	"snd_aloop"
1849 
1850 static struct platform_driver loopback_driver = {
1851 	.probe		= loopback_probe,
1852 	.driver		= {
1853 		.name	= SND_LOOPBACK_DRIVER,
1854 		.pm	= &loopback_pm,
1855 	},
1856 };
1857 
loopback_unregister_all(void)1858 static void loopback_unregister_all(void)
1859 {
1860 	int i;
1861 
1862 	for (i = 0; i < ARRAY_SIZE(devices); ++i)
1863 		platform_device_unregister(devices[i]);
1864 	platform_driver_unregister(&loopback_driver);
1865 }
1866 
alsa_card_loopback_init(void)1867 static int __init alsa_card_loopback_init(void)
1868 {
1869 	int i, err, cards;
1870 
1871 	err = platform_driver_register(&loopback_driver);
1872 	if (err < 0)
1873 		return err;
1874 
1875 
1876 	cards = 0;
1877 	for (i = 0; i < SNDRV_CARDS; i++) {
1878 		struct platform_device *device;
1879 		if (!enable[i])
1880 			continue;
1881 		device = platform_device_register_simple(SND_LOOPBACK_DRIVER,
1882 							 i, NULL, 0);
1883 		if (IS_ERR(device))
1884 			continue;
1885 		if (!platform_get_drvdata(device)) {
1886 			platform_device_unregister(device);
1887 			continue;
1888 		}
1889 		devices[i] = device;
1890 		cards++;
1891 	}
1892 	if (!cards) {
1893 #ifdef MODULE
1894 		pr_err("aloop: No loopback enabled\n");
1895 #endif
1896 		loopback_unregister_all();
1897 		return -ENODEV;
1898 	}
1899 	return 0;
1900 }
1901 
alsa_card_loopback_exit(void)1902 static void __exit alsa_card_loopback_exit(void)
1903 {
1904 	loopback_unregister_all();
1905 }
1906 
1907 module_init(alsa_card_loopback_init)
1908 module_exit(alsa_card_loopback_exit)
1909