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