]> bbs.cooldavid.org Git - net-next-2.6.git/blob - drivers/staging/memrar/memrar_handler.c
rar: Move the RAR driver into the right place as its now clean
[net-next-2.6.git] / drivers / staging / memrar / memrar_handler.c
1 /*
2  *      memrar_handler 1.0:  An Intel restricted access region handler device
3  *
4  *      Copyright (C) 2010 Intel Corporation. All rights reserved.
5  *
6  *      This program is free software; you can redistribute it and/or
7  *      modify it under the terms of version 2 of the GNU General
8  *      Public License as published by the Free Software Foundation.
9  *
10  *      This program is distributed in the hope that it will be
11  *      useful, but WITHOUT ANY WARRANTY; without even the implied
12  *      warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
13  *      PURPOSE.  See the GNU General Public License for more details.
14  *      You should have received a copy of the GNU General Public
15  *      License along with this program; if not, write to the Free
16  *      Software Foundation, Inc., 59 Temple Place - Suite 330,
17  *      Boston, MA  02111-1307, USA.
18  *      The full GNU General Public License is included in this
19  *      distribution in the file called COPYING.
20  *
21  * -------------------------------------------------------------------
22  *
23  *      Moorestown restricted access regions (RAR) provide isolated
24  *      areas of main memory that are only acceessible by authorized
25  *      devices.
26  *
27  *      The Intel Moorestown RAR handler module exposes a kernel space
28  *      RAR memory management mechanism.  It is essentially a
29  *      RAR-specific allocator.
30  *
31  *      Besides providing RAR buffer management, the RAR handler also
32  *      behaves in many ways like an OS virtual memory manager.  For
33  *      example, the RAR "handles" created by the RAR handler are
34  *      analogous to user space virtual addresses.
35  *
36  *      RAR memory itself is never accessed directly by the RAR
37  *      handler.
38  */
39
40 #include <linux/miscdevice.h>
41 #include <linux/fs.h>
42 #include <linux/slab.h>
43 #include <linux/kref.h>
44 #include <linux/mutex.h>
45 #include <linux/kernel.h>
46 #include <linux/uaccess.h>
47 #include <linux/mm.h>
48 #include <linux/ioport.h>
49 #include <linux/io.h>
50 #include <linux/rar_register.h>
51
52 #include "memrar.h"
53 #include "memrar_allocator.h"
54
55
56 #define MEMRAR_VER "1.0"
57
58 /*
59  * Moorestown supports three restricted access regions.
60  *
61  * We only care about the first two, video and audio.  The third,
62  * reserved for Chaabi and the P-unit, will be handled by their
63  * respective drivers.
64  */
65 #define MRST_NUM_RAR 2
66
67 /* ---------------- -------------------- ------------------- */
68
69 /**
70  * struct memrar_buffer_info - struct that keeps track of all RAR buffers
71  * @list:       Linked list of memrar_buffer_info objects.
72  * @buffer:     Core RAR buffer information.
73  * @refcount:   Reference count.
74  * @owner:      File handle corresponding to process that reserved the
75  *              block of memory in RAR.  This will be zero for buffers
76  *              allocated by other drivers instead of by a user space
77  *              process.
78  *
79  * This structure encapsulates a link list of RAR buffers, as well as
80  * other characteristics specific to a given list node, such as the
81  * reference count on the corresponding RAR buffer.
82  */
83 struct memrar_buffer_info {
84         struct list_head list;
85         struct RAR_buffer buffer;
86         struct kref refcount;
87         struct file *owner;
88 };
89
90 /**
91  * struct memrar_rar_info - characteristics of a given RAR
92  * @base:       Base bus address of the RAR.
93  * @length:     Length of the RAR.
94  * @iobase:     Virtual address of RAR mapped into kernel.
95  * @allocator:  Allocator associated with the RAR.  Note the allocator
96  *              "capacity" may be smaller than the RAR length if the
97  *              length is not a multiple of the configured allocator
98  *              block size.
99  * @buffers:    Table that keeps track of all reserved RAR buffers.
100  * @lock:       Lock used to synchronize access to RAR-specific data
101  *              structures.
102  *
103  * Each RAR has an associated memrar_rar_info structure that describes
104  * where in memory the RAR is located, how large it is, and a list of
105  * reserved RAR buffers inside that RAR.  Each RAR also has a mutex
106  * associated with it to reduce lock contention when operations on
107  * multiple RARs are performed in parallel.
108  */
109 struct memrar_rar_info {
110         dma_addr_t base;
111         unsigned long length;
112         void __iomem *iobase;
113         struct memrar_allocator *allocator;
114         struct memrar_buffer_info buffers;
115         struct mutex lock;
116         int allocated;  /* True if we own this RAR */
117 };
118
119 /*
120  * Array of RAR characteristics.
121  */
122 static struct memrar_rar_info memrars[MRST_NUM_RAR];
123
124 /* ---------------- -------------------- ------------------- */
125
126 /* Validate RAR type. */
127 static inline int memrar_is_valid_rar_type(u32 type)
128 {
129         return type == RAR_TYPE_VIDEO || type == RAR_TYPE_AUDIO;
130 }
131
132 /* Check if an address/handle falls with the given RAR memory range. */
133 static inline int memrar_handle_in_range(struct memrar_rar_info *rar,
134                                          u32 vaddr)
135 {
136         unsigned long const iobase = (unsigned long) (rar->iobase);
137         return (vaddr >= iobase && vaddr < iobase + rar->length);
138 }
139
140 /* Retrieve RAR information associated with the given handle. */
141 static struct memrar_rar_info *memrar_get_rar_info(u32 vaddr)
142 {
143         int i;
144         for (i = 0; i < MRST_NUM_RAR; ++i) {
145                 struct memrar_rar_info * const rar = &memrars[i];
146                 if (memrar_handle_in_range(rar, vaddr))
147                         return rar;
148         }
149
150         return NULL;
151 }
152
153 /**
154  *      memrar_get_bus address          -       handle to bus address
155  *
156  *      Retrieve bus address from given handle.
157  *
158  *      Returns address corresponding to given handle.  Zero if handle is
159  *      invalid.
160  */
161 static dma_addr_t memrar_get_bus_address(
162         struct memrar_rar_info *rar,
163         u32 vaddr)
164 {
165         unsigned long const iobase = (unsigned long) (rar->iobase);
166
167         if (!memrar_handle_in_range(rar, vaddr))
168                 return 0;
169
170         /*
171          * An assumption is made that the virtual address offset is
172          * the same as the bus address offset, at least based on the
173          * way this driver is implemented.  For example, vaddr + 2 ==
174          * baddr + 2.
175          *
176          * @todo Is that a valid assumption?
177          */
178         return rar->base + (vaddr - iobase);
179 }
180
181 /**
182  *      memrar_get_physical_address     -       handle to physical address
183  *
184  *      Retrieve physical address from given handle.
185  *
186  *      Returns address corresponding to given handle.  Zero if handle is
187  *      invalid.
188  */
189 static dma_addr_t memrar_get_physical_address(
190         struct memrar_rar_info *rar,
191         u32 vaddr)
192 {
193         /*
194          * @todo This assumes that the bus address and physical
195          *       address are the same.  That is true for Moorestown
196          *       but not necessarily on other platforms.  This
197          *       deficiency should be addressed at some point.
198          */
199         return memrar_get_bus_address(rar, vaddr);
200 }
201
202 /**
203  *      memrar_release_block    -       release a block to the pool
204  *      @kref: kref of block
205  *
206  *      Core block release code. A node has hit zero references so can
207  *      be released and the lists must be updated.
208  *
209  *      Note: This code removes the node from a list.  Make sure any list
210  *      iteration is performed using list_for_each_safe().
211  */
212 static void memrar_release_block_i(struct kref *ref)
213 {
214         /*
215          * Last reference is being released.  Remove from the table,
216          * and reclaim resources.
217          */
218
219         struct memrar_buffer_info * const node =
220                 container_of(ref, struct memrar_buffer_info, refcount);
221
222         struct RAR_block_info * const user_info =
223                 &node->buffer.info;
224
225         struct memrar_allocator * const allocator =
226                 memrars[user_info->type].allocator;
227
228         list_del(&node->list);
229
230         memrar_allocator_free(allocator, user_info->handle);
231
232         kfree(node);
233 }
234
235 /**
236  *      memrar_init_rar_resources       -       configure a RAR
237  *      @rarnum: rar that has been allocated
238  *      @devname: name of our device
239  *
240  *      Initialize RAR parameters, such as bus addresses, etc and make
241  *      the resource accessible.
242  */
243 static int memrar_init_rar_resources(int rarnum, char const *devname)
244 {
245         /* ---- Sanity Checks ----
246          * 1. RAR bus addresses in both Lincroft and Langwell RAR
247          *    registers should be the same.
248          *    a. There's no way we can do this through IA.
249          *
250          * 2. Secure device ID in Langwell RAR registers should be set
251          *    appropriately, e.g. only LPE DMA for the audio RAR, and
252          *    security for the other Langwell based RAR registers.
253          *    a. There's no way we can do this through IA.
254          *
255          * 3. Audio and video RAR registers and RAR access should be
256          *    locked down.  If not, enable RAR access control.  Except
257          *    for debugging purposes, there is no reason for them to
258          *    be unlocked.
259          *    a.  We can only do this for the Lincroft (IA) side.
260          *
261          * @todo Should the RAR handler driver even be aware of audio
262          *       and video RAR settings?
263          */
264
265         /*
266          * RAR buffer block size.
267          *
268          * We choose it to be the size of a page to simplify the
269          * /dev/memrar mmap() implementation and usage.  Otherwise
270          * paging is not involved once an RAR is locked down.
271          */
272         static size_t const RAR_BLOCK_SIZE = PAGE_SIZE;
273
274         dma_addr_t low, high;
275         struct memrar_rar_info * const rar = &memrars[rarnum];
276
277         BUG_ON(MRST_NUM_RAR != ARRAY_SIZE(memrars));
278         BUG_ON(!memrar_is_valid_rar_type(rarnum));
279         BUG_ON(rar->allocated);
280
281         mutex_init(&rar->lock);
282
283         /*
284          * Initialize the process table before we reach any
285          * code that exit on failure since the finalization
286          * code requires an initialized list.
287          */
288         INIT_LIST_HEAD(&rar->buffers.list);
289
290         if (rar_get_address(rarnum, &low, &high) != 0)
291                 /* No RAR is available. */
292                 return -ENODEV;
293         
294         if (low == 0 || high == 0) {
295                 rar->base      = 0;
296                 rar->length    = 0;
297                 rar->iobase    = NULL;
298                 rar->allocator = NULL;
299                 return -ENOSPC;
300         }
301
302         /*
303          * @todo Verify that LNC and LNW RAR register contents
304          *       addresses, security, etc are compatible and
305          *       consistent).
306          */
307
308         rar->length = high - low + 1;
309
310         /* Claim RAR memory as our own. */
311         if (request_mem_region(low, rar->length, devname) == NULL) {
312                 rar->length = 0;
313                 pr_err("%s: Unable to claim RAR[%d] memory.\n", devname, rarnum);
314                 pr_err("%s: RAR[%d] disabled.\n", devname, rarnum);
315                 return -EBUSY;
316         }
317
318         rar->base = low;
319
320         /*
321          * Now map it into the kernel address space.
322          *
323          * Note that the RAR memory may only be accessed by IA
324          * when debugging.  Otherwise attempts to access the
325          * RAR memory when it is locked down will result in
326          * behavior similar to writing to /dev/null and
327          * reading from /dev/zero.  This behavior is enforced
328          * by the hardware.  Even if we don't access the
329          * memory, mapping it into the kernel provides us with
330          * a convenient RAR handle to bus address mapping.
331          */
332         rar->iobase = ioremap_nocache(rar->base, rar->length);
333         if (rar->iobase == NULL) {
334                 pr_err("%s: Unable to map RAR memory.\n", devname);
335                 release_mem_region(low, rar->length);
336                 return -ENOMEM;
337         }
338
339         /* Initialize corresponding memory allocator. */
340         rar->allocator = memrar_create_allocator((unsigned long) rar->iobase,
341                                                 rar->length, RAR_BLOCK_SIZE);
342         if (rar->allocator == NULL) {
343                 iounmap(rar->iobase);
344                 release_mem_region(low, rar->length);
345                 return -ENOMEM;
346         }
347
348         pr_info("%s: BRAR[%d] bus address range = [0x%lx, 0x%lx]\n",
349                         devname, rarnum, (unsigned long) low, (unsigned long) high);
350
351         pr_info("%s: BRAR[%d] size = %zu KiB\n",
352                         devname, rarnum, rar->allocator->capacity / 1024);
353
354         rar->allocated = 1;
355         return 0;
356 }
357
358 /**
359  *      memrar_fini_rar_resources       -       free up RAR resources
360  *
361  *      Finalize RAR resources. Free up the resource tables, hand the memory
362  *      back to the kernel, unmap the device and release the address space.
363  */
364 static void memrar_fini_rar_resources(void)
365 {
366         int z;
367         struct memrar_buffer_info *pos;
368         struct memrar_buffer_info *tmp;
369
370         /*
371          * @todo Do we need to hold a lock at this point in time?
372          *       (module initialization failure or exit?)
373          */
374
375         for (z = MRST_NUM_RAR; z-- != 0; ) {
376                 struct memrar_rar_info * const rar = &memrars[z];
377
378                 if (!rar->allocated)
379                         continue;
380
381                 /* Clean up remaining resources. */
382
383                 list_for_each_entry_safe(pos,
384                                          tmp,
385                                          &rar->buffers.list,
386                                          list) {
387                         kref_put(&pos->refcount, memrar_release_block_i);
388                 }
389
390                 memrar_destroy_allocator(rar->allocator);
391                 rar->allocator = NULL;
392
393                 iounmap(rar->iobase);
394                 release_mem_region(rar->base, rar->length);
395
396                 rar->iobase = NULL;
397                 rar->base = 0;
398                 rar->length = 0;
399
400                 unregister_rar(z);
401         }
402 }
403
404 /**
405  *      memrar_reserve_block    -       handle an allocation request
406  *      @request: block being requested
407  *      @filp: owner it is tied to
408  *
409  *      Allocate a block of the requested RAR. If successful return the
410  *      request object filled in and zero, if not report an error code
411  */
412
413 static long memrar_reserve_block(struct RAR_buffer *request,
414                                  struct file *filp)
415 {
416         struct RAR_block_info * const rinfo = &request->info;
417         struct RAR_buffer *buffer;
418         struct memrar_buffer_info *buffer_info;
419         u32 handle;
420         struct memrar_rar_info *rar = NULL;
421
422         /* Prevent array overflow. */
423         if (!memrar_is_valid_rar_type(rinfo->type))
424                 return -EINVAL;
425
426         rar = &memrars[rinfo->type];
427         if (!rar->allocated)
428                 return -ENODEV;
429
430         /* Reserve memory in RAR. */
431         handle = memrar_allocator_alloc(rar->allocator, rinfo->size);
432         if (handle == 0)
433                 return -ENOMEM;
434
435         buffer_info = kmalloc(sizeof(*buffer_info), GFP_KERNEL);
436
437         if (buffer_info == NULL) {
438                 memrar_allocator_free(rar->allocator, handle);
439                 return -ENOMEM;
440         }
441
442         buffer = &buffer_info->buffer;
443         buffer->info.type = rinfo->type;
444         buffer->info.size = rinfo->size;
445
446         /* Memory handle corresponding to the bus address. */
447         buffer->info.handle = handle;
448         buffer->bus_address = memrar_get_bus_address(rar, handle);
449
450         /*
451          * Keep track of owner so that we can later cleanup if
452          * necessary.
453          */
454         buffer_info->owner = filp;
455
456         kref_init(&buffer_info->refcount);
457
458         mutex_lock(&rar->lock);
459         list_add(&buffer_info->list, &rar->buffers.list);
460         mutex_unlock(&rar->lock);
461
462         rinfo->handle = buffer->info.handle;
463         request->bus_address = buffer->bus_address;
464
465         return 0;
466 }
467
468 /**
469  *      memrar_release_block            -       release a RAR block
470  *      @addr: address in RAR space
471  *
472  *      Release a previously allocated block. Releases act on complete
473  *      blocks, partially freeing a block is not supported
474  */
475
476 static long memrar_release_block(u32 addr)
477 {
478         struct memrar_buffer_info *pos;
479         struct memrar_buffer_info *tmp;
480         struct memrar_rar_info * const rar = memrar_get_rar_info(addr);
481         long result = -EINVAL;
482
483         if (rar == NULL)
484                 return -ENOENT;
485
486         mutex_lock(&rar->lock);
487
488         /*
489          * Iterate through the buffer list to find the corresponding
490          * buffer to be released.
491          */
492         list_for_each_entry_safe(pos,
493                                  tmp,
494                                  &rar->buffers.list,
495                                  list) {
496                 struct RAR_block_info * const info =
497                         &pos->buffer.info;
498
499                 /*
500                  * Take into account handle offsets that may have been
501                  * added to the base handle, such as in the following
502                  * scenario:
503                  *
504                  *     u32 handle = base + offset;
505                  *     rar_handle_to_bus(handle);
506                  *     rar_release(handle);
507                  */
508                 if (addr >= info->handle
509                     && addr < (info->handle + info->size)
510                     && memrar_is_valid_rar_type(info->type)) {
511                         kref_put(&pos->refcount, memrar_release_block_i);
512                         result = 0;
513                         break;
514                 }
515         }
516
517         mutex_unlock(&rar->lock);
518
519         return result;
520 }
521
522 /**
523  *      memrar_get_stats        -       read statistics for a RAR
524  *      @r: statistics to be filled in
525  *
526  *      Returns the statistics data for the RAR, or an error code if
527  *      the request cannot be completed
528  */
529 static long memrar_get_stat(struct RAR_stat *r)
530 {
531         struct memrar_allocator *allocator;
532
533         if (!memrar_is_valid_rar_type(r->type))
534                 return -EINVAL;
535
536         if (!memrars[r->type].allocated)
537                 return -ENODEV;
538
539         allocator = memrars[r->type].allocator;
540
541         BUG_ON(allocator == NULL);
542
543         /*
544          * Allocator capacity doesn't change over time.  No
545          * need to synchronize.
546          */
547         r->capacity = allocator->capacity;
548
549         mutex_lock(&allocator->lock);
550         r->largest_block_size = allocator->largest_free_area;
551         mutex_unlock(&allocator->lock);
552         return 0;
553 }
554
555 /**
556  *      memrar_ioctl            -       ioctl callback
557  *      @filp: file issuing the request
558  *      @cmd: command
559  *      @arg: pointer to control information
560  *
561  *      Perform one of the ioctls supported by the memrar device
562  */
563
564 static long memrar_ioctl(struct file *filp,
565                          unsigned int cmd,
566                          unsigned long arg)
567 {
568         void __user *argp = (void __user *)arg;
569         long result = 0;
570
571         struct RAR_buffer buffer;
572         struct RAR_block_info * const request = &buffer.info;
573         struct RAR_stat rar_info;
574         u32 rar_handle;
575
576         switch (cmd) {
577         case RAR_HANDLER_RESERVE:
578                 if (copy_from_user(request,
579                                    argp,
580                                    sizeof(*request)))
581                         return -EFAULT;
582
583                 result = memrar_reserve_block(&buffer, filp);
584                 if (result != 0)
585                         return result;
586
587                 return copy_to_user(argp, request, sizeof(*request));
588
589         case RAR_HANDLER_RELEASE:
590                 if (copy_from_user(&rar_handle,
591                                    argp,
592                                    sizeof(rar_handle)))
593                         return -EFAULT;
594
595                 return memrar_release_block(rar_handle);
596
597         case RAR_HANDLER_STAT:
598                 if (copy_from_user(&rar_info,
599                                    argp,
600                                    sizeof(rar_info)))
601                         return -EFAULT;
602
603                 /*
604                  * Populate the RAR_stat structure based on the RAR
605                  * type given by the user
606                  */
607                 if (memrar_get_stat(&rar_info) != 0)
608                         return -EINVAL;
609
610                 /*
611                  * @todo Do we need to verify destination pointer
612                  *       "argp" is non-zero?  Is that already done by
613                  *       copy_to_user()?
614                  */
615                 return copy_to_user(argp,
616                                     &rar_info,
617                                     sizeof(rar_info)) ? -EFAULT : 0;
618
619         default:
620                 return -ENOTTY;
621         }
622
623         return 0;
624 }
625
626 /**
627  *      memrar_mmap             -       mmap helper for deubgging
628  *      @filp: handle doing the mapping
629  *      @vma: memory area
630  *
631  *      Support the mmap operation on the RAR space for debugging systems
632  *      when the memory is not locked down.
633  */
634
635 static int memrar_mmap(struct file *filp, struct vm_area_struct *vma)
636 {
637         /*
638          * This mmap() implementation is predominantly useful for
639          * debugging since the CPU will be prevented from accessing
640          * RAR memory by the hardware when RAR is properly locked
641          * down.
642          *
643          * In order for this implementation to be useful RAR memory
644          * must be not be locked down.  However, we only want to do
645          * that when debugging.  DO NOT leave RAR memory unlocked in a
646          * deployed device that utilizes RAR.
647          */
648
649         size_t const size = vma->vm_end - vma->vm_start;
650
651         /* Users pass the RAR handle as the mmap() offset parameter. */
652         unsigned long const handle = vma->vm_pgoff << PAGE_SHIFT;
653
654         struct memrar_rar_info * const rar = memrar_get_rar_info(handle);
655         unsigned long pfn;
656
657         /* Only allow priviledged apps to go poking around this way */
658         if (!capable(CAP_SYS_RAWIO))
659                 return -EPERM;
660
661         /* Invalid RAR handle or size passed to mmap(). */
662         if (rar == NULL
663             || handle == 0
664             || size > (handle - (unsigned long) rar->iobase))
665                 return -EINVAL;
666
667         /*
668          * Retrieve physical address corresponding to the RAR handle,
669          * and convert it to a page frame.
670          */
671         pfn = memrar_get_physical_address(rar, handle) >> PAGE_SHIFT;
672
673
674         pr_debug("memrar: mapping RAR range [0x%lx, 0x%lx) into user space.\n",
675                  handle,
676                  handle + size);
677
678         /*
679          * Map RAR memory into user space.  This is really only useful
680          * for debugging purposes since the memory won't be
681          * accessible, i.e. reads return zero and writes are ignored,
682          * when RAR access control is enabled.
683          */
684         if (remap_pfn_range(vma,
685                             vma->vm_start,
686                             pfn,
687                             size,
688                             vma->vm_page_prot))
689                 return -EAGAIN;
690
691         /* vma->vm_ops = &memrar_mem_ops; */
692
693         return 0;
694 }
695
696 /**
697  *      memrar_open             -       device open method
698  *      @inode: inode to open
699  *      @filp: file handle
700  *
701  *      As we support multiple arbitary opens there is no work to be done
702  *      really.
703  */
704
705 static int memrar_open(struct inode *inode, struct file *filp)
706 {
707         nonseekable_open(inode, filp);
708         return 0;
709 }
710
711 /**
712  *      memrar_release          -       close method for miscev
713  *      @inode: inode of device
714  *      @filp: handle that is going away
715  *
716  *      Free up all the regions that belong to this file handle. We use
717  *      the handle as a natural Linux style 'lifetime' indicator and to
718  *      ensure resources are not leaked when their owner explodes in an
719  *      unplanned fashion.
720  */
721
722 static int memrar_release(struct inode *inode, struct file *filp)
723 {
724         /* Free all regions associated with the given file handle. */
725
726         struct memrar_buffer_info *pos;
727         struct memrar_buffer_info *tmp;
728         int z;
729
730         for (z = 0; z != MRST_NUM_RAR; ++z) {
731                 struct memrar_rar_info * const rar = &memrars[z];
732
733                 mutex_lock(&rar->lock);
734
735                 list_for_each_entry_safe(pos,
736                                          tmp,
737                                          &rar->buffers.list,
738                                          list) {
739                         if (filp == pos->owner)
740                                 kref_put(&pos->refcount,
741                                          memrar_release_block_i);
742                 }
743
744                 mutex_unlock(&rar->lock);
745         }
746
747         return 0;
748 }
749
750 /**
751  *      rar_reserve             -       reserve RAR memory
752  *      @buffers: buffers to reserve
753  *      @count: number wanted
754  *
755  *      Reserve a series of buffers in the RAR space. Returns the number of
756  *      buffers successfully allocated
757  */
758
759 size_t rar_reserve(struct RAR_buffer *buffers, size_t count)
760 {
761         struct RAR_buffer * const end =
762                 (buffers == NULL ? buffers : buffers + count);
763         struct RAR_buffer *i;
764
765         size_t reserve_count = 0;
766
767         for (i = buffers; i != end; ++i) {
768                 if (memrar_reserve_block(i, NULL) == 0)
769                         ++reserve_count;
770                 else
771                         i->bus_address = 0;
772         }
773
774         return reserve_count;
775 }
776 EXPORT_SYMBOL(rar_reserve);
777
778 /**
779  *      rar_release             -       return RAR buffers
780  *      @buffers: buffers to release
781  *      @size: size of released block
782  *
783  *      Return a set of buffers to the RAR pool
784  */
785
786 size_t rar_release(struct RAR_buffer *buffers, size_t count)
787 {
788         struct RAR_buffer * const end =
789                 (buffers == NULL ? buffers : buffers + count);
790         struct RAR_buffer *i;
791
792         size_t release_count = 0;
793
794         for (i = buffers; i != end; ++i) {
795                 u32 * const handle = &i->info.handle;
796                 if (memrar_release_block(*handle) == 0) {
797                         /*
798                          * @todo We assume we should do this each time
799                          *       the ref count is decremented.  Should
800                          *       we instead only do this when the ref
801                          *       count has dropped to zero, and the
802                          *       buffer has been completely
803                          *       released/unmapped?
804                          */
805                         *handle = 0;
806                         ++release_count;
807                 }
808         }
809
810         return release_count;
811 }
812 EXPORT_SYMBOL(rar_release);
813
814 /**
815  *      rar_handle_to_bus       -       RAR to bus address
816  *      @buffers: RAR buffer structure
817  *      @count: number of buffers to convert
818  *
819  *      Turn a list of RAR handle mappings into actual bus addresses. Note
820  *      that when the device is locked down the bus addresses in question
821  *      are not CPU accessible.
822  */
823
824 size_t rar_handle_to_bus(struct RAR_buffer *buffers, size_t count)
825 {
826         struct RAR_buffer * const end =
827                 (buffers == NULL ? buffers : buffers + count);
828         struct RAR_buffer *i;
829         struct memrar_buffer_info *pos;
830
831         size_t conversion_count = 0;
832
833         /*
834          * Find all bus addresses corresponding to the given handles.
835          *
836          * @todo Not liking this nested loop.  Optimize.
837          */
838         for (i = buffers; i != end; ++i) {
839                 struct memrar_rar_info * const rar =
840                         memrar_get_rar_info(i->info.handle);
841
842                 /*
843                  * Check if we have a bogus handle, and then continue
844                  * with remaining buffers.
845                  */
846                 if (rar == NULL) {
847                         i->bus_address = 0;
848                         continue;
849                 }
850
851                 mutex_lock(&rar->lock);
852
853                 list_for_each_entry(pos, &rar->buffers.list, list) {
854                         struct RAR_block_info * const user_info =
855                                 &pos->buffer.info;
856
857                         /*
858                          * Take into account handle offsets that may
859                          * have been added to the base handle, such as
860                          * in the following scenario:
861                          *
862                          *     u32 handle = base + offset;
863                          *     rar_handle_to_bus(handle);
864                          */
865
866                         if (i->info.handle >= user_info->handle
867                             && i->info.handle < (user_info->handle
868                                                  + user_info->size)) {
869                                 u32 const offset =
870                                         i->info.handle - user_info->handle;
871
872                                 i->info.type = user_info->type;
873                                 i->info.size = user_info->size - offset;
874                                 i->bus_address =
875                                         pos->buffer.bus_address
876                                         + offset;
877
878                                 /* Increment the reference count. */
879                                 kref_get(&pos->refcount);
880
881                                 ++conversion_count;
882                                 break;
883                         } else {
884                                 i->bus_address = 0;
885                         }
886                 }
887
888                 mutex_unlock(&rar->lock);
889         }
890
891         return conversion_count;
892 }
893 EXPORT_SYMBOL(rar_handle_to_bus);
894
895 static const struct file_operations memrar_fops = {
896         .owner = THIS_MODULE,
897         .unlocked_ioctl = memrar_ioctl,
898         .mmap           = memrar_mmap,
899         .open           = memrar_open,
900         .release        = memrar_release,
901 };
902
903 static struct miscdevice memrar_miscdev = {
904         .minor = MISC_DYNAMIC_MINOR,    /* dynamic allocation */
905         .name = "memrar",               /* /dev/memrar */
906         .fops = &memrar_fops
907 };
908
909 static char const banner[] __initdata =
910         KERN_INFO
911         "Intel RAR Handler: " MEMRAR_VER " initialized.\n";
912
913 /**
914  *      memrar_registration_callback    -       RAR obtained
915  *      @rar: RAR number
916  *
917  *      We have been granted ownership of the RAR. Add it to our memory
918  *      management tables
919  */
920
921 static int memrar_registration_callback(unsigned long rar)
922 {
923         /*
924          * We initialize the RAR parameters early on so that we can
925          * discontinue memrar device initialization and registration
926          * if suitably configured RARs are not available.
927          */
928         return memrar_init_rar_resources(rar, memrar_miscdev.name);
929 }
930
931 /**
932  *      memrar_init     -       initialise RAR support
933  *
934  *      Initialise support for RAR handlers. This may get loaded before
935  *      the RAR support is activated, but the callbacks on the registration
936  *      will handle that situation for us anyway.
937  */
938
939 static int __init memrar_init(void)
940 {
941         int err;
942
943         printk(banner);
944
945         err = misc_register(&memrar_miscdev);
946         if (err)
947                 return err;
948
949         /* Now claim the two RARs we want */
950         err = register_rar(0, memrar_registration_callback, 0);
951         if (err)
952                 goto fail;
953
954         err = register_rar(1, memrar_registration_callback, 1);
955         if (err == 0)
956                 return 0;
957
958         /* It is possible rar 0 registered and allocated resources then rar 1
959            failed so do a full resource free */
960         memrar_fini_rar_resources();
961 fail:
962         misc_deregister(&memrar_miscdev);
963         return err;
964 }
965
966 /**
967  *      memrar_exit     -       unregister and unload
968  *
969  *      Unregister the device and then unload any mappings and release
970  *      the RAR resources
971  */
972
973 static void __exit memrar_exit(void)
974 {
975         misc_deregister(&memrar_miscdev);
976         memrar_fini_rar_resources();
977 }
978
979
980 module_init(memrar_init);
981 module_exit(memrar_exit);
982
983
984 MODULE_AUTHOR("Ossama Othman <ossama.othman@intel.com>");
985 MODULE_DESCRIPTION("Intel Restricted Access Region Handler");
986 MODULE_LICENSE("GPL");
987 MODULE_VERSION(MEMRAR_VER);
988
989
990
991 /*
992   Local Variables:
993     c-file-style: "linux"
994   End:
995 */