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