Merge with rsync://fileserver/linux
[pandora-kernel.git] / sound / core / memalloc.c
1 /*
2  *  Copyright (c) by Jaroslav Kysela <perex@suse.cz>
3  *                   Takashi Iwai <tiwai@suse.de>
4  * 
5  *  Generic memory allocators
6  *
7  *
8  *   This program is free software; you can redistribute it and/or modify
9  *   it under the terms of the GNU General Public License as published by
10  *   the Free Software Foundation; either version 2 of the License, or
11  *   (at your option) any later version.
12  *
13  *   This program is distributed in the hope that it will be useful,
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *   GNU General Public License for more details.
17  *
18  *   You should have received a copy of the GNU General Public License
19  *   along with this program; if not, write to the Free Software
20  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21  *
22  */
23
24 #include <linux/config.h>
25 #include <linux/module.h>
26 #include <linux/proc_fs.h>
27 #include <linux/init.h>
28 #include <linux/pci.h>
29 #include <linux/slab.h>
30 #include <linux/mm.h>
31 #include <asm/uaccess.h>
32 #include <linux/dma-mapping.h>
33 #include <linux/moduleparam.h>
34 #include <asm/semaphore.h>
35 #include <sound/memalloc.h>
36 #ifdef CONFIG_SBUS
37 #include <asm/sbus.h>
38 #endif
39
40
41 MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>, Jaroslav Kysela <perex@suse.cz>");
42 MODULE_DESCRIPTION("Memory allocator for ALSA system.");
43 MODULE_LICENSE("GPL");
44
45
46 #ifndef SNDRV_CARDS
47 #define SNDRV_CARDS     8
48 #endif
49
50 /*
51  */
52
53 void *snd_malloc_sgbuf_pages(struct device *device,
54                              size_t size, struct snd_dma_buffer *dmab,
55                              size_t *res_size);
56 int snd_free_sgbuf_pages(struct snd_dma_buffer *dmab);
57
58 /*
59  */
60
61 static DECLARE_MUTEX(list_mutex);
62 static LIST_HEAD(mem_list_head);
63
64 /* buffer preservation list */
65 struct snd_mem_list {
66         struct snd_dma_buffer buffer;
67         unsigned int id;
68         struct list_head list;
69 };
70
71 /* id for pre-allocated buffers */
72 #define SNDRV_DMA_DEVICE_UNUSED (unsigned int)-1
73
74 #ifdef CONFIG_SND_DEBUG
75 #define __ASTRING__(x) #x
76 #define snd_assert(expr, args...) do {\
77         if (!(expr)) {\
78                 printk(KERN_ERR "snd-malloc: BUG? (%s) (called from %p)\n", __ASTRING__(expr), __builtin_return_address(0));\
79                 args;\
80         }\
81 } while (0)
82 #else
83 #define snd_assert(expr, args...) /**/
84 #endif
85
86 /*
87  *  Hacks
88  */
89
90 #if defined(__i386__) || defined(__ppc__) || defined(__x86_64__)
91 /*
92  * A hack to allocate large buffers via dma_alloc_coherent()
93  *
94  * since dma_alloc_coherent always tries GFP_DMA when the requested
95  * pci memory region is below 32bit, it happens quite often that even
96  * 2 order of pages cannot be allocated.
97  *
98  * so in the following, we allocate at first without dma_mask, so that
99  * allocation will be done without GFP_DMA.  if the area doesn't match
100  * with the requested region, then realloate with the original dma_mask
101  * again.
102  *
103  * Really, we want to move this type of thing into dma_alloc_coherent()
104  * so dma_mask doesn't have to be messed with.
105  */
106
107 static void *snd_dma_hack_alloc_coherent(struct device *dev, size_t size,
108                                          dma_addr_t *dma_handle, int flags)
109 {
110         void *ret;
111         u64 dma_mask, coherent_dma_mask;
112
113         if (dev == NULL || !dev->dma_mask)
114                 return dma_alloc_coherent(dev, size, dma_handle, flags);
115         dma_mask = *dev->dma_mask;
116         coherent_dma_mask = dev->coherent_dma_mask;
117         *dev->dma_mask = 0xffffffff;    /* do without masking */
118         dev->coherent_dma_mask = 0xffffffff;    /* do without masking */
119         ret = dma_alloc_coherent(dev, size, dma_handle, flags);
120         *dev->dma_mask = dma_mask;      /* restore */
121         dev->coherent_dma_mask = coherent_dma_mask;     /* restore */
122         if (ret) {
123                 /* obtained address is out of range? */
124                 if (((unsigned long)*dma_handle + size - 1) & ~dma_mask) {
125                         /* reallocate with the proper mask */
126                         dma_free_coherent(dev, size, ret, *dma_handle);
127                         ret = dma_alloc_coherent(dev, size, dma_handle, flags);
128                 }
129         } else {
130                 /* wish to success now with the proper mask... */
131                 if (dma_mask != 0xffffffffUL) {
132                         /* allocation with GFP_ATOMIC to avoid the long stall */
133                         flags &= ~GFP_KERNEL;
134                         flags |= GFP_ATOMIC;
135                         ret = dma_alloc_coherent(dev, size, dma_handle, flags);
136                 }
137         }
138         return ret;
139 }
140
141 /* redefine dma_alloc_coherent for some architectures */
142 #undef dma_alloc_coherent
143 #define dma_alloc_coherent snd_dma_hack_alloc_coherent
144
145 #endif /* arch */
146
147 #if ! defined(__arm__)
148 #define NEED_RESERVE_PAGES
149 #endif
150
151 /*
152  *
153  *  Generic memory allocators
154  *
155  */
156
157 static long snd_allocated_pages; /* holding the number of allocated pages */
158
159 static inline void inc_snd_pages(int order)
160 {
161         snd_allocated_pages += 1 << order;
162 }
163
164 static inline void dec_snd_pages(int order)
165 {
166         snd_allocated_pages -= 1 << order;
167 }
168
169 static void mark_pages(struct page *page, int order)
170 {
171         struct page *last_page = page + (1 << order);
172         while (page < last_page)
173                 SetPageReserved(page++);
174 }
175
176 static void unmark_pages(struct page *page, int order)
177 {
178         struct page *last_page = page + (1 << order);
179         while (page < last_page)
180                 ClearPageReserved(page++);
181 }
182
183 /**
184  * snd_malloc_pages - allocate pages with the given size
185  * @size: the size to allocate in bytes
186  * @gfp_flags: the allocation conditions, GFP_XXX
187  *
188  * Allocates the physically contiguous pages with the given size.
189  *
190  * Returns the pointer of the buffer, or NULL if no enoguh memory.
191  */
192 void *snd_malloc_pages(size_t size, unsigned int gfp_flags)
193 {
194         int pg;
195         void *res;
196
197         snd_assert(size > 0, return NULL);
198         snd_assert(gfp_flags != 0, return NULL);
199         pg = get_order(size);
200         if ((res = (void *) __get_free_pages(gfp_flags, pg)) != NULL) {
201                 mark_pages(virt_to_page(res), pg);
202                 inc_snd_pages(pg);
203         }
204         return res;
205 }
206
207 /**
208  * snd_free_pages - release the pages
209  * @ptr: the buffer pointer to release
210  * @size: the allocated buffer size
211  *
212  * Releases the buffer allocated via snd_malloc_pages().
213  */
214 void snd_free_pages(void *ptr, size_t size)
215 {
216         int pg;
217
218         if (ptr == NULL)
219                 return;
220         pg = get_order(size);
221         dec_snd_pages(pg);
222         unmark_pages(virt_to_page(ptr), pg);
223         free_pages((unsigned long) ptr, pg);
224 }
225
226 /*
227  *
228  *  Bus-specific memory allocators
229  *
230  */
231
232 /* allocate the coherent DMA pages */
233 static void *snd_malloc_dev_pages(struct device *dev, size_t size, dma_addr_t *dma)
234 {
235         int pg;
236         void *res;
237         unsigned int gfp_flags;
238
239         snd_assert(size > 0, return NULL);
240         snd_assert(dma != NULL, return NULL);
241         pg = get_order(size);
242         gfp_flags = GFP_KERNEL
243                 | __GFP_NORETRY /* don't trigger OOM-killer */
244                 | __GFP_NOWARN; /* no stack trace print - this call is non-critical */
245         res = dma_alloc_coherent(dev, PAGE_SIZE << pg, dma, gfp_flags);
246         if (res != NULL) {
247 #ifdef NEED_RESERVE_PAGES
248                 mark_pages(virt_to_page(res), pg); /* should be dma_to_page() */
249 #endif
250                 inc_snd_pages(pg);
251         }
252
253         return res;
254 }
255
256 /* free the coherent DMA pages */
257 static void snd_free_dev_pages(struct device *dev, size_t size, void *ptr,
258                                dma_addr_t dma)
259 {
260         int pg;
261
262         if (ptr == NULL)
263                 return;
264         pg = get_order(size);
265         dec_snd_pages(pg);
266 #ifdef NEED_RESERVE_PAGES
267         unmark_pages(virt_to_page(ptr), pg); /* should be dma_to_page() */
268 #endif
269         dma_free_coherent(dev, PAGE_SIZE << pg, ptr, dma);
270 }
271
272 #ifdef CONFIG_SBUS
273
274 static void *snd_malloc_sbus_pages(struct device *dev, size_t size,
275                                    dma_addr_t *dma_addr)
276 {
277         struct sbus_dev *sdev = (struct sbus_dev *)dev;
278         int pg;
279         void *res;
280
281         snd_assert(size > 0, return NULL);
282         snd_assert(dma_addr != NULL, return NULL);
283         pg = get_order(size);
284         res = sbus_alloc_consistent(sdev, PAGE_SIZE * (1 << pg), dma_addr);
285         if (res != NULL)
286                 inc_snd_pages(pg);
287         return res;
288 }
289
290 static void snd_free_sbus_pages(struct device *dev, size_t size,
291                                 void *ptr, dma_addr_t dma_addr)
292 {
293         struct sbus_dev *sdev = (struct sbus_dev *)dev;
294         int pg;
295
296         if (ptr == NULL)
297                 return;
298         pg = get_order(size);
299         dec_snd_pages(pg);
300         sbus_free_consistent(sdev, PAGE_SIZE * (1 << pg), ptr, dma_addr);
301 }
302
303 #endif /* CONFIG_SBUS */
304
305 /*
306  *
307  *  ALSA generic memory management
308  *
309  */
310
311
312 /**
313  * snd_dma_alloc_pages - allocate the buffer area according to the given type
314  * @type: the DMA buffer type
315  * @device: the device pointer
316  * @size: the buffer size to allocate
317  * @dmab: buffer allocation record to store the allocated data
318  *
319  * Calls the memory-allocator function for the corresponding
320  * buffer type.
321  * 
322  * Returns zero if the buffer with the given size is allocated successfuly,
323  * other a negative value at error.
324  */
325 int snd_dma_alloc_pages(int type, struct device *device, size_t size,
326                         struct snd_dma_buffer *dmab)
327 {
328         snd_assert(size > 0, return -ENXIO);
329         snd_assert(dmab != NULL, return -ENXIO);
330
331         dmab->dev.type = type;
332         dmab->dev.dev = device;
333         dmab->bytes = 0;
334         switch (type) {
335         case SNDRV_DMA_TYPE_CONTINUOUS:
336                 dmab->area = snd_malloc_pages(size, (unsigned long)device);
337                 dmab->addr = 0;
338                 break;
339 #ifdef CONFIG_SBUS
340         case SNDRV_DMA_TYPE_SBUS:
341                 dmab->area = snd_malloc_sbus_pages(device, size, &dmab->addr);
342                 break;
343 #endif
344         case SNDRV_DMA_TYPE_DEV:
345                 dmab->area = snd_malloc_dev_pages(device, size, &dmab->addr);
346                 break;
347         case SNDRV_DMA_TYPE_DEV_SG:
348                 snd_malloc_sgbuf_pages(device, size, dmab, NULL);
349                 break;
350         default:
351                 printk(KERN_ERR "snd-malloc: invalid device type %d\n", type);
352                 dmab->area = NULL;
353                 dmab->addr = 0;
354                 return -ENXIO;
355         }
356         if (! dmab->area)
357                 return -ENOMEM;
358         dmab->bytes = size;
359         return 0;
360 }
361
362 /**
363  * snd_dma_alloc_pages_fallback - allocate the buffer area according to the given type with fallback
364  * @type: the DMA buffer type
365  * @device: the device pointer
366  * @size: the buffer size to allocate
367  * @dmab: buffer allocation record to store the allocated data
368  *
369  * Calls the memory-allocator function for the corresponding
370  * buffer type.  When no space is left, this function reduces the size and
371  * tries to allocate again.  The size actually allocated is stored in
372  * res_size argument.
373  * 
374  * Returns zero if the buffer with the given size is allocated successfuly,
375  * other a negative value at error.
376  */
377 int snd_dma_alloc_pages_fallback(int type, struct device *device, size_t size,
378                                  struct snd_dma_buffer *dmab)
379 {
380         int err;
381
382         snd_assert(size > 0, return -ENXIO);
383         snd_assert(dmab != NULL, return -ENXIO);
384
385         while ((err = snd_dma_alloc_pages(type, device, size, dmab)) < 0) {
386                 if (err != -ENOMEM)
387                         return err;
388                 size >>= 1;
389                 if (size <= PAGE_SIZE)
390                         return -ENOMEM;
391         }
392         if (! dmab->area)
393                 return -ENOMEM;
394         return 0;
395 }
396
397
398 /**
399  * snd_dma_free_pages - release the allocated buffer
400  * @dmab: the buffer allocation record to release
401  *
402  * Releases the allocated buffer via snd_dma_alloc_pages().
403  */
404 void snd_dma_free_pages(struct snd_dma_buffer *dmab)
405 {
406         switch (dmab->dev.type) {
407         case SNDRV_DMA_TYPE_CONTINUOUS:
408                 snd_free_pages(dmab->area, dmab->bytes);
409                 break;
410 #ifdef CONFIG_SBUS
411         case SNDRV_DMA_TYPE_SBUS:
412                 snd_free_sbus_pages(dmab->dev.dev, dmab->bytes, dmab->area, dmab->addr);
413                 break;
414 #endif
415         case SNDRV_DMA_TYPE_DEV:
416                 snd_free_dev_pages(dmab->dev.dev, dmab->bytes, dmab->area, dmab->addr);
417                 break;
418         case SNDRV_DMA_TYPE_DEV_SG:
419                 snd_free_sgbuf_pages(dmab);
420                 break;
421         default:
422                 printk(KERN_ERR "snd-malloc: invalid device type %d\n", dmab->dev.type);
423         }
424 }
425
426
427 /**
428  * snd_dma_get_reserved - get the reserved buffer for the given device
429  * @dmab: the buffer allocation record to store
430  * @id: the buffer id
431  *
432  * Looks for the reserved-buffer list and re-uses if the same buffer
433  * is found in the list.  When the buffer is found, it's removed from the free list.
434  *
435  * Returns the size of buffer if the buffer is found, or zero if not found.
436  */
437 size_t snd_dma_get_reserved_buf(struct snd_dma_buffer *dmab, unsigned int id)
438 {
439         struct list_head *p;
440         struct snd_mem_list *mem;
441
442         snd_assert(dmab, return 0);
443
444         down(&list_mutex);
445         list_for_each(p, &mem_list_head) {
446                 mem = list_entry(p, struct snd_mem_list, list);
447                 if (mem->id == id &&
448                     (mem->buffer.dev.dev == NULL || dmab->dev.dev == NULL ||
449                      ! memcmp(&mem->buffer.dev, &dmab->dev, sizeof(dmab->dev)))) {
450                         struct device *dev = dmab->dev.dev;
451                         list_del(p);
452                         *dmab = mem->buffer;
453                         if (dmab->dev.dev == NULL)
454                                 dmab->dev.dev = dev;
455                         kfree(mem);
456                         up(&list_mutex);
457                         return dmab->bytes;
458                 }
459         }
460         up(&list_mutex);
461         return 0;
462 }
463
464 /**
465  * snd_dma_reserve_buf - reserve the buffer
466  * @dmab: the buffer to reserve
467  * @id: the buffer id
468  *
469  * Reserves the given buffer as a reserved buffer.
470  * 
471  * Returns zero if successful, or a negative code at error.
472  */
473 int snd_dma_reserve_buf(struct snd_dma_buffer *dmab, unsigned int id)
474 {
475         struct snd_mem_list *mem;
476
477         snd_assert(dmab, return -EINVAL);
478         mem = kmalloc(sizeof(*mem), GFP_KERNEL);
479         if (! mem)
480                 return -ENOMEM;
481         down(&list_mutex);
482         mem->buffer = *dmab;
483         mem->id = id;
484         list_add_tail(&mem->list, &mem_list_head);
485         up(&list_mutex);
486         return 0;
487 }
488
489 /*
490  * purge all reserved buffers
491  */
492 static void free_all_reserved_pages(void)
493 {
494         struct list_head *p;
495         struct snd_mem_list *mem;
496
497         down(&list_mutex);
498         while (! list_empty(&mem_list_head)) {
499                 p = mem_list_head.next;
500                 mem = list_entry(p, struct snd_mem_list, list);
501                 list_del(p);
502                 snd_dma_free_pages(&mem->buffer);
503                 kfree(mem);
504         }
505         up(&list_mutex);
506 }
507
508
509 #ifdef CONFIG_PROC_FS
510 /*
511  * proc file interface
512  */
513 #define SND_MEM_PROC_FILE       "driver/snd-page-alloc"
514 struct proc_dir_entry *snd_mem_proc;
515
516 static int snd_mem_proc_read(char *page, char **start, off_t off,
517                              int count, int *eof, void *data)
518 {
519         int len = 0;
520         long pages = snd_allocated_pages >> (PAGE_SHIFT-12);
521         struct list_head *p;
522         struct snd_mem_list *mem;
523         int devno;
524         static char *types[] = { "UNKNOWN", "CONT", "DEV", "DEV-SG", "SBUS" };
525
526         down(&list_mutex);
527         len += snprintf(page + len, count - len,
528                         "pages  : %li bytes (%li pages per %likB)\n",
529                         pages * PAGE_SIZE, pages, PAGE_SIZE / 1024);
530         devno = 0;
531         list_for_each(p, &mem_list_head) {
532                 mem = list_entry(p, struct snd_mem_list, list);
533                 devno++;
534                 len += snprintf(page + len, count - len,
535                                 "buffer %d : ID %08x : type %s\n",
536                                 devno, mem->id, types[mem->buffer.dev.type]);
537                 len += snprintf(page + len, count - len,
538                                 "  addr = 0x%lx, size = %d bytes\n",
539                                 (unsigned long)mem->buffer.addr, (int)mem->buffer.bytes);
540         }
541         up(&list_mutex);
542         return len;
543 }
544
545 /* FIXME: for pci only - other bus? */
546 #ifdef CONFIG_PCI
547 #define gettoken(bufp) strsep(bufp, " \t\n")
548
549 static int snd_mem_proc_write(struct file *file, const char __user *buffer,
550                               unsigned long count, void *data)
551 {
552         char buf[128];
553         char *token, *p;
554
555         if (count > ARRAY_SIZE(buf) - 1)
556                 count = ARRAY_SIZE(buf) - 1;
557         if (copy_from_user(buf, buffer, count))
558                 return -EFAULT;
559         buf[ARRAY_SIZE(buf) - 1] = '\0';
560
561         p = buf;
562         token = gettoken(&p);
563         if (! token || *token == '#')
564                 return (int)count;
565         if (strcmp(token, "add") == 0) {
566                 char *endp;
567                 int vendor, device, size, buffers;
568                 long mask;
569                 int i, alloced;
570                 struct pci_dev *pci;
571
572                 if ((token = gettoken(&p)) == NULL ||
573                     (vendor = simple_strtol(token, NULL, 0)) <= 0 ||
574                     (token = gettoken(&p)) == NULL ||
575                     (device = simple_strtol(token, NULL, 0)) <= 0 ||
576                     (token = gettoken(&p)) == NULL ||
577                     (mask = simple_strtol(token, NULL, 0)) < 0 ||
578                     (token = gettoken(&p)) == NULL ||
579                     (size = memparse(token, &endp)) < 64*1024 ||
580                     size > 16*1024*1024 /* too big */ ||
581                     (token = gettoken(&p)) == NULL ||
582                     (buffers = simple_strtol(token, NULL, 0)) <= 0 ||
583                     buffers > 4) {
584                         printk(KERN_ERR "snd-page-alloc: invalid proc write format\n");
585                         return (int)count;
586                 }
587                 vendor &= 0xffff;
588                 device &= 0xffff;
589
590                 alloced = 0;
591                 pci = NULL;
592                 while ((pci = pci_find_device(vendor, device, pci)) != NULL) {
593                         if (mask > 0 && mask < 0xffffffff) {
594                                 if (pci_set_dma_mask(pci, mask) < 0 ||
595                                     pci_set_consistent_dma_mask(pci, mask) < 0) {
596                                         printk(KERN_ERR "snd-page-alloc: cannot set DMA mask %lx for pci %04x:%04x\n", mask, vendor, device);
597                                         return (int)count;
598                                 }
599                         }
600                         for (i = 0; i < buffers; i++) {
601                                 struct snd_dma_buffer dmab;
602                                 memset(&dmab, 0, sizeof(dmab));
603                                 if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
604                                                         size, &dmab) < 0) {
605                                         printk(KERN_ERR "snd-page-alloc: cannot allocate buffer pages (size = %d)\n", size);
606                                         return (int)count;
607                                 }
608                                 snd_dma_reserve_buf(&dmab, snd_dma_pci_buf_id(pci));
609                         }
610                         alloced++;
611                 }
612                 if (! alloced) {
613                         for (i = 0; i < buffers; i++) {
614                                 struct snd_dma_buffer dmab;
615                                 memset(&dmab, 0, sizeof(dmab));
616                                 /* FIXME: We can allocate only in ZONE_DMA
617                                  * without a device pointer!
618                                  */
619                                 if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, NULL,
620                                                         size, &dmab) < 0) {
621                                         printk(KERN_ERR "snd-page-alloc: cannot allocate buffer pages (size = %d)\n", size);
622                                         break;
623                                 }
624                                 snd_dma_reserve_buf(&dmab, (unsigned int)((vendor << 16) | device));
625                         }
626                 }
627         } else if (strcmp(token, "erase") == 0)
628                 /* FIXME: need for releasing each buffer chunk? */
629                 free_all_reserved_pages();
630         else
631                 printk(KERN_ERR "snd-page-alloc: invalid proc cmd\n");
632         return (int)count;
633 }
634 #endif /* CONFIG_PCI */
635 #endif /* CONFIG_PROC_FS */
636
637 /*
638  * module entry
639  */
640
641 static int __init snd_mem_init(void)
642 {
643 #ifdef CONFIG_PROC_FS
644         snd_mem_proc = create_proc_entry(SND_MEM_PROC_FILE, 0644, NULL);
645         if (snd_mem_proc) {
646                 snd_mem_proc->read_proc = snd_mem_proc_read;
647 #ifdef CONFIG_PCI
648                 snd_mem_proc->write_proc = snd_mem_proc_write;
649 #endif
650         }
651 #endif
652         return 0;
653 }
654
655 static void __exit snd_mem_exit(void)
656 {
657         if (snd_mem_proc)
658                 remove_proc_entry(SND_MEM_PROC_FILE, NULL);
659         free_all_reserved_pages();
660         if (snd_allocated_pages > 0)
661                 printk(KERN_ERR "snd-malloc: Memory leak?  pages not freed = %li\n", snd_allocated_pages);
662 }
663
664
665 module_init(snd_mem_init)
666 module_exit(snd_mem_exit)
667
668
669 /*
670  * exports
671  */
672 EXPORT_SYMBOL(snd_dma_alloc_pages);
673 EXPORT_SYMBOL(snd_dma_alloc_pages_fallback);
674 EXPORT_SYMBOL(snd_dma_free_pages);
675
676 EXPORT_SYMBOL(snd_dma_get_reserved_buf);
677 EXPORT_SYMBOL(snd_dma_reserve_buf);
678
679 EXPORT_SYMBOL(snd_malloc_pages);
680 EXPORT_SYMBOL(snd_free_pages);