modeset-double-buffered.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. /*
  2. * modeset - DRM Double-Buffered Modesetting Example
  3. *
  4. * Written 2012 by David Rheinsberg <david.rheinsberg@gmail.com>
  5. * Dedicated to the Public Domain.
  6. */
  7. /*
  8. * DRM Double-Buffered Modesetting Howto
  9. * This example extends the modeset.c howto and introduces double-buffering.
  10. * When drawing a new frame into a framebuffer, we should always draw into an
  11. * unused buffer and not into the front buffer. If we draw into the front
  12. * buffer, we might have drawn half the frame when the display-controller starts
  13. * scanning out the next frame. Hence, we see flickering on the screen.
  14. * The technique to avoid this is called double-buffering. We have two
  15. * framebuffers, the front buffer which is currently used for scanout and a
  16. * back-buffer that is used for drawing operations. When a frame is done, we
  17. * simply swap both buffers.
  18. * Swapping does not mean copying data, instead, only the pointers to the
  19. * buffers are swapped.
  20. *
  21. * Please read modeset.c before reading this file as most of the functions stay
  22. * the same. Only the differences are highlighted here.
  23. * Also note that triple-buffering or any other number of buffers can be easily
  24. * implemented by following the scheme here. However, in this example we limit
  25. * the number of buffers to 2 so it is easier to follow.
  26. */
  27. #define _GNU_SOURCE
  28. #include <errno.h>
  29. #include <fcntl.h>
  30. #include <stdbool.h>
  31. #include <stdint.h>
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <string.h>
  35. #include <sys/mman.h>
  36. #include <time.h>
  37. #include <unistd.h>
  38. #include <xf86drm.h>
  39. #include <xf86drmMode.h>
  40. struct modeset_buf;
  41. struct modeset_dev;
  42. static int modeset_find_crtc(int fd, drmModeRes *res, drmModeConnector *conn,
  43. struct modeset_dev *dev);
  44. static int modeset_create_fb(int fd, struct modeset_buf *buf);
  45. static void modeset_destroy_fb(int fd, struct modeset_buf *buf);
  46. static int modeset_setup_dev(int fd, drmModeRes *res, drmModeConnector *conn,
  47. struct modeset_dev *dev);
  48. static int modeset_open(int *out, const char *node);
  49. static int modeset_prepare(int fd);
  50. static void modeset_draw(int fd);
  51. static void modeset_cleanup(int fd);
  52. /*
  53. * modeset_open() stays the same as before.
  54. */
  55. static int modeset_open(int *out, const char *node)
  56. {
  57. int fd, ret;
  58. uint64_t has_dumb;
  59. fd = open(node, O_RDWR | O_CLOEXEC);
  60. if (fd < 0) {
  61. ret = -errno;
  62. fprintf(stderr, "cannot open '%s': %m\n", node);
  63. return ret;
  64. }
  65. if (drmGetCap(fd, DRM_CAP_DUMB_BUFFER, &has_dumb) < 0 ||
  66. !has_dumb) {
  67. fprintf(stderr, "drm device '%s' does not support dumb buffers\n",
  68. node);
  69. close(fd);
  70. return -EOPNOTSUPP;
  71. }
  72. *out = fd;
  73. return 0;
  74. }
  75. /*
  76. * Previously, we used the modeset_dev objects to hold buffer informations, too.
  77. * Technically, we could have split them but avoided this to make the
  78. * example simpler.
  79. * However, in this example we need 2 buffers. One back buffer and one front
  80. * buffer. So we introduce a new structure modeset_buf which contains everything
  81. * related to a single buffer. Each device now gets an array of two of these
  82. * buffers.
  83. * Each buffer consists of width, height, stride, size, handle, map and fb-id.
  84. * They have the same meaning as before.
  85. *
  86. * Each device also gets a new integer field: front_buf. This field contains the
  87. * index of the buffer that is currently used as front buffer / scanout buffer.
  88. * In our example it can be 0 or 1. We flip it by using XOR:
  89. * dev->front_buf ^= dev->front_buf
  90. *
  91. * Everything else stays the same.
  92. */
  93. struct modeset_buf {
  94. uint32_t width;
  95. uint32_t height;
  96. uint32_t stride;
  97. uint32_t size;
  98. uint32_t handle;
  99. uint8_t *map;
  100. uint32_t fb;
  101. };
  102. struct modeset_dev {
  103. struct modeset_dev *next;
  104. unsigned int front_buf;
  105. struct modeset_buf bufs[2];
  106. drmModeModeInfo mode;
  107. uint32_t conn;
  108. uint32_t crtc;
  109. drmModeCrtc *saved_crtc;
  110. };
  111. static struct modeset_dev *modeset_list = NULL;
  112. /*
  113. * modeset_prepare() stays the same.
  114. */
  115. static int modeset_prepare(int fd)
  116. {
  117. drmModeRes *res;
  118. drmModeConnector *conn;
  119. unsigned int i;
  120. struct modeset_dev *dev;
  121. int ret;
  122. /* retrieve resources */
  123. res = drmModeGetResources(fd);
  124. if (!res) {
  125. fprintf(stderr, "cannot retrieve DRM resources (%d): %m\n",
  126. errno);
  127. return -errno;
  128. }
  129. /* iterate all connectors */
  130. for (i = 0; i < res->count_connectors; ++i) {
  131. /* get information for each connector */
  132. conn = drmModeGetConnector(fd, res->connectors[i]);
  133. if (!conn) {
  134. fprintf(stderr, "cannot retrieve DRM connector %u:%u (%d): %m\n",
  135. i, res->connectors[i], errno);
  136. continue;
  137. }
  138. /* create a device structure */
  139. dev = malloc(sizeof(*dev));
  140. memset(dev, 0, sizeof(*dev));
  141. dev->conn = conn->connector_id;
  142. /* call helper function to prepare this connector */
  143. ret = modeset_setup_dev(fd, res, conn, dev);
  144. if (ret) {
  145. if (ret != -ENOENT) {
  146. errno = -ret;
  147. fprintf(stderr, "cannot setup device for connector %u:%u (%d): %m\n",
  148. i, res->connectors[i], errno);
  149. }
  150. free(dev);
  151. drmModeFreeConnector(conn);
  152. continue;
  153. }
  154. /* free connector data and link device into global list */
  155. drmModeFreeConnector(conn);
  156. dev->next = modeset_list;
  157. modeset_list = dev;
  158. }
  159. /* free resources again */
  160. drmModeFreeResources(res);
  161. return 0;
  162. }
  163. /*
  164. * modeset_setup_dev() sets up all resources for a single device. It mostly
  165. * stays the same, but one thing changes: We allocate two framebuffers instead
  166. * of one. That is, we call modeset_create_fb() twice.
  167. * We also copy the width/height information into both framebuffers so
  168. * modeset_create_fb() can use them without requiring a pointer to modeset_dev.
  169. */
  170. static int modeset_setup_dev(int fd, drmModeRes *res, drmModeConnector *conn,
  171. struct modeset_dev *dev)
  172. {
  173. int ret;
  174. /* check if a monitor is connected */
  175. if (conn->connection != DRM_MODE_CONNECTED) {
  176. fprintf(stderr, "ignoring unused connector %u\n",
  177. conn->connector_id);
  178. return -ENOENT;
  179. }
  180. /* check if there is at least one valid mode */
  181. if (conn->count_modes == 0) {
  182. fprintf(stderr, "no valid mode for connector %u\n",
  183. conn->connector_id);
  184. return -EFAULT;
  185. }
  186. /* copy the mode information into our device structure and into both
  187. * buffers */
  188. memcpy(&dev->mode, &conn->modes[0], sizeof(dev->mode));
  189. dev->bufs[0].width = conn->modes[0].hdisplay;
  190. dev->bufs[0].height = conn->modes[0].vdisplay;
  191. dev->bufs[1].width = conn->modes[0].hdisplay;
  192. dev->bufs[1].height = conn->modes[0].vdisplay;
  193. fprintf(stderr, "mode for connector %u is %ux%u\n",
  194. conn->connector_id, dev->bufs[0].width, dev->bufs[0].height);
  195. /* find a crtc for this connector */
  196. ret = modeset_find_crtc(fd, res, conn, dev);
  197. if (ret) {
  198. fprintf(stderr, "no valid crtc for connector %u\n",
  199. conn->connector_id);
  200. return ret;
  201. }
  202. /* create framebuffer #1 for this CRTC */
  203. ret = modeset_create_fb(fd, &dev->bufs[0]);
  204. if (ret) {
  205. fprintf(stderr, "cannot create framebuffer for connector %u\n",
  206. conn->connector_id);
  207. return ret;
  208. }
  209. /* create framebuffer #2 for this CRTC */
  210. ret = modeset_create_fb(fd, &dev->bufs[1]);
  211. if (ret) {
  212. fprintf(stderr, "cannot create framebuffer for connector %u\n",
  213. conn->connector_id);
  214. modeset_destroy_fb(fd, &dev->bufs[0]);
  215. return ret;
  216. }
  217. return 0;
  218. }
  219. /*
  220. * modeset_find_crtc() stays the same.
  221. */
  222. static int modeset_find_crtc(int fd, drmModeRes *res, drmModeConnector *conn,
  223. struct modeset_dev *dev)
  224. {
  225. drmModeEncoder *enc;
  226. unsigned int i, j;
  227. int32_t crtc;
  228. struct modeset_dev *iter;
  229. /* first try the currently conected encoder+crtc */
  230. if (conn->encoder_id)
  231. enc = drmModeGetEncoder(fd, conn->encoder_id);
  232. else
  233. enc = NULL;
  234. if (enc) {
  235. if (enc->crtc_id) {
  236. crtc = enc->crtc_id;
  237. for (iter = modeset_list; iter; iter = iter->next) {
  238. if (iter->crtc == crtc) {
  239. crtc = -1;
  240. break;
  241. }
  242. }
  243. if (crtc >= 0) {
  244. drmModeFreeEncoder(enc);
  245. dev->crtc = crtc;
  246. return 0;
  247. }
  248. }
  249. drmModeFreeEncoder(enc);
  250. }
  251. /* If the connector is not currently bound to an encoder or if the
  252. * encoder+crtc is already used by another connector (actually unlikely
  253. * but lets be safe), iterate all other available encoders to find a
  254. * matching CRTC. */
  255. for (i = 0; i < conn->count_encoders; ++i) {
  256. enc = drmModeGetEncoder(fd, conn->encoders[i]);
  257. if (!enc) {
  258. fprintf(stderr, "cannot retrieve encoder %u:%u (%d): %m\n",
  259. i, conn->encoders[i], errno);
  260. continue;
  261. }
  262. /* iterate all global CRTCs */
  263. for (j = 0; j < res->count_crtcs; ++j) {
  264. /* check whether this CRTC works with the encoder */
  265. if (!(enc->possible_crtcs & (1 << j)))
  266. continue;
  267. /* check that no other device already uses this CRTC */
  268. crtc = res->crtcs[j];
  269. for (iter = modeset_list; iter; iter = iter->next) {
  270. if (iter->crtc == crtc) {
  271. crtc = -1;
  272. break;
  273. }
  274. }
  275. /* we have found a CRTC, so save it and return */
  276. if (crtc >= 0) {
  277. drmModeFreeEncoder(enc);
  278. dev->crtc = crtc;
  279. return 0;
  280. }
  281. }
  282. drmModeFreeEncoder(enc);
  283. }
  284. fprintf(stderr, "cannot find suitable CRTC for connector %u\n",
  285. conn->connector_id);
  286. return -ENOENT;
  287. }
  288. /*
  289. * modeset_create_fb() is mostly the same as before. Buf instead of writing the
  290. * fields of a modeset_dev, we now require a buffer pointer passed as @buf.
  291. * Please note that buf->width and buf->height are initialized by
  292. * modeset_setup_dev() so we can use them here.
  293. */
  294. static int modeset_create_fb(int fd, struct modeset_buf *buf)
  295. {
  296. struct drm_mode_create_dumb creq;
  297. struct drm_mode_destroy_dumb dreq;
  298. struct drm_mode_map_dumb mreq;
  299. int ret;
  300. /* create dumb buffer */
  301. memset(&creq, 0, sizeof(creq));
  302. creq.width = buf->width;
  303. creq.height = buf->height;
  304. creq.bpp = 32;
  305. ret = drmIoctl(fd, DRM_IOCTL_MODE_CREATE_DUMB, &creq);
  306. if (ret < 0) {
  307. fprintf(stderr, "cannot create dumb buffer (%d): %m\n",
  308. errno);
  309. return -errno;
  310. }
  311. buf->stride = creq.pitch;
  312. buf->size = creq.size;
  313. buf->handle = creq.handle;
  314. /* create framebuffer object for the dumb-buffer */
  315. ret = drmModeAddFB(fd, buf->width, buf->height, 32, 32, buf->stride,
  316. buf->handle, &buf->fb);
  317. if (ret) {
  318. fprintf(stderr, "cannot create framebuffer (%d): %m\n",
  319. errno);
  320. ret = -errno;
  321. goto err_destroy;
  322. }
  323. /* prepare buffer for memory mapping */
  324. memset(&mreq, 0, sizeof(mreq));
  325. mreq.handle = buf->handle;
  326. ret = drmIoctl(fd, DRM_IOCTL_MODE_MAP_DUMB, &mreq);
  327. if (ret) {
  328. fprintf(stderr, "cannot map dumb buffer (%d): %m\n",
  329. errno);
  330. ret = -errno;
  331. goto err_fb;
  332. }
  333. /* perform actual memory mapping */
  334. buf->map = mmap(0, buf->size, PROT_READ | PROT_WRITE, MAP_SHARED,
  335. fd, mreq.offset);
  336. if (buf->map == MAP_FAILED) {
  337. fprintf(stderr, "cannot mmap dumb buffer (%d): %m\n",
  338. errno);
  339. ret = -errno;
  340. goto err_fb;
  341. }
  342. /* clear the framebuffer to 0 */
  343. memset(buf->map, 0, buf->size);
  344. return 0;
  345. err_fb:
  346. drmModeRmFB(fd, buf->fb);
  347. err_destroy:
  348. memset(&dreq, 0, sizeof(dreq));
  349. dreq.handle = buf->handle;
  350. drmIoctl(fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
  351. return ret;
  352. }
  353. /*
  354. * modeset_destroy_fb() is a new function. It does exactly the reverse of
  355. * modeset_create_fb() and destroys a single framebuffer. The modeset.c example
  356. * used to do this directly in modeset_cleanup().
  357. * We simply unmap the buffer, remove the drm-FB and destroy the memory buffer.
  358. */
  359. static void modeset_destroy_fb(int fd, struct modeset_buf *buf)
  360. {
  361. struct drm_mode_destroy_dumb dreq;
  362. /* unmap buffer */
  363. munmap(buf->map, buf->size);
  364. /* delete framebuffer */
  365. drmModeRmFB(fd, buf->fb);
  366. /* delete dumb buffer */
  367. memset(&dreq, 0, sizeof(dreq));
  368. dreq.handle = buf->handle;
  369. drmIoctl(fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
  370. }
  371. /*
  372. * main() also stays almost exactly the same as before. We only need to change
  373. * the way that we initially set the CRTCs. Instead of using the buffer
  374. * information from modeset_dev, we now use dev->bufs[iter->front_buf] to get
  375. * the current front-buffer and use this framebuffer for drmModeSetCrtc().
  376. */
  377. int main(int argc, char **argv)
  378. {
  379. int ret, fd;
  380. const char *card;
  381. struct modeset_dev *iter;
  382. struct modeset_buf *buf;
  383. /* check which DRM device to open */
  384. if (argc > 1)
  385. card = argv[1];
  386. else
  387. card = "/dev/dri/card0";
  388. fprintf(stderr, "using card '%s'\n", card);
  389. /* open the DRM device */
  390. ret = modeset_open(&fd, card);
  391. if (ret)
  392. goto out_return;
  393. /* prepare all connectors and CRTCs */
  394. ret = modeset_prepare(fd);
  395. if (ret)
  396. goto out_close;
  397. /* perform actual modesetting on each found connector+CRTC */
  398. for (iter = modeset_list; iter; iter = iter->next) {
  399. iter->saved_crtc = drmModeGetCrtc(fd, iter->crtc);
  400. buf = &iter->bufs[iter->front_buf];
  401. ret = drmModeSetCrtc(fd, iter->crtc, buf->fb, 0, 0,
  402. &iter->conn, 1, &iter->mode);
  403. if (ret)
  404. fprintf(stderr, "cannot set CRTC for connector %u (%d): %m\n",
  405. iter->conn, errno);
  406. }
  407. /* draw some colors for 5seconds */
  408. modeset_draw(fd);
  409. /* cleanup everything */
  410. modeset_cleanup(fd);
  411. ret = 0;
  412. out_close:
  413. close(fd);
  414. out_return:
  415. if (ret) {
  416. errno = -ret;
  417. fprintf(stderr, "modeset failed with error %d: %m\n", errno);
  418. } else {
  419. fprintf(stderr, "exiting\n");
  420. }
  421. return ret;
  422. }
  423. /*
  424. * A short helper function to compute a changing color value. No need to
  425. * understand it.
  426. */
  427. static uint8_t next_color(bool *up, uint8_t cur, unsigned int mod)
  428. {
  429. uint8_t next;
  430. next = cur + (*up ? 1 : -1) * (rand() % mod);
  431. if ((*up && next < cur) || (!*up && next > cur)) {
  432. *up = !*up;
  433. next = cur;
  434. }
  435. return next;
  436. }
  437. /*
  438. * modeset_draw() is the place where things change. The render-logic is the same
  439. * and we still draw a solid-color on the whole screen. However, we now have two
  440. * buffers and need to flip between them.
  441. *
  442. * So before drawing into a framebuffer, we need to find the back-buffer.
  443. * Remember, dev->font_buf is the index of the front buffer, so
  444. * dev->front_buf ^ 1 is the index of the back buffer. We simply use
  445. * dev->bufs[dev->front_buf ^ 1] to get the back-buffer and draw into it.
  446. *
  447. * After we finished drawing, we need to flip the buffers. We do this with the
  448. * same call as we initially set the CRTC: drmModeSetCrtc(). However, we now
  449. * pass the back-buffer as new framebuffer as we want to flip them.
  450. * The only thing left to do is to change the dev->front_buf index to point to
  451. * the new back-buffer (which was previously the front buffer).
  452. * We then sleep for a short time period and start drawing again.
  453. *
  454. * If you run this example, you will notice that there is almost no flickering,
  455. * anymore. The buffers are now swapped as a whole so each new frame shows
  456. * always the whole new image. If you look carefully, you will notice that the
  457. * modeset.c example showed many screen corruptions during redraw-cycles.
  458. *
  459. * However, this example is still not perfect. Imagine the display-controller is
  460. * currently scanning out a new image and we call drmModeSetCrtc()
  461. * simultaneously. It will then have the same effect as if we used a single
  462. * buffer and we get some tearing. But, the chance that this happens is a lot
  463. * less likely as with a single-buffer. This is because there is a long period
  464. * between each frame called vertical-blank where the display-controller does
  465. * not perform a scanout. If we swap the buffers in this period, we have the
  466. * guarantee that there will be no tearing. See the modeset-vsync.c example if
  467. * you want to know how you can guarantee that the swap takes place at a
  468. * vertical-sync.
  469. */
  470. static void modeset_draw(int fd)
  471. {
  472. uint8_t r, g, b;
  473. bool r_up, g_up, b_up;
  474. unsigned int i, j, k, off;
  475. struct modeset_dev *iter;
  476. struct modeset_buf *buf;
  477. int ret;
  478. srand(time(NULL));
  479. r = rand() % 0xff;
  480. g = rand() % 0xff;
  481. b = rand() % 0xff;
  482. r_up = g_up = b_up = true;
  483. for (i = 0; i < 50; ++i) {
  484. r = next_color(&r_up, r, 20);
  485. g = next_color(&g_up, g, 10);
  486. b = next_color(&b_up, b, 5);
  487. for (iter = modeset_list; iter; iter = iter->next) {
  488. buf = &iter->bufs[iter->front_buf ^ 1];
  489. for (j = 0; j < buf->height; ++j) {
  490. for (k = 0; k < buf->width; ++k) {
  491. off = buf->stride * j + k * 4;
  492. *(uint32_t*)&buf->map[off] =
  493. (r << 16) | (g << 8) | b;
  494. }
  495. }
  496. ret = drmModeSetCrtc(fd, iter->crtc, buf->fb, 0, 0,
  497. &iter->conn, 1, &iter->mode);
  498. if (ret)
  499. fprintf(stderr, "cannot flip CRTC for connector %u (%d): %m\n",
  500. iter->conn, errno);
  501. else
  502. iter->front_buf ^= 1;
  503. }
  504. usleep(100000);
  505. }
  506. }
  507. /*
  508. * modeset_cleanup() stays the same as before. But it now calls
  509. * modeset_destroy_fb() instead of accessing the framebuffers directly.
  510. */
  511. static void modeset_cleanup(int fd)
  512. {
  513. struct modeset_dev *iter;
  514. while (modeset_list) {
  515. /* remove from global list */
  516. iter = modeset_list;
  517. modeset_list = iter->next;
  518. /* restore saved CRTC configuration */
  519. drmModeSetCrtc(fd,
  520. iter->saved_crtc->crtc_id,
  521. iter->saved_crtc->buffer_id,
  522. iter->saved_crtc->x,
  523. iter->saved_crtc->y,
  524. &iter->conn,
  525. 1,
  526. &iter->saved_crtc->mode);
  527. drmModeFreeCrtc(iter->saved_crtc);
  528. /* destroy framebuffers */
  529. modeset_destroy_fb(fd, &iter->bufs[1]);
  530. modeset_destroy_fb(fd, &iter->bufs[0]);
  531. /* free allocated memory */
  532. free(iter);
  533. }
  534. }
  535. /*
  536. * This was a very short extension to the basic modesetting example that shows
  537. * how double-buffering is implemented. Double-buffering is the de-facto
  538. * standard in any graphics application so any other example will be based on
  539. * this. It is important to understand the ideas behind it as the code is pretty
  540. * easy and short compared to modeset.c.
  541. *
  542. * Double-buffering doesn't solve all problems. Vsync'ed page-flips solve most
  543. * of the problems that still occur, but has problems on it's own (see
  544. * modeset-vsync.c for a discussion).
  545. *
  546. * If you want more code, I can recommend reading the source-code of:
  547. * - plymouth (which uses dumb-buffers like this example; very easy to understand)
  548. * - kmscon (which uses libuterm to do this)
  549. * - wayland (very sophisticated DRM renderer; hard to understand fully as it
  550. * uses more complicated techniques like DRM planes)
  551. * - xserver (very hard to understand as it is split across many files/projects)
  552. *
  553. * Any feedback is welcome. Feel free to use this code freely for your own
  554. * documentation or projects.
  555. *
  556. * - Hosted on http://github.com/dvdhrm/docs
  557. * - Written by David Rheinsberg <david.rheinsberg@gmail.com>
  558. */