1 /**
2  * \file drm_fops.c
3  * File operations for DRM
4  *
5  * \author Rickard E. (Rik) Faith <faith@valinux.com>
6  * \author Daryll Strauss <daryll@valinux.com>
7  * \author Gareth Hughes <gareth@valinux.com>
8  */
9 
10 /*
11  * Created: Mon Jan  4 08:58:31 1999 by faith@valinux.com
12  *
13  * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
14  * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
15  * All Rights Reserved.
16  *
17  * Permission is hereby granted, free of charge, to any person obtaining a
18  * copy of this software and associated documentation files (the "Software"),
19  * to deal in the Software without restriction, including without limitation
20  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
21  * and/or sell copies of the Software, and to permit persons to whom the
22  * Software is furnished to do so, subject to the following conditions:
23  *
24  * The above copyright notice and this permission notice (including the next
25  * paragraph) shall be included in all copies or substantial portions of the
26  * Software.
27  *
28  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
31  * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
32  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
33  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
34  * OTHER DEALINGS IN THE SOFTWARE.
35  */
36 
37 #include "drmP.h"
38 #include <linux/poll.h>
39 #include <linux/slab.h>
40 #include <linux/module.h>
41 
42 /* from BKL pushdown: note that nothing else serializes idr_find() */
43 DEFINE_MUTEX(drm_global_mutex);
44 EXPORT_SYMBOL(drm_global_mutex);
45 
46 static int drm_open_helper(struct inode *inode, struct file *filp,
47 			   struct drm_device * dev);
48 
drm_setup(struct drm_device * dev)49 static int drm_setup(struct drm_device * dev)
50 {
51 	int i;
52 	int ret;
53 
54 	if (dev->driver->firstopen) {
55 		ret = dev->driver->firstopen(dev);
56 		if (ret != 0)
57 			return ret;
58 	}
59 
60 	atomic_set(&dev->ioctl_count, 0);
61 	atomic_set(&dev->vma_count, 0);
62 
63 	if (drm_core_check_feature(dev, DRIVER_HAVE_DMA) &&
64 	    !drm_core_check_feature(dev, DRIVER_MODESET)) {
65 		dev->buf_use = 0;
66 		atomic_set(&dev->buf_alloc, 0);
67 
68 		i = drm_dma_setup(dev);
69 		if (i < 0)
70 			return i;
71 	}
72 
73 	for (i = 0; i < ARRAY_SIZE(dev->counts); i++)
74 		atomic_set(&dev->counts[i], 0);
75 
76 	dev->sigdata.lock = NULL;
77 
78 	dev->queue_count = 0;
79 	dev->queue_reserved = 0;
80 	dev->queue_slots = 0;
81 	dev->queuelist = NULL;
82 	dev->context_flag = 0;
83 	dev->interrupt_flag = 0;
84 	dev->dma_flag = 0;
85 	dev->last_context = 0;
86 	dev->last_switch = 0;
87 	dev->last_checked = 0;
88 	init_waitqueue_head(&dev->context_wait);
89 	dev->if_version = 0;
90 
91 	dev->ctx_start = 0;
92 	dev->lck_start = 0;
93 
94 	dev->buf_async = NULL;
95 	init_waitqueue_head(&dev->buf_readers);
96 	init_waitqueue_head(&dev->buf_writers);
97 
98 	DRM_DEBUG("\n");
99 
100 	/*
101 	 * The kernel's context could be created here, but is now created
102 	 * in drm_dma_enqueue.  This is more resource-efficient for
103 	 * hardware that does not do DMA, but may mean that
104 	 * drm_select_queue fails between the time the interrupt is
105 	 * initialized and the time the queues are initialized.
106 	 */
107 
108 	return 0;
109 }
110 
111 /**
112  * Open file.
113  *
114  * \param inode device inode
115  * \param filp file pointer.
116  * \return zero on success or a negative number on failure.
117  *
118  * Searches the DRM device with the same minor number, calls open_helper(), and
119  * increments the device open count. If the open count was previous at zero,
120  * i.e., it's the first that the device is open, then calls setup().
121  */
drm_open(struct inode * inode,struct file * filp)122 int drm_open(struct inode *inode, struct file *filp)
123 {
124 	struct drm_device *dev = NULL;
125 	int minor_id = iminor(inode);
126 	struct drm_minor *minor;
127 	int retcode = 0;
128 
129 	minor = idr_find(&drm_minors_idr, minor_id);
130 	if (!minor)
131 		return -ENODEV;
132 
133 	if (!(dev = minor->dev))
134 		return -ENODEV;
135 
136 	retcode = drm_open_helper(inode, filp, dev);
137 	if (!retcode) {
138 		atomic_inc(&dev->counts[_DRM_STAT_OPENS]);
139 		if (!dev->open_count++)
140 			retcode = drm_setup(dev);
141 	}
142 	if (!retcode) {
143 		mutex_lock(&dev->struct_mutex);
144 		if (minor->type == DRM_MINOR_LEGACY) {
145 			if (dev->dev_mapping == NULL)
146 				dev->dev_mapping = inode->i_mapping;
147 			else if (dev->dev_mapping != inode->i_mapping)
148 				retcode = -ENODEV;
149 		}
150 		mutex_unlock(&dev->struct_mutex);
151 	}
152 
153 	return retcode;
154 }
155 EXPORT_SYMBOL(drm_open);
156 
157 /**
158  * File \c open operation.
159  *
160  * \param inode device inode.
161  * \param filp file pointer.
162  *
163  * Puts the dev->fops corresponding to the device minor number into
164  * \p filp, call the \c open method, and restore the file operations.
165  */
drm_stub_open(struct inode * inode,struct file * filp)166 int drm_stub_open(struct inode *inode, struct file *filp)
167 {
168 	struct drm_device *dev = NULL;
169 	struct drm_minor *minor;
170 	int minor_id = iminor(inode);
171 	int err = -ENODEV;
172 	const struct file_operations *old_fops;
173 
174 	DRM_DEBUG("\n");
175 
176 	mutex_lock(&drm_global_mutex);
177 	minor = idr_find(&drm_minors_idr, minor_id);
178 	if (!minor)
179 		goto out;
180 
181 	if (!(dev = minor->dev))
182 		goto out;
183 
184 	old_fops = filp->f_op;
185 	filp->f_op = fops_get(dev->driver->fops);
186 	if (filp->f_op == NULL) {
187 		filp->f_op = old_fops;
188 		goto out;
189 	}
190 	if (filp->f_op->open && (err = filp->f_op->open(inode, filp))) {
191 		fops_put(filp->f_op);
192 		filp->f_op = fops_get(old_fops);
193 	}
194 	fops_put(old_fops);
195 
196 out:
197 	mutex_unlock(&drm_global_mutex);
198 	return err;
199 }
200 
201 /**
202  * Check whether DRI will run on this CPU.
203  *
204  * \return non-zero if the DRI will run on this CPU, or zero otherwise.
205  */
drm_cpu_valid(void)206 static int drm_cpu_valid(void)
207 {
208 #if defined(__i386__)
209 	if (boot_cpu_data.x86 == 3)
210 		return 0;	/* No cmpxchg on a 386 */
211 #endif
212 #if defined(__sparc__) && !defined(__sparc_v9__)
213 	return 0;		/* No cmpxchg before v9 sparc. */
214 #endif
215 	return 1;
216 }
217 
218 /**
219  * Called whenever a process opens /dev/drm.
220  *
221  * \param inode device inode.
222  * \param filp file pointer.
223  * \param dev device.
224  * \return zero on success or a negative number on failure.
225  *
226  * Creates and initializes a drm_file structure for the file private data in \p
227  * filp and add it into the double linked list in \p dev.
228  */
drm_open_helper(struct inode * inode,struct file * filp,struct drm_device * dev)229 static int drm_open_helper(struct inode *inode, struct file *filp,
230 			   struct drm_device * dev)
231 {
232 	int minor_id = iminor(inode);
233 	struct drm_file *priv;
234 	int ret;
235 
236 	if (filp->f_flags & O_EXCL)
237 		return -EBUSY;	/* No exclusive opens */
238 	if (!drm_cpu_valid())
239 		return -EINVAL;
240 	if (dev->switch_power_state != DRM_SWITCH_POWER_ON)
241 		return -EINVAL;
242 
243 	DRM_DEBUG("pid = %d, minor = %d\n", task_pid_nr(current), minor_id);
244 
245 	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
246 	if (!priv)
247 		return -ENOMEM;
248 
249 	filp->private_data = priv;
250 	priv->filp = filp;
251 	priv->uid = current_euid();
252 	priv->pid = task_pid_nr(current);
253 	priv->minor = idr_find(&drm_minors_idr, minor_id);
254 	priv->ioctl_count = 0;
255 	/* for compatibility root is always authenticated */
256 	priv->authenticated = capable(CAP_SYS_ADMIN);
257 	priv->lock_count = 0;
258 
259 	INIT_LIST_HEAD(&priv->lhead);
260 	INIT_LIST_HEAD(&priv->fbs);
261 	INIT_LIST_HEAD(&priv->event_list);
262 	init_waitqueue_head(&priv->event_wait);
263 	priv->event_space = 4096; /* set aside 4k for event buffer */
264 
265 	if (dev->driver->driver_features & DRIVER_GEM)
266 		drm_gem_open(dev, priv);
267 
268 	if (dev->driver->open) {
269 		ret = dev->driver->open(dev, priv);
270 		if (ret < 0)
271 			goto out_free;
272 	}
273 
274 
275 	/* if there is no current master make this fd it */
276 	mutex_lock(&dev->struct_mutex);
277 	if (!priv->minor->master) {
278 		/* create a new master */
279 		priv->minor->master = drm_master_create(priv->minor);
280 		if (!priv->minor->master) {
281 			mutex_unlock(&dev->struct_mutex);
282 			ret = -ENOMEM;
283 			goto out_free;
284 		}
285 
286 		priv->is_master = 1;
287 		/* take another reference for the copy in the local file priv */
288 		priv->master = drm_master_get(priv->minor->master);
289 
290 		priv->authenticated = 1;
291 
292 		mutex_unlock(&dev->struct_mutex);
293 		if (dev->driver->master_create) {
294 			ret = dev->driver->master_create(dev, priv->master);
295 			if (ret) {
296 				mutex_lock(&dev->struct_mutex);
297 				/* drop both references if this fails */
298 				drm_master_put(&priv->minor->master);
299 				drm_master_put(&priv->master);
300 				mutex_unlock(&dev->struct_mutex);
301 				goto out_free;
302 			}
303 		}
304 		mutex_lock(&dev->struct_mutex);
305 		if (dev->driver->master_set) {
306 			ret = dev->driver->master_set(dev, priv, true);
307 			if (ret) {
308 				/* drop both references if this fails */
309 				drm_master_put(&priv->minor->master);
310 				drm_master_put(&priv->master);
311 				mutex_unlock(&dev->struct_mutex);
312 				goto out_free;
313 			}
314 		}
315 		mutex_unlock(&dev->struct_mutex);
316 	} else {
317 		/* get a reference to the master */
318 		priv->master = drm_master_get(priv->minor->master);
319 		mutex_unlock(&dev->struct_mutex);
320 	}
321 
322 	mutex_lock(&dev->struct_mutex);
323 	list_add(&priv->lhead, &dev->filelist);
324 	mutex_unlock(&dev->struct_mutex);
325 
326 #ifdef __alpha__
327 	/*
328 	 * Default the hose
329 	 */
330 	if (!dev->hose) {
331 		struct pci_dev *pci_dev;
332 		pci_dev = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, NULL);
333 		if (pci_dev) {
334 			dev->hose = pci_dev->sysdata;
335 			pci_dev_put(pci_dev);
336 		}
337 		if (!dev->hose) {
338 			struct pci_bus *b = pci_bus_b(pci_root_buses.next);
339 			if (b)
340 				dev->hose = b->sysdata;
341 		}
342 	}
343 #endif
344 
345 	return 0;
346       out_free:
347 	kfree(priv);
348 	filp->private_data = NULL;
349 	return ret;
350 }
351 
352 /** No-op. */
drm_fasync(int fd,struct file * filp,int on)353 int drm_fasync(int fd, struct file *filp, int on)
354 {
355 	struct drm_file *priv = filp->private_data;
356 	struct drm_device *dev = priv->minor->dev;
357 
358 	DRM_DEBUG("fd = %d, device = 0x%lx\n", fd,
359 		  (long)old_encode_dev(priv->minor->device));
360 	return fasync_helper(fd, filp, on, &dev->buf_async);
361 }
362 EXPORT_SYMBOL(drm_fasync);
363 
364 /*
365  * Reclaim locked buffers; note that this may be a bad idea if the current
366  * context doesn't have the hw lock...
367  */
drm_reclaim_locked_buffers(struct drm_device * dev,struct file * f)368 static void drm_reclaim_locked_buffers(struct drm_device *dev, struct file *f)
369 {
370 	struct drm_file *file_priv = f->private_data;
371 
372 	if (drm_i_have_hw_lock(dev, file_priv)) {
373 		dev->driver->reclaim_buffers_locked(dev, file_priv);
374 	} else {
375 		unsigned long _end = jiffies + 3 * DRM_HZ;
376 		int locked = 0;
377 
378 		drm_idlelock_take(&file_priv->master->lock);
379 
380 		/*
381 		 * Wait for a while.
382 		 */
383 		do {
384 			spin_lock_bh(&file_priv->master->lock.spinlock);
385 			locked = file_priv->master->lock.idle_has_lock;
386 			spin_unlock_bh(&file_priv->master->lock.spinlock);
387 			if (locked)
388 				break;
389 			schedule();
390 		} while (!time_after_eq(jiffies, _end));
391 
392 		if (!locked) {
393 			DRM_ERROR("reclaim_buffers_locked() deadlock. Please rework this\n"
394 				  "\tdriver to use reclaim_buffers_idlelocked() instead.\n"
395 				  "\tI will go on reclaiming the buffers anyway.\n");
396 		}
397 
398 		dev->driver->reclaim_buffers_locked(dev, file_priv);
399 		drm_idlelock_release(&file_priv->master->lock);
400 	}
401 }
402 
drm_master_release(struct drm_device * dev,struct file * filp)403 static void drm_master_release(struct drm_device *dev, struct file *filp)
404 {
405 	struct drm_file *file_priv = filp->private_data;
406 
407 	if (dev->driver->reclaim_buffers_locked &&
408 	    file_priv->master->lock.hw_lock)
409 		drm_reclaim_locked_buffers(dev, filp);
410 
411 	if (dev->driver->reclaim_buffers_idlelocked &&
412 	    file_priv->master->lock.hw_lock) {
413 		drm_idlelock_take(&file_priv->master->lock);
414 		dev->driver->reclaim_buffers_idlelocked(dev, file_priv);
415 		drm_idlelock_release(&file_priv->master->lock);
416 	}
417 
418 
419 	if (drm_i_have_hw_lock(dev, file_priv)) {
420 		DRM_DEBUG("File %p released, freeing lock for context %d\n",
421 			  filp, _DRM_LOCKING_CONTEXT(file_priv->master->lock.hw_lock->lock));
422 		drm_lock_free(&file_priv->master->lock,
423 			      _DRM_LOCKING_CONTEXT(file_priv->master->lock.hw_lock->lock));
424 	}
425 
426 	if (drm_core_check_feature(dev, DRIVER_HAVE_DMA) &&
427 	    !dev->driver->reclaim_buffers_locked) {
428 		dev->driver->reclaim_buffers(dev, file_priv);
429 	}
430 }
431 
drm_events_release(struct drm_file * file_priv)432 static void drm_events_release(struct drm_file *file_priv)
433 {
434 	struct drm_device *dev = file_priv->minor->dev;
435 	struct drm_pending_event *e, *et;
436 	struct drm_pending_vblank_event *v, *vt;
437 	unsigned long flags;
438 
439 	spin_lock_irqsave(&dev->event_lock, flags);
440 
441 	/* Remove pending flips */
442 	list_for_each_entry_safe(v, vt, &dev->vblank_event_list, base.link)
443 		if (v->base.file_priv == file_priv) {
444 			list_del(&v->base.link);
445 			drm_vblank_put(dev, v->pipe);
446 			v->base.destroy(&v->base);
447 		}
448 
449 	/* Remove unconsumed events */
450 	list_for_each_entry_safe(e, et, &file_priv->event_list, link)
451 		e->destroy(e);
452 
453 	spin_unlock_irqrestore(&dev->event_lock, flags);
454 }
455 
456 /**
457  * Release file.
458  *
459  * \param inode device inode
460  * \param file_priv DRM file private.
461  * \return zero on success or a negative number on failure.
462  *
463  * If the hardware lock is held then free it, and take it again for the kernel
464  * context since it's necessary to reclaim buffers. Unlink the file private
465  * data from its list and free it. Decreases the open count and if it reaches
466  * zero calls drm_lastclose().
467  */
drm_release(struct inode * inode,struct file * filp)468 int drm_release(struct inode *inode, struct file *filp)
469 {
470 	struct drm_file *file_priv = filp->private_data;
471 	struct drm_device *dev = file_priv->minor->dev;
472 	int retcode = 0;
473 
474 	mutex_lock(&drm_global_mutex);
475 
476 	DRM_DEBUG("open_count = %d\n", dev->open_count);
477 
478 	if (dev->driver->preclose)
479 		dev->driver->preclose(dev, file_priv);
480 
481 	/* ========================================================
482 	 * Begin inline drm_release
483 	 */
484 
485 	DRM_DEBUG("pid = %d, device = 0x%lx, open_count = %d\n",
486 		  task_pid_nr(current),
487 		  (long)old_encode_dev(file_priv->minor->device),
488 		  dev->open_count);
489 
490 	/* Release any auth tokens that might point to this file_priv,
491 	   (do that under the drm_global_mutex) */
492 	if (file_priv->magic)
493 		(void) drm_remove_magic(file_priv->master, file_priv->magic);
494 
495 	/* if the master has gone away we can't do anything with the lock */
496 	if (file_priv->minor->master)
497 		drm_master_release(dev, filp);
498 
499 	drm_events_release(file_priv);
500 
501 	if (dev->driver->driver_features & DRIVER_GEM)
502 		drm_gem_release(dev, file_priv);
503 
504 	if (dev->driver->driver_features & DRIVER_MODESET)
505 		drm_fb_release(file_priv);
506 
507 	mutex_lock(&dev->ctxlist_mutex);
508 	if (!list_empty(&dev->ctxlist)) {
509 		struct drm_ctx_list *pos, *n;
510 
511 		list_for_each_entry_safe(pos, n, &dev->ctxlist, head) {
512 			if (pos->tag == file_priv &&
513 			    pos->handle != DRM_KERNEL_CONTEXT) {
514 				if (dev->driver->context_dtor)
515 					dev->driver->context_dtor(dev,
516 								  pos->handle);
517 
518 				drm_ctxbitmap_free(dev, pos->handle);
519 
520 				list_del(&pos->head);
521 				kfree(pos);
522 				--dev->ctx_count;
523 			}
524 		}
525 	}
526 	mutex_unlock(&dev->ctxlist_mutex);
527 
528 	mutex_lock(&dev->struct_mutex);
529 
530 	if (file_priv->is_master) {
531 		struct drm_master *master = file_priv->master;
532 		struct drm_file *temp;
533 		list_for_each_entry(temp, &dev->filelist, lhead) {
534 			if ((temp->master == file_priv->master) &&
535 			    (temp != file_priv))
536 				temp->authenticated = 0;
537 		}
538 
539 		/**
540 		 * Since the master is disappearing, so is the
541 		 * possibility to lock.
542 		 */
543 
544 		if (master->lock.hw_lock) {
545 			if (dev->sigdata.lock == master->lock.hw_lock)
546 				dev->sigdata.lock = NULL;
547 			master->lock.hw_lock = NULL;
548 			master->lock.file_priv = NULL;
549 			wake_up_interruptible_all(&master->lock.lock_queue);
550 		}
551 
552 		if (file_priv->minor->master == file_priv->master) {
553 			/* drop the reference held my the minor */
554 			if (dev->driver->master_drop)
555 				dev->driver->master_drop(dev, file_priv, true);
556 			drm_master_put(&file_priv->minor->master);
557 		}
558 	}
559 
560 	/* drop the reference held my the file priv */
561 	drm_master_put(&file_priv->master);
562 	file_priv->is_master = 0;
563 	list_del(&file_priv->lhead);
564 	mutex_unlock(&dev->struct_mutex);
565 
566 	if (dev->driver->postclose)
567 		dev->driver->postclose(dev, file_priv);
568 	kfree(file_priv);
569 
570 	/* ========================================================
571 	 * End inline drm_release
572 	 */
573 
574 	atomic_inc(&dev->counts[_DRM_STAT_CLOSES]);
575 	if (!--dev->open_count) {
576 		if (atomic_read(&dev->ioctl_count)) {
577 			DRM_ERROR("Device busy: %d\n",
578 				  atomic_read(&dev->ioctl_count));
579 			retcode = -EBUSY;
580 		} else
581 			retcode = drm_lastclose(dev);
582 	}
583 	mutex_unlock(&drm_global_mutex);
584 
585 	return retcode;
586 }
587 EXPORT_SYMBOL(drm_release);
588 
589 static bool
drm_dequeue_event(struct drm_file * file_priv,size_t total,size_t max,struct drm_pending_event ** out)590 drm_dequeue_event(struct drm_file *file_priv,
591 		  size_t total, size_t max, struct drm_pending_event **out)
592 {
593 	struct drm_device *dev = file_priv->minor->dev;
594 	struct drm_pending_event *e;
595 	unsigned long flags;
596 	bool ret = false;
597 
598 	spin_lock_irqsave(&dev->event_lock, flags);
599 
600 	*out = NULL;
601 	if (list_empty(&file_priv->event_list))
602 		goto out;
603 	e = list_first_entry(&file_priv->event_list,
604 			     struct drm_pending_event, link);
605 	if (e->event->length + total > max)
606 		goto out;
607 
608 	file_priv->event_space += e->event->length;
609 	list_del(&e->link);
610 	*out = e;
611 	ret = true;
612 
613 out:
614 	spin_unlock_irqrestore(&dev->event_lock, flags);
615 	return ret;
616 }
617 
drm_read(struct file * filp,char __user * buffer,size_t count,loff_t * offset)618 ssize_t drm_read(struct file *filp, char __user *buffer,
619 		 size_t count, loff_t *offset)
620 {
621 	struct drm_file *file_priv = filp->private_data;
622 	struct drm_pending_event *e;
623 	size_t total;
624 	ssize_t ret;
625 
626 	ret = wait_event_interruptible(file_priv->event_wait,
627 				       !list_empty(&file_priv->event_list));
628 	if (ret < 0)
629 		return ret;
630 
631 	total = 0;
632 	while (drm_dequeue_event(file_priv, total, count, &e)) {
633 		if (copy_to_user(buffer + total,
634 				 e->event, e->event->length)) {
635 			total = -EFAULT;
636 			break;
637 		}
638 
639 		total += e->event->length;
640 		e->destroy(e);
641 	}
642 
643 	return total;
644 }
645 EXPORT_SYMBOL(drm_read);
646 
drm_poll(struct file * filp,struct poll_table_struct * wait)647 unsigned int drm_poll(struct file *filp, struct poll_table_struct *wait)
648 {
649 	struct drm_file *file_priv = filp->private_data;
650 	unsigned int mask = 0;
651 
652 	poll_wait(filp, &file_priv->event_wait, wait);
653 
654 	if (!list_empty(&file_priv->event_list))
655 		mask |= POLLIN | POLLRDNORM;
656 
657 	return mask;
658 }
659 EXPORT_SYMBOL(drm_poll);
660