drm.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (C) 2015-2016 Gerd Hoffmann <kraxel@redhat.com>
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include "qemu/osdep.h"
  18. #include "qemu/drm.h"
  19. #include <glob.h>
  20. #include <dirent.h>
  21. int qemu_drm_rendernode_open(const char *rendernode)
  22. {
  23. DIR *dir;
  24. struct dirent *e;
  25. struct stat st;
  26. int r, fd, ret;
  27. char *p;
  28. if (rendernode) {
  29. return open(rendernode, O_RDWR | O_CLOEXEC | O_NOCTTY | O_NONBLOCK);
  30. }
  31. dir = opendir("/dev/dri");
  32. if (!dir) {
  33. return -1;
  34. }
  35. fd = -1;
  36. while ((e = readdir(dir))) {
  37. if (strncmp(e->d_name, "renderD", 7)) {
  38. continue;
  39. }
  40. p = g_strdup_printf("/dev/dri/%s", e->d_name);
  41. r = open(p, O_RDWR | O_CLOEXEC | O_NOCTTY | O_NONBLOCK);
  42. if (r < 0) {
  43. g_free(p);
  44. continue;
  45. }
  46. /*
  47. * prefer fstat() over checking e->d_type == DT_CHR for
  48. * portability reasons
  49. */
  50. ret = fstat(r, &st);
  51. if (ret < 0 || (st.st_mode & S_IFMT) != S_IFCHR) {
  52. close(r);
  53. g_free(p);
  54. continue;
  55. }
  56. fd = r;
  57. g_free(p);
  58. break;
  59. }
  60. closedir(dir);
  61. if (fd < 0) {
  62. return -1;
  63. }
  64. return fd;
  65. }