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