c793634b301258de5380bd070a15cb63e977b080
[profile/ivi/libdrm.git] / bsd-core / drm_bufs.c
1 /*-
2  * Copyright 1999, 2000 Precision Insight, Inc., Cedar Park, Texas.
3  * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the next
14  * paragraph) shall be included in all copies or substantial portions of the
15  * Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20  * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
21  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23  * OTHER DEALINGS IN THE SOFTWARE.
24  *
25  * Authors:
26  *    Rickard E. (Rik) Faith <faith@valinux.com>
27  *    Gareth Hughes <gareth@valinux.com>
28  *
29  */
30
31 /** @file drm_bufs.c
32  * Implementation of the ioctls for setup of DRM mappings and DMA buffers.
33  */
34
35 #include "dev/pci/pcireg.h"
36
37 #include "drmP.h"
38
39 /*
40  * Compute order.  Can be made faster.
41  */
42 int drm_order(unsigned long size)
43 {
44         int order;
45         unsigned long tmp;
46
47         for ( order = 0, tmp = size ; tmp >>= 1 ; ++order );
48
49         if ( size & ~(1 << order) )
50                 ++order;
51
52         return order;
53 }
54
55 /* Allocation of PCI memory resources (framebuffer, registers, etc.) for
56  * drm_get_resource_*.  Note that they are not RF_ACTIVE, so there's no virtual
57  * address for accessing them.  Cleaned up at unload.
58  */
59 static int drm_alloc_resource(struct drm_device *dev, int resource)
60 {
61         if (resource >= DRM_MAX_PCI_RESOURCE) {
62                 DRM_ERROR("Resource %d too large\n", resource);
63                 return 1;
64         }
65
66         DRM_UNLOCK();
67         if (dev->pcir[resource] != NULL) {
68                 DRM_LOCK();
69                 return 0;
70         }
71
72         dev->pcirid[resource] = PCIR_BAR(resource);
73         dev->pcir[resource] = bus_alloc_resource_any(dev->device,
74             SYS_RES_MEMORY, &dev->pcirid[resource], RF_SHAREABLE);
75         DRM_LOCK();
76
77         if (dev->pcir[resource] == NULL) {
78                 DRM_ERROR("Couldn't find resource 0x%x\n", resource);
79                 return 1;
80         }
81
82         return 0;
83 }
84
85 unsigned long drm_get_resource_start(struct drm_device *dev,
86                                      unsigned int resource)
87 {
88         if (drm_alloc_resource(dev, resource) != 0)
89                 return 0;
90
91         return rman_get_start(dev->pcir[resource]);
92 }
93
94 unsigned long drm_get_resource_len(struct drm_device *dev,
95                                    unsigned int resource)
96 {
97         if (drm_alloc_resource(dev, resource) != 0)
98                 return 0;
99
100         return rman_get_size(dev->pcir[resource]);
101 }
102
103 int drm_addmap(struct drm_device * dev, unsigned long offset,
104                unsigned long size,
105     drm_map_type_t type, drm_map_flags_t flags, drm_local_map_t **map_ptr)
106 {
107         drm_local_map_t *map;
108         int align;
109         /*drm_agp_mem_t *entry;
110         int valid;*/
111
112         /* Only allow shared memory to be removable since we only keep enough
113          * book keeping information about shared memory to allow for removal
114          * when processes fork.
115          */
116         if ((flags & _DRM_REMOVABLE) && type != _DRM_SHM) {
117                 DRM_ERROR("Requested removable map for non-DRM_SHM\n");
118                 return EINVAL;
119         }
120         if ((offset & PAGE_MASK) || (size & PAGE_MASK)) {
121                 DRM_ERROR("offset/size not page aligned: 0x%lx/0x%lx\n",
122                     offset, size);
123                 return EINVAL;
124         }
125         if (offset + size < offset) {
126                 DRM_ERROR("offset and size wrap around: 0x%lx/0x%lx\n",
127                     offset, size);
128                 return EINVAL;
129         }
130
131         DRM_DEBUG("offset = 0x%08lx, size = 0x%08lx, type = %d\n", offset,
132             size, type);
133
134         /* Check if this is just another version of a kernel-allocated map, and
135          * just hand that back if so.
136          */
137         if (type == _DRM_REGISTERS || type == _DRM_FRAME_BUFFER ||
138             type == _DRM_SHM) {
139                 TAILQ_FOREACH(map, &dev->maplist, link) {
140                         if (map->type == type && (map->offset == offset ||
141                             (map->type == _DRM_SHM &&
142                             map->flags == _DRM_CONTAINS_LOCK))) {
143                                 map->size = size;
144                                 DRM_DEBUG("Found kernel map %d\n", type);
145                                 goto done;
146                         }
147                 }
148         }
149         DRM_UNLOCK();
150
151         /* Allocate a new map structure, fill it in, and do any type-specific
152          * initialization necessary.
153          */
154         map = malloc(sizeof(*map), M_DRM, M_ZERO | M_NOWAIT);
155         if ( !map ) {
156                 DRM_LOCK();
157                 return ENOMEM;
158         }
159
160         map->offset = offset;
161         map->size = size;
162         map->type = type;
163         map->flags = flags;
164
165         switch ( map->type ) {
166         case _DRM_REGISTERS:
167                 map->handle = drm_ioremap(dev, map);
168                 if (!(map->flags & _DRM_WRITE_COMBINING))
169                         break;
170                 /* FALLTHROUGH */
171         case _DRM_FRAME_BUFFER:
172                 if (drm_mtrr_add(map->offset, map->size, DRM_MTRR_WC) == 0)
173                         map->mtrr = 1;
174                 break;
175         case _DRM_SHM:
176                 map->handle = malloc(map->size, M_DRM, M_NOWAIT);
177                 DRM_DEBUG( "%lu %d %p\n",
178                            map->size, drm_order(map->size), map->handle );
179                 if ( !map->handle ) {
180                         free(map, M_DRM);
181                         DRM_LOCK();
182                         return ENOMEM;
183                 }
184                 map->offset = (unsigned long)map->handle;
185                 if ( map->flags & _DRM_CONTAINS_LOCK ) {
186                         /* Prevent a 2nd X Server from creating a 2nd lock */
187                         DRM_LOCK();
188                         if (dev->lock.hw_lock != NULL) {
189                                 DRM_UNLOCK();
190                                 free(map->handle, M_DRM);
191                                 free(map, M_DRM);
192                                 return EBUSY;
193                         }
194                         dev->lock.hw_lock = map->handle; /* Pointer to lock */
195                         DRM_UNLOCK();
196                 }
197                 break;
198         case _DRM_AGP:
199                 /*valid = 0;*/
200                 /* In some cases (i810 driver), user space may have already
201                  * added the AGP base itself, because dev->agp->base previously
202                  * only got set during AGP enable.  So, only add the base
203                  * address if the map's offset isn't already within the
204                  * aperture.
205                  */
206                 if (map->offset < dev->agp->base ||
207                     map->offset > dev->agp->base +
208                     dev->agp->info.ai_aperture_size - 1) {
209                         map->offset += dev->agp->base;
210                 }
211                 map->mtrr   = dev->agp->mtrr; /* for getmap */
212                 /*for (entry = dev->agp->memory; entry; entry = entry->next) {
213                         if ((map->offset >= entry->bound) &&
214                             (map->offset + map->size <=
215                             entry->bound + entry->pages * PAGE_SIZE)) {
216                                 valid = 1;
217                                 break;
218                         }
219                 }
220                 if (!valid) {
221                         free(map, M_DRM);
222                         DRM_LOCK();
223                         return EACCES;
224                 }*/
225                 break;
226         case _DRM_SCATTER_GATHER:
227                 if (!dev->sg) {
228                         free(map, M_DRM);
229                         DRM_LOCK();
230                         return EINVAL;
231                 }
232                 map->offset = map->offset + dev->sg->handle;
233                 break;
234         case _DRM_CONSISTENT:
235                 /* Unfortunately, we don't get any alignment specification from
236                  * the caller, so we have to guess.  drm_pci_alloc requires
237                  * a power-of-two alignment, so try to align the bus address of
238                  * the map to it size if possible, otherwise just assume
239                  * PAGE_SIZE alignment.
240                  */
241                 align = map->size;
242                 if ((align & (align - 1)) != 0)
243                         align = PAGE_SIZE;
244                 map->dmah = drm_pci_alloc(dev, map->size, align, 0xfffffffful);
245                 if (map->dmah == NULL) {
246                         free(map, M_DRM);
247                         DRM_LOCK();
248                         return ENOMEM;
249                 }
250                 map->handle = map->dmah->vaddr;
251                 map->offset = map->dmah->busaddr;
252                 break;
253         default:
254                 DRM_ERROR("Bad map type %d\n", map->type);
255                 free(map, M_DRM);
256                 DRM_LOCK();
257                 return EINVAL;
258         }
259
260         DRM_LOCK();
261         TAILQ_INSERT_TAIL(&dev->maplist, map, link);
262
263 done:
264         /* Jumped to, with lock held, when a kernel map is found. */
265
266         DRM_DEBUG("Added map %d 0x%lx/0x%lx\n", map->type, map->offset,
267             map->size);
268
269         *map_ptr = map;
270
271         return 0;
272 }
273
274 int drm_addmap_ioctl(struct drm_device *dev, void *data,
275                      struct drm_file *file_priv)
276 {
277         drm_map_t *request = data;
278         drm_local_map_t *map;
279         int err;
280
281         if (!(dev->flags & (FREAD|FWRITE)))
282                 return EACCES; /* Require read/write */
283
284         if (!DRM_SUSER(DRM_CURPROC) && request->type != _DRM_AGP)
285                 return EACCES;
286
287         DRM_LOCK();
288         err = drm_addmap(dev, request->offset, request->size, request->type,
289             request->flags, &map);
290         DRM_UNLOCK();
291         if (err != 0)
292                 return err;
293
294         request->offset = map->offset;
295         request->size = map->size;
296         request->type = map->type;
297         request->flags = map->flags;
298         request->mtrr   = map->mtrr;
299         request->handle = map->handle;
300
301         if (request->type != _DRM_SHM) {
302                 request->handle = (void *)request->offset;
303         }
304
305         return 0;
306 }
307
308 void drm_rmmap(struct drm_device *dev, drm_local_map_t *map)
309 {
310         DRM_SPINLOCK_ASSERT(&dev->dev_lock);
311
312         TAILQ_REMOVE(&dev->maplist, map, link);
313
314         switch (map->type) {
315         case _DRM_REGISTERS:
316                 if (map->bsr == NULL)
317                         drm_ioremapfree(map);
318                 /* FALLTHROUGH */
319         case _DRM_FRAME_BUFFER:
320                 if (map->mtrr) {
321                         int __unused retcode;
322                         
323                         retcode = drm_mtrr_del(0, map->offset, map->size,
324                             DRM_MTRR_WC);
325                         DRM_DEBUG("mtrr_del = %d\n", retcode);
326                 }
327                 break;
328         case _DRM_SHM:
329                 free(map->handle, M_DRM);
330                 break;
331         case _DRM_AGP:
332         case _DRM_SCATTER_GATHER:
333                 break;
334         case _DRM_CONSISTENT:
335                 drm_pci_free(dev, map->dmah);
336                 break;
337         default:
338                 DRM_ERROR("Bad map type %d\n", map->type);
339                 break;
340         }
341
342         if (map->bsr != NULL) {
343                 bus_release_resource(dev->device, SYS_RES_MEMORY, map->rid,
344                     map->bsr);
345         }
346
347         free(map, M_DRM);
348 }
349
350 /* Remove a map private from list and deallocate resources if the mapping
351  * isn't in use.
352  */
353
354 int drm_rmmap_ioctl(struct drm_device *dev, void *data,
355                     struct drm_file *file_priv)
356 {
357         drm_local_map_t *map;
358         drm_map_t *request = data;
359
360         DRM_LOCK();
361         TAILQ_FOREACH(map, &dev->maplist, link) {
362                 if (map->handle == request->handle &&
363                     map->flags & _DRM_REMOVABLE)
364                         break;
365         }
366
367         /* No match found. */
368         if (map == NULL) {
369                 DRM_UNLOCK();
370                 return EINVAL;
371         }
372
373         drm_rmmap(dev, map);
374
375         DRM_UNLOCK();
376
377         return 0;
378 }
379
380
381 static void drm_cleanup_buf_error(struct drm_device *dev,
382                                   drm_buf_entry_t *entry)
383 {
384         int i;
385
386         if (entry->seg_count) {
387                 for (i = 0; i < entry->seg_count; i++) {
388                         drm_pci_free(dev, entry->seglist[i]);
389                 }
390                 free(entry->seglist, M_DRM);
391
392                 entry->seg_count = 0;
393         }
394
395         if (entry->buf_count) {
396                 for (i = 0; i < entry->buf_count; i++) {
397                         free(entry->buflist[i].dev_private, M_DRM);
398                 }
399                 free(entry->buflist, M_DRM);
400
401                 entry->buf_count = 0;
402         }
403 }
404
405 static int drm_do_addbufs_agp(struct drm_device *dev, drm_buf_desc_t *request)
406 {
407         drm_device_dma_t *dma = dev->dma;
408         drm_buf_entry_t *entry;
409         /*drm_agp_mem_t *agp_entry;
410         int valid*/
411         drm_buf_t *buf;
412         unsigned long offset;
413         unsigned long agp_offset;
414         int count;
415         int order;
416         int size;
417         int alignment;
418         int page_order;
419         int total;
420         int byte_count;
421         int i;
422         drm_buf_t **temp_buflist;
423
424         count = request->count;
425         order = drm_order(request->size);
426         size = 1 << order;
427
428         alignment  = (request->flags & _DRM_PAGE_ALIGN)
429                 ? round_page(size) : size;
430         page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
431         total = PAGE_SIZE << page_order;
432
433         byte_count = 0;
434         agp_offset = dev->agp->base + request->agp_start;
435
436         DRM_DEBUG( "count:      %d\n",  count );
437         DRM_DEBUG( "order:      %d\n",  order );
438         DRM_DEBUG( "size:       %d\n",  size );
439         DRM_DEBUG( "agp_offset: 0x%lx\n", agp_offset );
440         DRM_DEBUG( "alignment:  %d\n",  alignment );
441         DRM_DEBUG( "page_order: %d\n",  page_order );
442         DRM_DEBUG( "total:      %d\n",  total );
443
444         /* Make sure buffers are located in AGP memory that we own */
445         /* Breaks MGA due to drm_alloc_agp not setting up entries for the
446          * memory.  Safe to ignore for now because these ioctls are still
447          * root-only.
448          */
449         /*valid = 0;
450         for (agp_entry = dev->agp->memory; agp_entry;
451             agp_entry = agp_entry->next) {
452                 if ((agp_offset >= agp_entry->bound) &&
453                     (agp_offset + total * count <=
454                     agp_entry->bound + agp_entry->pages * PAGE_SIZE)) {
455                         valid = 1;
456                         break;
457                 }
458         }
459         if (!valid) {
460                 DRM_DEBUG("zone invalid\n");
461                 return EINVAL;
462         }*/
463
464         entry = &dma->bufs[order];
465
466         entry->buflist = malloc(count * sizeof(*entry->buflist), M_DRM,
467             M_NOWAIT | M_ZERO);
468         if ( !entry->buflist ) {
469                 return ENOMEM;
470         }
471
472         entry->buf_size = size;
473         entry->page_order = page_order;
474
475         offset = 0;
476
477         while ( entry->buf_count < count ) {
478                 buf          = &entry->buflist[entry->buf_count];
479                 buf->idx     = dma->buf_count + entry->buf_count;
480                 buf->total   = alignment;
481                 buf->order   = order;
482                 buf->used    = 0;
483
484                 buf->offset  = (dma->byte_count + offset);
485                 buf->bus_address = agp_offset + offset;
486                 buf->address = (void *)(agp_offset + offset);
487                 buf->next    = NULL;
488                 buf->pending = 0;
489                 buf->file_priv = NULL;
490
491                 buf->dev_priv_size = dev->driver.buf_priv_size;
492                 buf->dev_private = malloc(buf->dev_priv_size, M_DRM,
493                     M_NOWAIT | M_ZERO);
494                 if (buf->dev_private == NULL) {
495                         /* Set count correctly so we free the proper amount. */
496                         entry->buf_count = count;
497                         drm_cleanup_buf_error(dev, entry);
498                         return ENOMEM;
499                 }
500
501                 offset += alignment;
502                 entry->buf_count++;
503                 byte_count += PAGE_SIZE << page_order;
504         }
505
506         DRM_DEBUG( "byte_count: %d\n", byte_count );
507
508         temp_buflist = realloc(dma->buflist,
509             (dma->buf_count + entry->buf_count) * sizeof(*dma->buflist), M_DRM,
510             M_NOWAIT);
511         if (temp_buflist == NULL) {
512                 /* Free the entry because it isn't valid */
513                 drm_cleanup_buf_error(dev, entry);
514                 return ENOMEM;
515         }
516         dma->buflist = temp_buflist;
517
518         for ( i = 0 ; i < entry->buf_count ; i++ ) {
519                 dma->buflist[i + dma->buf_count] = &entry->buflist[i];
520         }
521
522         dma->buf_count += entry->buf_count;
523         dma->byte_count += byte_count;
524
525         DRM_DEBUG( "dma->buf_count : %d\n", dma->buf_count );
526         DRM_DEBUG( "entry->buf_count : %d\n", entry->buf_count );
527
528         request->count = entry->buf_count;
529         request->size = size;
530
531         dma->flags = _DRM_DMA_USE_AGP;
532
533         return 0;
534 }
535
536 static int drm_do_addbufs_pci(struct drm_device *dev, drm_buf_desc_t *request)
537 {
538         drm_device_dma_t *dma = dev->dma;
539         int count;
540         int order;
541         int size;
542         int total;
543         int page_order;
544         drm_buf_entry_t *entry;
545         drm_buf_t *buf;
546         int alignment;
547         unsigned long offset;
548         int i;
549         int byte_count;
550         int page_count;
551         unsigned long *temp_pagelist;
552         drm_buf_t **temp_buflist;
553
554         count = request->count;
555         order = drm_order(request->size);
556         size = 1 << order;
557
558         DRM_DEBUG( "count=%d, size=%d (%d), order=%d\n",
559                    request->count, request->size, size, order );
560
561         alignment = (request->flags & _DRM_PAGE_ALIGN)
562                 ? round_page(size) : size;
563         page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
564         total = PAGE_SIZE << page_order;
565
566         entry = &dma->bufs[order];
567
568         entry->buflist = malloc(count * sizeof(*entry->buflist), M_DRM,
569             M_NOWAIT | M_ZERO);
570         entry->seglist = malloc(count * sizeof(*entry->seglist), M_DRM,
571             M_NOWAIT | M_ZERO);
572
573         /* Keep the original pagelist until we know all the allocations
574          * have succeeded
575          */
576         temp_pagelist = malloc((dma->page_count + (count << page_order)) *
577             sizeof(*dma->pagelist), M_DRM, M_NOWAIT);
578
579         if (entry->buflist == NULL || entry->seglist == NULL || 
580             temp_pagelist == NULL) {
581                 free(entry->buflist, M_DRM);
582                 free(entry->seglist, M_DRM);
583                 return ENOMEM;
584         }
585         
586         memcpy(temp_pagelist, dma->pagelist, dma->page_count * 
587             sizeof(*dma->pagelist));
588
589         DRM_DEBUG( "pagelist: %d entries\n",
590                    dma->page_count + (count << page_order) );
591
592         entry->buf_size = size;
593         entry->page_order = page_order;
594         byte_count = 0;
595         page_count = 0;
596
597         while ( entry->buf_count < count ) {
598                 drm_dma_handle_t *dmah = drm_pci_alloc(dev, size, alignment,
599                     0xfffffffful);
600                 if (dmah == NULL) {
601                         /* Set count correctly so we free the proper amount. */
602                         entry->buf_count = count;
603                         entry->seg_count = count;
604                         drm_cleanup_buf_error(dev, entry);
605                         free(temp_pagelist, M_DRM);
606                         return ENOMEM;
607                 }
608
609                 entry->seglist[entry->seg_count++] = dmah;
610                 for ( i = 0 ; i < (1 << page_order) ; i++ ) {
611                         DRM_DEBUG( "page %d @ %p\n",
612                                    dma->page_count + page_count,
613                                    (char *)dmah->vaddr + PAGE_SIZE * i );
614                         temp_pagelist[dma->page_count + page_count++] = 
615                             (long)dmah->vaddr + PAGE_SIZE * i;
616                 }
617                 for ( offset = 0 ;
618                       offset + size <= total && entry->buf_count < count ;
619                       offset += alignment, ++entry->buf_count ) {
620                         buf          = &entry->buflist[entry->buf_count];
621                         buf->idx     = dma->buf_count + entry->buf_count;
622                         buf->total   = alignment;
623                         buf->order   = order;
624                         buf->used    = 0;
625                         buf->offset  = (dma->byte_count + byte_count + offset);
626                         buf->address = ((char *)dmah->vaddr + offset);
627                         buf->bus_address = dmah->busaddr + offset;
628                         buf->next    = NULL;
629                         buf->pending = 0;
630                         buf->file_priv = NULL;
631
632                         buf->dev_priv_size = dev->driver.buf_priv_size;
633                         buf->dev_private = malloc(buf->dev_priv_size, M_DRM,
634                             M_NOWAIT | M_ZERO);
635                         if (buf->dev_private == NULL) {
636                                 /* Set count correctly so we free the proper amount. */
637                                 entry->buf_count = count;
638                                 entry->seg_count = count;
639                                 drm_cleanup_buf_error(dev, entry);
640                                 free(temp_pagelist, M_DRM);
641                                 return ENOMEM;
642                         }
643
644                         DRM_DEBUG( "buffer %d @ %p\n",
645                                    entry->buf_count, buf->address );
646                 }
647                 byte_count += PAGE_SIZE << page_order;
648         }
649
650         temp_buflist = realloc(dma->buflist,
651             (dma->buf_count + entry->buf_count) * sizeof(*dma->buflist), M_DRM,
652             M_NOWAIT);
653         if (temp_buflist == NULL) {
654                 /* Free the entry because it isn't valid */
655                 drm_cleanup_buf_error(dev, entry);
656                 free(temp_pagelist, M_DRM);
657                 return ENOMEM;
658         }
659         dma->buflist = temp_buflist;
660
661         for ( i = 0 ; i < entry->buf_count ; i++ ) {
662                 dma->buflist[i + dma->buf_count] = &entry->buflist[i];
663         }
664
665         /* No allocations failed, so now we can replace the orginal pagelist
666          * with the new one.
667          */
668         free(dma->pagelist, M_DRM);
669         dma->pagelist = temp_pagelist;
670
671         dma->buf_count += entry->buf_count;
672         dma->seg_count += entry->seg_count;
673         dma->page_count += entry->seg_count << page_order;
674         dma->byte_count += PAGE_SIZE * (entry->seg_count << page_order);
675
676         request->count = entry->buf_count;
677         request->size = size;
678
679         return 0;
680
681 }
682
683 static int drm_do_addbufs_sg(struct drm_device *dev, drm_buf_desc_t *request)
684 {
685         drm_device_dma_t *dma = dev->dma;
686         drm_buf_entry_t *entry;
687         drm_buf_t *buf;
688         unsigned long offset;
689         unsigned long agp_offset;
690         int count;
691         int order;
692         int size;
693         int alignment;
694         int page_order;
695         int total;
696         int byte_count;
697         int i;
698         drm_buf_t **temp_buflist;
699
700         count = request->count;
701         order = drm_order(request->size);
702         size = 1 << order;
703
704         alignment  = (request->flags & _DRM_PAGE_ALIGN)
705                 ? round_page(size) : size;
706         page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
707         total = PAGE_SIZE << page_order;
708
709         byte_count = 0;
710         agp_offset = request->agp_start;
711
712         DRM_DEBUG( "count:      %d\n",  count );
713         DRM_DEBUG( "order:      %d\n",  order );
714         DRM_DEBUG( "size:       %d\n",  size );
715         DRM_DEBUG( "agp_offset: %ld\n", agp_offset );
716         DRM_DEBUG( "alignment:  %d\n",  alignment );
717         DRM_DEBUG( "page_order: %d\n",  page_order );
718         DRM_DEBUG( "total:      %d\n",  total );
719
720         entry = &dma->bufs[order];
721
722         entry->buflist = malloc(count * sizeof(*entry->buflist), M_DRM,
723             M_NOWAIT | M_ZERO);
724         if (entry->buflist == NULL)
725                 return ENOMEM;
726
727         entry->buf_size = size;
728         entry->page_order = page_order;
729
730         offset = 0;
731
732         while ( entry->buf_count < count ) {
733                 buf          = &entry->buflist[entry->buf_count];
734                 buf->idx     = dma->buf_count + entry->buf_count;
735                 buf->total   = alignment;
736                 buf->order   = order;
737                 buf->used    = 0;
738
739                 buf->offset  = (dma->byte_count + offset);
740                 buf->bus_address = agp_offset + offset;
741                 buf->address = (void *)(agp_offset + offset + dev->sg->handle);
742                 buf->next    = NULL;
743                 buf->pending = 0;
744                 buf->file_priv = NULL;
745
746                 buf->dev_priv_size = dev->driver.buf_priv_size;
747                 buf->dev_private = malloc(buf->dev_priv_size, M_DRM,
748                     M_NOWAIT | M_ZERO);
749                 if (buf->dev_private == NULL) {
750                         /* Set count correctly so we free the proper amount. */
751                         entry->buf_count = count;
752                         drm_cleanup_buf_error(dev, entry);
753                         return ENOMEM;
754                 }
755
756                 DRM_DEBUG( "buffer %d @ %p\n",
757                            entry->buf_count, buf->address );
758
759                 offset += alignment;
760                 entry->buf_count++;
761                 byte_count += PAGE_SIZE << page_order;
762         }
763
764         DRM_DEBUG( "byte_count: %d\n", byte_count );
765
766         temp_buflist = realloc(dma->buflist,
767             (dma->buf_count + entry->buf_count) * sizeof(*dma->buflist), M_DRM,
768             M_NOWAIT);
769         if (temp_buflist == NULL) {
770                 /* Free the entry because it isn't valid */
771                 drm_cleanup_buf_error(dev, entry);
772                 return ENOMEM;
773         }
774         dma->buflist = temp_buflist;
775
776         for ( i = 0 ; i < entry->buf_count ; i++ ) {
777                 dma->buflist[i + dma->buf_count] = &entry->buflist[i];
778         }
779
780         dma->buf_count += entry->buf_count;
781         dma->byte_count += byte_count;
782
783         DRM_DEBUG( "dma->buf_count : %d\n", dma->buf_count );
784         DRM_DEBUG( "entry->buf_count : %d\n", entry->buf_count );
785
786         request->count = entry->buf_count;
787         request->size = size;
788
789         dma->flags = _DRM_DMA_USE_SG;
790
791         return 0;
792 }
793
794 int drm_addbufs_agp(struct drm_device *dev, drm_buf_desc_t *request)
795 {
796         int order, ret;
797
798         if (request->count < 0 || request->count > 4096)
799                 return EINVAL;
800         
801         order = drm_order(request->size);
802         if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
803                 return EINVAL;
804
805         DRM_SPINLOCK(&dev->dma_lock);
806
807         /* No more allocations after first buffer-using ioctl. */
808         if (dev->buf_use != 0) {
809                 DRM_SPINUNLOCK(&dev->dma_lock);
810                 return EBUSY;
811         }
812         /* No more than one allocation per order */
813         if (dev->dma->bufs[order].buf_count != 0) {
814                 DRM_SPINUNLOCK(&dev->dma_lock);
815                 return ENOMEM;
816         }
817
818         ret = drm_do_addbufs_agp(dev, request);
819
820         DRM_SPINUNLOCK(&dev->dma_lock);
821
822         return ret;
823 }
824
825 int drm_addbufs_sg(struct drm_device *dev, drm_buf_desc_t *request)
826 {
827         int order, ret;
828
829         if (!DRM_SUSER(DRM_CURPROC))
830                 return EACCES;
831
832         if (request->count < 0 || request->count > 4096)
833                 return EINVAL;
834
835         order = drm_order(request->size);
836         if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
837                 return EINVAL;
838
839         DRM_SPINLOCK(&dev->dma_lock);
840
841         /* No more allocations after first buffer-using ioctl. */
842         if (dev->buf_use != 0) {
843                 DRM_SPINUNLOCK(&dev->dma_lock);
844                 return EBUSY;
845         }
846         /* No more than one allocation per order */
847         if (dev->dma->bufs[order].buf_count != 0) {
848                 DRM_SPINUNLOCK(&dev->dma_lock);
849                 return ENOMEM;
850         }
851
852         ret = drm_do_addbufs_sg(dev, request);
853
854         DRM_SPINUNLOCK(&dev->dma_lock);
855
856         return ret;
857 }
858
859 int drm_addbufs_pci(struct drm_device *dev, drm_buf_desc_t *request)
860 {
861         int order, ret;
862
863         if (!DRM_SUSER(DRM_CURPROC))
864                 return EACCES;
865
866         if (request->count < 0 || request->count > 4096)
867                 return EINVAL;
868
869         order = drm_order(request->size);
870         if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
871                 return EINVAL;
872
873         DRM_SPINLOCK(&dev->dma_lock);
874
875         /* No more allocations after first buffer-using ioctl. */
876         if (dev->buf_use != 0) {
877                 DRM_SPINUNLOCK(&dev->dma_lock);
878                 return EBUSY;
879         }
880         /* No more than one allocation per order */
881         if (dev->dma->bufs[order].buf_count != 0) {
882                 DRM_SPINUNLOCK(&dev->dma_lock);
883                 return ENOMEM;
884         }
885
886         ret = drm_do_addbufs_pci(dev, request);
887
888         DRM_SPINUNLOCK(&dev->dma_lock);
889
890         return ret;
891 }
892
893 int drm_addbufs_ioctl(struct drm_device *dev, void *data,
894                       struct drm_file *file_priv)
895 {
896         drm_buf_desc_t *request = data;
897         int err;
898
899         if (request->flags & _DRM_AGP_BUFFER)
900                 err = drm_addbufs_agp(dev, request);
901         else if (request->flags & _DRM_SG_BUFFER)
902                 err = drm_addbufs_sg(dev, request);
903         else
904                 err = drm_addbufs_pci(dev, request);
905
906         return err;
907 }
908
909 int drm_infobufs(struct drm_device *dev, void *data, struct drm_file *file_priv)
910 {
911         drm_device_dma_t *dma = dev->dma;
912         drm_buf_info_t *request = data;
913         int i;
914         int count;
915         int retcode = 0;
916
917         DRM_SPINLOCK(&dev->dma_lock);
918         ++dev->buf_use;         /* Can't allocate more after this call */
919         DRM_SPINUNLOCK(&dev->dma_lock);
920
921         for ( i = 0, count = 0 ; i < DRM_MAX_ORDER + 1 ; i++ ) {
922                 if ( dma->bufs[i].buf_count ) ++count;
923         }
924
925         DRM_DEBUG( "count = %d\n", count );
926
927         if ( request->count >= count ) {
928                 for ( i = 0, count = 0 ; i < DRM_MAX_ORDER + 1 ; i++ ) {
929                         if ( dma->bufs[i].buf_count ) {
930                                 drm_buf_desc_t from;
931
932                                 from.count = dma->bufs[i].buf_count;
933                                 from.size = dma->bufs[i].buf_size;
934                                 from.low_mark = dma->bufs[i].freelist.low_mark;
935                                 from.high_mark = dma->bufs[i].freelist.high_mark;
936
937                                 if (DRM_COPY_TO_USER(&request->list[count], &from,
938                                     sizeof(drm_buf_desc_t)) != 0) {
939                                         retcode = EFAULT;
940                                         break;
941                                 }
942
943                                 DRM_DEBUG( "%d %d %d %d %d\n",
944                                            i,
945                                            dma->bufs[i].buf_count,
946                                            dma->bufs[i].buf_size,
947                                            dma->bufs[i].freelist.low_mark,
948                                            dma->bufs[i].freelist.high_mark );
949                                 ++count;
950                         }
951                 }
952         }
953         request->count = count;
954
955         return retcode;
956 }
957
958 int drm_markbufs(struct drm_device *dev, void *data, struct drm_file *file_priv)
959 {
960         drm_device_dma_t *dma = dev->dma;
961         drm_buf_desc_t *request = data;
962         int order;
963
964         DRM_DEBUG( "%d, %d, %d\n",
965                    request->size, request->low_mark, request->high_mark );
966         
967
968         order = drm_order(request->size);       
969         if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER ||
970             request->low_mark < 0 || request->high_mark < 0) {
971                 return EINVAL;
972         }
973
974         DRM_SPINLOCK(&dev->dma_lock);
975         if (request->low_mark > dma->bufs[order].buf_count ||
976             request->high_mark > dma->bufs[order].buf_count) {
977                 DRM_SPINUNLOCK(&dev->dma_lock);
978                 return EINVAL;
979         }
980
981         dma->bufs[order].freelist.low_mark  = request->low_mark;
982         dma->bufs[order].freelist.high_mark = request->high_mark;
983         DRM_SPINUNLOCK(&dev->dma_lock);
984
985         return 0;
986 }
987
988 int drm_freebufs(struct drm_device *dev, void *data, struct drm_file *file_priv)
989 {
990         drm_device_dma_t *dma = dev->dma;
991         drm_buf_free_t *request = data;
992         int i;
993         int idx;
994         drm_buf_t *buf;
995         int retcode = 0;
996
997         DRM_DEBUG( "%d\n", request->count );
998         
999         DRM_SPINLOCK(&dev->dma_lock);
1000         for ( i = 0 ; i < request->count ; i++ ) {
1001                 if (DRM_COPY_FROM_USER(&idx, &request->list[i], sizeof(idx))) {
1002                         retcode = EFAULT;
1003                         break;
1004                 }
1005                 if ( idx < 0 || idx >= dma->buf_count ) {
1006                         DRM_ERROR( "Index %d (of %d max)\n",
1007                                    idx, dma->buf_count - 1 );
1008                         retcode = EINVAL;
1009                         break;
1010                 }
1011                 buf = dma->buflist[idx];
1012                 if ( buf->file_priv != file_priv ) {
1013                         DRM_ERROR("Process %d freeing buffer not owned\n",
1014                                    DRM_CURRENTPID);
1015                         retcode = EINVAL;
1016                         break;
1017                 }
1018                 drm_free_buffer(dev, buf);
1019         }
1020         DRM_SPINUNLOCK(&dev->dma_lock);
1021
1022         return retcode;
1023 }
1024
1025 int drm_mapbufs(struct drm_device *dev, void *data, struct drm_file *file_priv)
1026 {
1027         drm_device_dma_t *dma = dev->dma;
1028         int retcode = 0;
1029         const int zero = 0;
1030         vm_offset_t address;
1031         struct vmspace *vms;
1032 #ifdef __FreeBSD__
1033         vm_ooffset_t foff;
1034         vm_size_t size;
1035         vm_offset_t vaddr;
1036 #elif defined(__NetBSD__) || defined(__OpenBSD__)
1037         struct vnode *vn;
1038         voff_t foff;
1039         vsize_t size;
1040         vaddr_t vaddr;
1041 #endif /* __NetBSD__ || __OpenBSD__ */
1042
1043         drm_buf_map_t *request = data;
1044         int i;
1045
1046 #if defined(__NetBSD__) || defined(__OpenBSD__)
1047         if (!vfinddev(kdev, VCHR, &vn))
1048                 return 0;       /* FIXME: Shouldn't this be EINVAL or something? */
1049 #endif /* __NetBSD__ || __OpenBSD */
1050
1051 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
1052         vms = DRM_CURPROC->td_proc->p_vmspace;
1053 #else
1054         vms = DRM_CURPROC->p_vmspace;
1055 #endif
1056
1057         DRM_SPINLOCK(&dev->dma_lock);
1058         dev->buf_use++;         /* Can't allocate more after this call */
1059         DRM_SPINUNLOCK(&dev->dma_lock);
1060
1061         if (request->count < dma->buf_count)
1062                 goto done;
1063
1064         if ((dev->driver.use_agp && (dma->flags & _DRM_DMA_USE_AGP)) ||
1065             (dev->driver.use_sg && (dma->flags & _DRM_DMA_USE_SG))) {
1066                 drm_local_map_t *map = dev->agp_buffer_map;
1067
1068                 if (map == NULL) {
1069                         retcode = EINVAL;
1070                         goto done;
1071                 }
1072                 size = round_page(map->size);
1073                 foff = map->offset;
1074         } else {
1075                 size = round_page(dma->byte_count),
1076                 foff = 0;
1077         }
1078
1079 #ifdef __FreeBSD__
1080         vaddr = round_page((vm_offset_t)vms->vm_daddr + MAXDSIZ);
1081 #if __FreeBSD_version >= 600023
1082         retcode = vm_mmap(&vms->vm_map, &vaddr, size, PROT_READ | PROT_WRITE,
1083             VM_PROT_ALL, MAP_SHARED, OBJT_DEVICE, dev->devnode, foff);
1084 #else
1085         retcode = vm_mmap(&vms->vm_map, &vaddr, size, PROT_READ | PROT_WRITE,
1086             VM_PROT_ALL, MAP_SHARED, SLIST_FIRST(&dev->devnode->si_hlist),
1087             foff);
1088 #endif
1089 #elif defined(__NetBSD__) || defined(__OpenBSD__)
1090         vaddr = round_page((vaddr_t)vms->vm_daddr + MAXDSIZ);
1091         retcode = uvm_mmap(&vms->vm_map, &vaddr, size,
1092             UVM_PROT_READ | UVM_PROT_WRITE, UVM_PROT_ALL, MAP_SHARED,
1093             &vn->v_uobj, foff, p->p_rlimit[RLIMIT_MEMLOCK].rlim_cur);
1094 #endif /* __NetBSD__ || __OpenBSD */
1095         if (retcode)
1096                 goto done;
1097
1098         request->virtual = (void *)vaddr;
1099
1100         for ( i = 0 ; i < dma->buf_count ; i++ ) {
1101                 if (DRM_COPY_TO_USER(&request->list[i].idx,
1102                     &dma->buflist[i]->idx, sizeof(request->list[0].idx))) {
1103                         retcode = EFAULT;
1104                         goto done;
1105                 }
1106                 if (DRM_COPY_TO_USER(&request->list[i].total,
1107                     &dma->buflist[i]->total, sizeof(request->list[0].total))) {
1108                         retcode = EFAULT;
1109                         goto done;
1110                 }
1111                 if (DRM_COPY_TO_USER(&request->list[i].used, &zero,
1112                     sizeof(zero))) {
1113                         retcode = EFAULT;
1114                         goto done;
1115                 }
1116                 address = vaddr + dma->buflist[i]->offset; /* *** */
1117                 if (DRM_COPY_TO_USER(&request->list[i].address, &address,
1118                     sizeof(address))) {
1119                         retcode = EFAULT;
1120                         goto done;
1121                 }
1122         }
1123
1124  done:
1125         request->count = dma->buf_count;
1126
1127         DRM_DEBUG( "%d buffers, retcode = %d\n", request->count, retcode );
1128
1129         return retcode;
1130 }