xref: /linux/sound/core/rawmidi.c (revision 8c3529f0a8faaac7d73333486f69da1617ecc579)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Abstract layer for MIDI v1.0 stream
4  *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
5  */
6 
7 #include <sound/core.h>
8 #include <linux/major.h>
9 #include <linux/init.h>
10 #include <linux/sched/signal.h>
11 #include <linux/slab.h>
12 #include <linux/time.h>
13 #include <linux/wait.h>
14 #include <linux/mutex.h>
15 #include <linux/module.h>
16 #include <linux/delay.h>
17 #include <linux/mm.h>
18 #include <linux/nospec.h>
19 #include <sound/rawmidi.h>
20 #include <sound/info.h>
21 #include <sound/control.h>
22 #include <sound/minors.h>
23 #include <sound/initval.h>
24 #include <sound/ump.h>
25 
26 MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
27 MODULE_DESCRIPTION("Midlevel RawMidi code for ALSA.");
28 MODULE_LICENSE("GPL");
29 
30 #ifdef CONFIG_SND_OSSEMUL
31 static int midi_map[SNDRV_CARDS] __ro_after_init;
32 static int amidi_map[SNDRV_CARDS] __ro_after_init = {[0 ... (SNDRV_CARDS-1)] = 1};
33 module_param_array(midi_map, int, NULL, 0444);
34 MODULE_PARM_DESC(midi_map, "Raw MIDI device number assigned to 1st OSS device.");
35 module_param_array(amidi_map, int, NULL, 0444);
36 MODULE_PARM_DESC(amidi_map, "Raw MIDI device number assigned to 2nd OSS device.");
37 #endif /* CONFIG_SND_OSSEMUL */
38 
39 /* upper bound for draining the output buffer */
40 #define SNDRV_RAWMIDI_DRAIN_TIMEOUT	(10 * HZ)
41 /* interval at which drain progress is re-checked */
42 #define SNDRV_RAWMIDI_DRAIN_POLL	(HZ / 5)
43 /* polls without progress before the drain is considered stalled */
44 #define SNDRV_RAWMIDI_DRAIN_STALLS	5
45 
46 static int snd_rawmidi_dev_free(struct snd_device *device);
47 static int snd_rawmidi_dev_register(struct snd_device *device);
48 static int snd_rawmidi_dev_disconnect(struct snd_device *device);
49 
50 static LIST_HEAD(snd_rawmidi_devices);
51 static DEFINE_MUTEX(register_mutex);
52 
53 #define rmidi_err(rmidi, fmt, args...) \
54 	dev_err((rmidi)->dev, fmt, ##args)
55 #define rmidi_warn(rmidi, fmt, args...) \
56 	dev_warn((rmidi)->dev, fmt, ##args)
57 #define rmidi_dbg(rmidi, fmt, args...) \
58 	dev_dbg((rmidi)->dev, fmt, ##args)
59 
60 struct snd_rawmidi_status32 {
61 	s32 stream;
62 	s32 tstamp_sec;			/* Timestamp */
63 	s32 tstamp_nsec;
64 	u32 avail;			/* available bytes */
65 	u32 xruns;			/* count of overruns since last status (in bytes) */
66 	unsigned char reserved[16];	/* reserved for future use */
67 };
68 
69 #define SNDRV_RAWMIDI_IOCTL_STATUS32	_IOWR('W', 0x20, struct snd_rawmidi_status32)
70 
71 struct snd_rawmidi_status64 {
72 	int stream;
73 	u8 rsvd[4];			/* alignment */
74 	s64 tstamp_sec;			/* Timestamp */
75 	s64 tstamp_nsec;
76 	size_t avail;			/* available bytes */
77 	size_t xruns;			/* count of overruns since last status (in bytes) */
78 	unsigned char reserved[16];	/* reserved for future use */
79 };
80 
81 #define SNDRV_RAWMIDI_IOCTL_STATUS64	_IOWR('W', 0x20, struct snd_rawmidi_status64)
82 
83 #define rawmidi_is_ump(rmidi) \
84 	(IS_ENABLED(CONFIG_SND_UMP) && ((rmidi)->info_flags & SNDRV_RAWMIDI_INFO_UMP))
85 
86 static struct snd_rawmidi *snd_rawmidi_search(struct snd_card *card, int device)
87 {
88 	struct snd_rawmidi *rawmidi;
89 
90 	list_for_each_entry(rawmidi, &snd_rawmidi_devices, list)
91 		if (rawmidi->card == card && rawmidi->device == device)
92 			return rawmidi;
93 	return NULL;
94 }
95 
96 static inline unsigned short snd_rawmidi_file_flags(struct file *file)
97 {
98 	switch (file->f_mode & (FMODE_READ | FMODE_WRITE)) {
99 	case FMODE_WRITE:
100 		return SNDRV_RAWMIDI_LFLG_OUTPUT;
101 	case FMODE_READ:
102 		return SNDRV_RAWMIDI_LFLG_INPUT;
103 	default:
104 		return SNDRV_RAWMIDI_LFLG_OPEN;
105 	}
106 }
107 
108 static inline bool __snd_rawmidi_ready(struct snd_rawmidi_runtime *runtime)
109 {
110 	return runtime->avail >= runtime->avail_min;
111 }
112 
113 static bool snd_rawmidi_ready(struct snd_rawmidi_substream *substream)
114 {
115 	guard(spinlock_irqsave)(&substream->lock);
116 	return __snd_rawmidi_ready(substream->runtime);
117 }
118 
119 static inline int snd_rawmidi_ready_append(struct snd_rawmidi_substream *substream,
120 					   size_t count)
121 {
122 	struct snd_rawmidi_runtime *runtime = substream->runtime;
123 
124 	return runtime->avail >= runtime->avail_min &&
125 	       (!substream->append || runtime->avail >= count);
126 }
127 
128 static void snd_rawmidi_input_event_work(struct work_struct *work)
129 {
130 	struct snd_rawmidi_runtime *runtime =
131 		container_of(work, struct snd_rawmidi_runtime, event_work);
132 
133 	if (runtime->event)
134 		runtime->event(runtime->substream);
135 }
136 
137 /* buffer refcount management: call with substream->lock held */
138 static inline void snd_rawmidi_buffer_ref(struct snd_rawmidi_runtime *runtime)
139 {
140 	runtime->buffer_ref++;
141 }
142 
143 static inline void snd_rawmidi_buffer_unref(struct snd_rawmidi_runtime *runtime)
144 {
145 	runtime->buffer_ref--;
146 }
147 
148 static void snd_rawmidi_buffer_ref_sync(struct snd_rawmidi_substream *substream)
149 {
150 	int loop = HZ;
151 
152 	spin_lock_irq(&substream->lock);
153 	while (substream->runtime->buffer_ref) {
154 		spin_unlock_irq(&substream->lock);
155 		if (!--loop) {
156 			rmidi_err(substream->rmidi, "Buffer ref sync timeout\n");
157 			return;
158 		}
159 		schedule_timeout_uninterruptible(1);
160 		spin_lock_irq(&substream->lock);
161 	}
162 	spin_unlock_irq(&substream->lock);
163 }
164 
165 static int snd_rawmidi_runtime_create(struct snd_rawmidi_substream *substream)
166 {
167 	struct snd_rawmidi_runtime *runtime;
168 
169 	runtime = kzalloc_obj(*runtime);
170 	if (!runtime)
171 		return -ENOMEM;
172 	runtime->substream = substream;
173 	init_waitqueue_head(&runtime->sleep);
174 	INIT_WORK(&runtime->event_work, snd_rawmidi_input_event_work);
175 	runtime->event = NULL;
176 	runtime->buffer_size = PAGE_SIZE;
177 	runtime->avail_min = 1;
178 	if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
179 		runtime->avail = 0;
180 	else
181 		runtime->avail = runtime->buffer_size;
182 	runtime->buffer = kvzalloc(runtime->buffer_size, GFP_KERNEL);
183 	if (!runtime->buffer) {
184 		kfree(runtime);
185 		return -ENOMEM;
186 	}
187 	runtime->appl_ptr = runtime->hw_ptr = 0;
188 	substream->runtime = runtime;
189 	if (rawmidi_is_ump(substream->rmidi))
190 		runtime->align = 3;
191 	return 0;
192 }
193 
194 /* get the current alignment (either 0 or 3) */
195 static inline int get_align(struct snd_rawmidi_runtime *runtime)
196 {
197 	if (IS_ENABLED(CONFIG_SND_UMP))
198 		return runtime->align;
199 	else
200 		return 0;
201 }
202 
203 /* get the trimmed size with the current alignment */
204 #define get_aligned_size(runtime, size) ((size) & ~get_align(runtime))
205 
206 static int snd_rawmidi_runtime_free(struct snd_rawmidi_substream *substream)
207 {
208 	struct snd_rawmidi_runtime *runtime = substream->runtime;
209 
210 	kvfree(runtime->buffer);
211 	kfree(runtime);
212 	substream->runtime = NULL;
213 	return 0;
214 }
215 
216 static inline void snd_rawmidi_output_trigger(struct snd_rawmidi_substream *substream, int up)
217 {
218 	if (!substream->opened || substream->disconnected)
219 		return;
220 	substream->ops->trigger(substream, up);
221 }
222 
223 static void snd_rawmidi_input_trigger(struct snd_rawmidi_substream *substream, int up)
224 {
225 	if (!substream->opened || substream->disconnected)
226 		return;
227 	substream->ops->trigger(substream, up);
228 	if (!up)
229 		cancel_work_sync(&substream->runtime->event_work);
230 }
231 
232 static void __reset_runtime_ptrs(struct snd_rawmidi_runtime *runtime,
233 				 bool is_input)
234 {
235 	runtime->drain = 0;
236 	runtime->appl_ptr = runtime->hw_ptr = 0;
237 	runtime->avail = is_input ? 0 : runtime->buffer_size;
238 }
239 
240 static void reset_runtime_ptrs(struct snd_rawmidi_substream *substream,
241 			       bool is_input)
242 {
243 	guard(spinlock_irqsave)(&substream->lock);
244 	if (substream->opened && substream->runtime)
245 		__reset_runtime_ptrs(substream->runtime, is_input);
246 }
247 
248 int snd_rawmidi_drop_output(struct snd_rawmidi_substream *substream)
249 {
250 	snd_rawmidi_output_trigger(substream, 0);
251 	reset_runtime_ptrs(substream, false);
252 	return 0;
253 }
254 EXPORT_SYMBOL(snd_rawmidi_drop_output);
255 
256 static bool output_drained(struct snd_rawmidi_runtime *runtime)
257 {
258 	return runtime->avail >= runtime->buffer_size;
259 }
260 
261 int snd_rawmidi_drain_output(struct snd_rawmidi_substream *substream)
262 {
263 	struct snd_rawmidi_runtime *runtime;
264 	size_t avail, prev_avail;
265 	unsigned int stalls = 0;
266 	unsigned long deadline;
267 	long timeout, wait;
268 	bool done;
269 	int err = 0;
270 
271 	scoped_guard(spinlock_irq, &substream->lock) {
272 		runtime = substream->runtime;
273 		if (!substream->opened || !runtime || !runtime->buffer ||
274 		    substream->disconnected)
275 			return -EINVAL;
276 		snd_rawmidi_buffer_ref(runtime);
277 		runtime->drain = 1;
278 		prev_avail = runtime->avail;
279 	}
280 
281 	/*
282 	 * Wait for the device to consume the buffer.  Rather than always
283 	 * sleeping for the whole timeout, sample the free space and stop
284 	 * early once it has not increased for a second.  A substream that
285 	 * is still making progress is given as long as it needs, within the
286 	 * same overall limit as before.
287 	 */
288 	deadline = jiffies + SNDRV_RAWMIDI_DRAIN_TIMEOUT;
289 	for (;;) {
290 		/* signed difference, so this is safe across a jiffies wrap */
291 		wait = (long)(deadline - jiffies);
292 		if (wait <= 0) {
293 			timeout = 0;
294 			break;
295 		}
296 		wait = min_t(long, SNDRV_RAWMIDI_DRAIN_POLL, wait);
297 		timeout = wait_event_interruptible_timeout(runtime->sleep,
298 							   output_drained(runtime), wait);
299 		scoped_guard(spinlock_irq, &substream->lock) {
300 			avail = runtime->avail;
301 			done = output_drained(runtime);
302 		}
303 		if (done || signal_pending(current))
304 			break;
305 		if (avail == prev_avail) {
306 			if (++stalls >= SNDRV_RAWMIDI_DRAIN_STALLS) {
307 				timeout = 0;
308 				break;
309 			}
310 		} else {
311 			stalls = 0;
312 			prev_avail = avail;
313 		}
314 	}
315 
316 	scoped_guard(spinlock_irq, &substream->lock) {
317 		if (signal_pending(current))
318 			err = -ERESTARTSYS;
319 		if (runtime->avail < runtime->buffer_size && !timeout) {
320 			dev_warn_ratelimited(substream->rmidi->dev,
321 					     "rawmidi drain error (avail = %li, buffer_size = %li)\n",
322 					     (long)runtime->avail,
323 					     (long)runtime->buffer_size);
324 			err = -EIO;
325 		}
326 		runtime->drain = 0;
327 	}
328 
329 	if (err != -ERESTARTSYS) {
330 		/* we need wait a while to make sure that Tx FIFOs are empty */
331 		if (substream->ops->drain)
332 			substream->ops->drain(substream);
333 		else
334 			msleep(50);
335 		snd_rawmidi_drop_output(substream);
336 	}
337 
338 	scoped_guard(spinlock_irq, &substream->lock)
339 		snd_rawmidi_buffer_unref(runtime);
340 
341 	return err;
342 }
343 EXPORT_SYMBOL(snd_rawmidi_drain_output);
344 
345 int snd_rawmidi_drain_input(struct snd_rawmidi_substream *substream)
346 {
347 	snd_rawmidi_input_trigger(substream, 0);
348 	reset_runtime_ptrs(substream, true);
349 	return 0;
350 }
351 EXPORT_SYMBOL(snd_rawmidi_drain_input);
352 
353 /* look for an available substream for the given stream direction;
354  * if a specific subdevice is given, try to assign it
355  */
356 static int assign_substream(struct snd_rawmidi *rmidi, int subdevice,
357 			    int stream, int mode,
358 			    struct snd_rawmidi_substream **sub_ret)
359 {
360 	struct snd_rawmidi_substream *substream;
361 	struct snd_rawmidi_str *s = &rmidi->streams[stream];
362 	static const unsigned int info_flags[2] = {
363 		[SNDRV_RAWMIDI_STREAM_OUTPUT] = SNDRV_RAWMIDI_INFO_OUTPUT,
364 		[SNDRV_RAWMIDI_STREAM_INPUT] = SNDRV_RAWMIDI_INFO_INPUT,
365 	};
366 
367 	if (!(rmidi->info_flags & info_flags[stream]))
368 		return -ENXIO;
369 	if (subdevice >= 0 && subdevice >= s->substream_count)
370 		return -ENODEV;
371 
372 	list_for_each_entry(substream, &s->substreams, list) {
373 		if (substream->opened) {
374 			if (stream == SNDRV_RAWMIDI_STREAM_INPUT ||
375 			    !(mode & SNDRV_RAWMIDI_LFLG_APPEND) ||
376 			    !substream->append)
377 				continue;
378 		}
379 		if (subdevice < 0 || subdevice == substream->number) {
380 			*sub_ret = substream;
381 			return 0;
382 		}
383 	}
384 	return -EAGAIN;
385 }
386 
387 /* open and do ref-counting for the given substream */
388 static int open_substream(struct snd_rawmidi *rmidi,
389 			  struct snd_rawmidi_substream *substream,
390 			  int mode)
391 {
392 	int err;
393 
394 	if (substream->use_count == 0) {
395 		err = snd_rawmidi_runtime_create(substream);
396 		if (err < 0)
397 			return err;
398 		err = substream->ops->open(substream);
399 		if (err < 0) {
400 			snd_rawmidi_runtime_free(substream);
401 			return err;
402 		}
403 		guard(spinlock_irq)(&substream->lock);
404 		substream->opened = 1;
405 		substream->active_sensing = 0;
406 		if (mode & SNDRV_RAWMIDI_LFLG_APPEND)
407 			substream->append = 1;
408 		substream->pid = get_pid(task_pid(current));
409 		rmidi->streams[substream->stream].substream_opened++;
410 	}
411 	substream->use_count++;
412 	return 0;
413 }
414 
415 static void close_substream(struct snd_rawmidi *rmidi,
416 			    struct snd_rawmidi_substream *substream,
417 			    int cleanup);
418 
419 static int rawmidi_open_priv(struct snd_rawmidi *rmidi, int subdevice, int mode,
420 			     struct snd_rawmidi_file *rfile)
421 {
422 	struct snd_rawmidi_substream *sinput = NULL, *soutput = NULL;
423 	int err;
424 
425 	rfile->input = rfile->output = NULL;
426 	if (mode & SNDRV_RAWMIDI_LFLG_INPUT) {
427 		err = assign_substream(rmidi, subdevice,
428 				       SNDRV_RAWMIDI_STREAM_INPUT,
429 				       mode, &sinput);
430 		if (err < 0)
431 			return err;
432 	}
433 	if (mode & SNDRV_RAWMIDI_LFLG_OUTPUT) {
434 		err = assign_substream(rmidi, subdevice,
435 				       SNDRV_RAWMIDI_STREAM_OUTPUT,
436 				       mode, &soutput);
437 		if (err < 0)
438 			return err;
439 	}
440 
441 	if (sinput) {
442 		err = open_substream(rmidi, sinput, mode);
443 		if (err < 0)
444 			return err;
445 	}
446 	if (soutput) {
447 		err = open_substream(rmidi, soutput, mode);
448 		if (err < 0) {
449 			if (sinput)
450 				close_substream(rmidi, sinput, 0);
451 			return err;
452 		}
453 	}
454 
455 	rfile->rmidi = rmidi;
456 	rfile->input = sinput;
457 	rfile->output = soutput;
458 	return 0;
459 }
460 
461 /* called from sound/core/seq/seq_midi.c and sound/core/ump.c */
462 int snd_rawmidi_kernel_open_nested(struct snd_rawmidi *rmidi, int subdevice,
463 				   int mode, struct snd_rawmidi_file *rfile,
464 				   int depth)
465 {
466 	int err;
467 
468 	if (snd_BUG_ON(!rfile))
469 		return -EINVAL;
470 	if (!try_module_get(rmidi->card->module))
471 		return -ENXIO;
472 
473 	mutex_lock_nested(&rmidi->open_mutex, depth);
474 	err = rawmidi_open_priv(rmidi, subdevice, mode, rfile);
475 	if (err < 0)
476 		module_put(rmidi->card->module);
477 	mutex_unlock(&rmidi->open_mutex);
478 	return err;
479 }
480 EXPORT_SYMBOL(snd_rawmidi_kernel_open_nested);
481 
482 static int snd_rawmidi_open(struct inode *inode, struct file *file)
483 {
484 	int maj = imajor(inode);
485 	struct snd_card *card;
486 	int subdevice;
487 	unsigned short fflags;
488 	int err;
489 	struct snd_rawmidi *rmidi;
490 	struct snd_rawmidi_file *rawmidi_file = NULL;
491 	wait_queue_entry_t wait;
492 
493 	if ((file->f_flags & O_APPEND) && !(file->f_flags & O_NONBLOCK))
494 		return -EINVAL;		/* invalid combination */
495 
496 	stream_open(inode, file);
497 
498 	if (maj == snd_major) {
499 		rmidi = snd_lookup_minor_data(iminor(inode),
500 					      SNDRV_DEVICE_TYPE_RAWMIDI);
501 #ifdef CONFIG_SND_OSSEMUL
502 	} else if (maj == SOUND_MAJOR) {
503 		rmidi = snd_lookup_oss_minor_data(iminor(inode),
504 						  SNDRV_OSS_DEVICE_TYPE_MIDI);
505 #endif
506 	} else
507 		return -ENXIO;
508 
509 	if (rmidi == NULL)
510 		return -ENODEV;
511 
512 	if (!try_module_get(rmidi->card->module)) {
513 		snd_card_unref(rmidi->card);
514 		return -ENXIO;
515 	}
516 
517 	mutex_lock(&rmidi->open_mutex);
518 	card = rmidi->card;
519 	err = snd_card_file_add(card, file);
520 	if (err < 0)
521 		goto __error_card;
522 	fflags = snd_rawmidi_file_flags(file);
523 	if ((file->f_flags & O_APPEND) || maj == SOUND_MAJOR) /* OSS emul? */
524 		fflags |= SNDRV_RAWMIDI_LFLG_APPEND;
525 	rawmidi_file = kmalloc_obj(*rawmidi_file);
526 	if (rawmidi_file == NULL) {
527 		err = -ENOMEM;
528 		goto __error;
529 	}
530 	rawmidi_file->user_pversion = 0;
531 	init_waitqueue_entry(&wait, current);
532 	add_wait_queue(&rmidi->open_wait, &wait);
533 	while (1) {
534 		subdevice = snd_ctl_get_preferred_subdevice(card, SND_CTL_SUBDEV_RAWMIDI);
535 		err = rawmidi_open_priv(rmidi, subdevice, fflags, rawmidi_file);
536 		if (err >= 0)
537 			break;
538 		if (err == -EAGAIN) {
539 			if (file->f_flags & O_NONBLOCK) {
540 				err = -EBUSY;
541 				break;
542 			}
543 		} else
544 			break;
545 		set_current_state(TASK_INTERRUPTIBLE);
546 		mutex_unlock(&rmidi->open_mutex);
547 		schedule();
548 		mutex_lock(&rmidi->open_mutex);
549 		if (rmidi->card->shutdown) {
550 			err = -ENODEV;
551 			break;
552 		}
553 		if (signal_pending(current)) {
554 			err = -ERESTARTSYS;
555 			break;
556 		}
557 	}
558 	remove_wait_queue(&rmidi->open_wait, &wait);
559 	if (err < 0) {
560 		kfree(rawmidi_file);
561 		goto __error;
562 	}
563 #ifdef CONFIG_SND_OSSEMUL
564 	if (rawmidi_file->input && rawmidi_file->input->runtime)
565 		rawmidi_file->input->runtime->oss = (maj == SOUND_MAJOR);
566 	if (rawmidi_file->output && rawmidi_file->output->runtime)
567 		rawmidi_file->output->runtime->oss = (maj == SOUND_MAJOR);
568 #endif
569 	file->private_data = rawmidi_file;
570 	mutex_unlock(&rmidi->open_mutex);
571 	snd_card_unref(rmidi->card);
572 	return 0;
573 
574  __error:
575 	snd_card_file_remove(card, file);
576  __error_card:
577 	mutex_unlock(&rmidi->open_mutex);
578 	module_put(rmidi->card->module);
579 	snd_card_unref(rmidi->card);
580 	return err;
581 }
582 
583 static void close_substream(struct snd_rawmidi *rmidi,
584 			    struct snd_rawmidi_substream *substream,
585 			    int cleanup)
586 {
587 	if (--substream->use_count)
588 		return;
589 
590 	if (cleanup && !substream->disconnected) {
591 		if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
592 			snd_rawmidi_input_trigger(substream, 0);
593 		else {
594 			if (substream->active_sensing) {
595 				unsigned char buf = 0xfe;
596 				/* sending single active sensing message
597 				 * to shut the device up
598 				 */
599 				snd_rawmidi_kernel_write(substream, &buf, 1);
600 			}
601 			if (snd_rawmidi_drain_output(substream) == -ERESTARTSYS)
602 				snd_rawmidi_output_trigger(substream, 0);
603 		}
604 		snd_rawmidi_buffer_ref_sync(substream);
605 	}
606 	scoped_guard(spinlock_irq, &substream->lock) {
607 		substream->opened = 0;
608 		substream->append = 0;
609 	}
610 	/* Drain input work queued after the earlier cancellation. */
611 	if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
612 		cancel_work_sync(&substream->runtime->event_work);
613 	substream->ops->close(substream);
614 	if (substream->runtime->private_free)
615 		substream->runtime->private_free(substream);
616 	snd_rawmidi_runtime_free(substream);
617 	put_pid(substream->pid);
618 	substream->pid = NULL;
619 	rmidi->streams[substream->stream].substream_opened--;
620 }
621 
622 static void rawmidi_release_priv(struct snd_rawmidi_file *rfile)
623 {
624 	struct snd_rawmidi *rmidi;
625 
626 	rmidi = rfile->rmidi;
627 	if (rfile->input) {
628 		close_substream(rmidi, rfile->input, 1);
629 		rfile->input = NULL;
630 	}
631 	if (rfile->output) {
632 		close_substream(rmidi, rfile->output, 1);
633 		rfile->output = NULL;
634 	}
635 	rfile->rmidi = NULL;
636 	wake_up(&rmidi->open_wait);
637 }
638 
639 /* called from sound/core/seq/seq_midi.c */
640 int snd_rawmidi_kernel_release_nested(struct snd_rawmidi_file *rfile,
641 				      int depth)
642 {
643 	struct snd_rawmidi *rmidi;
644 
645 	if (snd_BUG_ON(!rfile))
646 		return -ENXIO;
647 
648 	rmidi = rfile->rmidi;
649 	mutex_lock_nested(&rmidi->open_mutex, depth);
650 	rawmidi_release_priv(rfile);
651 	mutex_unlock(&rmidi->open_mutex);
652 	module_put(rmidi->card->module);
653 	return 0;
654 }
655 EXPORT_SYMBOL(snd_rawmidi_kernel_release_nested);
656 
657 static int snd_rawmidi_release(struct inode *inode, struct file *file)
658 {
659 	struct snd_rawmidi_file *rfile;
660 	struct snd_rawmidi *rmidi;
661 	struct module *module;
662 
663 	rfile = file->private_data;
664 	rmidi = rfile->rmidi;
665 	scoped_guard(mutex, &rmidi->open_mutex)
666 		rawmidi_release_priv(rfile);
667 	kfree(rfile);
668 	module = rmidi->card->module;
669 	snd_card_file_remove(rmidi->card, file);
670 	module_put(module);
671 	return 0;
672 }
673 
674 static int snd_rawmidi_info(struct snd_rawmidi_substream *substream,
675 			    struct snd_rawmidi_info *info)
676 {
677 	struct snd_rawmidi *rmidi;
678 
679 	if (substream == NULL)
680 		return -ENODEV;
681 	rmidi = substream->rmidi;
682 	memset(info, 0, sizeof(*info));
683 	info->card = rmidi->card->number;
684 	info->device = rmidi->device;
685 	info->subdevice = substream->number;
686 	info->stream = substream->stream;
687 	info->flags = rmidi->info_flags;
688 	if (substream->inactive)
689 		info->flags |= SNDRV_RAWMIDI_INFO_STREAM_INACTIVE;
690 	strscpy(info->id, rmidi->id);
691 	strscpy(info->name, rmidi->name);
692 	strscpy(info->subname, substream->name);
693 	info->subdevices_count = substream->pstr->substream_count;
694 	info->subdevices_avail = (substream->pstr->substream_count -
695 				  substream->pstr->substream_opened);
696 	info->tied_device = rmidi->tied_device;
697 	return 0;
698 }
699 
700 static int snd_rawmidi_info_user(struct snd_rawmidi_substream *substream,
701 				 struct snd_rawmidi_info __user *_info)
702 {
703 	struct snd_rawmidi_info info;
704 	int err;
705 
706 	err = snd_rawmidi_info(substream, &info);
707 	if (err < 0)
708 		return err;
709 	if (copy_to_user(_info, &info, sizeof(struct snd_rawmidi_info)))
710 		return -EFAULT;
711 	return 0;
712 }
713 
714 static int __snd_rawmidi_info_select(struct snd_card *card,
715 				     struct snd_rawmidi_info *info)
716 {
717 	struct snd_rawmidi *rmidi;
718 	struct snd_rawmidi_str *pstr;
719 	struct snd_rawmidi_substream *substream;
720 
721 	rmidi = snd_rawmidi_search(card, info->device);
722 	if (!rmidi)
723 		return -ENXIO;
724 	if (info->stream < 0 || info->stream > 1)
725 		return -EINVAL;
726 	info->stream = array_index_nospec(info->stream, 2);
727 	pstr = &rmidi->streams[info->stream];
728 	if (pstr->substream_count == 0)
729 		return -ENOENT;
730 	if (info->subdevice >= pstr->substream_count)
731 		return -ENXIO;
732 	list_for_each_entry(substream, &pstr->substreams, list) {
733 		if ((unsigned int)substream->number == info->subdevice)
734 			return snd_rawmidi_info(substream, info);
735 	}
736 	return -ENXIO;
737 }
738 
739 int snd_rawmidi_info_select(struct snd_card *card, struct snd_rawmidi_info *info)
740 {
741 	guard(mutex)(&register_mutex);
742 	return __snd_rawmidi_info_select(card, info);
743 }
744 EXPORT_SYMBOL(snd_rawmidi_info_select);
745 
746 static int snd_rawmidi_info_select_user(struct snd_card *card,
747 					struct snd_rawmidi_info __user *_info)
748 {
749 	int err;
750 	struct snd_rawmidi_info info;
751 
752 	if (get_user(info.device, &_info->device))
753 		return -EFAULT;
754 	if (get_user(info.stream, &_info->stream))
755 		return -EFAULT;
756 	if (get_user(info.subdevice, &_info->subdevice))
757 		return -EFAULT;
758 	err = snd_rawmidi_info_select(card, &info);
759 	if (err < 0)
760 		return err;
761 	if (copy_to_user(_info, &info, sizeof(struct snd_rawmidi_info)))
762 		return -EFAULT;
763 	return 0;
764 }
765 
766 static int resize_runtime_buffer(struct snd_rawmidi_substream *substream,
767 				 struct snd_rawmidi_params *params,
768 				 bool is_input)
769 {
770 	struct snd_rawmidi_runtime *runtime = substream->runtime;
771 	char *newbuf, *oldbuf;
772 	unsigned int framing = params->mode & SNDRV_RAWMIDI_MODE_FRAMING_MASK;
773 
774 	if (params->buffer_size < 32 || params->buffer_size > 1024L * 1024L)
775 		return -EINVAL;
776 	if (framing == SNDRV_RAWMIDI_MODE_FRAMING_TSTAMP && (params->buffer_size & 0x1f) != 0)
777 		return -EINVAL;
778 	if (params->avail_min < 1 || params->avail_min > params->buffer_size)
779 		return -EINVAL;
780 	if (params->buffer_size & get_align(runtime))
781 		return -EINVAL;
782 	if (params->buffer_size != runtime->buffer_size) {
783 		newbuf = kvzalloc(params->buffer_size, GFP_KERNEL);
784 		if (!newbuf)
785 			return -ENOMEM;
786 		spin_lock_irq(&substream->lock);
787 		if (runtime->buffer_ref) {
788 			spin_unlock_irq(&substream->lock);
789 			kvfree(newbuf);
790 			return -EBUSY;
791 		}
792 		oldbuf = runtime->buffer;
793 		runtime->buffer = newbuf;
794 		runtime->buffer_size = params->buffer_size;
795 		__reset_runtime_ptrs(runtime, is_input);
796 		spin_unlock_irq(&substream->lock);
797 		kvfree(oldbuf);
798 	}
799 	runtime->avail_min = params->avail_min;
800 	return 0;
801 }
802 
803 int snd_rawmidi_output_params(struct snd_rawmidi_substream *substream,
804 			      struct snd_rawmidi_params *params)
805 {
806 	int err;
807 
808 	snd_rawmidi_drain_output(substream);
809 	guard(mutex)(&substream->rmidi->open_mutex);
810 	if (substream->append && substream->use_count > 1)
811 		return -EBUSY;
812 	err = resize_runtime_buffer(substream, params, false);
813 	if (!err)
814 		substream->active_sensing = !params->no_active_sensing;
815 	return err;
816 }
817 EXPORT_SYMBOL(snd_rawmidi_output_params);
818 
819 int snd_rawmidi_input_params(struct snd_rawmidi_substream *substream,
820 			     struct snd_rawmidi_params *params)
821 {
822 	unsigned int framing = params->mode & SNDRV_RAWMIDI_MODE_FRAMING_MASK;
823 	unsigned int clock_type = params->mode & SNDRV_RAWMIDI_MODE_CLOCK_MASK;
824 	int err;
825 
826 	snd_rawmidi_drain_input(substream);
827 	guard(mutex)(&substream->rmidi->open_mutex);
828 	if (framing == SNDRV_RAWMIDI_MODE_FRAMING_NONE && clock_type != SNDRV_RAWMIDI_MODE_CLOCK_NONE)
829 		err = -EINVAL;
830 	else if (clock_type > SNDRV_RAWMIDI_MODE_CLOCK_MONOTONIC_RAW)
831 		err = -EINVAL;
832 	else if (framing > SNDRV_RAWMIDI_MODE_FRAMING_TSTAMP)
833 		err = -EINVAL;
834 	else
835 		err = resize_runtime_buffer(substream, params, true);
836 
837 	if (!err) {
838 		substream->framing = framing;
839 		substream->clock_type = clock_type;
840 	}
841 	return err;
842 }
843 EXPORT_SYMBOL(snd_rawmidi_input_params);
844 
845 static int snd_rawmidi_output_status(struct snd_rawmidi_substream *substream,
846 				     struct snd_rawmidi_status64 *status)
847 {
848 	struct snd_rawmidi_runtime *runtime = substream->runtime;
849 
850 	memset(status, 0, sizeof(*status));
851 	status->stream = SNDRV_RAWMIDI_STREAM_OUTPUT;
852 	guard(spinlock_irq)(&substream->lock);
853 	status->avail = runtime->avail;
854 	return 0;
855 }
856 
857 static int snd_rawmidi_input_status(struct snd_rawmidi_substream *substream,
858 				    struct snd_rawmidi_status64 *status)
859 {
860 	struct snd_rawmidi_runtime *runtime = substream->runtime;
861 
862 	memset(status, 0, sizeof(*status));
863 	status->stream = SNDRV_RAWMIDI_STREAM_INPUT;
864 	guard(spinlock_irq)(&substream->lock);
865 	status->avail = runtime->avail;
866 	status->xruns = runtime->xruns;
867 	runtime->xruns = 0;
868 	return 0;
869 }
870 
871 static int snd_rawmidi_ioctl_status32(struct snd_rawmidi_file *rfile,
872 				      struct snd_rawmidi_status32 __user *argp)
873 {
874 	int err = 0;
875 	struct snd_rawmidi_status32 __user *status = argp;
876 	struct snd_rawmidi_status32 status32;
877 	struct snd_rawmidi_status64 status64;
878 
879 	if (copy_from_user(&status32, argp,
880 			   sizeof(struct snd_rawmidi_status32)))
881 		return -EFAULT;
882 
883 	switch (status32.stream) {
884 	case SNDRV_RAWMIDI_STREAM_OUTPUT:
885 		if (rfile->output == NULL)
886 			return -EINVAL;
887 		err = snd_rawmidi_output_status(rfile->output, &status64);
888 		break;
889 	case SNDRV_RAWMIDI_STREAM_INPUT:
890 		if (rfile->input == NULL)
891 			return -EINVAL;
892 		err = snd_rawmidi_input_status(rfile->input, &status64);
893 		break;
894 	default:
895 		return -EINVAL;
896 	}
897 	if (err < 0)
898 		return err;
899 
900 	status32 = (struct snd_rawmidi_status32) {
901 		.stream = status64.stream,
902 		.tstamp_sec = status64.tstamp_sec,
903 		.tstamp_nsec = status64.tstamp_nsec,
904 		.avail = status64.avail,
905 		.xruns = status64.xruns,
906 	};
907 
908 	if (copy_to_user(status, &status32, sizeof(*status)))
909 		return -EFAULT;
910 
911 	return 0;
912 }
913 
914 static int snd_rawmidi_ioctl_status64(struct snd_rawmidi_file *rfile,
915 				      struct snd_rawmidi_status64 __user *argp)
916 {
917 	int err = 0;
918 	struct snd_rawmidi_status64 status;
919 
920 	if (copy_from_user(&status, argp, sizeof(struct snd_rawmidi_status64)))
921 		return -EFAULT;
922 
923 	switch (status.stream) {
924 	case SNDRV_RAWMIDI_STREAM_OUTPUT:
925 		if (rfile->output == NULL)
926 			return -EINVAL;
927 		err = snd_rawmidi_output_status(rfile->output, &status);
928 		break;
929 	case SNDRV_RAWMIDI_STREAM_INPUT:
930 		if (rfile->input == NULL)
931 			return -EINVAL;
932 		err = snd_rawmidi_input_status(rfile->input, &status);
933 		break;
934 	default:
935 		return -EINVAL;
936 	}
937 	if (err < 0)
938 		return err;
939 	if (copy_to_user(argp, &status,
940 			 sizeof(struct snd_rawmidi_status64)))
941 		return -EFAULT;
942 	return 0;
943 }
944 
945 static long snd_rawmidi_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
946 {
947 	struct snd_rawmidi_file *rfile;
948 	struct snd_rawmidi *rmidi;
949 	void __user *argp = (void __user *)arg;
950 
951 	rfile = file->private_data;
952 	if (((cmd >> 8) & 0xff) != 'W')
953 		return -ENOTTY;
954 	switch (cmd) {
955 	case SNDRV_RAWMIDI_IOCTL_PVERSION:
956 		return put_user(SNDRV_RAWMIDI_VERSION, (int __user *)argp) ? -EFAULT : 0;
957 	case SNDRV_RAWMIDI_IOCTL_INFO:
958 	{
959 		int stream;
960 		struct snd_rawmidi_info __user *info = argp;
961 
962 		if (get_user(stream, &info->stream))
963 			return -EFAULT;
964 		switch (stream) {
965 		case SNDRV_RAWMIDI_STREAM_INPUT:
966 			return snd_rawmidi_info_user(rfile->input, info);
967 		case SNDRV_RAWMIDI_STREAM_OUTPUT:
968 			return snd_rawmidi_info_user(rfile->output, info);
969 		default:
970 			return -EINVAL;
971 		}
972 	}
973 	case SNDRV_RAWMIDI_IOCTL_USER_PVERSION:
974 		if (get_user(rfile->user_pversion, (unsigned int __user *)arg))
975 			return -EFAULT;
976 		return 0;
977 
978 	case SNDRV_RAWMIDI_IOCTL_PARAMS:
979 	{
980 		struct snd_rawmidi_params params;
981 
982 		if (copy_from_user(&params, argp, sizeof(struct snd_rawmidi_params)))
983 			return -EFAULT;
984 		if (rfile->user_pversion < SNDRV_PROTOCOL_VERSION(2, 0, 2)) {
985 			params.mode = 0;
986 			memset(params.reserved, 0, sizeof(params.reserved));
987 		}
988 		switch (params.stream) {
989 		case SNDRV_RAWMIDI_STREAM_OUTPUT:
990 			if (rfile->output == NULL)
991 				return -EINVAL;
992 			return snd_rawmidi_output_params(rfile->output, &params);
993 		case SNDRV_RAWMIDI_STREAM_INPUT:
994 			if (rfile->input == NULL)
995 				return -EINVAL;
996 			return snd_rawmidi_input_params(rfile->input, &params);
997 		default:
998 			return -EINVAL;
999 		}
1000 	}
1001 	case SNDRV_RAWMIDI_IOCTL_STATUS32:
1002 		return snd_rawmidi_ioctl_status32(rfile, argp);
1003 	case SNDRV_RAWMIDI_IOCTL_STATUS64:
1004 		return snd_rawmidi_ioctl_status64(rfile, argp);
1005 	case SNDRV_RAWMIDI_IOCTL_DROP:
1006 	{
1007 		int val;
1008 
1009 		if (get_user(val, (int __user *) argp))
1010 			return -EFAULT;
1011 		switch (val) {
1012 		case SNDRV_RAWMIDI_STREAM_OUTPUT:
1013 			if (rfile->output == NULL)
1014 				return -EINVAL;
1015 			return snd_rawmidi_drop_output(rfile->output);
1016 		default:
1017 			return -EINVAL;
1018 		}
1019 	}
1020 	case SNDRV_RAWMIDI_IOCTL_DRAIN:
1021 	{
1022 		int val;
1023 
1024 		if (get_user(val, (int __user *) argp))
1025 			return -EFAULT;
1026 		switch (val) {
1027 		case SNDRV_RAWMIDI_STREAM_OUTPUT:
1028 			if (rfile->output == NULL)
1029 				return -EINVAL;
1030 			return snd_rawmidi_drain_output(rfile->output);
1031 		case SNDRV_RAWMIDI_STREAM_INPUT:
1032 			if (rfile->input == NULL)
1033 				return -EINVAL;
1034 			return snd_rawmidi_drain_input(rfile->input);
1035 		default:
1036 			return -EINVAL;
1037 		}
1038 	}
1039 	default:
1040 		rmidi = rfile->rmidi;
1041 		if (rmidi->ops && rmidi->ops->ioctl)
1042 			return rmidi->ops->ioctl(rmidi, cmd, argp);
1043 		rmidi_dbg(rmidi, "rawmidi: unknown command = 0x%x\n", cmd);
1044 	}
1045 	return -ENOTTY;
1046 }
1047 
1048 /* ioctl to find the next device; either legacy or UMP depending on @find_ump */
1049 static int snd_rawmidi_next_device(struct snd_card *card, int __user *argp,
1050 				   bool find_ump)
1051 
1052 {
1053 	struct snd_rawmidi *rmidi;
1054 	int device;
1055 	bool is_ump;
1056 
1057 	if (get_user(device, argp))
1058 		return -EFAULT;
1059 	if (device >= SNDRV_RAWMIDI_DEVICES) /* next device is -1 */
1060 		device = SNDRV_RAWMIDI_DEVICES - 1;
1061 	scoped_guard(mutex, &register_mutex) {
1062 		device = device < 0 ? 0 : device + 1;
1063 		for (; device < SNDRV_RAWMIDI_DEVICES; device++) {
1064 			rmidi = snd_rawmidi_search(card, device);
1065 			if (!rmidi)
1066 				continue;
1067 			is_ump = rawmidi_is_ump(rmidi);
1068 			if (find_ump == is_ump)
1069 				break;
1070 		}
1071 		if (device == SNDRV_RAWMIDI_DEVICES)
1072 			device = -1;
1073 	}
1074 	if (put_user(device, argp))
1075 		return -EFAULT;
1076 	return 0;
1077 }
1078 
1079 #if IS_ENABLED(CONFIG_SND_UMP)
1080 /* inquiry of UMP endpoint and block info via control API */
1081 static int snd_rawmidi_call_ump_ioctl(struct snd_card *card, int cmd,
1082 				      void __user *argp)
1083 {
1084 	struct snd_ump_endpoint_info __user *info = argp;
1085 	struct snd_rawmidi *rmidi;
1086 	int device;
1087 
1088 	if (get_user(device, &info->device))
1089 		return -EFAULT;
1090 	guard(mutex)(&register_mutex);
1091 	rmidi = snd_rawmidi_search(card, device);
1092 	if (rmidi && rmidi->ops && rmidi->ops->ioctl)
1093 		return rmidi->ops->ioctl(rmidi, cmd, argp);
1094 	else
1095 		return -ENXIO;
1096 }
1097 #endif
1098 
1099 static int snd_rawmidi_control_ioctl(struct snd_card *card,
1100 				     struct snd_ctl_file *control,
1101 				     unsigned int cmd,
1102 				     unsigned long arg)
1103 {
1104 	void __user *argp = (void __user *)arg;
1105 
1106 	switch (cmd) {
1107 	case SNDRV_CTL_IOCTL_RAWMIDI_NEXT_DEVICE:
1108 		return snd_rawmidi_next_device(card, argp, false);
1109 #if IS_ENABLED(CONFIG_SND_UMP)
1110 	case SNDRV_CTL_IOCTL_UMP_NEXT_DEVICE:
1111 		return snd_rawmidi_next_device(card, argp, true);
1112 	case SNDRV_CTL_IOCTL_UMP_ENDPOINT_INFO:
1113 		return snd_rawmidi_call_ump_ioctl(card, SNDRV_UMP_IOCTL_ENDPOINT_INFO, argp);
1114 	case SNDRV_CTL_IOCTL_UMP_BLOCK_INFO:
1115 		return snd_rawmidi_call_ump_ioctl(card, SNDRV_UMP_IOCTL_BLOCK_INFO, argp);
1116 #endif
1117 	case SNDRV_CTL_IOCTL_RAWMIDI_PREFER_SUBDEVICE:
1118 	{
1119 		int val;
1120 
1121 		if (get_user(val, (int __user *)argp))
1122 			return -EFAULT;
1123 		control->preferred_subdevice[SND_CTL_SUBDEV_RAWMIDI] = val;
1124 		return 0;
1125 	}
1126 	case SNDRV_CTL_IOCTL_RAWMIDI_INFO:
1127 		return snd_rawmidi_info_select_user(card, argp);
1128 	}
1129 	return -ENOIOCTLCMD;
1130 }
1131 
1132 static int receive_with_tstamp_framing(struct snd_rawmidi_substream *substream,
1133 			const unsigned char *buffer, int src_count, const struct timespec64 *tstamp)
1134 {
1135 	struct snd_rawmidi_runtime *runtime = substream->runtime;
1136 	struct snd_rawmidi_framing_tstamp *dest_ptr;
1137 	struct snd_rawmidi_framing_tstamp frame = { .tv_sec = tstamp->tv_sec, .tv_nsec = tstamp->tv_nsec };
1138 	int orig_count = src_count;
1139 	int frame_size = sizeof(struct snd_rawmidi_framing_tstamp);
1140 	int align = get_align(runtime);
1141 
1142 	BUILD_BUG_ON(frame_size != 0x20);
1143 	if (snd_BUG_ON((runtime->hw_ptr & 0x1f) != 0))
1144 		return -EINVAL;
1145 
1146 	while (src_count > align) {
1147 		if ((int)(runtime->buffer_size - runtime->avail) < frame_size) {
1148 			runtime->xruns += src_count;
1149 			break;
1150 		}
1151 		if (src_count >= SNDRV_RAWMIDI_FRAMING_DATA_LENGTH)
1152 			frame.length = SNDRV_RAWMIDI_FRAMING_DATA_LENGTH;
1153 		else {
1154 			frame.length = get_aligned_size(runtime, src_count);
1155 			if (!frame.length)
1156 				break;
1157 			memset(frame.data, 0, SNDRV_RAWMIDI_FRAMING_DATA_LENGTH);
1158 		}
1159 		memcpy(frame.data, buffer, frame.length);
1160 		buffer += frame.length;
1161 		src_count -= frame.length;
1162 		dest_ptr = (struct snd_rawmidi_framing_tstamp *) (runtime->buffer + runtime->hw_ptr);
1163 		*dest_ptr = frame;
1164 		runtime->avail += frame_size;
1165 		runtime->hw_ptr += frame_size;
1166 		runtime->hw_ptr %= runtime->buffer_size;
1167 	}
1168 	return orig_count - src_count;
1169 }
1170 
1171 static struct timespec64 get_framing_tstamp(struct snd_rawmidi_substream *substream)
1172 {
1173 	struct timespec64 ts64 = {0, 0};
1174 
1175 	switch (substream->clock_type) {
1176 	case SNDRV_RAWMIDI_MODE_CLOCK_MONOTONIC_RAW:
1177 		ktime_get_raw_ts64(&ts64);
1178 		break;
1179 	case SNDRV_RAWMIDI_MODE_CLOCK_MONOTONIC:
1180 		ktime_get_ts64(&ts64);
1181 		break;
1182 	case SNDRV_RAWMIDI_MODE_CLOCK_REALTIME:
1183 		ktime_get_real_ts64(&ts64);
1184 		break;
1185 	}
1186 	return ts64;
1187 }
1188 
1189 /**
1190  * snd_rawmidi_receive - receive the input data from the device
1191  * @substream: the rawmidi substream
1192  * @buffer: the buffer pointer
1193  * @count: the data size to read
1194  *
1195  * Reads the data from the internal buffer.
1196  *
1197  * Return: The size of read data, or a negative error code on failure.
1198  */
1199 int snd_rawmidi_receive(struct snd_rawmidi_substream *substream,
1200 			const unsigned char *buffer, int count)
1201 {
1202 	struct timespec64 ts64 = get_framing_tstamp(substream);
1203 	int result = 0, count1;
1204 	struct snd_rawmidi_runtime *runtime;
1205 
1206 	guard(spinlock_irqsave)(&substream->lock);
1207 	if (!substream->opened || substream->disconnected)
1208 		return -EBADFD;
1209 	runtime = substream->runtime;
1210 	if (!runtime || !runtime->buffer) {
1211 		rmidi_dbg(substream->rmidi,
1212 			  "snd_rawmidi_receive: input is not active!!!\n");
1213 		return -EINVAL;
1214 	}
1215 
1216 	count = get_aligned_size(runtime, count);
1217 	if (!count)
1218 		return result;
1219 
1220 	if (substream->framing == SNDRV_RAWMIDI_MODE_FRAMING_TSTAMP) {
1221 		result = receive_with_tstamp_framing(substream, buffer, count, &ts64);
1222 	} else if (count == 1) {	/* special case, faster code */
1223 		substream->bytes++;
1224 		if (runtime->avail < runtime->buffer_size) {
1225 			runtime->buffer[runtime->hw_ptr++] = buffer[0];
1226 			runtime->hw_ptr %= runtime->buffer_size;
1227 			runtime->avail++;
1228 			result++;
1229 		} else {
1230 			runtime->xruns++;
1231 		}
1232 	} else {
1233 		substream->bytes += count;
1234 		count1 = runtime->buffer_size - runtime->hw_ptr;
1235 		if (count1 > count)
1236 			count1 = count;
1237 		if (count1 > (int)(runtime->buffer_size - runtime->avail))
1238 			count1 = runtime->buffer_size - runtime->avail;
1239 		count1 = get_aligned_size(runtime, count1);
1240 		if (!count1)
1241 			return result;
1242 		memcpy(runtime->buffer + runtime->hw_ptr, buffer, count1);
1243 		runtime->hw_ptr += count1;
1244 		runtime->hw_ptr %= runtime->buffer_size;
1245 		runtime->avail += count1;
1246 		count -= count1;
1247 		result += count1;
1248 		if (count > 0) {
1249 			buffer += count1;
1250 			count1 = count;
1251 			if (count1 > (int)(runtime->buffer_size - runtime->avail)) {
1252 				count1 = runtime->buffer_size - runtime->avail;
1253 				runtime->xruns += count - count1;
1254 			}
1255 			if (count1 > 0) {
1256 				memcpy(runtime->buffer, buffer, count1);
1257 				runtime->hw_ptr = count1;
1258 				runtime->avail += count1;
1259 				result += count1;
1260 			}
1261 		}
1262 	}
1263 	if (result > 0) {
1264 		if (runtime->event)
1265 			schedule_work(&runtime->event_work);
1266 		else if (__snd_rawmidi_ready(runtime))
1267 			wake_up(&runtime->sleep);
1268 	}
1269 	return result;
1270 }
1271 EXPORT_SYMBOL(snd_rawmidi_receive);
1272 
1273 static long snd_rawmidi_kernel_read1(struct snd_rawmidi_substream *substream,
1274 				     unsigned char __user *userbuf,
1275 				     unsigned char *kernelbuf, long count)
1276 {
1277 	unsigned long flags;
1278 	long result = 0, count1;
1279 	struct snd_rawmidi_runtime *runtime = substream->runtime;
1280 	unsigned long appl_ptr;
1281 	int err = 0;
1282 
1283 	spin_lock_irqsave(&substream->lock, flags);
1284 	snd_rawmidi_buffer_ref(runtime);
1285 	while (count > 0 && runtime->avail) {
1286 		count1 = runtime->buffer_size - runtime->appl_ptr;
1287 		if (count1 > count)
1288 			count1 = count;
1289 		if (count1 > (int)runtime->avail)
1290 			count1 = runtime->avail;
1291 
1292 		/* update runtime->appl_ptr before unlocking for userbuf */
1293 		appl_ptr = runtime->appl_ptr;
1294 		runtime->appl_ptr += count1;
1295 		runtime->appl_ptr %= runtime->buffer_size;
1296 		runtime->avail -= count1;
1297 
1298 		if (kernelbuf)
1299 			memcpy(kernelbuf + result, runtime->buffer + appl_ptr, count1);
1300 		if (userbuf) {
1301 			spin_unlock_irqrestore(&substream->lock, flags);
1302 			if (copy_to_user(userbuf + result,
1303 					 runtime->buffer + appl_ptr, count1))
1304 				err = -EFAULT;
1305 			spin_lock_irqsave(&substream->lock, flags);
1306 			if (err)
1307 				goto out;
1308 		}
1309 		result += count1;
1310 		count -= count1;
1311 	}
1312  out:
1313 	snd_rawmidi_buffer_unref(runtime);
1314 	spin_unlock_irqrestore(&substream->lock, flags);
1315 	return result > 0 ? result : err;
1316 }
1317 
1318 long snd_rawmidi_kernel_read(struct snd_rawmidi_substream *substream,
1319 			     unsigned char *buf, long count)
1320 {
1321 	snd_rawmidi_input_trigger(substream, 1);
1322 	return snd_rawmidi_kernel_read1(substream, NULL/*userbuf*/, buf, count);
1323 }
1324 EXPORT_SYMBOL(snd_rawmidi_kernel_read);
1325 
1326 static ssize_t snd_rawmidi_read(struct file *file, char __user *buf, size_t count,
1327 				loff_t *offset)
1328 {
1329 	long result;
1330 	int count1;
1331 	struct snd_rawmidi_file *rfile;
1332 	struct snd_rawmidi_substream *substream;
1333 	struct snd_rawmidi_runtime *runtime;
1334 
1335 	rfile = file->private_data;
1336 	substream = rfile->input;
1337 	if (substream == NULL)
1338 		return -EIO;
1339 	runtime = substream->runtime;
1340 	snd_rawmidi_input_trigger(substream, 1);
1341 	result = 0;
1342 	while (count > 0) {
1343 		spin_lock_irq(&substream->lock);
1344 		while (!__snd_rawmidi_ready(runtime)) {
1345 			wait_queue_entry_t wait;
1346 
1347 			if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
1348 				spin_unlock_irq(&substream->lock);
1349 				return result > 0 ? result : -EAGAIN;
1350 			}
1351 			init_waitqueue_entry(&wait, current);
1352 			add_wait_queue(&runtime->sleep, &wait);
1353 			set_current_state(TASK_INTERRUPTIBLE);
1354 			spin_unlock_irq(&substream->lock);
1355 			schedule();
1356 			remove_wait_queue(&runtime->sleep, &wait);
1357 			if (rfile->rmidi->card->shutdown)
1358 				return -ENODEV;
1359 			if (signal_pending(current))
1360 				return result > 0 ? result : -ERESTARTSYS;
1361 			spin_lock_irq(&substream->lock);
1362 			if (!runtime->avail) {
1363 				spin_unlock_irq(&substream->lock);
1364 				return result > 0 ? result : -EIO;
1365 			}
1366 		}
1367 		spin_unlock_irq(&substream->lock);
1368 		count1 = snd_rawmidi_kernel_read1(substream,
1369 						  (unsigned char __user *)buf,
1370 						  NULL/*kernelbuf*/,
1371 						  count);
1372 		if (count1 < 0)
1373 			return result > 0 ? result : count1;
1374 		result += count1;
1375 		buf += count1;
1376 		count -= count1;
1377 	}
1378 	return result;
1379 }
1380 
1381 /**
1382  * snd_rawmidi_transmit_empty - check whether the output buffer is empty
1383  * @substream: the rawmidi substream
1384  *
1385  * Return: 1 if the internal output buffer is empty, 0 if not.
1386  */
1387 int snd_rawmidi_transmit_empty(struct snd_rawmidi_substream *substream)
1388 {
1389 	struct snd_rawmidi_runtime *runtime;
1390 
1391 	guard(spinlock_irqsave)(&substream->lock);
1392 	runtime = substream->runtime;
1393 	if (!substream->opened || !runtime || !runtime->buffer) {
1394 		rmidi_dbg(substream->rmidi,
1395 			  "snd_rawmidi_transmit_empty: output is not active!!!\n");
1396 		return 1;
1397 	}
1398 	return (runtime->avail >= runtime->buffer_size);
1399 }
1400 EXPORT_SYMBOL(snd_rawmidi_transmit_empty);
1401 
1402 /*
1403  * __snd_rawmidi_transmit_peek - copy data from the internal buffer
1404  * @substream: the rawmidi substream
1405  * @buffer: the buffer pointer
1406  * @count: data size to transfer
1407  *
1408  * This is a variant of snd_rawmidi_transmit_peek() without spinlock.
1409  */
1410 static int __snd_rawmidi_transmit_peek(struct snd_rawmidi_substream *substream,
1411 				       unsigned char *buffer, int count)
1412 {
1413 	int result, count1;
1414 	struct snd_rawmidi_runtime *runtime = substream->runtime;
1415 
1416 	if (runtime->buffer == NULL) {
1417 		rmidi_dbg(substream->rmidi,
1418 			  "snd_rawmidi_transmit_peek: output is not active!!!\n");
1419 		return -EINVAL;
1420 	}
1421 	result = 0;
1422 	if (runtime->avail >= runtime->buffer_size) {
1423 		/* warning: lowlevel layer MUST trigger down the hardware */
1424 		goto __skip;
1425 	}
1426 	if (count == 1) {	/* special case, faster code */
1427 		*buffer = runtime->buffer[runtime->hw_ptr];
1428 		result++;
1429 	} else {
1430 		count1 = runtime->buffer_size - runtime->hw_ptr;
1431 		if (count1 > count)
1432 			count1 = count;
1433 		if (count1 > (int)(runtime->buffer_size - runtime->avail))
1434 			count1 = runtime->buffer_size - runtime->avail;
1435 		count1 = get_aligned_size(runtime, count1);
1436 		if (!count1)
1437 			goto __skip;
1438 		memcpy(buffer, runtime->buffer + runtime->hw_ptr, count1);
1439 		count -= count1;
1440 		result += count1;
1441 		if (count > 0) {
1442 			if (count > (int)(runtime->buffer_size - runtime->avail - count1))
1443 				count = runtime->buffer_size - runtime->avail - count1;
1444 			count = get_aligned_size(runtime, count);
1445 			if (!count)
1446 				goto __skip;
1447 			memcpy(buffer + count1, runtime->buffer, count);
1448 			result += count;
1449 		}
1450 	}
1451       __skip:
1452 	return result;
1453 }
1454 
1455 /**
1456  * snd_rawmidi_transmit_peek - copy data from the internal buffer
1457  * @substream: the rawmidi substream
1458  * @buffer: the buffer pointer
1459  * @count: data size to transfer
1460  *
1461  * Copies data from the internal output buffer to the given buffer.
1462  *
1463  * Call this in the interrupt handler when the midi output is ready,
1464  * and call snd_rawmidi_transmit_ack() after the transmission is
1465  * finished.
1466  *
1467  * Return: The size of copied data, or a negative error code on failure.
1468  */
1469 int snd_rawmidi_transmit_peek(struct snd_rawmidi_substream *substream,
1470 			      unsigned char *buffer, int count)
1471 {
1472 	guard(spinlock_irqsave)(&substream->lock);
1473 	if (!substream->opened || !substream->runtime)
1474 		return -EBADFD;
1475 	return __snd_rawmidi_transmit_peek(substream, buffer, count);
1476 }
1477 EXPORT_SYMBOL(snd_rawmidi_transmit_peek);
1478 
1479 /*
1480  * __snd_rawmidi_transmit_ack - acknowledge the transmission
1481  * @substream: the rawmidi substream
1482  * @count: the transferred count
1483  *
1484  * This is a variant of __snd_rawmidi_transmit_ack() without spinlock.
1485  */
1486 static int __snd_rawmidi_transmit_ack(struct snd_rawmidi_substream *substream,
1487 				      int count)
1488 {
1489 	struct snd_rawmidi_runtime *runtime = substream->runtime;
1490 
1491 	if (runtime->buffer == NULL) {
1492 		rmidi_dbg(substream->rmidi,
1493 			  "snd_rawmidi_transmit_ack: output is not active!!!\n");
1494 		return -EINVAL;
1495 	}
1496 	snd_BUG_ON(runtime->avail + count > runtime->buffer_size);
1497 	count = get_aligned_size(runtime, count);
1498 	runtime->hw_ptr += count;
1499 	runtime->hw_ptr %= runtime->buffer_size;
1500 	runtime->avail += count;
1501 	substream->bytes += count;
1502 	if (count > 0) {
1503 		if (runtime->drain || __snd_rawmidi_ready(runtime))
1504 			wake_up(&runtime->sleep);
1505 	}
1506 	return count;
1507 }
1508 
1509 /**
1510  * snd_rawmidi_transmit_ack - acknowledge the transmission
1511  * @substream: the rawmidi substream
1512  * @count: the transferred count
1513  *
1514  * Advances the hardware pointer for the internal output buffer with
1515  * the given size and updates the condition.
1516  * Call after the transmission is finished.
1517  *
1518  * Return: The advanced size if successful, or a negative error code on failure.
1519  */
1520 int snd_rawmidi_transmit_ack(struct snd_rawmidi_substream *substream, int count)
1521 {
1522 	guard(spinlock_irqsave)(&substream->lock);
1523 	if (!substream->opened || !substream->runtime)
1524 		return -EBADFD;
1525 	return __snd_rawmidi_transmit_ack(substream, count);
1526 }
1527 EXPORT_SYMBOL(snd_rawmidi_transmit_ack);
1528 
1529 /**
1530  * snd_rawmidi_transmit - copy from the buffer to the device
1531  * @substream: the rawmidi substream
1532  * @buffer: the buffer pointer
1533  * @count: the data size to transfer
1534  *
1535  * Copies data from the buffer to the device and advances the pointer.
1536  *
1537  * Return: The copied size if successful, or a negative error code on failure.
1538  */
1539 int snd_rawmidi_transmit(struct snd_rawmidi_substream *substream,
1540 			 unsigned char *buffer, int count)
1541 {
1542 	guard(spinlock_irqsave)(&substream->lock);
1543 	if (!substream->opened)
1544 		return -EBADFD;
1545 	count = __snd_rawmidi_transmit_peek(substream, buffer, count);
1546 	if (count <= 0)
1547 		return count;
1548 	return __snd_rawmidi_transmit_ack(substream, count);
1549 }
1550 EXPORT_SYMBOL(snd_rawmidi_transmit);
1551 
1552 /**
1553  * snd_rawmidi_proceed - Discard the all pending bytes and proceed
1554  * @substream: rawmidi substream
1555  *
1556  * Return: the number of discarded bytes
1557  */
1558 int snd_rawmidi_proceed(struct snd_rawmidi_substream *substream)
1559 {
1560 	struct snd_rawmidi_runtime *runtime;
1561 	int count = 0;
1562 
1563 	guard(spinlock_irqsave)(&substream->lock);
1564 	runtime = substream->runtime;
1565 	if (substream->opened && runtime &&
1566 	    runtime->avail < runtime->buffer_size) {
1567 		count = runtime->buffer_size - runtime->avail;
1568 		__snd_rawmidi_transmit_ack(substream, count);
1569 	}
1570 	return count;
1571 }
1572 EXPORT_SYMBOL(snd_rawmidi_proceed);
1573 
1574 static long snd_rawmidi_kernel_write1(struct snd_rawmidi_substream *substream,
1575 				      const unsigned char __user *userbuf,
1576 				      const unsigned char *kernelbuf,
1577 				      long count)
1578 {
1579 	unsigned long flags;
1580 	long count1, result;
1581 	struct snd_rawmidi_runtime *runtime = substream->runtime;
1582 	unsigned long appl_ptr;
1583 
1584 	if (!kernelbuf && !userbuf)
1585 		return -EINVAL;
1586 	if (snd_BUG_ON(!runtime->buffer))
1587 		return -EINVAL;
1588 
1589 	result = 0;
1590 	spin_lock_irqsave(&substream->lock, flags);
1591 	if (substream->append) {
1592 		if ((long)runtime->avail < count) {
1593 			spin_unlock_irqrestore(&substream->lock, flags);
1594 			return -EAGAIN;
1595 		}
1596 	}
1597 	snd_rawmidi_buffer_ref(runtime);
1598 	while (count > 0 && runtime->avail > 0) {
1599 		count1 = runtime->buffer_size - runtime->appl_ptr;
1600 		if (count1 > count)
1601 			count1 = count;
1602 		if (count1 > (long)runtime->avail)
1603 			count1 = runtime->avail;
1604 
1605 		/* update runtime->appl_ptr before unlocking for userbuf */
1606 		appl_ptr = runtime->appl_ptr;
1607 		runtime->appl_ptr += count1;
1608 		runtime->appl_ptr %= runtime->buffer_size;
1609 		runtime->avail -= count1;
1610 
1611 		if (kernelbuf)
1612 			memcpy(runtime->buffer + appl_ptr,
1613 			       kernelbuf + result, count1);
1614 		else if (userbuf) {
1615 			spin_unlock_irqrestore(&substream->lock, flags);
1616 			if (copy_from_user(runtime->buffer + appl_ptr,
1617 					   userbuf + result, count1)) {
1618 				spin_lock_irqsave(&substream->lock, flags);
1619 				result = result > 0 ? result : -EFAULT;
1620 				goto __end;
1621 			}
1622 			spin_lock_irqsave(&substream->lock, flags);
1623 		}
1624 		result += count1;
1625 		count -= count1;
1626 	}
1627       __end:
1628 	count1 = runtime->avail < runtime->buffer_size;
1629 	snd_rawmidi_buffer_unref(runtime);
1630 	spin_unlock_irqrestore(&substream->lock, flags);
1631 	if (count1)
1632 		snd_rawmidi_output_trigger(substream, 1);
1633 	return result;
1634 }
1635 
1636 long snd_rawmidi_kernel_write(struct snd_rawmidi_substream *substream,
1637 			      const unsigned char *buf, long count)
1638 {
1639 	return snd_rawmidi_kernel_write1(substream, NULL, buf, count);
1640 }
1641 EXPORT_SYMBOL(snd_rawmidi_kernel_write);
1642 
1643 static ssize_t snd_rawmidi_write(struct file *file, const char __user *buf,
1644 				 size_t count, loff_t *offset)
1645 {
1646 	long result, timeout;
1647 	int count1;
1648 	struct snd_rawmidi_file *rfile;
1649 	struct snd_rawmidi_runtime *runtime;
1650 	struct snd_rawmidi_substream *substream;
1651 
1652 	rfile = file->private_data;
1653 	substream = rfile->output;
1654 	runtime = substream->runtime;
1655 	/* we cannot put an atomic message to our buffer */
1656 	if (substream->append && count > runtime->buffer_size)
1657 		return -EIO;
1658 	result = 0;
1659 	while (count > 0) {
1660 		spin_lock_irq(&substream->lock);
1661 		while (!snd_rawmidi_ready_append(substream, count)) {
1662 			wait_queue_entry_t wait;
1663 
1664 			if (file->f_flags & O_NONBLOCK) {
1665 				spin_unlock_irq(&substream->lock);
1666 				return result > 0 ? result : -EAGAIN;
1667 			}
1668 			init_waitqueue_entry(&wait, current);
1669 			add_wait_queue(&runtime->sleep, &wait);
1670 			set_current_state(TASK_INTERRUPTIBLE);
1671 			spin_unlock_irq(&substream->lock);
1672 			timeout = schedule_timeout(30 * HZ);
1673 			remove_wait_queue(&runtime->sleep, &wait);
1674 			if (rfile->rmidi->card->shutdown)
1675 				return -ENODEV;
1676 			if (signal_pending(current))
1677 				return result > 0 ? result : -ERESTARTSYS;
1678 			spin_lock_irq(&substream->lock);
1679 			if (!runtime->avail && !timeout) {
1680 				spin_unlock_irq(&substream->lock);
1681 				return result > 0 ? result : -EIO;
1682 			}
1683 		}
1684 		spin_unlock_irq(&substream->lock);
1685 		count1 = snd_rawmidi_kernel_write1(substream, buf, NULL, count);
1686 		if (count1 < 0)
1687 			return result > 0 ? result : count1;
1688 		result += count1;
1689 		buf += count1;
1690 		if ((size_t)count1 < count && (file->f_flags & O_NONBLOCK))
1691 			break;
1692 		count -= count1;
1693 	}
1694 	if (file->f_flags & O_DSYNC) {
1695 		spin_lock_irq(&substream->lock);
1696 		while (runtime->avail != runtime->buffer_size) {
1697 			wait_queue_entry_t wait;
1698 			unsigned int last_avail = runtime->avail;
1699 
1700 			init_waitqueue_entry(&wait, current);
1701 			add_wait_queue(&runtime->sleep, &wait);
1702 			set_current_state(TASK_INTERRUPTIBLE);
1703 			spin_unlock_irq(&substream->lock);
1704 			timeout = schedule_timeout(30 * HZ);
1705 			remove_wait_queue(&runtime->sleep, &wait);
1706 			if (signal_pending(current))
1707 				return result > 0 ? result : -ERESTARTSYS;
1708 			if (runtime->avail == last_avail && !timeout)
1709 				return result > 0 ? result : -EIO;
1710 			spin_lock_irq(&substream->lock);
1711 		}
1712 		spin_unlock_irq(&substream->lock);
1713 	}
1714 	return result;
1715 }
1716 
1717 static __poll_t snd_rawmidi_poll(struct file *file, poll_table *wait)
1718 {
1719 	struct snd_rawmidi_file *rfile;
1720 	struct snd_rawmidi_runtime *runtime;
1721 	__poll_t mask;
1722 
1723 	rfile = file->private_data;
1724 	if (rfile->input != NULL) {
1725 		runtime = rfile->input->runtime;
1726 		snd_rawmidi_input_trigger(rfile->input, 1);
1727 		poll_wait(file, &runtime->sleep, wait);
1728 	}
1729 	if (rfile->output != NULL) {
1730 		runtime = rfile->output->runtime;
1731 		poll_wait(file, &runtime->sleep, wait);
1732 	}
1733 	mask = 0;
1734 	if (rfile->input != NULL) {
1735 		if (snd_rawmidi_ready(rfile->input))
1736 			mask |= EPOLLIN | EPOLLRDNORM;
1737 	}
1738 	if (rfile->output != NULL) {
1739 		if (snd_rawmidi_ready(rfile->output))
1740 			mask |= EPOLLOUT | EPOLLWRNORM;
1741 	}
1742 	return mask;
1743 }
1744 
1745 /*
1746  */
1747 #ifdef CONFIG_COMPAT
1748 #include "rawmidi_compat.c"
1749 #else
1750 #define snd_rawmidi_ioctl_compat	NULL
1751 #endif
1752 
1753 /*
1754  */
1755 
1756 static void snd_rawmidi_proc_info_read(struct snd_info_entry *entry,
1757 				       struct snd_info_buffer *buffer)
1758 {
1759 	struct snd_rawmidi *rmidi;
1760 	struct snd_rawmidi_substream *substream;
1761 	struct snd_rawmidi_runtime *runtime;
1762 	unsigned long buffer_size, avail, xruns;
1763 	unsigned int clock_type;
1764 	static const char *clock_names[4] = { "none", "realtime", "monotonic", "monotonic raw" };
1765 
1766 	rmidi = entry->private_data;
1767 	snd_iprintf(buffer, "%s\n\n", rmidi->name);
1768 	if (IS_ENABLED(CONFIG_SND_UMP))
1769 		snd_iprintf(buffer, "Type: %s\n",
1770 			    rawmidi_is_ump(rmidi) ? "UMP" : "Legacy");
1771 	if (rmidi->ops && rmidi->ops->proc_read)
1772 		rmidi->ops->proc_read(entry, buffer);
1773 	guard(mutex)(&rmidi->open_mutex);
1774 	if (rmidi->info_flags & SNDRV_RAWMIDI_INFO_OUTPUT) {
1775 		list_for_each_entry(substream,
1776 				    &rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT].substreams,
1777 				    list) {
1778 			snd_iprintf(buffer,
1779 				    "Output %d\n"
1780 				    "  Tx bytes     : %lu\n",
1781 				    substream->number,
1782 				    (unsigned long) substream->bytes);
1783 			if (substream->opened) {
1784 				snd_iprintf(buffer,
1785 				    "  Owner PID    : %d\n",
1786 				    pid_vnr(substream->pid));
1787 				runtime = substream->runtime;
1788 				scoped_guard(spinlock_irq, &substream->lock) {
1789 					buffer_size = runtime->buffer_size;
1790 					avail = runtime->avail;
1791 				}
1792 				snd_iprintf(buffer,
1793 				    "  Mode         : %s\n"
1794 				    "  Buffer size  : %lu\n"
1795 				    "  Avail        : %lu\n",
1796 				    runtime->oss ? "OSS compatible" : "native",
1797 				    buffer_size, avail);
1798 			}
1799 		}
1800 	}
1801 	if (rmidi->info_flags & SNDRV_RAWMIDI_INFO_INPUT) {
1802 		list_for_each_entry(substream,
1803 				    &rmidi->streams[SNDRV_RAWMIDI_STREAM_INPUT].substreams,
1804 				    list) {
1805 			snd_iprintf(buffer,
1806 				    "Input %d\n"
1807 				    "  Rx bytes     : %lu\n",
1808 				    substream->number,
1809 				    (unsigned long) substream->bytes);
1810 			if (substream->opened) {
1811 				snd_iprintf(buffer,
1812 					    "  Owner PID    : %d\n",
1813 					    pid_vnr(substream->pid));
1814 				runtime = substream->runtime;
1815 				scoped_guard(spinlock_irq, &substream->lock) {
1816 					buffer_size = runtime->buffer_size;
1817 					avail = runtime->avail;
1818 					xruns = runtime->xruns;
1819 				}
1820 				snd_iprintf(buffer,
1821 					    "  Buffer size  : %lu\n"
1822 					    "  Avail        : %lu\n"
1823 					    "  Overruns     : %lu\n",
1824 					    buffer_size, avail, xruns);
1825 				if (substream->framing == SNDRV_RAWMIDI_MODE_FRAMING_TSTAMP) {
1826 					clock_type = substream->clock_type >> SNDRV_RAWMIDI_MODE_CLOCK_SHIFT;
1827 					if (!snd_BUG_ON(clock_type >= ARRAY_SIZE(clock_names)))
1828 						snd_iprintf(buffer,
1829 							    "  Framing      : tstamp\n"
1830 							    "  Clock type   : %s\n",
1831 							    clock_names[clock_type]);
1832 				}
1833 			}
1834 		}
1835 	}
1836 }
1837 
1838 /*
1839  *  Register functions
1840  */
1841 
1842 static const struct file_operations snd_rawmidi_f_ops = {
1843 	.owner		=	THIS_MODULE,
1844 	.read		=	snd_rawmidi_read,
1845 	.write		=	snd_rawmidi_write,
1846 	.open		=	snd_rawmidi_open,
1847 	.release	=	snd_rawmidi_release,
1848 	.poll		=	snd_rawmidi_poll,
1849 	.unlocked_ioctl	=	snd_rawmidi_ioctl,
1850 	.compat_ioctl	=	snd_rawmidi_ioctl_compat,
1851 };
1852 
1853 static int snd_rawmidi_alloc_substreams(struct snd_rawmidi *rmidi,
1854 					struct snd_rawmidi_str *stream,
1855 					int direction,
1856 					int count)
1857 {
1858 	struct snd_rawmidi_substream *substream;
1859 	int idx;
1860 
1861 	for (idx = 0; idx < count; idx++) {
1862 		substream = kzalloc_obj(*substream);
1863 		if (!substream)
1864 			return -ENOMEM;
1865 		substream->stream = direction;
1866 		substream->number = idx;
1867 		substream->rmidi = rmidi;
1868 		substream->pstr = stream;
1869 		spin_lock_init(&substream->lock);
1870 		list_add_tail(&substream->list, &stream->substreams);
1871 		stream->substream_count++;
1872 	}
1873 	return 0;
1874 }
1875 
1876 /* used for both rawmidi and ump */
1877 int snd_rawmidi_init(struct snd_rawmidi *rmidi,
1878 		     struct snd_card *card, char *id, int device,
1879 		     int output_count, int input_count,
1880 		     unsigned int info_flags)
1881 {
1882 	int err;
1883 	static const struct snd_device_ops ops = {
1884 		.dev_free = snd_rawmidi_dev_free,
1885 		.dev_register = snd_rawmidi_dev_register,
1886 		.dev_disconnect = snd_rawmidi_dev_disconnect,
1887 	};
1888 
1889 	rmidi->card = card;
1890 	rmidi->device = device;
1891 	mutex_init(&rmidi->open_mutex);
1892 	init_waitqueue_head(&rmidi->open_wait);
1893 	INIT_LIST_HEAD(&rmidi->streams[SNDRV_RAWMIDI_STREAM_INPUT].substreams);
1894 	INIT_LIST_HEAD(&rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT].substreams);
1895 	rmidi->info_flags = info_flags;
1896 
1897 	if (id != NULL)
1898 		strscpy(rmidi->id, id, sizeof(rmidi->id));
1899 
1900 	err = snd_device_alloc(&rmidi->dev, card);
1901 	if (err < 0)
1902 		return err;
1903 	if (rawmidi_is_ump(rmidi))
1904 		dev_set_name(rmidi->dev, "umpC%iD%i", card->number, device);
1905 	else
1906 		dev_set_name(rmidi->dev, "midiC%iD%i", card->number, device);
1907 
1908 	err = snd_rawmidi_alloc_substreams(rmidi,
1909 					   &rmidi->streams[SNDRV_RAWMIDI_STREAM_INPUT],
1910 					   SNDRV_RAWMIDI_STREAM_INPUT,
1911 					   input_count);
1912 	if (err < 0)
1913 		return err;
1914 	err = snd_rawmidi_alloc_substreams(rmidi,
1915 					   &rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT],
1916 					   SNDRV_RAWMIDI_STREAM_OUTPUT,
1917 					   output_count);
1918 	if (err < 0)
1919 		return err;
1920 	err = snd_device_new(card, SNDRV_DEV_RAWMIDI, rmidi, &ops);
1921 	if (err < 0)
1922 		return err;
1923 	return 0;
1924 }
1925 EXPORT_SYMBOL_GPL(snd_rawmidi_init);
1926 
1927 /**
1928  * snd_rawmidi_new - create a rawmidi instance
1929  * @card: the card instance
1930  * @id: the id string
1931  * @device: the device index
1932  * @output_count: the number of output streams
1933  * @input_count: the number of input streams
1934  * @rrawmidi: the pointer to store the new rawmidi instance
1935  *
1936  * Creates a new rawmidi instance.
1937  * Use snd_rawmidi_set_ops() to set the operators to the new instance.
1938  *
1939  * Return: Zero if successful, or a negative error code on failure.
1940  */
1941 int snd_rawmidi_new(struct snd_card *card, char *id, int device,
1942 		    int output_count, int input_count,
1943 		    struct snd_rawmidi **rrawmidi)
1944 {
1945 	struct snd_rawmidi *rmidi;
1946 	int err;
1947 
1948 	if (rrawmidi)
1949 		*rrawmidi = NULL;
1950 	rmidi = kzalloc_obj(*rmidi);
1951 	if (!rmidi)
1952 		return -ENOMEM;
1953 	err = snd_rawmidi_init(rmidi, card, id, device,
1954 			       output_count, input_count, 0);
1955 	if (err < 0) {
1956 		snd_rawmidi_free(rmidi);
1957 		return err;
1958 	}
1959 	if (rrawmidi)
1960 		*rrawmidi = rmidi;
1961 	return 0;
1962 }
1963 EXPORT_SYMBOL(snd_rawmidi_new);
1964 
1965 static void snd_rawmidi_free_substreams(struct snd_rawmidi_str *stream)
1966 {
1967 	struct snd_rawmidi_substream *substream;
1968 
1969 	while (!list_empty(&stream->substreams)) {
1970 		substream = list_entry(stream->substreams.next, struct snd_rawmidi_substream, list);
1971 		list_del(&substream->list);
1972 		kfree(substream);
1973 	}
1974 }
1975 
1976 /* called from ump.c, too */
1977 int snd_rawmidi_free(struct snd_rawmidi *rmidi)
1978 {
1979 	if (!rmidi)
1980 		return 0;
1981 
1982 	snd_info_free_entry(rmidi->proc_entry);
1983 	rmidi->proc_entry = NULL;
1984 	if (rmidi->ops && rmidi->ops->dev_unregister)
1985 		rmidi->ops->dev_unregister(rmidi);
1986 
1987 	snd_rawmidi_free_substreams(&rmidi->streams[SNDRV_RAWMIDI_STREAM_INPUT]);
1988 	snd_rawmidi_free_substreams(&rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT]);
1989 	if (rmidi->private_free)
1990 		rmidi->private_free(rmidi);
1991 	put_device(rmidi->dev);
1992 	kfree(rmidi);
1993 	return 0;
1994 }
1995 EXPORT_SYMBOL_GPL(snd_rawmidi_free);
1996 
1997 static int snd_rawmidi_dev_free(struct snd_device *device)
1998 {
1999 	struct snd_rawmidi *rmidi = device->device_data;
2000 
2001 	return snd_rawmidi_free(rmidi);
2002 }
2003 
2004 #if IS_ENABLED(CONFIG_SND_SEQUENCER)
2005 static void snd_rawmidi_dev_seq_free(struct snd_seq_device *device)
2006 {
2007 	struct snd_rawmidi *rmidi = device->private_data;
2008 
2009 	rmidi->seq_dev = NULL;
2010 }
2011 #endif
2012 
2013 static int snd_rawmidi_dev_register(struct snd_device *device)
2014 {
2015 	int err;
2016 	struct snd_info_entry *entry;
2017 	char name[16];
2018 	struct snd_rawmidi *rmidi = device->device_data;
2019 
2020 	if (rmidi->device >= SNDRV_RAWMIDI_DEVICES)
2021 		return -ENOMEM;
2022 	err = 0;
2023 	scoped_guard(mutex, &register_mutex) {
2024 		if (snd_rawmidi_search(rmidi->card, rmidi->device))
2025 			err = -EBUSY;
2026 		else
2027 			list_add_tail(&rmidi->list, &snd_rawmidi_devices);
2028 	}
2029 	if (err < 0)
2030 		return err;
2031 
2032 	err = snd_register_device(SNDRV_DEVICE_TYPE_RAWMIDI,
2033 				  rmidi->card, rmidi->device,
2034 				  &snd_rawmidi_f_ops, rmidi, rmidi->dev);
2035 	if (err < 0) {
2036 		rmidi_err(rmidi, "unable to register\n");
2037 		goto error;
2038 	}
2039 	if (rmidi->ops && rmidi->ops->dev_register) {
2040 		err = rmidi->ops->dev_register(rmidi);
2041 		if (err < 0)
2042 			goto error_unregister;
2043 	}
2044 #ifdef CONFIG_SND_OSSEMUL
2045 	rmidi->ossreg = 0;
2046 	if (!rawmidi_is_ump(rmidi) &&
2047 	    (int)rmidi->device == midi_map[rmidi->card->number]) {
2048 		if (snd_register_oss_device(SNDRV_OSS_DEVICE_TYPE_MIDI,
2049 					    rmidi->card, 0, &snd_rawmidi_f_ops,
2050 					    rmidi) < 0) {
2051 			rmidi_err(rmidi,
2052 				  "unable to register OSS rawmidi device %i:%i\n",
2053 				  rmidi->card->number, 0);
2054 		} else {
2055 			rmidi->ossreg++;
2056 #ifdef SNDRV_OSS_INFO_DEV_MIDI
2057 			snd_oss_info_register(SNDRV_OSS_INFO_DEV_MIDI, rmidi->card->number, rmidi->name);
2058 #endif
2059 		}
2060 	}
2061 	if (!rawmidi_is_ump(rmidi) &&
2062 	    (int)rmidi->device == amidi_map[rmidi->card->number]) {
2063 		if (snd_register_oss_device(SNDRV_OSS_DEVICE_TYPE_MIDI,
2064 					    rmidi->card, 1, &snd_rawmidi_f_ops,
2065 					    rmidi) < 0) {
2066 			rmidi_err(rmidi,
2067 				  "unable to register OSS rawmidi device %i:%i\n",
2068 				  rmidi->card->number, 1);
2069 		} else {
2070 			rmidi->ossreg++;
2071 		}
2072 	}
2073 #endif /* CONFIG_SND_OSSEMUL */
2074 	sprintf(name, "midi%d", rmidi->device);
2075 	entry = snd_info_create_card_entry(rmidi->card, name, rmidi->card->proc_root);
2076 	if (entry) {
2077 		entry->private_data = rmidi;
2078 		entry->c.text.read = snd_rawmidi_proc_info_read;
2079 		if (snd_info_register(entry) < 0) {
2080 			snd_info_free_entry(entry);
2081 			entry = NULL;
2082 		}
2083 	}
2084 	rmidi->proc_entry = entry;
2085 #if IS_ENABLED(CONFIG_SND_SEQUENCER)
2086 	/* no own registration mechanism? */
2087 	if (!rmidi->ops || !rmidi->ops->dev_register) {
2088 		if (snd_seq_device_new(rmidi->card, rmidi->device, SNDRV_SEQ_DEV_ID_MIDISYNTH, 0, &rmidi->seq_dev) >= 0) {
2089 			rmidi->seq_dev->private_data = rmidi;
2090 			rmidi->seq_dev->private_free = snd_rawmidi_dev_seq_free;
2091 			sprintf(rmidi->seq_dev->name, "MIDI %d-%d", rmidi->card->number, rmidi->device);
2092 			snd_device_register(rmidi->card, rmidi->seq_dev);
2093 		}
2094 	}
2095 #endif
2096 	return 0;
2097 
2098  error_unregister:
2099 	snd_unregister_device(rmidi->dev);
2100  error:
2101 	scoped_guard(mutex, &register_mutex)
2102 		list_del(&rmidi->list);
2103 	return err;
2104 }
2105 
2106 static int snd_rawmidi_dev_disconnect(struct snd_device *device)
2107 {
2108 	struct snd_rawmidi *rmidi = device->device_data;
2109 	int dir;
2110 
2111 	guard(mutex)(&register_mutex);
2112 	guard(mutex)(&rmidi->open_mutex);
2113 	wake_up(&rmidi->open_wait);
2114 	list_del_init(&rmidi->list);
2115 	for (dir = 0; dir < 2; dir++) {
2116 		struct snd_rawmidi_substream *s;
2117 
2118 		list_for_each_entry(s, &rmidi->streams[dir].substreams, list) {
2119 			scoped_guard(spinlock_irq, &s->lock)
2120 				s->disconnected = true;
2121 			if (s->runtime) {
2122 				s->ops->trigger(s, 0);
2123 				cancel_work_sync(&s->runtime->event_work);
2124 				wake_up(&s->runtime->sleep);
2125 			}
2126 		}
2127 	}
2128 
2129 #ifdef CONFIG_SND_OSSEMUL
2130 	if (rmidi->ossreg) {
2131 		if ((int)rmidi->device == midi_map[rmidi->card->number]) {
2132 			snd_unregister_oss_device(SNDRV_OSS_DEVICE_TYPE_MIDI, rmidi->card, 0);
2133 #ifdef SNDRV_OSS_INFO_DEV_MIDI
2134 			snd_oss_info_unregister(SNDRV_OSS_INFO_DEV_MIDI, rmidi->card->number);
2135 #endif
2136 		}
2137 		if ((int)rmidi->device == amidi_map[rmidi->card->number])
2138 			snd_unregister_oss_device(SNDRV_OSS_DEVICE_TYPE_MIDI, rmidi->card, 1);
2139 		rmidi->ossreg = 0;
2140 	}
2141 #endif /* CONFIG_SND_OSSEMUL */
2142 	snd_unregister_device(rmidi->dev);
2143 	return 0;
2144 }
2145 
2146 /**
2147  * snd_rawmidi_set_ops - set the rawmidi operators
2148  * @rmidi: the rawmidi instance
2149  * @stream: the stream direction, SNDRV_RAWMIDI_STREAM_XXX
2150  * @ops: the operator table
2151  *
2152  * Sets the rawmidi operators for the given stream direction.
2153  */
2154 void snd_rawmidi_set_ops(struct snd_rawmidi *rmidi, int stream,
2155 			 const struct snd_rawmidi_ops *ops)
2156 {
2157 	struct snd_rawmidi_substream *substream;
2158 
2159 	list_for_each_entry(substream, &rmidi->streams[stream].substreams, list)
2160 		substream->ops = ops;
2161 }
2162 EXPORT_SYMBOL(snd_rawmidi_set_ops);
2163 
2164 /*
2165  *  ENTRY functions
2166  */
2167 
2168 static int __init alsa_rawmidi_init(void)
2169 {
2170 	snd_ctl_register_ioctl(snd_rawmidi_control_ioctl);
2171 	snd_ctl_register_ioctl_compat(snd_rawmidi_control_ioctl);
2172 #ifdef CONFIG_SND_OSSEMUL
2173 	/* check device map table */
2174 	for (int i = 0; i < SNDRV_CARDS; i++) {
2175 		if (midi_map[i] < 0 || midi_map[i] >= SNDRV_RAWMIDI_DEVICES) {
2176 			pr_err("ALSA: rawmidi: invalid midi_map[%d] = %d\n",
2177 			       i, midi_map[i]);
2178 			midi_map[i] = 0;
2179 		}
2180 		if (amidi_map[i] < 0 || amidi_map[i] >= SNDRV_RAWMIDI_DEVICES) {
2181 			pr_err("ALSA: rawmidi: invalid amidi_map[%d] = %d\n",
2182 			       i, amidi_map[i]);
2183 			amidi_map[i] = 1;
2184 		}
2185 	}
2186 #endif /* CONFIG_SND_OSSEMUL */
2187 	return 0;
2188 }
2189 
2190 static void __exit alsa_rawmidi_exit(void)
2191 {
2192 	snd_ctl_unregister_ioctl(snd_rawmidi_control_ioctl);
2193 	snd_ctl_unregister_ioctl_compat(snd_rawmidi_control_ioctl);
2194 }
2195 
2196 module_init(alsa_rawmidi_init)
2197 module_exit(alsa_rawmidi_exit)
2198