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