xref: /freebsd/sys/dev/drm2/drm_bufs.c (revision 814aaaa7da4dab462d90e12e7b48b75f2093ccfd)
1 /**
2  * \file drm_bufs.c
3  * Generic buffer template
4  *
5  * \author Rickard E. (Rik) Faith <faith@valinux.com>
6  * \author Gareth Hughes <gareth@valinux.com>
7  */
8 
9 /*
10  * Created: Thu Nov 23 03:10:50 2000 by gareth@valinux.com
11  *
12  * Copyright 1999, 2000 Precision Insight, Inc., Cedar Park, Texas.
13  * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
14  * All Rights Reserved.
15  *
16  * Permission is hereby granted, free of charge, to any person obtaining a
17  * copy of this software and associated documentation files (the "Software"),
18  * to deal in the Software without restriction, including without limitation
19  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
20  * and/or sell copies of the Software, and to permit persons to whom the
21  * Software is furnished to do so, subject to the following conditions:
22  *
23  * The above copyright notice and this permission notice (including the next
24  * paragraph) shall be included in all copies or substantial portions of the
25  * Software.
26  *
27  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
30  * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
31  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
32  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
33  * OTHER DEALINGS IN THE SOFTWARE.
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/param.h>
40 #include <sys/shm.h>
41 
42 #include <linux/vmalloc.h>
43 #include <linux/slab.h>
44 
45 #include <dev/pci/pcireg.h>
46 
47 #include <dev/drm2/drmP.h>
48 
49 /* Allocation of PCI memory resources (framebuffer, registers, etc.) for
50  * drm_get_resource_*.  Note that they are not RF_ACTIVE, so there's no virtual
51  * address for accessing them.  Cleaned up at unload.
52  */
53 static int drm_alloc_resource(struct drm_device *dev, int resource)
54 {
55 	struct resource *res;
56 	int rid;
57 
58 	if (resource >= DRM_MAX_PCI_RESOURCE) {
59 		DRM_ERROR("Resource %d too large\n", resource);
60 		return 1;
61 	}
62 
63 	if (dev->pcir[resource] != NULL) {
64 		return 0;
65 	}
66 
67 	rid = PCIR_BAR(resource);
68 	res = bus_alloc_resource_any(dev->dev, SYS_RES_MEMORY, &rid,
69 	    RF_SHAREABLE);
70 	if (res == NULL) {
71 		DRM_ERROR("Couldn't find resource 0x%x\n", resource);
72 		return 1;
73 	}
74 
75 	if (dev->pcir[resource] == NULL) {
76 		dev->pcirid[resource] = rid;
77 		dev->pcir[resource] = res;
78 	}
79 
80 	return 0;
81 }
82 
83 unsigned long drm_get_resource_start(struct drm_device *dev,
84 				     unsigned int resource)
85 {
86 	unsigned long start;
87 
88 	mtx_lock(&dev->pcir_lock);
89 
90 	if (drm_alloc_resource(dev, resource) != 0)
91 		return 0;
92 
93 	start = rman_get_start(dev->pcir[resource]);
94 
95 	mtx_unlock(&dev->pcir_lock);
96 
97 	return (start);
98 }
99 
100 unsigned long drm_get_resource_len(struct drm_device *dev,
101 				   unsigned int resource)
102 {
103 	unsigned long len;
104 
105 	mtx_lock(&dev->pcir_lock);
106 
107 	if (drm_alloc_resource(dev, resource) != 0)
108 		return 0;
109 
110 	len = rman_get_size(dev->pcir[resource]);
111 
112 	mtx_unlock(&dev->pcir_lock);
113 
114 	return (len);
115 }
116 
117 static struct drm_map_list *drm_find_matching_map(struct drm_device *dev,
118 						  struct drm_local_map *map)
119 {
120 	struct drm_map_list *entry;
121 	list_for_each_entry(entry, &dev->maplist, head) {
122 		/*
123 		 * Because the kernel-userspace ABI is fixed at a 32-bit offset
124 		 * while PCI resources may live above that, we only compare the
125 		 * lower 32 bits of the map offset for maps of type
126 		 * _DRM_FRAMEBUFFER or _DRM_REGISTERS.
127 		 * It is assumed that if a driver have more than one resource
128 		 * of each type, the lower 32 bits are different.
129 		 */
130 		if (!entry->map ||
131 		    map->type != entry->map->type ||
132 		    entry->master != dev->primary->master)
133 			continue;
134 		switch (map->type) {
135 		case _DRM_SHM:
136 			if (map->flags != _DRM_CONTAINS_LOCK)
137 				break;
138 			return entry;
139 		case _DRM_REGISTERS:
140 		case _DRM_FRAME_BUFFER:
141 			if ((entry->map->offset & 0xffffffff) ==
142 			    (map->offset & 0xffffffff))
143 				return entry;
144 		default: /* Make gcc happy */
145 			;
146 		}
147 		if (entry->map->offset == map->offset)
148 			return entry;
149 	}
150 
151 	return NULL;
152 }
153 
154 static int drm_map_handle(struct drm_device *dev, struct drm_hash_item *hash,
155 			  unsigned long user_token, int hashed_handle, int shm)
156 {
157 	int use_hashed_handle, shift;
158 	unsigned long add;
159 
160 #if (BITS_PER_LONG == 64)
161 	use_hashed_handle = ((user_token & 0xFFFFFFFF00000000UL) || hashed_handle);
162 #elif (BITS_PER_LONG == 32)
163 	use_hashed_handle = hashed_handle;
164 #else
165 #error Unsupported long size. Neither 64 nor 32 bits.
166 #endif
167 
168 	if (!use_hashed_handle) {
169 		int ret;
170 		hash->key = user_token >> PAGE_SHIFT;
171 		ret = drm_ht_insert_item(&dev->map_hash, hash);
172 		if (ret != -EINVAL)
173 			return ret;
174 	}
175 
176 	shift = 0;
177 	add = DRM_MAP_HASH_OFFSET >> PAGE_SHIFT;
178 	if (shm && (SHMLBA > PAGE_SIZE)) {
179 		int bits = ilog2(SHMLBA >> PAGE_SHIFT) + 1;
180 
181 		/* For shared memory, we have to preserve the SHMLBA
182 		 * bits of the eventual vma->vm_pgoff value during
183 		 * mmap().  Otherwise we run into cache aliasing problems
184 		 * on some platforms.  On these platforms, the pgoff of
185 		 * a mmap() request is used to pick a suitable virtual
186 		 * address for the mmap() region such that it will not
187 		 * cause cache aliasing problems.
188 		 *
189 		 * Therefore, make sure the SHMLBA relevant bits of the
190 		 * hash value we use are equal to those in the original
191 		 * kernel virtual address.
192 		 */
193 		shift = bits;
194 		add |= ((user_token >> PAGE_SHIFT) & ((1UL << bits) - 1UL));
195 	}
196 
197 	return drm_ht_just_insert_please(&dev->map_hash, hash,
198 					 user_token, 32 - PAGE_SHIFT - 3,
199 					 shift, add);
200 }
201 
202 /**
203  * Core function to create a range of memory available for mapping by a
204  * non-root process.
205  *
206  * Adjusts the memory offset to its absolute value according to the mapping
207  * type.  Adds the map to the map list drm_device::maplist. Adds MTRR's where
208  * applicable and if supported by the kernel.
209  */
210 static int drm_addmap_core(struct drm_device * dev, resource_size_t offset,
211 			   unsigned int size, enum drm_map_type type,
212 			   enum drm_map_flags flags,
213 			   struct drm_map_list ** maplist)
214 {
215 	struct drm_local_map *map;
216 	struct drm_map_list *list;
217 	drm_dma_handle_t *dmah;
218 	unsigned long user_token;
219 	int ret;
220 	int align;
221 
222 	map = kmalloc(sizeof(*map), GFP_KERNEL);
223 	if (!map)
224 		return -ENOMEM;
225 
226 	map->offset = offset;
227 	map->size = size;
228 	map->flags = flags;
229 	map->type = type;
230 
231 	/* Only allow shared memory to be removable since we only keep enough
232 	 * book keeping information about shared memory to allow for removal
233 	 * when processes fork.
234 	 */
235 	if ((map->flags & _DRM_REMOVABLE) && map->type != _DRM_SHM) {
236 		kfree(map);
237 		return -EINVAL;
238 	}
239 	DRM_DEBUG("offset = 0x%08llx, size = 0x%08lx, type = %d\n",
240 		  (unsigned long long)map->offset, map->size, map->type);
241 
242 	/* page-align _DRM_SHM maps. They are allocated here so there is no security
243 	 * hole created by that and it works around various broken drivers that use
244 	 * a non-aligned quantity to map the SAREA. --BenH
245 	 */
246 	if (map->type == _DRM_SHM)
247 		map->size = PAGE_ALIGN(map->size);
248 
249 	/*
250 	 * FreeBSD port note: FreeBSD's PAGE_MASK is the inverse of
251 	 * Linux's one. That's why the test below doesn't inverse the
252 	 * constant.
253 	 */
254 	if ((map->offset & ((resource_size_t)PAGE_MASK)) || (map->size & (PAGE_MASK))) {
255 		kfree(map);
256 		return -EINVAL;
257 	}
258 	map->mtrr = -1;
259 	map->handle = NULL;
260 
261 	switch (map->type) {
262 	case _DRM_REGISTERS:
263 	case _DRM_FRAME_BUFFER:
264 #ifdef __linux__
265 #if !defined(__sparc__) && !defined(__alpha__) && !defined(__ia64__) && !defined(__powerpc64__) && !defined(__x86_64__) && !defined(__arm__)
266 		if (map->offset + (map->size-1) < map->offset ||
267 		    map->offset < virt_to_phys(high_memory)) {
268 			kfree(map);
269 			return -EINVAL;
270 		}
271 #endif
272 #endif
273 		/* Some drivers preinitialize some maps, without the X Server
274 		 * needing to be aware of it.  Therefore, we just return success
275 		 * when the server tries to create a duplicate map.
276 		 */
277 		list = drm_find_matching_map(dev, map);
278 		if (list != NULL) {
279 			if (list->map->size != map->size) {
280 				DRM_DEBUG("Matching maps of type %d with "
281 					  "mismatched sizes, (%ld vs %ld)\n",
282 					  map->type, map->size,
283 					  list->map->size);
284 				list->map->size = map->size;
285 			}
286 
287 			kfree(map);
288 			*maplist = list;
289 			return 0;
290 		}
291 
292 		if (drm_core_has_MTRR(dev)) {
293 			if (map->type == _DRM_FRAME_BUFFER ||
294 			    (map->flags & _DRM_WRITE_COMBINING)) {
295 				if (drm_mtrr_add(
296 				    map->offset, map->size,
297 				    DRM_MTRR_WC) == 0)
298 					map->mtrr = 1;
299 			}
300 		}
301 		if (map->type == _DRM_REGISTERS) {
302 			drm_core_ioremap(map, dev);
303 			if (!map->handle) {
304 				kfree(map);
305 				return -ENOMEM;
306 			}
307 		}
308 
309 		break;
310 	case _DRM_SHM:
311 		list = drm_find_matching_map(dev, map);
312 		if (list != NULL) {
313 			if(list->map->size != map->size) {
314 				DRM_DEBUG("Matching maps of type %d with "
315 					  "mismatched sizes, (%ld vs %ld)\n",
316 					  map->type, map->size, list->map->size);
317 				list->map->size = map->size;
318 			}
319 
320 			kfree(map);
321 			*maplist = list;
322 			return 0;
323 		}
324 		map->handle = vmalloc_user(map->size);
325 		DRM_DEBUG("%lu %d %p\n",
326 			  map->size, drm_order(map->size), map->handle);
327 		if (!map->handle) {
328 			kfree(map);
329 			return -ENOMEM;
330 		}
331 		map->offset = (unsigned long)map->handle;
332 		if (map->flags & _DRM_CONTAINS_LOCK) {
333 			/* Prevent a 2nd X Server from creating a 2nd lock */
334 			if (dev->primary->master->lock.hw_lock != NULL) {
335 				kfree(map->handle);
336 				kfree(map);
337 				return -EBUSY;
338 			}
339 			dev->sigdata.lock = dev->primary->master->lock.hw_lock = map->handle;	/* Pointer to lock */
340 		}
341 		break;
342 	case _DRM_AGP: {
343 		struct drm_agp_mem *entry;
344 		int valid = 0;
345 
346 		if (!drm_core_has_AGP(dev)) {
347 			kfree(map);
348 			return -EINVAL;
349 		}
350 #ifdef __linux__
351 #ifdef __alpha__
352 		map->offset += dev->hose->mem_space->start;
353 #endif
354 #endif
355 		/* In some cases (i810 driver), user space may have already
356 		 * added the AGP base itself, because dev->agp->base previously
357 		 * only got set during AGP enable.  So, only add the base
358 		 * address if the map's offset isn't already within the
359 		 * aperture.
360 		 */
361 		if (map->offset < dev->agp->base ||
362 		    map->offset > dev->agp->base +
363 		    dev->agp->agp_info.ai_aperture_size * 1024 * 1024 - 1) {
364 			map->offset += dev->agp->base;
365 		}
366 		map->mtrr = dev->agp->agp_mtrr;	/* for getmap */
367 
368 		/* This assumes the DRM is in total control of AGP space.
369 		 * It's not always the case as AGP can be in the control
370 		 * of user space (i.e. i810 driver). So this loop will get
371 		 * skipped and we double check that dev->agp->memory is
372 		 * actually set as well as being invalid before EPERM'ing
373 		 */
374 		list_for_each_entry(entry, &dev->agp->memory, head) {
375 			if ((map->offset >= entry->bound) &&
376 			    (map->offset + map->size <= entry->bound + entry->pages * PAGE_SIZE)) {
377 				valid = 1;
378 				break;
379 			}
380 		}
381 		if (!list_empty(&dev->agp->memory) && !valid) {
382 			kfree(map);
383 			return -EPERM;
384 		}
385 		DRM_DEBUG("AGP offset = 0x%08llx, size = 0x%08lx\n",
386 			  (unsigned long long)map->offset, map->size);
387 
388 		break;
389 	}
390 	case _DRM_GEM:
391 		DRM_ERROR("tried to addmap GEM object\n");
392 		break;
393 	case _DRM_SCATTER_GATHER:
394 		if (!dev->sg) {
395 			kfree(map);
396 			return -EINVAL;
397 		}
398 		map->handle = (void *)(dev->sg->vaddr + offset);
399 		map->offset += dev->sg->vaddr;
400 		break;
401 	case _DRM_CONSISTENT:
402 		/* dma_addr_t is 64bit on i386 with CONFIG_HIGHMEM64G,
403 		 * As we're limiting the address to 2^32-1 (or less),
404 		 * casting it down to 32 bits is no problem, but we
405 		 * need to point to a 64bit variable first. */
406 		align = map->size;
407 		if ((align & (align - 1)) != 0)
408 			align = PAGE_SIZE;
409 		dmah = drm_pci_alloc(dev, map->size, align, BUS_SPACE_MAXADDR);
410 		if (!dmah) {
411 			kfree(map);
412 			return -ENOMEM;
413 		}
414 		map->handle = dmah->vaddr;
415 		map->offset = dmah->busaddr;
416 		map->dmah = dmah;
417 		break;
418 	default:
419 		kfree(map);
420 		return -EINVAL;
421 	}
422 
423 	list = kzalloc(sizeof(*list), GFP_KERNEL);
424 	if (!list) {
425 		if (map->type == _DRM_REGISTERS)
426 			drm_core_ioremapfree(map, dev);
427 		kfree(map);
428 		return -EINVAL;
429 	}
430 	list->map = map;
431 
432 	DRM_LOCK(dev);
433 	list_add(&list->head, &dev->maplist);
434 
435 	/* Assign a 32-bit handle */
436 	/* We do it here so that dev->struct_mutex protects the increment */
437 	user_token = (map->type == _DRM_SHM) ? (unsigned long)map->handle :
438 		map->offset;
439 	ret = drm_map_handle(dev, &list->hash, user_token, 0,
440 			     (map->type == _DRM_SHM));
441 	if (ret) {
442 		if (map->type == _DRM_REGISTERS)
443 			drm_core_ioremapfree(map, dev);
444 		kfree(map);
445 		kfree(list);
446 		DRM_UNLOCK(dev);
447 		return ret;
448 	}
449 
450 	list->user_token = list->hash.key << PAGE_SHIFT;
451 	DRM_UNLOCK(dev);
452 
453 	if (!(map->flags & _DRM_DRIVER))
454 		list->master = dev->primary->master;
455 	*maplist = list;
456 	return 0;
457 	}
458 
459 int drm_addmap(struct drm_device * dev, resource_size_t offset,
460 	       unsigned int size, enum drm_map_type type,
461 	       enum drm_map_flags flags, struct drm_local_map ** map_ptr)
462 {
463 	struct drm_map_list *list;
464 	int rc;
465 
466 	rc = drm_addmap_core(dev, offset, size, type, flags, &list);
467 	if (!rc)
468 		*map_ptr = list->map;
469 	return rc;
470 }
471 
472 EXPORT_SYMBOL(drm_addmap);
473 
474 /**
475  * Ioctl to specify a range of memory that is available for mapping by a
476  * non-root process.
477  *
478  * \param inode device inode.
479  * \param file_priv DRM file private.
480  * \param cmd command.
481  * \param arg pointer to a drm_map structure.
482  * \return zero on success or a negative value on error.
483  *
484  */
485 int drm_addmap_ioctl(struct drm_device *dev, void *data,
486 		     struct drm_file *file_priv)
487 {
488 	struct drm_map *map = data;
489 	struct drm_map_list *maplist;
490 	int err;
491 
492 	if (!(DRM_SUSER(DRM_CURPROC) || map->type == _DRM_AGP || map->type == _DRM_SHM))
493 		return -EPERM;
494 
495 	err = drm_addmap_core(dev, map->offset, map->size, map->type,
496 			      map->flags, &maplist);
497 
498 	if (err)
499 		return err;
500 
501 	/* avoid a warning on 64-bit, this casting isn't very nice, but the API is set so too late */
502 	map->handle = (void *)(unsigned long)maplist->user_token;
503 	return 0;
504 }
505 
506 /**
507  * Remove a map private from list and deallocate resources if the mapping
508  * isn't in use.
509  *
510  * Searches the map on drm_device::maplist, removes it from the list, see if
511  * its being used, and free any associate resource (such as MTRR's) if it's not
512  * being on use.
513  *
514  * \sa drm_addmap
515  */
516 int drm_rmmap_locked(struct drm_device *dev, struct drm_local_map *map)
517 {
518 	struct drm_map_list *r_list = NULL, *list_t;
519 	int found = 0;
520 	struct drm_master *master;
521 
522 	/* Find the list entry for the map and remove it */
523 	list_for_each_entry_safe(r_list, list_t, &dev->maplist, head) {
524 		if (r_list->map == map) {
525 			master = r_list->master;
526 			list_del(&r_list->head);
527 			drm_ht_remove_key(&dev->map_hash,
528 					  r_list->user_token >> PAGE_SHIFT);
529 			kfree(r_list);
530 			found = 1;
531 			break;
532 		}
533 	}
534 
535 	if (!found)
536 		return -EINVAL;
537 
538 	switch (map->type) {
539 	case _DRM_REGISTERS:
540 		drm_core_ioremapfree(map, dev);
541 		/* FALLTHROUGH */
542 	case _DRM_FRAME_BUFFER:
543 		if (drm_core_has_MTRR(dev) && map->mtrr >= 0) {
544 			int retcode;
545 			retcode = drm_mtrr_del(map->mtrr, map->offset,
546 			    map->size, DRM_MTRR_WC);
547 			DRM_DEBUG("mtrr_del=%d\n", retcode);
548 		}
549 		break;
550 	case _DRM_SHM:
551 		kfree(map->handle);
552 		if (master) {
553 			if (dev->sigdata.lock == master->lock.hw_lock)
554 				dev->sigdata.lock = NULL;
555 			master->lock.hw_lock = NULL;   /* SHM removed */
556 			master->lock.file_priv = NULL;
557 			DRM_WAKEUP_INT((void *)&master->lock.lock_queue);
558 		}
559 		break;
560 	case _DRM_AGP:
561 	case _DRM_SCATTER_GATHER:
562 		break;
563 	case _DRM_CONSISTENT:
564 		drm_pci_free(dev, map->dmah);
565 		break;
566 	case _DRM_GEM:
567 		DRM_ERROR("tried to rmmap GEM object\n");
568 		break;
569 	}
570 	kfree(map);
571 
572 	return 0;
573 }
574 EXPORT_SYMBOL(drm_rmmap_locked);
575 
576 int drm_rmmap(struct drm_device *dev, struct drm_local_map *map)
577 {
578 	int ret;
579 
580 	DRM_LOCK(dev);
581 	ret = drm_rmmap_locked(dev, map);
582 	DRM_UNLOCK(dev);
583 
584 	return ret;
585 }
586 EXPORT_SYMBOL(drm_rmmap);
587 
588 /* The rmmap ioctl appears to be unnecessary.  All mappings are torn down on
589  * the last close of the device, and this is necessary for cleanup when things
590  * exit uncleanly.  Therefore, having userland manually remove mappings seems
591  * like a pointless exercise since they're going away anyway.
592  *
593  * One use case might be after addmap is allowed for normal users for SHM and
594  * gets used by drivers that the server doesn't need to care about.  This seems
595  * unlikely.
596  *
597  * \param inode device inode.
598  * \param file_priv DRM file private.
599  * \param cmd command.
600  * \param arg pointer to a struct drm_map structure.
601  * \return zero on success or a negative value on error.
602  */
603 int drm_rmmap_ioctl(struct drm_device *dev, void *data,
604 		    struct drm_file *file_priv)
605 {
606 	struct drm_map *request = data;
607 	struct drm_local_map *map = NULL;
608 	struct drm_map_list *r_list;
609 	int ret;
610 
611 	DRM_LOCK(dev);
612 	list_for_each_entry(r_list, &dev->maplist, head) {
613 		if (r_list->map &&
614 		    r_list->user_token == (unsigned long)request->handle &&
615 		    r_list->map->flags & _DRM_REMOVABLE) {
616 			map = r_list->map;
617 			break;
618 		}
619 	}
620 
621 	/* List has wrapped around to the head pointer, or its empty we didn't
622 	 * find anything.
623 	 */
624 	if (list_empty(&dev->maplist) || !map) {
625 		DRM_UNLOCK(dev);
626 		return -EINVAL;
627 	}
628 
629 	/* Register and framebuffer maps are permanent */
630 	if ((map->type == _DRM_REGISTERS) || (map->type == _DRM_FRAME_BUFFER)) {
631 		DRM_UNLOCK(dev);
632 		return 0;
633 	}
634 
635 	ret = drm_rmmap_locked(dev, map);
636 
637 	DRM_UNLOCK(dev);
638 
639 	return ret;
640 }
641 
642 /**
643  * Cleanup after an error on one of the addbufs() functions.
644  *
645  * \param dev DRM device.
646  * \param entry buffer entry where the error occurred.
647  *
648  * Frees any pages and buffers associated with the given entry.
649  */
650 static void drm_cleanup_buf_error(struct drm_device * dev,
651 				  struct drm_buf_entry * entry)
652 {
653 	int i;
654 
655 	if (entry->seg_count) {
656 		for (i = 0; i < entry->seg_count; i++) {
657 			if (entry->seglist[i]) {
658 				drm_pci_free(dev, entry->seglist[i]);
659 			}
660 		}
661 		kfree(entry->seglist);
662 
663 		entry->seg_count = 0;
664 	}
665 
666 	if (entry->buf_count) {
667 		for (i = 0; i < entry->buf_count; i++) {
668 			kfree(entry->buflist[i].dev_private);
669 		}
670 		kfree(entry->buflist);
671 
672 		entry->buf_count = 0;
673 	}
674 }
675 
676 #if __OS_HAS_AGP
677 /**
678  * Add AGP buffers for DMA transfers.
679  *
680  * \param dev struct drm_device to which the buffers are to be added.
681  * \param request pointer to a struct drm_buf_desc describing the request.
682  * \return zero on success or a negative number on failure.
683  *
684  * After some sanity checks creates a drm_buf structure for each buffer and
685  * reallocates the buffer list of the same size order to accommodate the new
686  * buffers.
687  */
688 int drm_addbufs_agp(struct drm_device * dev, struct drm_buf_desc * request)
689 {
690 	struct drm_device_dma *dma = dev->dma;
691 	struct drm_buf_entry *entry;
692 	struct drm_agp_mem *agp_entry;
693 	struct drm_buf *buf;
694 	unsigned long offset;
695 	unsigned long agp_offset;
696 	int count;
697 	int order;
698 	int size;
699 	int alignment;
700 	int page_order;
701 	int total;
702 	int byte_count;
703 	int i, valid;
704 	struct drm_buf **temp_buflist;
705 
706 	if (!dma)
707 		return -EINVAL;
708 
709 	count = request->count;
710 	order = drm_order(request->size);
711 	size = 1 << order;
712 
713 	alignment = (request->flags & _DRM_PAGE_ALIGN)
714 	    ? PAGE_ALIGN(size) : size;
715 	page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
716 	total = PAGE_SIZE << page_order;
717 
718 	byte_count = 0;
719 	agp_offset = dev->agp->base + request->agp_start;
720 
721 	DRM_DEBUG("count:      %d\n", count);
722 	DRM_DEBUG("order:      %d\n", order);
723 	DRM_DEBUG("size:       %d\n", size);
724 	DRM_DEBUG("agp_offset: %lx\n", agp_offset);
725 	DRM_DEBUG("alignment:  %d\n", alignment);
726 	DRM_DEBUG("page_order: %d\n", page_order);
727 	DRM_DEBUG("total:      %d\n", total);
728 
729 	if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
730 		return -EINVAL;
731 
732 	/* Make sure buffers are located in AGP memory that we own */
733 	valid = 0;
734 	list_for_each_entry(agp_entry, &dev->agp->memory, head) {
735 		if ((agp_offset >= agp_entry->bound) &&
736 		    (agp_offset + total * count <= agp_entry->bound + agp_entry->pages * PAGE_SIZE)) {
737 			valid = 1;
738 			break;
739 		}
740 	}
741 	if (!list_empty(&dev->agp->memory) && !valid) {
742 		DRM_DEBUG("zone invalid\n");
743 		return -EINVAL;
744 	}
745 	mtx_lock(&dev->count_lock);
746 	if (dev->buf_use) {
747 		mtx_unlock(&dev->count_lock);
748 		return -EBUSY;
749 	}
750 	atomic_inc(&dev->buf_alloc);
751 	mtx_unlock(&dev->count_lock);
752 
753 	DRM_LOCK(dev);
754 	entry = &dma->bufs[order];
755 	if (entry->buf_count) {
756 		DRM_UNLOCK(dev);
757 		atomic_dec(&dev->buf_alloc);
758 		return -ENOMEM;	/* May only call once for each order */
759 	}
760 
761 	if (count < 0 || count > 4096) {
762 		DRM_UNLOCK(dev);
763 		atomic_dec(&dev->buf_alloc);
764 		return -EINVAL;
765 	}
766 
767 	entry->buflist = kcalloc(count, sizeof(*entry->buflist), GFP_KERNEL);
768 	if (!entry->buflist) {
769 		DRM_UNLOCK(dev);
770 		atomic_dec(&dev->buf_alloc);
771 		return -ENOMEM;
772 	}
773 
774 	entry->buf_size = size;
775 	entry->page_order = page_order;
776 
777 	offset = 0;
778 
779 	while (entry->buf_count < count) {
780 		buf = &entry->buflist[entry->buf_count];
781 		buf->idx = dma->buf_count + entry->buf_count;
782 		buf->total = alignment;
783 		buf->order = order;
784 		buf->used = 0;
785 
786 		buf->offset = (dma->byte_count + offset);
787 		buf->bus_address = agp_offset + offset;
788 		buf->address = (void *)(agp_offset + offset);
789 		buf->next = NULL;
790 		buf->waiting = 0;
791 		buf->pending = 0;
792 		buf->file_priv = NULL;
793 
794 		buf->dev_priv_size = dev->driver->dev_priv_size;
795 		buf->dev_private = kzalloc(buf->dev_priv_size, GFP_KERNEL);
796 		if (!buf->dev_private) {
797 			/* Set count correctly so we free the proper amount. */
798 			entry->buf_count = count;
799 			drm_cleanup_buf_error(dev, entry);
800 			DRM_UNLOCK(dev);
801 			atomic_dec(&dev->buf_alloc);
802 			return -ENOMEM;
803 		}
804 
805 		DRM_DEBUG("buffer %d @ %p\n", entry->buf_count, buf->address);
806 
807 		offset += alignment;
808 		entry->buf_count++;
809 		byte_count += PAGE_SIZE << page_order;
810 	}
811 
812 	DRM_DEBUG("byte_count: %d\n", byte_count);
813 
814 	temp_buflist = krealloc(dma->buflist,
815 	    (dma->buf_count + entry->buf_count) * sizeof(*dma->buflist), GFP_KERNEL);
816 	if (!temp_buflist) {
817 		/* Free the entry because it isn't valid */
818 		drm_cleanup_buf_error(dev, entry);
819 		DRM_UNLOCK(dev);
820 		atomic_dec(&dev->buf_alloc);
821 		return -ENOMEM;
822 	}
823 	dma->buflist = temp_buflist;
824 
825 	for (i = 0; i < entry->buf_count; i++) {
826 		dma->buflist[i + dma->buf_count] = &entry->buflist[i];
827 	}
828 
829 	dma->buf_count += entry->buf_count;
830 	dma->seg_count += entry->seg_count;
831 	dma->page_count += byte_count >> PAGE_SHIFT;
832 	dma->byte_count += byte_count;
833 
834 	DRM_DEBUG("dma->buf_count : %d\n", dma->buf_count);
835 	DRM_DEBUG("entry->buf_count : %d\n", entry->buf_count);
836 
837 	DRM_UNLOCK(dev);
838 
839 	request->count = entry->buf_count;
840 	request->size = size;
841 
842 	dma->flags = _DRM_DMA_USE_AGP;
843 
844 	atomic_dec(&dev->buf_alloc);
845 	return 0;
846 }
847 EXPORT_SYMBOL(drm_addbufs_agp);
848 #endif				/* __OS_HAS_AGP */
849 
850 int drm_addbufs_pci(struct drm_device * dev, struct drm_buf_desc * request)
851 {
852 	struct drm_device_dma *dma = dev->dma;
853 	int count;
854 	int order;
855 	int size;
856 	int total;
857 	int page_order;
858 	struct drm_buf_entry *entry;
859 	drm_dma_handle_t *dmah;
860 	struct drm_buf *buf;
861 	int alignment;
862 	unsigned long offset;
863 	int i;
864 	int byte_count;
865 	int page_count;
866 	unsigned long *temp_pagelist;
867 	struct drm_buf **temp_buflist;
868 
869 	if (!drm_core_check_feature(dev, DRIVER_PCI_DMA))
870 		return -EINVAL;
871 
872 	if (!dma)
873 		return -EINVAL;
874 
875 	if (!DRM_SUSER(DRM_CURPROC))
876 		return -EPERM;
877 
878 	count = request->count;
879 	order = drm_order(request->size);
880 	size = 1 << order;
881 
882 	DRM_DEBUG("count=%d, size=%d (%d), order=%d\n",
883 		  request->count, request->size, size, order);
884 
885 	if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
886 		return -EINVAL;
887 
888 	alignment = (request->flags & _DRM_PAGE_ALIGN)
889 	    ? PAGE_ALIGN(size) : size;
890 	page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
891 	total = PAGE_SIZE << page_order;
892 
893 	mtx_lock(&dev->count_lock);
894 	if (dev->buf_use) {
895 		mtx_unlock(&dev->count_lock);
896 		return -EBUSY;
897 	}
898 	atomic_inc(&dev->buf_alloc);
899 	mtx_unlock(&dev->count_lock);
900 
901 	DRM_LOCK(dev);
902 	entry = &dma->bufs[order];
903 	if (entry->buf_count) {
904 		DRM_UNLOCK(dev);
905 		atomic_dec(&dev->buf_alloc);
906 		return -ENOMEM;	/* May only call once for each order */
907 	}
908 
909 	if (count < 0 || count > 4096) {
910 		DRM_UNLOCK(dev);
911 		atomic_dec(&dev->buf_alloc);
912 		return -EINVAL;
913 	}
914 
915 	entry->buflist = kcalloc(count, sizeof(*entry->buflist), GFP_KERNEL);
916 	if (!entry->buflist) {
917 		DRM_UNLOCK(dev);
918 		atomic_dec(&dev->buf_alloc);
919 		return -ENOMEM;
920 	}
921 
922 	entry->seglist = kcalloc(count, sizeof(*entry->seglist), GFP_KERNEL);
923 	if (!entry->seglist) {
924 		kfree(entry->buflist);
925 		DRM_UNLOCK(dev);
926 		atomic_dec(&dev->buf_alloc);
927 		return -ENOMEM;
928 	}
929 
930 	/* Keep the original pagelist until we know all the allocations
931 	 * have succeeded
932 	 */
933 	temp_pagelist = kmalloc_array(dma->page_count + (count << page_order),
934 				      sizeof(*dma->pagelist),
935 				      GFP_KERNEL);
936 	if (!temp_pagelist) {
937 		kfree(entry->buflist);
938 		kfree(entry->seglist);
939 		DRM_UNLOCK(dev);
940 		atomic_dec(&dev->buf_alloc);
941 		return -ENOMEM;
942 	}
943 	memcpy(temp_pagelist,
944 	       dma->pagelist, dma->page_count * sizeof(*dma->pagelist));
945 	DRM_DEBUG("pagelist: %d entries\n",
946 		  dma->page_count + (count << page_order));
947 
948 	entry->buf_size = size;
949 	entry->page_order = page_order;
950 	byte_count = 0;
951 	page_count = 0;
952 
953 	while (entry->buf_count < count) {
954 
955 		dmah = drm_pci_alloc(dev, PAGE_SIZE << page_order, 0x1000, BUS_SPACE_MAXADDR);
956 
957 		if (!dmah) {
958 			/* Set count correctly so we free the proper amount. */
959 			entry->buf_count = count;
960 			entry->seg_count = count;
961 			drm_cleanup_buf_error(dev, entry);
962 			kfree(temp_pagelist);
963 			DRM_UNLOCK(dev);
964 			atomic_dec(&dev->buf_alloc);
965 			return -ENOMEM;
966 		}
967 		entry->seglist[entry->seg_count++] = dmah;
968 		for (i = 0; i < (1 << page_order); i++) {
969 			DRM_DEBUG("page %d @ 0x%08lx\n",
970 				  dma->page_count + page_count,
971 				  (unsigned long)dmah->vaddr + PAGE_SIZE * i);
972 			temp_pagelist[dma->page_count + page_count++]
973 				= (unsigned long)dmah->vaddr + PAGE_SIZE * i;
974 		}
975 		for (offset = 0;
976 		     offset + size <= total && entry->buf_count < count;
977 		     offset += alignment, ++entry->buf_count) {
978 			buf = &entry->buflist[entry->buf_count];
979 			buf->idx = dma->buf_count + entry->buf_count;
980 			buf->total = alignment;
981 			buf->order = order;
982 			buf->used = 0;
983 			buf->offset = (dma->byte_count + byte_count + offset);
984 			buf->address = (void *)((char *)dmah->vaddr + offset);
985 			buf->bus_address = dmah->busaddr + offset;
986 			buf->next = NULL;
987 			buf->waiting = 0;
988 			buf->pending = 0;
989 			buf->file_priv = NULL;
990 
991 			buf->dev_priv_size = dev->driver->dev_priv_size;
992 			buf->dev_private = kzalloc(buf->dev_priv_size,
993 						GFP_KERNEL);
994 			if (!buf->dev_private) {
995 				/* Set count correctly so we free the proper amount. */
996 				entry->buf_count = count;
997 				entry->seg_count = count;
998 				drm_cleanup_buf_error(dev, entry);
999 				kfree(temp_pagelist);
1000 				DRM_UNLOCK(dev);
1001 				atomic_dec(&dev->buf_alloc);
1002 				return -ENOMEM;
1003 			}
1004 
1005 			DRM_DEBUG("buffer %d @ %p\n",
1006 				  entry->buf_count, buf->address);
1007 		}
1008 		byte_count += PAGE_SIZE << page_order;
1009 	}
1010 
1011 	temp_buflist = krealloc(dma->buflist,
1012 				(dma->buf_count + entry->buf_count) *
1013 				sizeof(*dma->buflist), GFP_KERNEL);
1014 	if (!temp_buflist) {
1015 		/* Free the entry because it isn't valid */
1016 		drm_cleanup_buf_error(dev, entry);
1017 		kfree(temp_pagelist);
1018 		DRM_UNLOCK(dev);
1019 		atomic_dec(&dev->buf_alloc);
1020 		return -ENOMEM;
1021 	}
1022 	dma->buflist = temp_buflist;
1023 
1024 	for (i = 0; i < entry->buf_count; i++) {
1025 		dma->buflist[i + dma->buf_count] = &entry->buflist[i];
1026 	}
1027 
1028 	/* No allocations failed, so now we can replace the original pagelist
1029 	 * with the new one.
1030 	 */
1031 	if (dma->page_count) {
1032 		kfree(dma->pagelist);
1033 	}
1034 	dma->pagelist = temp_pagelist;
1035 
1036 	dma->buf_count += entry->buf_count;
1037 	dma->seg_count += entry->seg_count;
1038 	dma->page_count += entry->seg_count << page_order;
1039 	dma->byte_count += PAGE_SIZE * (entry->seg_count << page_order);
1040 
1041 	DRM_UNLOCK(dev);
1042 
1043 	request->count = entry->buf_count;
1044 	request->size = size;
1045 
1046 	if (request->flags & _DRM_PCI_BUFFER_RO)
1047 		dma->flags = _DRM_DMA_USE_PCI_RO;
1048 
1049 	atomic_dec(&dev->buf_alloc);
1050 	return 0;
1051 
1052 }
1053 EXPORT_SYMBOL(drm_addbufs_pci);
1054 
1055 static int drm_addbufs_sg(struct drm_device * dev, struct drm_buf_desc * request)
1056 {
1057 	struct drm_device_dma *dma = dev->dma;
1058 	struct drm_buf_entry *entry;
1059 	struct drm_buf *buf;
1060 	unsigned long offset;
1061 	unsigned long agp_offset;
1062 	int count;
1063 	int order;
1064 	int size;
1065 	int alignment;
1066 	int page_order;
1067 	int total;
1068 	int byte_count;
1069 	int i;
1070 	struct drm_buf **temp_buflist;
1071 
1072 	if (!drm_core_check_feature(dev, DRIVER_SG))
1073 		return -EINVAL;
1074 
1075 	if (!dma)
1076 		return -EINVAL;
1077 
1078 	if (!DRM_SUSER(DRM_CURPROC))
1079 		return -EPERM;
1080 
1081 	count = request->count;
1082 	order = drm_order(request->size);
1083 	size = 1 << order;
1084 
1085 	alignment = (request->flags & _DRM_PAGE_ALIGN)
1086 	    ? PAGE_ALIGN(size) : size;
1087 	page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
1088 	total = PAGE_SIZE << page_order;
1089 
1090 	byte_count = 0;
1091 	agp_offset = request->agp_start;
1092 
1093 	DRM_DEBUG("count:      %d\n", count);
1094 	DRM_DEBUG("order:      %d\n", order);
1095 	DRM_DEBUG("size:       %d\n", size);
1096 	DRM_DEBUG("agp_offset: %lu\n", agp_offset);
1097 	DRM_DEBUG("alignment:  %d\n", alignment);
1098 	DRM_DEBUG("page_order: %d\n", page_order);
1099 	DRM_DEBUG("total:      %d\n", total);
1100 
1101 	if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
1102 		return -EINVAL;
1103 
1104 	mtx_lock(&dev->count_lock);
1105 	if (dev->buf_use) {
1106 		mtx_unlock(&dev->count_lock);
1107 		return -EBUSY;
1108 	}
1109 	atomic_inc(&dev->buf_alloc);
1110 	mtx_unlock(&dev->count_lock);
1111 
1112 	DRM_LOCK(dev);
1113 	entry = &dma->bufs[order];
1114 	if (entry->buf_count) {
1115 		DRM_UNLOCK(dev);
1116 		atomic_dec(&dev->buf_alloc);
1117 		return -ENOMEM;	/* May only call once for each order */
1118 	}
1119 
1120 	if (count < 0 || count > 4096) {
1121 		DRM_UNLOCK(dev);
1122 		atomic_dec(&dev->buf_alloc);
1123 		return -EINVAL;
1124 	}
1125 
1126 	entry->buflist = kcalloc(count, sizeof(*entry->buflist), GFP_KERNEL);
1127 	if (!entry->buflist) {
1128 		DRM_UNLOCK(dev);
1129 		atomic_dec(&dev->buf_alloc);
1130 		return -ENOMEM;
1131 	}
1132 
1133 	entry->buf_size = size;
1134 	entry->page_order = page_order;
1135 
1136 	offset = 0;
1137 
1138 	while (entry->buf_count < count) {
1139 		buf = &entry->buflist[entry->buf_count];
1140 		buf->idx = dma->buf_count + entry->buf_count;
1141 		buf->total = alignment;
1142 		buf->order = order;
1143 		buf->used = 0;
1144 
1145 		buf->offset = (dma->byte_count + offset);
1146 		buf->bus_address = agp_offset + offset;
1147 		buf->address = (void *)(agp_offset + offset
1148 					+ (unsigned long)dev->sg->vaddr);
1149 		buf->next = NULL;
1150 		buf->waiting = 0;
1151 		buf->pending = 0;
1152 		buf->file_priv = NULL;
1153 
1154 		buf->dev_priv_size = dev->driver->dev_priv_size;
1155 		buf->dev_private = kzalloc(buf->dev_priv_size, GFP_KERNEL);
1156 		if (!buf->dev_private) {
1157 			/* Set count correctly so we free the proper amount. */
1158 			entry->buf_count = count;
1159 			drm_cleanup_buf_error(dev, entry);
1160 			DRM_UNLOCK(dev);
1161 			atomic_dec(&dev->buf_alloc);
1162 			return -ENOMEM;
1163 		}
1164 
1165 		DRM_DEBUG("buffer %d @ %p\n", entry->buf_count, buf->address);
1166 
1167 		offset += alignment;
1168 		entry->buf_count++;
1169 		byte_count += PAGE_SIZE << page_order;
1170 	}
1171 
1172 	DRM_DEBUG("byte_count: %d\n", byte_count);
1173 
1174 	temp_buflist = krealloc(dma->buflist,
1175 				(dma->buf_count + entry->buf_count) *
1176 				sizeof(*dma->buflist), GFP_KERNEL);
1177 	if (!temp_buflist) {
1178 		/* Free the entry because it isn't valid */
1179 		drm_cleanup_buf_error(dev, entry);
1180 		DRM_UNLOCK(dev);
1181 		atomic_dec(&dev->buf_alloc);
1182 		return -ENOMEM;
1183 	}
1184 	dma->buflist = temp_buflist;
1185 
1186 	for (i = 0; i < entry->buf_count; i++) {
1187 		dma->buflist[i + dma->buf_count] = &entry->buflist[i];
1188 	}
1189 
1190 	dma->buf_count += entry->buf_count;
1191 	dma->seg_count += entry->seg_count;
1192 	dma->page_count += byte_count >> PAGE_SHIFT;
1193 	dma->byte_count += byte_count;
1194 
1195 	DRM_DEBUG("dma->buf_count : %d\n", dma->buf_count);
1196 	DRM_DEBUG("entry->buf_count : %d\n", entry->buf_count);
1197 
1198 	DRM_UNLOCK(dev);
1199 
1200 	request->count = entry->buf_count;
1201 	request->size = size;
1202 
1203 	dma->flags = _DRM_DMA_USE_SG;
1204 
1205 	atomic_dec(&dev->buf_alloc);
1206 	return 0;
1207 }
1208 
1209 static int drm_addbufs_fb(struct drm_device * dev, struct drm_buf_desc * request)
1210 {
1211 	struct drm_device_dma *dma = dev->dma;
1212 	struct drm_buf_entry *entry;
1213 	struct drm_buf *buf;
1214 	unsigned long offset;
1215 	unsigned long agp_offset;
1216 	int count;
1217 	int order;
1218 	int size;
1219 	int alignment;
1220 	int page_order;
1221 	int total;
1222 	int byte_count;
1223 	int i;
1224 	struct drm_buf **temp_buflist;
1225 
1226 	if (!drm_core_check_feature(dev, DRIVER_FB_DMA))
1227 		return -EINVAL;
1228 
1229 	if (!dma)
1230 		return -EINVAL;
1231 
1232 	if (!DRM_SUSER(DRM_CURPROC))
1233 		return -EPERM;
1234 
1235 	count = request->count;
1236 	order = drm_order(request->size);
1237 	size = 1 << order;
1238 
1239 	alignment = (request->flags & _DRM_PAGE_ALIGN)
1240 	    ? PAGE_ALIGN(size) : size;
1241 	page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
1242 	total = PAGE_SIZE << page_order;
1243 
1244 	byte_count = 0;
1245 	agp_offset = request->agp_start;
1246 
1247 	DRM_DEBUG("count:      %d\n", count);
1248 	DRM_DEBUG("order:      %d\n", order);
1249 	DRM_DEBUG("size:       %d\n", size);
1250 	DRM_DEBUG("agp_offset: %lu\n", agp_offset);
1251 	DRM_DEBUG("alignment:  %d\n", alignment);
1252 	DRM_DEBUG("page_order: %d\n", page_order);
1253 	DRM_DEBUG("total:      %d\n", total);
1254 
1255 	if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
1256 		return -EINVAL;
1257 
1258 	mtx_lock(&dev->count_lock);
1259 	if (dev->buf_use) {
1260 		mtx_unlock(&dev->count_lock);
1261 		return -EBUSY;
1262 	}
1263 	atomic_inc(&dev->buf_alloc);
1264 	mtx_unlock(&dev->count_lock);
1265 
1266 	DRM_LOCK(dev);
1267 	entry = &dma->bufs[order];
1268 	if (entry->buf_count) {
1269 		DRM_UNLOCK(dev);
1270 		atomic_dec(&dev->buf_alloc);
1271 		return -ENOMEM;	/* May only call once for each order */
1272 	}
1273 
1274 	if (count < 0 || count > 4096) {
1275 		DRM_UNLOCK(dev);
1276 		atomic_dec(&dev->buf_alloc);
1277 		return -EINVAL;
1278 	}
1279 
1280 	entry->buflist = kzalloc(count * sizeof(*entry->buflist), GFP_KERNEL);
1281 	if (!entry->buflist) {
1282 		DRM_UNLOCK(dev);
1283 		atomic_dec(&dev->buf_alloc);
1284 		return -ENOMEM;
1285 	}
1286 
1287 	entry->buf_size = size;
1288 	entry->page_order = page_order;
1289 
1290 	offset = 0;
1291 
1292 	while (entry->buf_count < count) {
1293 		buf = &entry->buflist[entry->buf_count];
1294 		buf->idx = dma->buf_count + entry->buf_count;
1295 		buf->total = alignment;
1296 		buf->order = order;
1297 		buf->used = 0;
1298 
1299 		buf->offset = (dma->byte_count + offset);
1300 		buf->bus_address = agp_offset + offset;
1301 		buf->address = (void *)(agp_offset + offset);
1302 		buf->next = NULL;
1303 		buf->waiting = 0;
1304 		buf->pending = 0;
1305 		buf->file_priv = NULL;
1306 
1307 		buf->dev_priv_size = dev->driver->dev_priv_size;
1308 		buf->dev_private = kmalloc(buf->dev_priv_size, GFP_KERNEL);
1309 		if (!buf->dev_private) {
1310 			/* Set count correctly so we free the proper amount. */
1311 			entry->buf_count = count;
1312 			drm_cleanup_buf_error(dev, entry);
1313 			DRM_UNLOCK(dev);
1314 			atomic_dec(&dev->buf_alloc);
1315 			return -ENOMEM;
1316 		}
1317 
1318 		DRM_DEBUG("buffer %d @ %p\n", entry->buf_count, buf->address);
1319 
1320 		offset += alignment;
1321 		entry->buf_count++;
1322 		byte_count += PAGE_SIZE << page_order;
1323 	}
1324 
1325 	DRM_DEBUG("byte_count: %d\n", byte_count);
1326 
1327 	temp_buflist = krealloc(dma->buflist,
1328 	    (dma->buf_count + entry->buf_count) * sizeof(*dma->buflist), GFP_KERNEL);
1329 	if (!temp_buflist) {
1330 		/* Free the entry because it isn't valid */
1331 		drm_cleanup_buf_error(dev, entry);
1332 		DRM_UNLOCK(dev);
1333 		atomic_dec(&dev->buf_alloc);
1334 		return -ENOMEM;
1335 	}
1336 	dma->buflist = temp_buflist;
1337 
1338 	for (i = 0; i < entry->buf_count; i++) {
1339 		dma->buflist[i + dma->buf_count] = &entry->buflist[i];
1340 	}
1341 
1342 	dma->buf_count += entry->buf_count;
1343 	dma->seg_count += entry->seg_count;
1344 	dma->page_count += byte_count >> PAGE_SHIFT;
1345 	dma->byte_count += byte_count;
1346 
1347 	DRM_DEBUG("dma->buf_count : %d\n", dma->buf_count);
1348 	DRM_DEBUG("entry->buf_count : %d\n", entry->buf_count);
1349 
1350 	DRM_UNLOCK(dev);
1351 
1352 	request->count = entry->buf_count;
1353 	request->size = size;
1354 
1355 	dma->flags = _DRM_DMA_USE_FB;
1356 
1357 	atomic_dec(&dev->buf_alloc);
1358 	return 0;
1359 }
1360 
1361 
1362 /**
1363  * Add buffers for DMA transfers (ioctl).
1364  *
1365  * \param inode device inode.
1366  * \param file_priv DRM file private.
1367  * \param cmd command.
1368  * \param arg pointer to a struct drm_buf_desc request.
1369  * \return zero on success or a negative number on failure.
1370  *
1371  * According with the memory type specified in drm_buf_desc::flags and the
1372  * build options, it dispatches the call either to addbufs_agp(),
1373  * addbufs_sg() or addbufs_pci() for AGP, scatter-gather or consistent
1374  * PCI memory respectively.
1375  */
1376 int drm_addbufs(struct drm_device *dev, void *data,
1377 		struct drm_file *file_priv)
1378 {
1379 	struct drm_buf_desc *request = data;
1380 	int ret;
1381 
1382 	if (!drm_core_check_feature(dev, DRIVER_HAVE_DMA))
1383 		return -EINVAL;
1384 
1385 #if __OS_HAS_AGP
1386 	if (request->flags & _DRM_AGP_BUFFER)
1387 		ret = drm_addbufs_agp(dev, request);
1388 	else
1389 #endif
1390 	if (request->flags & _DRM_SG_BUFFER)
1391 		ret = drm_addbufs_sg(dev, request);
1392 	else if (request->flags & _DRM_FB_BUFFER)
1393 		ret = drm_addbufs_fb(dev, request);
1394 	else
1395 		ret = drm_addbufs_pci(dev, request);
1396 
1397 	return ret;
1398 }
1399 
1400 /**
1401  * Get information about the buffer mappings.
1402  *
1403  * This was originally mean for debugging purposes, or by a sophisticated
1404  * client library to determine how best to use the available buffers (e.g.,
1405  * large buffers can be used for image transfer).
1406  *
1407  * \param inode device inode.
1408  * \param file_priv DRM file private.
1409  * \param cmd command.
1410  * \param arg pointer to a drm_buf_info structure.
1411  * \return zero on success or a negative number on failure.
1412  *
1413  * Increments drm_device::buf_use while holding the drm_device::count_lock
1414  * lock, preventing of allocating more buffers after this call. Information
1415  * about each requested buffer is then copied into user space.
1416  */
1417 int drm_infobufs(struct drm_device *dev, void *data,
1418 		 struct drm_file *file_priv)
1419 {
1420 	struct drm_device_dma *dma = dev->dma;
1421 	struct drm_buf_info *request = data;
1422 	int i;
1423 	int count;
1424 
1425 	if (!drm_core_check_feature(dev, DRIVER_HAVE_DMA))
1426 		return -EINVAL;
1427 
1428 	if (!dma)
1429 		return -EINVAL;
1430 
1431 	mtx_lock(&dev->count_lock);
1432 	if (atomic_read(&dev->buf_alloc)) {
1433 		mtx_unlock(&dev->count_lock);
1434 		return -EBUSY;
1435 	}
1436 	++dev->buf_use;		/* Can't allocate more after this call */
1437 	mtx_unlock(&dev->count_lock);
1438 
1439 	for (i = 0, count = 0; i < DRM_MAX_ORDER + 1; i++) {
1440 		if (dma->bufs[i].buf_count)
1441 			++count;
1442 	}
1443 
1444 	DRM_DEBUG("count = %d\n", count);
1445 
1446 	if (request->count >= count) {
1447 		for (i = 0, count = 0; i < DRM_MAX_ORDER + 1; i++) {
1448 			if (dma->bufs[i].buf_count) {
1449 				struct drm_buf_desc __user *to =
1450 				    &request->list[count];
1451 				struct drm_buf_entry *from = &dma->bufs[i];
1452 				struct drm_freelist *list = &dma->bufs[i].freelist;
1453 				if (copy_to_user(&to->count,
1454 						 &from->buf_count,
1455 						 sizeof(from->buf_count)) ||
1456 				    copy_to_user(&to->size,
1457 						 &from->buf_size,
1458 						 sizeof(from->buf_size)) ||
1459 				    copy_to_user(&to->low_mark,
1460 						 &list->low_mark,
1461 						 sizeof(list->low_mark)) ||
1462 				    copy_to_user(&to->high_mark,
1463 						 &list->high_mark,
1464 						 sizeof(list->high_mark)))
1465 					return -EFAULT;
1466 
1467 				DRM_DEBUG("%d %d %d %d %d\n",
1468 					  i,
1469 					  dma->bufs[i].buf_count,
1470 					  dma->bufs[i].buf_size,
1471 					  dma->bufs[i].freelist.low_mark,
1472 					  dma->bufs[i].freelist.high_mark);
1473 				++count;
1474 			}
1475 		}
1476 	}
1477 	request->count = count;
1478 
1479 	return 0;
1480 }
1481 
1482 /**
1483  * Specifies a low and high water mark for buffer allocation
1484  *
1485  * \param inode device inode.
1486  * \param file_priv DRM file private.
1487  * \param cmd command.
1488  * \param arg a pointer to a drm_buf_desc structure.
1489  * \return zero on success or a negative number on failure.
1490  *
1491  * Verifies that the size order is bounded between the admissible orders and
1492  * updates the respective drm_device_dma::bufs entry low and high water mark.
1493  *
1494  * \note This ioctl is deprecated and mostly never used.
1495  */
1496 int drm_markbufs(struct drm_device *dev, void *data,
1497 		 struct drm_file *file_priv)
1498 {
1499 	struct drm_device_dma *dma = dev->dma;
1500 	struct drm_buf_desc *request = data;
1501 	int order;
1502 	struct drm_buf_entry *entry;
1503 
1504 	if (!drm_core_check_feature(dev, DRIVER_HAVE_DMA))
1505 		return -EINVAL;
1506 
1507 	if (!dma)
1508 		return -EINVAL;
1509 
1510 	DRM_DEBUG("%d, %d, %d\n",
1511 		  request->size, request->low_mark, request->high_mark);
1512 	order = drm_order(request->size);
1513 	if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
1514 		return -EINVAL;
1515 	entry = &dma->bufs[order];
1516 
1517 	if (request->low_mark < 0 || request->low_mark > entry->buf_count)
1518 		return -EINVAL;
1519 	if (request->high_mark < 0 || request->high_mark > entry->buf_count)
1520 		return -EINVAL;
1521 
1522 	entry->freelist.low_mark = request->low_mark;
1523 	entry->freelist.high_mark = request->high_mark;
1524 
1525 	return 0;
1526 }
1527 
1528 /**
1529  * Unreserve the buffers in list, previously reserved using drmDMA.
1530  *
1531  * \param inode device inode.
1532  * \param file_priv DRM file private.
1533  * \param cmd command.
1534  * \param arg pointer to a drm_buf_free structure.
1535  * \return zero on success or a negative number on failure.
1536  *
1537  * Calls free_buffer() for each used buffer.
1538  * This function is primarily used for debugging.
1539  */
1540 int drm_freebufs(struct drm_device *dev, void *data,
1541 		 struct drm_file *file_priv)
1542 {
1543 	struct drm_device_dma *dma = dev->dma;
1544 	struct drm_buf_free *request = data;
1545 	int i;
1546 	int idx;
1547 	struct drm_buf *buf;
1548 
1549 	if (!drm_core_check_feature(dev, DRIVER_HAVE_DMA))
1550 		return -EINVAL;
1551 
1552 	if (!dma)
1553 		return -EINVAL;
1554 
1555 	DRM_DEBUG("%d\n", request->count);
1556 	for (i = 0; i < request->count; i++) {
1557 		if (copy_from_user(&idx, &request->list[i], sizeof(idx)))
1558 			return -EFAULT;
1559 		if (idx < 0 || idx >= dma->buf_count) {
1560 			DRM_ERROR("Index %d (of %d max)\n",
1561 				  idx, dma->buf_count - 1);
1562 			return -EINVAL;
1563 		}
1564 		buf = dma->buflist[idx];
1565 		if (buf->file_priv != file_priv) {
1566 			DRM_ERROR("Process %d freeing buffer not owned\n",
1567 				  DRM_CURRENTPID);
1568 			return -EINVAL;
1569 		}
1570 		drm_free_buffer(dev, buf);
1571 	}
1572 
1573 	return 0;
1574 }
1575 
1576 /**
1577  * Maps all of the DMA buffers into client-virtual space (ioctl).
1578  *
1579  * \param inode device inode.
1580  * \param file_priv DRM file private.
1581  * \param cmd command.
1582  * \param arg pointer to a drm_buf_map structure.
1583  * \return zero on success or a negative number on failure.
1584  *
1585  * Maps the AGP, SG or PCI buffer region with vm_mmap(), and copies information
1586  * about each buffer into user space. For PCI buffers, it calls vm_mmap() with
1587  * offset equal to 0, which drm_mmap() interpretes as PCI buffers and calls
1588  * drm_mmap_dma().
1589  */
1590 int drm_mapbufs(struct drm_device *dev, void *data,
1591 	        struct drm_file *file_priv)
1592 {
1593 	struct drm_device_dma *dma = dev->dma;
1594 	int retcode = 0;
1595 	const int zero = 0;
1596 	vm_offset_t virtual;
1597 	vm_offset_t address;
1598 	struct vmspace *vms;
1599 	struct drm_buf_map *request = data;
1600 	int i;
1601 
1602 	if (!drm_core_check_feature(dev, DRIVER_HAVE_DMA))
1603 		return -EINVAL;
1604 
1605 	if (!dma)
1606 		return -EINVAL;
1607 
1608 	mtx_lock(&dev->count_lock);
1609 	if (atomic_read(&dev->buf_alloc)) {
1610 		mtx_unlock(&dev->count_lock);
1611 		return -EBUSY;
1612 	}
1613 	dev->buf_use++;		/* Can't allocate more after this call */
1614 	mtx_unlock(&dev->count_lock);
1615 
1616 	vms = DRM_CURPROC->td_proc->p_vmspace;
1617 
1618 	if (request->count >= dma->buf_count) {
1619 		if ((drm_core_has_AGP(dev) && (dma->flags & _DRM_DMA_USE_AGP))
1620 		    || (drm_core_check_feature(dev, DRIVER_SG)
1621 			&& (dma->flags & _DRM_DMA_USE_SG))
1622 		    || (drm_core_check_feature(dev, DRIVER_FB_DMA)
1623 			&& (dma->flags & _DRM_DMA_USE_FB))) {
1624 			struct drm_local_map *map = dev->agp_buffer_map;
1625 			vm_ooffset_t token = dev->agp_buffer_token;
1626 
1627 			if (!map) {
1628 				retcode = -EINVAL;
1629 				goto done;
1630 			}
1631 			retcode = vm_mmap(&vms->vm_map, &virtual, map->size,
1632 			    VM_PROT_READ | VM_PROT_WRITE, VM_PROT_ALL,
1633 			    MAP_SHARED | MAP_NOSYNC, OBJT_DEVICE,
1634 			    file_priv->minor->device, token);
1635 		} else {
1636 			retcode = vm_mmap(&vms->vm_map, &virtual, dma->byte_count,
1637 			    VM_PROT_READ | VM_PROT_WRITE, VM_PROT_ALL,
1638 			    MAP_SHARED | MAP_NOSYNC, OBJT_DEVICE,
1639 			    file_priv->minor->device, 0);
1640 		}
1641 		if (retcode) {
1642 			/* Real error */
1643 			retcode = -retcode;
1644 			goto done;
1645 		}
1646 		request->virtual = (void __user *)virtual;
1647 
1648 		for (i = 0; i < dma->buf_count; i++) {
1649 			if (copy_to_user(&request->list[i].idx,
1650 					 &dma->buflist[i]->idx,
1651 					 sizeof(request->list[0].idx))) {
1652 				retcode = -EFAULT;
1653 				goto done;
1654 			}
1655 			if (copy_to_user(&request->list[i].total,
1656 					 &dma->buflist[i]->total,
1657 					 sizeof(request->list[0].total))) {
1658 				retcode = -EFAULT;
1659 				goto done;
1660 			}
1661 			if (copy_to_user(&request->list[i].used,
1662 					 &zero, sizeof(zero))) {
1663 				retcode = -EFAULT;
1664 				goto done;
1665 			}
1666 			address = virtual + dma->buflist[i]->offset;	/* *** */
1667 			if (copy_to_user(&request->list[i].address,
1668 					 &address, sizeof(address))) {
1669 				retcode = -EFAULT;
1670 				goto done;
1671 			}
1672 		}
1673 	}
1674       done:
1675 	request->count = dma->buf_count;
1676 	DRM_DEBUG("%d buffers, retcode = %d\n", request->count, retcode);
1677 
1678 	return retcode;
1679 }
1680 
1681 /**
1682  * Compute size order.  Returns the exponent of the smaller power of two which
1683  * is greater or equal to given number.
1684  *
1685  * \param size size.
1686  * \return order.
1687  *
1688  * \todo Can be made faster.
1689  */
1690 int drm_order(unsigned long size)
1691 {
1692 	int order;
1693 	unsigned long tmp;
1694 
1695 	for (order = 0, tmp = size >> 1; tmp; tmp >>= 1, order++) ;
1696 
1697 	if (size & (size - 1))
1698 		++order;
1699 
1700 	return order;
1701 }
1702 EXPORT_SYMBOL(drm_order);
1703