upload tizen1.0 source
[kernel/linux-2.6.36.git] / mm / cma.c
1 /*
2  * Contiguous Memory Allocator framework
3  * Copyright (c) 2010 by Samsung Electronics.
4  * Written by Michal Nazarewicz (m.nazarewicz@samsung.com)
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License or (at your optional) any later version of the license.
10  */
11
12 /*
13  * See Documentation/contiguous-memory.txt for details.
14  */
15
16 #define pr_fmt(fmt) "cma: " fmt
17
18 #ifdef CONFIG_CMA_DEBUG
19 #  define DEBUG
20 #endif
21
22 #ifndef CONFIG_NO_BOOTMEM
23 #  include <linux/bootmem.h>   /* alloc_bootmem_pages_nopanic() */
24 #endif
25 #ifdef CONFIG_HAVE_MEMBLOCK
26 #  include <linux/memblock.h>  /* memblock*() */
27 #endif
28 #include <linux/device.h>      /* struct device, dev_name() */
29 #include <linux/errno.h>       /* Error numbers */
30 #include <linux/err.h>         /* IS_ERR, PTR_ERR, etc. */
31 #include <linux/mm.h>          /* PAGE_ALIGN() */
32 #include <linux/module.h>      /* EXPORT_SYMBOL_GPL() */
33 #include <linux/mutex.h>       /* mutex */
34 #include <linux/slab.h>        /* kmalloc() */
35 #include <linux/string.h>      /* str*() */
36
37 #include <linux/cma.h>
38 #include <linux/vmalloc.h>
39
40 /*
41  * Protects cma_regions, cma_allocators, cma_map, cma_map_length,
42  * cma_kobj, cma_sysfs_regions and cma_chunks_by_start.
43  */
44 static DEFINE_MUTEX(cma_mutex);
45
46
47
48 /************************* Map attribute *************************/
49
50 static const char *cma_map;
51 static size_t cma_map_length;
52
53 /*
54  * map-attr      ::= [ rules [ ';' ] ]
55  * rules         ::= rule [ ';' rules ]
56  * rule          ::= patterns '=' regions
57  * patterns      ::= pattern [ ',' patterns ]
58  * regions       ::= REG-NAME [ ',' regions ]
59  * pattern       ::= dev-pattern [ '/' TYPE-NAME ] | '/' TYPE-NAME
60  *
61  * See Documentation/contiguous-memory.txt for details.
62  */
63 static ssize_t cma_map_validate(const char *param)
64 {
65         const char *ch = param;
66
67         if (*ch == '\0' || *ch == '\n')
68                 return 0;
69
70         for (;;) {
71                 const char *start = ch;
72
73                 while (*ch && *ch != '\n' && *ch != ';' && *ch != '=')
74                         ++ch;
75
76                 if (*ch != '=' || start == ch) {
77                         pr_err("map: expecting \"<patterns>=<regions>\" near %s\n",
78                                start);
79                         return -EINVAL;
80                 }
81
82                 while (*++ch != ';')
83                         if (*ch == '\0' || *ch == '\n')
84                                 return ch - param;
85                 if (ch[1] == '\0' || ch[1] == '\n')
86                         return ch - param;
87                 ++ch;
88         }
89 }
90
91 static int __init cma_map_param(char *param)
92 {
93         ssize_t len;
94
95         pr_debug("param: map: %s\n", param);
96
97         len = cma_map_validate(param);
98         if (len < 0)
99                 return len;
100
101         cma_map = param;
102         cma_map_length = len;
103         return 0;
104 }
105
106 #if defined CONFIG_CMA_CMDLINE
107
108 early_param("cma.map", cma_map_param);
109
110 #endif
111
112
113
114 /************************* Early regions *************************/
115
116 struct list_head cma_early_regions __initdata =
117         LIST_HEAD_INIT(cma_early_regions);
118
119 #ifdef CONFIG_CMA_CMDLINE
120
121 /*
122  * regions-attr ::= [ regions [ ';' ] ]
123  * regions      ::= region [ ';' regions ]
124  *
125  * region       ::= [ '-' ] reg-name
126  *                    '=' size
127  *                  [ '@' start ]
128  *                  [ '/' alignment ]
129  *                  [ ':' alloc-name ]
130  *
131  * See Documentation/contiguous-memory.txt for details.
132  *
133  * Example:
134  * cma=reg1=64M:bf;reg2=32M@0x100000:bf;reg3=64M/1M:bf
135  *
136  * If allocator is ommited the first available allocater will be used.
137  */
138
139 #define NUMPARSE(cond_ch, type, cond) ({                                \
140                 unsigned long long v = 0;                               \
141                 if (*param == (cond_ch)) {                              \
142                         const char *const msg = param + 1;              \
143                         v = memparse(msg, &param);                      \
144                         if (!v || v > ~(type)0 || !(cond)) {            \
145                                 pr_err("param: invalid value near %s\n", msg); \
146                                 ret = -EINVAL;                          \
147                                 break;                                  \
148                         }                                               \
149                 }                                                       \
150                 v;                                                      \
151         })
152
153 static int __init cma_param_parse(char *param)
154 {
155         static struct cma_region regions[16];
156
157         size_t left = ARRAY_SIZE(regions);
158         struct cma_region *reg = regions;
159         int ret = 0;
160
161         pr_debug("param: %s\n", param);
162
163         for (; *param; ++reg) {
164                 dma_addr_t start, alignment;
165                 size_t size;
166
167                 if (unlikely(!--left)) {
168                         pr_err("param: too many early regions\n");
169                         return -ENOSPC;
170                 }
171
172                 /* Parse name */
173                 reg->name = param;
174                 param = strchr(param, '=');
175                 if (!param || param == reg->name) {
176                         pr_err("param: expected \"<name>=\" near %s\n",
177                                reg->name);
178                         ret = -EINVAL;
179                         break;
180                 }
181                 *param = '\0';
182
183                 /* Parse numbers */
184                 size      = NUMPARSE('\0', size_t, true);
185                 start     = NUMPARSE('@', dma_addr_t, true);
186                 alignment = NUMPARSE('/', dma_addr_t, (v & (v - 1)) == 0);
187
188                 alignment = max(alignment, (dma_addr_t)PAGE_SIZE);
189                 start     = ALIGN(start, alignment);
190                 size      = PAGE_ALIGN(size);
191                 if (start + size < start) {
192                         pr_err("param: invalid start, size combination\n");
193                         ret = -EINVAL;
194                         break;
195                 }
196
197                 /* Parse allocator */
198                 if (*param == ':') {
199                         reg->alloc_name = ++param;
200                         while (*param && *param != ';')
201                                 ++param;
202                         if (param == reg->alloc_name)
203                                 reg->alloc_name = NULL;
204                 }
205
206                 /* Go to next */
207                 if (*param == ';') {
208                         *param = '\0';
209                         ++param;
210                 } else if (*param) {
211                         pr_err("param: expecting ';' or end of parameter near %s\n",
212                                param);
213                         ret = -EINVAL;
214                         break;
215                 }
216
217                 /* Add */
218                 reg->size      = size;
219                 reg->start     = start;
220                 reg->alignment = alignment;
221                 reg->copy_name = 1;
222
223                 list_add_tail(&reg->list, &cma_early_regions);
224
225                 pr_debug("param: registering early region %s (%p@%p/%p)\n",
226                          reg->name, (void *)reg->size, (void *)reg->start,
227                          (void *)reg->alignment);
228         }
229
230         return ret;
231 }
232 early_param("cma", cma_param_parse);
233
234 #undef NUMPARSE
235
236 #endif
237
238
239 int __init __must_check cma_early_region_register(struct cma_region *reg)
240 {
241         dma_addr_t start, alignment;
242         size_t size;
243
244         if (reg->alignment & (reg->alignment - 1))
245                 return -EINVAL;
246
247         alignment = max(reg->alignment, (dma_addr_t)PAGE_SIZE);
248         start     = ALIGN(reg->start, alignment);
249         size      = PAGE_ALIGN(reg->size);
250
251         if (start + size < start)
252                 return -EINVAL;
253
254         reg->size      = size;
255         reg->start     = start;
256         reg->alignment = alignment;
257
258         list_add_tail(&reg->list, &cma_early_regions);
259
260         pr_debug("param: registering early region %s (%p@%p/%p)\n",
261                  reg->name, (void *)reg->size, (void *)reg->start,
262                  (void *)reg->alignment);
263
264         return 0;
265 }
266
267
268
269 /************************* Regions & Allocators *************************/
270
271 static void __cma_sysfs_region_add(struct cma_region *reg);
272
273 static int __cma_region_attach_alloc(struct cma_region *reg);
274 static void __maybe_unused __cma_region_detach_alloc(struct cma_region *reg);
275
276
277 /* List of all regions.  Named regions are kept before unnamed. */
278 static LIST_HEAD(cma_regions);
279
280 #define cma_foreach_region(reg) \
281         list_for_each_entry(reg, &cma_regions, list)
282
283 int __must_check cma_region_register(struct cma_region *reg)
284 {
285         const char *name, *alloc_name;
286         struct cma_region *r;
287         char *ch = NULL;
288         int ret = 0;
289
290         if (!reg->size || reg->start + reg->size < reg->start)
291                 return -EINVAL;
292
293         reg->users = 0;
294         reg->used = 0;
295         reg->private_data = NULL;
296         reg->registered = 0;
297         reg->free_space = reg->size;
298
299         /* Copy name and alloc_name */
300         name = reg->name;
301         alloc_name = reg->alloc_name;
302         if (reg->copy_name && (reg->name || reg->alloc_name)) {
303                 size_t name_size, alloc_size;
304
305                 name_size  = reg->name       ? strlen(reg->name) + 1       : 0;
306                 alloc_size = reg->alloc_name ? strlen(reg->alloc_name) + 1 : 0;
307
308                 ch = kmalloc(name_size + alloc_size, GFP_KERNEL);
309                 if (!ch) {
310                         pr_err("%s: not enough memory to allocate name\n",
311                                reg->name ?: "(private)");
312                         return -ENOMEM;
313                 }
314
315                 if (name_size) {
316                         memcpy(ch, reg->name, name_size);
317                         name = ch;
318                         ch += name_size;
319                 }
320
321                 if (alloc_size) {
322                         memcpy(ch, reg->alloc_name, alloc_size);
323                         alloc_name = ch;
324                 }
325         }
326
327         mutex_lock(&cma_mutex);
328
329         /* Don't let regions overlap */
330         cma_foreach_region(r)
331                 if (r->start + r->size > reg->start &&
332                     r->start < reg->start + reg->size) {
333                         ret = -EADDRINUSE;
334                         goto done;
335                 }
336
337         if (reg->alloc) {
338                 ret = __cma_region_attach_alloc(reg);
339                 if (unlikely(ret < 0))
340                         goto done;
341         }
342
343         reg->name = name;
344         reg->alloc_name = alloc_name;
345         reg->registered = 1;
346         ch = NULL;
347
348         /*
349          * Keep named at the beginning and unnamed (private) at the
350          * end.  This helps in traversal when named region is looked
351          * for.
352          */
353         if (name)
354                 list_add(&reg->list, &cma_regions);
355         else
356                 list_add_tail(&reg->list, &cma_regions);
357
358         __cma_sysfs_region_add(reg);
359
360 done:
361         mutex_unlock(&cma_mutex);
362
363         pr_debug("%s: region %sregistered\n",
364                  reg->name ?: "(private)", ret ? "not " : "");
365         kfree(ch);
366
367         return ret;
368 }
369 EXPORT_SYMBOL_GPL(cma_region_register);
370
371 static struct cma_region *__must_check
372 __cma_region_find(const char **namep)
373 {
374         struct cma_region *reg;
375         const char *ch, *name;
376         size_t n;
377
378         ch = *namep;
379         while (*ch && *ch != ',' && *ch != ';')
380                 ++ch;
381         name = *namep;
382         *namep = *ch == ',' ? ch + 1 : ch;
383         n = ch - name;
384
385         /*
386          * Named regions are kept in front of unnamed so if we
387          * encounter unnamed region we can stop.
388          */
389         cma_foreach_region(reg)
390                 if (!reg->name)
391                         break;
392                 else if (!strncmp(name, reg->name, n) && !reg->name[n])
393                         return reg;
394
395         return NULL;
396 }
397
398
399 /* List of all allocators. */
400 static LIST_HEAD(cma_allocators);
401
402 #define cma_foreach_allocator(alloc) \
403         list_for_each_entry(alloc, &cma_allocators, list)
404
405 int cma_allocator_register(struct cma_allocator *alloc)
406 {
407         struct cma_region *reg;
408         int first;
409
410         if (!alloc->alloc || !alloc->free)
411                 return -EINVAL;
412
413         mutex_lock(&cma_mutex);
414
415         first = list_empty(&cma_allocators);
416
417         list_add_tail(&alloc->list, &cma_allocators);
418
419         /*
420          * Attach this allocator to all allocator-less regions that
421          * request this particular allocator (reg->alloc_name equals
422          * alloc->name) or if region wants the first available
423          * allocator and we are the first.
424          */
425         cma_foreach_region(reg) {
426                 if (reg->alloc)
427                         continue;
428                 if (reg->alloc_name
429                   ? alloc->name && !strcmp(alloc->name, reg->alloc_name)
430                   : (!reg->used && first))
431                         continue;
432
433                 reg->alloc = alloc;
434                 __cma_region_attach_alloc(reg);
435         }
436
437         mutex_unlock(&cma_mutex);
438
439         pr_debug("%s: allocator registered\n", alloc->name ?: "(unnamed)");
440
441         return 0;
442 }
443 EXPORT_SYMBOL_GPL(cma_allocator_register);
444
445 static struct cma_allocator *__must_check
446 __cma_allocator_find(const char *name)
447 {
448         struct cma_allocator *alloc;
449
450         if (!name)
451                 return list_empty(&cma_allocators)
452                         ? NULL
453                         : list_entry(cma_allocators.next,
454                                      struct cma_allocator, list);
455
456         cma_foreach_allocator(alloc)
457                 if (alloc->name && !strcmp(name, alloc->name))
458                         return alloc;
459
460         return NULL;
461 }
462
463
464
465 /************************* Initialise CMA *************************/
466
467 int __init cma_set_defaults(struct cma_region *regions, const char *map)
468 {
469         if (map) {
470                 int ret = cma_map_param((char *)map);
471                 if (unlikely(ret < 0))
472                         return ret;
473         }
474
475         if (!regions)
476                 return 0;
477
478         for (; regions->size; ++regions) {
479                 int ret = cma_early_region_register(regions);
480                 if (unlikely(ret < 0))
481                         return ret;
482         }
483
484         return 0;
485 }
486
487
488 int __init cma_early_region_reserve(struct cma_region *reg)
489 {
490         int tried = 0;
491
492         if (!reg->size || (reg->alignment & (reg->alignment - 1)) ||
493             reg->reserved)
494                 return -EINVAL;
495
496 #ifndef CONFIG_NO_BOOTMEM
497
498         tried = 1;
499
500         {
501                 void *ptr = __alloc_bootmem_nopanic(reg->size, reg->alignment,
502                                                     reg->start);
503                 if (ptr) {
504                         reg->start = virt_to_phys(ptr);
505                         reg->reserved = 1;
506                         return 0;
507                 }
508         }
509
510 #endif
511
512 #ifdef CONFIG_HAVE_MEMBLOCK
513
514         tried = 1;
515
516         if (reg->start) {
517                 if (!memblock_is_region_reserved(reg->start, reg->size) &&
518                     memblock_reserve(reg->start, reg->size) >= 0) {
519                         reg->reserved = 1;
520                         return 0;
521                 }
522         } else {
523                 /*
524                  * Use __memblock_alloc_base() since
525                  * memblock_alloc_base() panic()s.
526                  */
527                 u64 ret = __memblock_alloc_base(reg->size, reg->alignment, 0);
528                 if (ret &&
529                     ret < ~(dma_addr_t)0 &&
530                     ret + reg->size < ~(dma_addr_t)0 &&
531                     ret + reg->size > ret) {
532                         reg->start = ret;
533                         reg->reserved = 1;
534                         return 0;
535                 }
536
537                 if (ret)
538                         memblock_free(ret, reg->size);
539         }
540
541 #endif
542
543         return tried ? -ENOMEM : -EOPNOTSUPP;
544 }
545
546 void __init cma_early_regions_reserve(int (*reserve)(struct cma_region *reg))
547 {
548         struct cma_region *reg;
549
550         pr_debug("init: reserving early regions\n");
551
552         if (!reserve)
553                 reserve = cma_early_region_reserve;
554
555         list_for_each_entry(reg, &cma_early_regions, list) {
556                 if (reg->reserved) {
557                         /* nothing */
558                 } else if (reserve(reg) >= 0) {
559                         pr_debug("init: %s: reserved %p@%p\n",
560                                  reg->name ?: "(private)",
561                                  (void *)reg->size, (void *)reg->start);
562                         reg->reserved = 1;
563                 } else {
564                         pr_warn("init: %s: unable to reserve %p@%p/%p\n",
565                                 reg->name ?: "(private)",
566                                 (void *)reg->size, (void *)reg->start,
567                                 (void *)reg->alignment);
568                 }
569         }
570 }
571
572
573 static int __init cma_init(void)
574 {
575         struct cma_region *reg, *n;
576
577         pr_debug("init: initialising\n");
578
579         if (cma_map) {
580                 char *val = kmemdup(cma_map, cma_map_length + 1, GFP_KERNEL);
581                 cma_map = val;
582                 if (!val)
583                         return -ENOMEM;
584                 val[cma_map_length] = '\0';
585         }
586
587         list_for_each_entry_safe(reg, n, &cma_early_regions, list) {
588                 INIT_LIST_HEAD(&reg->list);
589                 /*
590                  * We don't care if there was an error.  It's a pity
591                  * but there's not much we can do about it any way.
592                  * If the error is on a region that was parsed from
593                  * command line then it will stay and waste a bit of
594                  * space; if it was registered using
595                  * cma_early_region_register() it's caller's
596                  * responsibility to do something about it.
597                  */
598                 if (reg->reserved && cma_region_register(reg) < 0)
599                         /* ignore error */;
600         }
601
602         INIT_LIST_HEAD(&cma_early_regions);
603
604         return 0;
605 }
606 /*
607  * We want to be initialised earlier than module_init/__initcall so
608  * that drivers that want to grab memory at boot time will get CMA
609  * ready.  subsys_initcall() seems early enough and not too early at
610  * the same time.
611  */
612 subsys_initcall(cma_init);
613
614
615
616 /************************* SysFS *************************/
617
618 #if defined CONFIG_CMA_SYSFS
619
620 static struct kobject cma_sysfs_regions;
621 static int cma_sysfs_regions_ready;
622
623
624 #define CMA_ATTR_INLINE(_type, _name)                                   \
625         (&((struct cma_ ## _type ## _attribute){                        \
626                 .attr   = {                                             \
627                         .name   = __stringify(_name),                   \
628                         .mode   = 0644,                                 \
629                 },                                                      \
630                 .show   = cma_sysfs_ ## _type ## _ ## _name ## _show,   \
631                 .store  = cma_sysfs_ ## _type ## _ ## _name ## _store,  \
632         }).attr)
633
634 #define CMA_ATTR_RO_INLINE(_type, _name)                                \
635         (&((struct cma_ ## _type ## _attribute){                        \
636                 .attr   = {                                             \
637                         .name   = __stringify(_name),                   \
638                         .mode   = 0444,                                 \
639                 },                                                      \
640                 .show   = cma_sysfs_ ## _type ## _ ## _name ## _show,   \
641         }).attr)
642
643
644 struct cma_root_attribute {
645         struct attribute attr;
646         ssize_t (*show)(char *buf);
647         int (*store)(const char *buf);
648 };
649
650 static ssize_t cma_sysfs_root_map_show(char *page)
651 {
652         ssize_t len;
653
654         len = cma_map_length;
655         if (!len) {
656                 *page = 0;
657                 len = 0;
658         } else {
659                 if (len > (size_t)PAGE_SIZE - 1)
660                         len = (size_t)PAGE_SIZE - 1;
661                 memcpy(page, cma_map, len);
662                 page[len++] = '\n';
663         }
664
665         return len;
666 }
667
668 static int cma_sysfs_root_map_store(const char *page)
669 {
670         ssize_t len = cma_map_validate(page);
671         char *val = NULL;
672
673         if (len < 0)
674                 return len;
675
676         if (len) {
677                 val = kmemdup(page, len + 1, GFP_KERNEL);
678                 if (!val)
679                         return -ENOMEM;
680                 val[len] = '\0';
681         }
682
683         kfree(cma_map);
684         cma_map = val;
685         cma_map_length = len;
686
687         return 0;
688 }
689
690 static ssize_t cma_sysfs_root_allocators_show(char *page)
691 {
692         struct cma_allocator *alloc;
693         size_t left = PAGE_SIZE;
694         char *ch = page;
695
696         cma_foreach_allocator(alloc) {
697                 ssize_t l = snprintf(ch, left, "%s ", alloc->name ?: "-");
698                 ch   += l;
699                 left -= l;
700         }
701
702         if (ch != page)
703                 ch[-1] = '\n';
704         return ch - page;
705 }
706
707 static ssize_t
708 cma_sysfs_root_show(struct kobject *kobj, struct attribute *attr, char *buf)
709 {
710         struct cma_root_attribute *rattr =
711                 container_of(attr, struct cma_root_attribute, attr);
712         ssize_t ret;
713
714         mutex_lock(&cma_mutex);
715         ret = rattr->show(buf);
716         mutex_unlock(&cma_mutex);
717
718         return ret;
719 }
720
721 static ssize_t
722 cma_sysfs_root_store(struct kobject *kobj, struct attribute *attr,
723                        const char *buf, size_t count)
724 {
725         struct cma_root_attribute *rattr =
726                 container_of(attr, struct cma_root_attribute, attr);
727         int ret;
728
729         mutex_lock(&cma_mutex);
730         ret = rattr->store(buf);
731         mutex_unlock(&cma_mutex);
732
733         return ret < 0 ? ret : count;
734 }
735
736 static struct kobj_type cma_sysfs_root_type = {
737         .sysfs_ops      = &(const struct sysfs_ops){
738                 .show   = cma_sysfs_root_show,
739                 .store  = cma_sysfs_root_store,
740         },
741         .default_attrs  = (struct attribute * []) {
742                 CMA_ATTR_INLINE(root, map),
743                 CMA_ATTR_RO_INLINE(root, allocators),
744                 NULL
745         },
746 };
747
748 static int __init cma_sysfs_init(void)
749 {
750         static struct kobject root;
751         static struct kobj_type fake_type;
752
753         struct cma_region *reg;
754         int ret;
755
756         /* Root */
757         ret = kobject_init_and_add(&root, &cma_sysfs_root_type,
758                                    mm_kobj, "contiguous");
759         if (unlikely(ret < 0)) {
760                 pr_err("init: unable to add root kobject: %d\n", ret);
761                 return ret;
762         }
763
764         /* Regions */
765         ret = kobject_init_and_add(&cma_sysfs_regions, &fake_type,
766                                    &root, "regions");
767         if (unlikely(ret < 0)) {
768                 pr_err("init: unable to add regions kobject: %d\n", ret);
769                 return ret;
770         }
771
772         mutex_lock(&cma_mutex);
773         cma_sysfs_regions_ready = 1;
774         cma_foreach_region(reg)
775                 __cma_sysfs_region_add(reg);
776         mutex_unlock(&cma_mutex);
777
778         return 0;
779 }
780 device_initcall(cma_sysfs_init);
781
782
783
784 struct cma_region_attribute {
785         struct attribute attr;
786         ssize_t (*show)(struct cma_region *reg, char *buf);
787         int (*store)(struct cma_region *reg, const char *buf);
788 };
789
790
791 static ssize_t cma_sysfs_region_name_show(struct cma_region *reg, char *page)
792 {
793         return reg->name ? snprintf(page, PAGE_SIZE, "%s\n", reg->name) : 0;
794 }
795
796 static ssize_t cma_sysfs_region_start_show(struct cma_region *reg, char *page)
797 {
798         return snprintf(page, PAGE_SIZE, "%p\n", (void *)reg->start);
799 }
800
801 static ssize_t cma_sysfs_region_size_show(struct cma_region *reg, char *page)
802 {
803         return snprintf(page, PAGE_SIZE, "%zu\n", reg->size);
804 }
805
806 static ssize_t cma_sysfs_region_free_show(struct cma_region *reg, char *page)
807 {
808         return snprintf(page, PAGE_SIZE, "%zu\n", reg->free_space);
809 }
810
811 static ssize_t cma_sysfs_region_users_show(struct cma_region *reg, char *page)
812 {
813         return snprintf(page, PAGE_SIZE, "%u\n", reg->users);
814 }
815
816 static ssize_t cma_sysfs_region_alloc_show(struct cma_region *reg, char *page)
817 {
818         if (reg->alloc)
819                 return snprintf(page, PAGE_SIZE, "%s\n",
820                                 reg->alloc->name ?: "-");
821         else if (reg->alloc_name)
822                 return snprintf(page, PAGE_SIZE, "[%s]\n", reg->alloc_name);
823         else
824                 return 0;
825 }
826
827 static int
828 cma_sysfs_region_alloc_store(struct cma_region *reg, const char *page)
829 {
830         char *s;
831
832         if (reg->alloc && reg->users)
833                 return -EBUSY;
834
835         if (!*page || *page == '\n') {
836                 s = NULL;
837         } else {
838                 size_t len;
839
840                 for (s = (char *)page; *++s && *s != '\n'; )
841                         /* nop */;
842
843                 len = s - page;
844                 s = kmemdup(page, len + 1, GFP_KERNEL);
845                 if (!s)
846                         return -ENOMEM;
847                 s[len] = '\0';
848         }
849
850         if (reg->alloc)
851                 __cma_region_detach_alloc(reg);
852
853         if (reg->free_alloc_name)
854                 kfree(reg->alloc_name);
855
856         reg->alloc_name = s;
857         reg->free_alloc_name = !!s;
858
859         return 0;
860 }
861
862
863 static ssize_t
864 cma_sysfs_region_show(struct kobject *kobj, struct attribute *attr,
865                       char *buf)
866 {
867         struct cma_region *reg = container_of(kobj, struct cma_region, kobj);
868         struct cma_region_attribute *rattr =
869                 container_of(attr, struct cma_region_attribute, attr);
870         ssize_t ret;
871
872         mutex_lock(&cma_mutex);
873         ret = rattr->show(reg, buf);
874         mutex_unlock(&cma_mutex);
875
876         return ret;
877 }
878
879 static int
880 cma_sysfs_region_store(struct kobject *kobj, struct attribute *attr,
881                        const char *buf, size_t count)
882 {
883         struct cma_region *reg = container_of(kobj, struct cma_region, kobj);
884         struct cma_region_attribute *rattr =
885                 container_of(attr, struct cma_region_attribute, attr);
886         int ret;
887
888         mutex_lock(&cma_mutex);
889         ret = rattr->store(reg, buf);
890         mutex_unlock(&cma_mutex);
891
892         return ret < 0 ? ret : count;
893 }
894
895 static struct kobj_type cma_sysfs_region_type = {
896         .sysfs_ops      = &(const struct sysfs_ops){
897                 .show   = cma_sysfs_region_show,
898                 .store  = cma_sysfs_region_store,
899         },
900         .default_attrs  = (struct attribute * []) {
901                 CMA_ATTR_RO_INLINE(region, name),
902                 CMA_ATTR_RO_INLINE(region, start),
903                 CMA_ATTR_RO_INLINE(region, size),
904                 CMA_ATTR_RO_INLINE(region, free),
905                 CMA_ATTR_RO_INLINE(region, users),
906                 CMA_ATTR_INLINE(region, alloc),
907                 NULL
908         },
909 };
910
911 static void __cma_sysfs_region_add(struct cma_region *reg)
912 {
913         int ret;
914
915         if (!cma_sysfs_regions_ready)
916                 return;
917
918         memset(&reg->kobj, 0, sizeof reg->kobj);
919
920         ret = kobject_init_and_add(&reg->kobj, &cma_sysfs_region_type,
921                                    &cma_sysfs_regions,
922                                    "%p", (void *)reg->start);
923
924         if (reg->name &&
925             sysfs_create_link(&cma_sysfs_regions, &reg->kobj, reg->name) < 0)
926                 /* Ignore any errors. */;
927 }
928
929 #else
930
931 static void __cma_sysfs_region_add(struct cma_region *reg)
932 {
933         /* nop */
934 }
935
936 #endif
937
938
939 /************************* Chunks *************************/
940
941 /* All chunks sorted by start address. */
942 static struct rb_root cma_chunks_by_start;
943
944 static struct cma_chunk *__must_check __cma_chunk_find(dma_addr_t addr)
945 {
946         struct cma_chunk *chunk;
947         struct rb_node *n;
948
949         for (n = cma_chunks_by_start.rb_node; n; ) {
950                 chunk = rb_entry(n, struct cma_chunk, by_start);
951                 if (addr < chunk->start)
952                         n = n->rb_left;
953                 else if (addr > chunk->start)
954                         n = n->rb_right;
955                 else
956                         return chunk;
957         }
958         WARN(1, KERN_WARNING "no chunk starting at %p\n", (void *)addr);
959         return NULL;
960 }
961
962 static int __must_check __cma_chunk_insert(struct cma_chunk *chunk)
963 {
964         struct rb_node **new, *parent = NULL;
965         typeof(chunk->start) addr = chunk->start;
966
967         for (new = &cma_chunks_by_start.rb_node; *new; ) {
968                 struct cma_chunk *c =
969                         container_of(*new, struct cma_chunk, by_start);
970
971                 parent = *new;
972                 if (addr < c->start) {
973                         new = &(*new)->rb_left;
974                 } else if (addr > c->start) {
975                         new = &(*new)->rb_right;
976                 } else {
977                         /*
978                          * We should never be here.  If we are it
979                          * means allocator gave us an invalid chunk
980                          * (one that has already been allocated) so we
981                          * refuse to accept it.  Our caller will
982                          * recover by freeing the chunk.
983                          */
984                         WARN_ON(1);
985                         return -EADDRINUSE;
986                 }
987         }
988
989         rb_link_node(&chunk->by_start, parent, new);
990         rb_insert_color(&chunk->by_start, &cma_chunks_by_start);
991
992         return 0;
993 }
994
995 static void __cma_chunk_free(struct cma_chunk *chunk)
996 {
997         rb_erase(&chunk->by_start, &cma_chunks_by_start);
998
999         chunk->reg->alloc->free(chunk);
1000         --chunk->reg->users;
1001         chunk->reg->free_space += chunk->size;
1002 }
1003
1004
1005 /************************* The Device API *************************/
1006
1007 static const char *__must_check
1008 __cma_where_from(const struct device *dev, const char *type);
1009
1010
1011 /* Allocate. */
1012
1013 static dma_addr_t __must_check
1014 __cma_alloc_from_region(struct cma_region *reg,
1015                         size_t size, dma_addr_t alignment)
1016 {
1017         struct cma_chunk *chunk;
1018
1019         pr_debug("allocate %p/%p from %s\n",
1020                  (void *)size, (void *)alignment,
1021                  reg ? reg->name ?: "(private)" : "(null)");
1022
1023         if (!reg || reg->free_space < size)
1024                 return -ENOMEM;
1025
1026         if (!reg->alloc) {
1027                 if (!reg->used)
1028                         __cma_region_attach_alloc(reg);
1029                 if (!reg->alloc)
1030                         return -ENOMEM;
1031         }
1032
1033         chunk = reg->alloc->alloc(reg, size, alignment);
1034         if (!chunk)
1035                 return -ENOMEM;
1036
1037         if (unlikely(__cma_chunk_insert(chunk) < 0)) {
1038                 /* We should *never* be here. */
1039                 chunk->reg->alloc->free(chunk);
1040                 kfree(chunk);
1041                 return -EADDRINUSE;
1042         }
1043
1044         chunk->reg = reg;
1045         ++reg->users;
1046         reg->free_space -= chunk->size;
1047         pr_debug("allocated at %p\n", (void *)chunk->start);
1048         return chunk->start;
1049 }
1050
1051 dma_addr_t __must_check
1052 cma_alloc_from_region(struct cma_region *reg,
1053                       size_t size, dma_addr_t alignment)
1054 {
1055         dma_addr_t addr;
1056
1057         pr_debug("allocate %p/%p from %s\n",
1058                  (void *)size, (void *)alignment,
1059                  reg ? reg->name ?: "(private)" : "(null)");
1060
1061         if (!size || alignment & (alignment - 1) || !reg)
1062                 return -EINVAL;
1063
1064         mutex_lock(&cma_mutex);
1065
1066         addr = reg->registered ?
1067                 __cma_alloc_from_region(reg, PAGE_ALIGN(size),
1068                                         max(alignment, (dma_addr_t)PAGE_SIZE)) :
1069                 -EINVAL;
1070
1071         mutex_unlock(&cma_mutex);
1072
1073         return addr;
1074 }
1075 EXPORT_SYMBOL_GPL(cma_alloc_from_region);
1076
1077 dma_addr_t __must_check
1078 __cma_alloc(const struct device *dev, const char *type,
1079             dma_addr_t size, dma_addr_t alignment)
1080 {
1081         struct cma_region *reg;
1082         const char *from;
1083         dma_addr_t addr;
1084
1085         if (dev)
1086                 pr_debug("allocate %p/%p for %s/%s\n",
1087                          (void *)size, (void *)alignment,
1088                          dev_name(dev), type ?: "");
1089
1090         if (!size || alignment & (alignment - 1))
1091                 return -EINVAL;
1092
1093         size = PAGE_ALIGN(size);
1094         if (alignment < PAGE_SIZE)
1095                 alignment = PAGE_SIZE;
1096
1097         mutex_lock(&cma_mutex);
1098
1099         from = __cma_where_from(dev, type);
1100         if (unlikely(IS_ERR(from))) {
1101                 addr = PTR_ERR(from);
1102                 goto done;
1103         }
1104
1105         pr_debug("allocate %p/%p from one of %s\n",
1106                  (void *)size, (void *)alignment, from);
1107
1108         while (*from && *from != ';') {
1109                 reg = __cma_region_find(&from);
1110                 addr = __cma_alloc_from_region(reg, size, alignment);
1111                 if (!IS_ERR_VALUE(addr))
1112                         goto done;
1113         }
1114
1115         pr_debug("not enough memory\n");
1116         addr = -ENOMEM;
1117
1118 done:
1119         mutex_unlock(&cma_mutex);
1120
1121         return addr;
1122 }
1123 EXPORT_SYMBOL_GPL(__cma_alloc);
1124
1125
1126 void *cma_get_virt(dma_addr_t phys, dma_addr_t size, int noncached)
1127 {
1128         unsigned long num_pages, i;
1129         struct page **pages;
1130         void *virt;
1131
1132         if (noncached) {
1133                 num_pages = size >> PAGE_SHIFT;
1134                 pages = kmalloc(num_pages * sizeof(struct page *), GFP_KERNEL);
1135
1136                 if (!pages)
1137                         return ERR_PTR(-ENOMEM);
1138
1139                 for (i = 0; i < num_pages; i++)
1140                         pages[i] = pfn_to_page((phys >> PAGE_SHIFT) + i);
1141
1142                 virt = vmap(pages, num_pages, VM_MAP,
1143                         pgprot_writecombine(PAGE_KERNEL));
1144
1145                 if (!virt) {
1146                         kfree(pages);
1147                         return ERR_PTR(-ENOMEM);
1148                 }
1149
1150                 kfree(pages);
1151         } else {
1152                 virt = phys_to_virt((unsigned long)phys);
1153         }
1154
1155         return virt;
1156 }
1157 EXPORT_SYMBOL_GPL(cma_get_virt);
1158
1159 /* Query information about regions. */
1160 static void __cma_info_add(struct cma_info *infop, struct cma_region *reg)
1161 {
1162         infop->total_size += reg->size;
1163         infop->free_size += reg->free_space;
1164         if (infop->lower_bound > reg->start)
1165                 infop->lower_bound = reg->start;
1166         if (infop->upper_bound < reg->start + reg->size)
1167                 infop->upper_bound = reg->start + reg->size;
1168         ++infop->count;
1169 }
1170
1171 int
1172 __cma_info(struct cma_info *infop, const struct device *dev, const char *type)
1173 {
1174         struct cma_info info = { ~(dma_addr_t)0, 0, 0, 0, 0 };
1175         struct cma_region *reg;
1176         const char *from;
1177         int ret;
1178
1179         if (unlikely(!infop))
1180                 return -EINVAL;
1181
1182         mutex_lock(&cma_mutex);
1183
1184         from = __cma_where_from(dev, type);
1185         if (IS_ERR(from)) {
1186                 ret = PTR_ERR(from);
1187                 info.lower_bound = 0;
1188                 goto done;
1189         }
1190
1191         while (*from && *from != ';') {
1192                 reg = __cma_region_find(&from);
1193                 if (reg)
1194                         __cma_info_add(&info, reg);
1195         }
1196
1197         ret = 0;
1198 done:
1199         mutex_unlock(&cma_mutex);
1200
1201         memcpy(infop, &info, sizeof info);
1202         return ret;
1203 }
1204 EXPORT_SYMBOL_GPL(__cma_info);
1205
1206
1207 /* Freeing. */
1208 int cma_free(dma_addr_t addr)
1209 {
1210         struct cma_chunk *c;
1211         int ret;
1212
1213         mutex_lock(&cma_mutex);
1214
1215         c = __cma_chunk_find(addr);
1216
1217         if (c) {
1218                 __cma_chunk_free(c);
1219                 ret = 0;
1220         } else {
1221                 ret = -ENOENT;
1222         }
1223
1224         mutex_unlock(&cma_mutex);
1225
1226         if (c)
1227                 pr_debug("free(%p): freed\n", (void *)addr);
1228         else
1229                 pr_err("free(%p): not found\n", (void *)addr);
1230         return ret;
1231 }
1232 EXPORT_SYMBOL_GPL(cma_free);
1233
1234
1235 /************************* Miscellaneous *************************/
1236
1237 static int __cma_region_attach_alloc(struct cma_region *reg)
1238 {
1239         struct cma_allocator *alloc;
1240         int ret;
1241
1242         /*
1243          * If reg->alloc is set then caller wants us to use this
1244          * allocator.  Otherwise we need to find one by name.
1245          */
1246         if (reg->alloc) {
1247                 alloc = reg->alloc;
1248         } else {
1249                 alloc = __cma_allocator_find(reg->alloc_name);
1250                 if (!alloc) {
1251                         pr_warn("init: %s: %s: no such allocator\n",
1252                                 reg->name ?: "(private)",
1253                                 reg->alloc_name ?: "(default)");
1254                         reg->used = 1;
1255                         return -ENOENT;
1256                 }
1257         }
1258
1259         /* Try to initialise the allocator. */
1260         reg->private_data = NULL;
1261         ret = alloc->init ? alloc->init(reg) : 0;
1262         if (unlikely(ret < 0)) {
1263                 pr_err("init: %s: %s: unable to initialise allocator\n",
1264                        reg->name ?: "(private)", alloc->name ?: "(unnamed)");
1265                 reg->alloc = NULL;
1266                 reg->used = 1;
1267         } else {
1268                 reg->alloc = alloc;
1269                 pr_debug("init: %s: %s: initialised allocator\n",
1270                          reg->name ?: "(private)", alloc->name ?: "(unnamed)");
1271         }
1272         return ret;
1273 }
1274
1275 static void __cma_region_detach_alloc(struct cma_region *reg)
1276 {
1277         if (!reg->alloc)
1278                 return;
1279
1280         if (reg->alloc->cleanup)
1281                 reg->alloc->cleanup(reg);
1282
1283         reg->alloc = NULL;
1284         reg->used = 1;
1285 }
1286
1287
1288 /*
1289  * s            ::= rules
1290  * rules        ::= rule [ ';' rules ]
1291  * rule         ::= patterns '=' regions
1292  * patterns     ::= pattern [ ',' patterns ]
1293  * regions      ::= REG-NAME [ ',' regions ]
1294  * pattern      ::= dev-pattern [ '/' TYPE-NAME ] | '/' TYPE-NAME
1295  */
1296 static const char *__must_check
1297 __cma_where_from(const struct device *dev, const char *type)
1298 {
1299         /*
1300          * This function matches the pattern from the map attribute
1301          * agains given device name and type.  Type may be of course
1302          * NULL or an emtpy string.
1303          */
1304
1305         const char *s, *name;
1306         int name_matched = 0;
1307
1308         /*
1309          * If dev is NULL we were called in alternative form where
1310          * type is the from string.  All we have to do is return it.
1311          */
1312         if (!dev)
1313                 return type ?: ERR_PTR(-EINVAL);
1314
1315         if (!cma_map)
1316                 return ERR_PTR(-ENOENT);
1317
1318         name = dev_name(dev);
1319         if (WARN_ON(!name || !*name))
1320                 return ERR_PTR(-EINVAL);
1321
1322         if (!type)
1323                 type = "common";
1324
1325         /*
1326          * Now we go throught the cma_map attribute.
1327          */
1328         for (s = cma_map; *s; ++s) {
1329                 const char *c;
1330
1331                 /*
1332                  * If the pattern starts with a slash, the device part of the
1333                  * pattern matches if it matched previously.
1334                  */
1335                 if (*s == '/') {
1336                         if (!name_matched)
1337                                 goto look_for_next;
1338                         goto match_type;
1339                 }
1340
1341                 /*
1342                  * We are now trying to match the device name.  This also
1343                  * updates the name_matched variable.  If, while reading the
1344                  * spec, we ecnounter comma it means that the pattern does not
1345                  * match and we need to start over with another pattern (the
1346                  * one afther the comma).  If we encounter equal sign we need
1347                  * to start over with another rule.  If there is a character
1348                  * that does not match, we neet to look for a comma (to get
1349                  * another pattern) or semicolon (to get another rule) and try
1350                  * again if there is one somewhere.
1351                  */
1352
1353                 name_matched = 0;
1354
1355                 for (c = name; *s != '*' && *c; ++c, ++s)
1356                         if (*s == '=')
1357                                 goto next_rule;
1358                         else if (*s == ',')
1359                                 goto next_pattern;
1360                         else if (*s != '?' && *c != *s)
1361                                 goto look_for_next;
1362                 if (*s == '*')
1363                         ++s;
1364
1365                 name_matched = 1;
1366
1367                 /*
1368                  * Now we need to match the type part of the pattern.  If the
1369                  * pattern is missing it we match only if type points to an
1370                  * empty string.  Otherwise wy try to match it just like name.
1371                  */
1372                 if (*s == '/') {
1373 match_type:             /* s points to '/' */
1374                         ++s;
1375
1376                         for (c = type; *s && *c; ++c, ++s)
1377                                 if (*s == '=')
1378                                         goto next_rule;
1379                                 else if (*s == ',')
1380                                         goto next_pattern;
1381                                 else if (*c != *s)
1382                                         goto look_for_next;
1383                 }
1384
1385                 /* Return the string behind the '=' sign of the rule. */
1386                 if (*s == '=')
1387                         return s + 1;
1388                 else if (*s == ',')
1389                         return strchr(s, '=') + 1;
1390
1391                 /* Pattern did not match */
1392
1393 look_for_next:
1394                 do {
1395                         ++s;
1396                 } while (*s != ',' && *s != '=');
1397                 if (*s == ',')
1398                         continue;
1399
1400 next_rule:      /* s points to '=' */
1401                 s = strchr(s, ';');
1402                 if (!s)
1403                         break;
1404
1405 next_pattern:
1406                 continue;
1407         }
1408
1409         return ERR_PTR(-ENOENT);
1410 }