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