modeset.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. /*
  2. * modeset - DRM Modesetting Example
  3. *
  4. * Written 2012 by David Rheinsberg <david.rheinsberg@gmail.com>
  5. * Dedicated to the Public Domain.
  6. */
  7. /*
  8. * DRM Modesetting Howto
  9. * This document describes the DRM modesetting API. Before we can use the DRM
  10. * API, we have to include xf86drm.h and xf86drmMode.h. Both are provided by
  11. * libdrm which every major distribution ships by default. It has no other
  12. * dependencies and is pretty small.
  13. *
  14. * Please ignore all forward-declarations of functions which are used later. I
  15. * reordered the functions so you can read this document from top to bottom. If
  16. * you reimplement it, you would probably reorder the functions to avoid all the
  17. * nasty forward declarations.
  18. *
  19. * For easier reading, we ignore all memory-allocation errors of malloc() and
  20. * friends here. However, we try to correctly handle all other kinds of errors
  21. * that may occur.
  22. *
  23. * All functions and global variables are prefixed with "modeset_*" in this
  24. * file. So it should be clear whether a function is a local helper or if it is
  25. * provided by some external library.
  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_dev;
  41. static int modeset_find_crtc(int fd, drmModeRes *res, drmModeConnector *conn,
  42. struct modeset_dev *dev);
  43. static int modeset_create_fb(int fd, struct modeset_dev *dev);
  44. static int modeset_setup_dev(int fd, drmModeRes *res, drmModeConnector *conn,
  45. struct modeset_dev *dev);
  46. static int modeset_open(int *out, const char *node);
  47. static int modeset_prepare(int fd);
  48. static void modeset_draw(void);
  49. static void modeset_cleanup(int fd);
  50. /*
  51. * When the linux kernel detects a graphics-card on your machine, it loads the
  52. * correct device driver (located in kernel-tree at ./drivers/gpu/drm/<xy>) and
  53. * provides two character-devices to control it. Udev (or whatever hotplugging
  54. * application you use) will create them as:
  55. * /dev/dri/card0
  56. * /dev/dri/controlID64
  57. * We only need the first one. You can hard-code this path into your application
  58. * like we do here, but it is recommended to use libudev with real hotplugging
  59. * and multi-seat support. However, this is beyond the scope of this document.
  60. * Also note that if you have multiple graphics-cards, there may also be
  61. * /dev/dri/card1, /dev/dri/card2, ...
  62. *
  63. * We simply use /dev/dri/card0 here but the user can specify another path on
  64. * the command line.
  65. *
  66. * modeset_open(out, node): This small helper function opens the DRM device
  67. * which is given as @node. The new fd is stored in @out on success. On failure,
  68. * a negative error code is returned.
  69. * After opening the file, we also check for the DRM_CAP_DUMB_BUFFER capability.
  70. * If the driver supports this capability, we can create simple memory-mapped
  71. * buffers without any driver-dependent code. As we want to avoid any radeon,
  72. * nvidia, intel, etc. specific code, we depend on DUMB_BUFFERs here.
  73. */
  74. static int modeset_open(int *out, const char *node)
  75. {
  76. int fd, ret;
  77. uint64_t has_dumb;
  78. fd = open(node, O_RDWR | O_CLOEXEC);
  79. if (fd < 0) {
  80. ret = -errno;
  81. fprintf(stderr, "cannot open '%s': %m\n", node);
  82. return ret;
  83. }
  84. if (drmGetCap(fd, DRM_CAP_DUMB_BUFFER, &has_dumb) < 0 ||
  85. !has_dumb) {
  86. fprintf(stderr, "drm device '%s' does not support dumb buffers\n",
  87. node);
  88. close(fd);
  89. return -EOPNOTSUPP;
  90. }
  91. *out = fd;
  92. return 0;
  93. }
  94. /*
  95. * As a next step we need to find our available display devices. libdrm provides
  96. * a drmModeRes structure that contains all the needed information. We can
  97. * retrieve it via drmModeGetResources(fd) and free it via
  98. * drmModeFreeResources(res) again.
  99. *
  100. * A physical connector on your graphics card is called a "connector". You can
  101. * plug a monitor into it and control what is displayed. We are definitely
  102. * interested in what connectors are currently used, so we simply iterate
  103. * through the list of connectors and try to display a test-picture on each
  104. * available monitor.
  105. * However, this isn't as easy as it sounds. First, we need to check whether the
  106. * connector is actually used (a monitor is plugged in and turned on). Then we
  107. * need to find a CRTC that can control this connector. CRTCs are described
  108. * later on. After that we create a framebuffer object. If we have all this, we
  109. * can mmap() the framebuffer and draw a test-picture into it. Then we can tell
  110. * the DRM device to show the framebuffer on the given CRTC with the selected
  111. * connector.
  112. *
  113. * As we want to draw moving pictures on the framebuffer, we actually have to
  114. * remember all these settings. Therefore, we create one "struct modeset_dev"
  115. * object for each connector+crtc+framebuffer pair that we successfully
  116. * initialized and push it into the global device-list.
  117. *
  118. * Each field of this structure is described when it is first used. But as a
  119. * summary:
  120. * "struct modeset_dev" contains: {
  121. * - @next: points to the next device in the single-linked list
  122. *
  123. * - @width: width of our buffer object
  124. * - @height: height of our buffer object
  125. * - @stride: stride value of our buffer object
  126. * - @size: size of the memory mapped buffer
  127. * - @handle: a DRM handle to the buffer object that we can draw into
  128. * - @map: pointer to the memory mapped buffer
  129. *
  130. * - @mode: the display mode that we want to use
  131. * - @fb: a framebuffer handle with our buffer object as scanout buffer
  132. * - @conn: the connector ID that we want to use with this buffer
  133. * - @crtc: the crtc ID that we want to use with this connector
  134. * - @saved_crtc: the configuration of the crtc before we changed it. We use it
  135. * so we can restore the same mode when we exit.
  136. * }
  137. */
  138. struct modeset_dev {
  139. struct modeset_dev *next;
  140. uint32_t width;
  141. uint32_t height;
  142. uint32_t stride;
  143. uint32_t size;
  144. uint32_t handle;
  145. uint8_t *map;
  146. drmModeModeInfo mode;
  147. uint32_t fb;
  148. uint32_t conn;
  149. uint32_t crtc;
  150. drmModeCrtc *saved_crtc;
  151. };
  152. static struct modeset_dev *modeset_list = NULL;
  153. /*
  154. * So as next step we need to actually prepare all connectors that we find. We
  155. * do this in this little helper function:
  156. *
  157. * modeset_prepare(fd): This helper function takes the DRM fd as argument and
  158. * then simply retrieves the resource-info from the device. It then iterates
  159. * through all connectors and calls other helper functions to initialize this
  160. * connector (described later on).
  161. * If the initialization was successful, we simply add this object as new device
  162. * into the global modeset device list.
  163. *
  164. * The resource-structure contains a list of all connector-IDs. We use the
  165. * helper function drmModeGetConnector() to retrieve more information on each
  166. * connector. After we are done with it, we free it again with
  167. * drmModeFreeConnector().
  168. * Our helper modeset_setup_dev() returns -ENOENT if the connector is currently
  169. * unused and no monitor is plugged in. So we can ignore this connector.
  170. */
  171. static int modeset_prepare(int fd)
  172. {
  173. drmModeRes *res;
  174. drmModeConnector *conn;
  175. unsigned int i;
  176. struct modeset_dev *dev;
  177. int ret;
  178. /* retrieve resources */
  179. res = drmModeGetResources(fd);
  180. if (!res) {
  181. fprintf(stderr, "cannot retrieve DRM resources (%d): %m\n",
  182. errno);
  183. return -errno;
  184. }
  185. /* iterate all connectors */
  186. for (i = 0; i < res->count_connectors; ++i) {
  187. /* get information for each connector */
  188. conn = drmModeGetConnector(fd, res->connectors[i]);
  189. if (!conn) {
  190. fprintf(stderr, "cannot retrieve DRM connector %u:%u (%d): %m\n",
  191. i, res->connectors[i], errno);
  192. continue;
  193. }
  194. /* create a device structure */
  195. dev = malloc(sizeof(*dev));
  196. memset(dev, 0, sizeof(*dev));
  197. dev->conn = conn->connector_id;
  198. /* call helper function to prepare this connector */
  199. ret = modeset_setup_dev(fd, res, conn, dev);
  200. if (ret) {
  201. if (ret != -ENOENT) {
  202. errno = -ret;
  203. fprintf(stderr, "cannot setup device for connector %u:%u (%d): %m\n",
  204. i, res->connectors[i], errno);
  205. }
  206. free(dev);
  207. drmModeFreeConnector(conn);
  208. continue;
  209. }
  210. /* free connector data and link device into global list */
  211. drmModeFreeConnector(conn);
  212. dev->next = modeset_list;
  213. modeset_list = dev;
  214. }
  215. /* free resources again */
  216. drmModeFreeResources(res);
  217. return 0;
  218. }
  219. /*
  220. * Now we dig deeper into setting up a single connector. As described earlier,
  221. * we need to check several things first:
  222. * * If the connector is currently unused, that is, no monitor is plugged in,
  223. * then we can ignore it.
  224. * * We have to find a suitable resolution and refresh-rate. All this is
  225. * available in drmModeModeInfo structures saved for each crtc. We simply
  226. * use the first mode that is available. This is always the mode with the
  227. * highest resolution.
  228. * A more sophisticated mode-selection should be done in real applications,
  229. * though.
  230. * * Then we need to find an CRTC that can drive this connector. A CRTC is an
  231. * internal resource of each graphics-card. The number of CRTCs controls how
  232. * many connectors can be controlled indepedently. That is, a graphics-cards
  233. * may have more connectors than CRTCs, which means, not all monitors can be
  234. * controlled independently.
  235. * There is actually the possibility to control multiple connectors via a
  236. * single CRTC if the monitors should display the same content. However, we
  237. * do not make use of this here.
  238. * So think of connectors as pipelines to the connected monitors and the
  239. * CRTCs are the controllers that manage which data goes to which pipeline.
  240. * If there are more pipelines than CRTCs, then we cannot control all of
  241. * them at the same time.
  242. * * We need to create a framebuffer for this connector. A framebuffer is a
  243. * memory buffer that we can write XRGB32 data into. So we use this to
  244. * render our graphics and then the CRTC can scan-out this data from the
  245. * framebuffer onto the monitor.
  246. */
  247. static int modeset_setup_dev(int fd, drmModeRes *res, drmModeConnector *conn,
  248. struct modeset_dev *dev)
  249. {
  250. int ret;
  251. /* check if a monitor is connected */
  252. if (conn->connection != DRM_MODE_CONNECTED) {
  253. fprintf(stderr, "ignoring unused connector %u\n",
  254. conn->connector_id);
  255. return -ENOENT;
  256. }
  257. /* check if there is at least one valid mode */
  258. if (conn->count_modes == 0) {
  259. fprintf(stderr, "no valid mode for connector %u\n",
  260. conn->connector_id);
  261. return -EFAULT;
  262. }
  263. /* copy the mode information into our device structure */
  264. memcpy(&dev->mode, &conn->modes[0], sizeof(dev->mode));
  265. dev->width = conn->modes[0].hdisplay;
  266. dev->height = conn->modes[0].vdisplay;
  267. fprintf(stderr, "mode for connector %u is %ux%u\n",
  268. conn->connector_id, dev->width, dev->height);
  269. drmMsg("[%s,%d]: connector_id=%d\n",__FUNCTION__,__LINE__, conn->connector_id);
  270. /* find a crtc for this connector */
  271. ret = modeset_find_crtc(fd, res, conn, dev);
  272. if (ret) {
  273. fprintf(stderr, "no valid crtc for connector %u\n",
  274. conn->connector_id);
  275. return ret;
  276. }
  277. /* create a framebuffer for this CRTC */
  278. ret = modeset_create_fb(fd, dev);
  279. if (ret) {
  280. fprintf(stderr, "cannot create framebuffer for connector %u\n",
  281. conn->connector_id);
  282. return ret;
  283. }
  284. return 0;
  285. }
  286. /*
  287. * modeset_find_crtc(fd, res, conn, dev): This small helper tries to find a
  288. * suitable CRTC for the given connector. We have actually have to introduce one
  289. * more DRM object to make this more clear: Encoders.
  290. * Encoders help the CRTC to convert data from a framebuffer into the right
  291. * format that can be used for the chosen connector. We do not have to
  292. * understand any more of these conversions to make use of it. However, you must
  293. * know that each connector has a limited list of encoders that it can use. And
  294. * each encoder can only work with a limited list of CRTCs. So what we do is
  295. * trying each encoder that is available and looking for a CRTC that this
  296. * encoder can work with. If we find the first working combination, we are happy
  297. * and write it into the @dev structure.
  298. * But before iterating all available encoders, we first try the currently
  299. * active encoder+crtc on a connector to avoid a full modeset.
  300. *
  301. * However, before we can use a CRTC we must make sure that no other device,
  302. * that we setup previously, is already using this CRTC. Remember, we can only
  303. * drive one connector per CRTC! So we simply iterate through the "modeset_list"
  304. * of previously setup devices and check that this CRTC wasn't used before.
  305. * Otherwise, we continue with the next CRTC/Encoder combination.
  306. */
  307. static int modeset_find_crtc(int fd, drmModeRes *res, drmModeConnector *conn,
  308. struct modeset_dev *dev)
  309. {
  310. drmModeEncoder *enc;
  311. unsigned int i, j;
  312. int32_t crtc;
  313. struct modeset_dev *iter;
  314. drmMsg("[%s,%d]: connector_id=%d, encoder_id=%d, res->count_crtcs=%d,count_encoders=%d\n",__FUNCTION__,__LINE__,
  315. conn->connector_id,conn->encoder_id, res->count_crtcs,
  316. conn->count_encoders);
  317. /* first try the currently conected encoder+crtc */
  318. if (conn->encoder_id)
  319. enc = drmModeGetEncoder(fd, conn->encoder_id);
  320. else
  321. enc = NULL;
  322. if (enc) {
  323. drmMsg("[%s,%d]: crtc_id=%d\n",__FUNCTION__,__LINE__, enc->crtc_id);
  324. if (enc->crtc_id) {
  325. crtc = enc->crtc_id;
  326. for (iter = modeset_list; iter; iter = iter->next) {
  327. if (iter->crtc == crtc) {
  328. crtc = -1;
  329. break;
  330. }
  331. }
  332. drmMsg("[%s,%d]: crtc=%d\n",__FUNCTION__,__LINE__, crtc);
  333. if (crtc >= 0) {
  334. drmModeFreeEncoder(enc);
  335. dev->crtc = crtc;
  336. return 0;
  337. }
  338. }
  339. drmModeFreeEncoder(enc);
  340. }
  341. /* If the connector is not currently bound to an encoder or if the
  342. * encoder+crtc is already used by another connector (actually unlikely
  343. * but lets be safe), iterate all other available encoders to find a
  344. * matching CRTC. */
  345. for (i = 0; i < conn->count_encoders; ++i) {
  346. enc = drmModeGetEncoder(fd, conn->encoders[i]);
  347. if (!enc) {
  348. fprintf(stderr, "cannot retrieve encoder %u:%u (%d): %m\n",
  349. i, conn->encoders[i], errno);
  350. continue;
  351. }
  352. /* iterate all global CRTCs */
  353. for (j = 0; j < res->count_crtcs; ++j) {
  354. /* check whether this CRTC works with the encoder */
  355. if (!(enc->possible_crtcs & (1 << j)))
  356. continue;
  357. /* check that no other device already uses this CRTC */
  358. crtc = res->crtcs[j];
  359. for (iter = modeset_list; iter; iter = iter->next) {
  360. if (iter->crtc == crtc) {
  361. crtc = -1;
  362. break;
  363. }
  364. }
  365. /* we have found a CRTC, so save it and return */
  366. if (crtc >= 0) {
  367. drmModeFreeEncoder(enc);
  368. dev->crtc = crtc;
  369. return 0;
  370. }
  371. }
  372. drmModeFreeEncoder(enc);
  373. }
  374. fprintf(stderr, "cannot find suitable CRTC for connector %u\n",
  375. conn->connector_id);
  376. return -ENOENT;
  377. }
  378. /*
  379. * modeset_create_fb(fd, dev): After we have found a crtc+connector+mode
  380. * combination, we need to actually create a suitable framebuffer that we can
  381. * use with it. There are actually two ways to do that:
  382. * * We can create a so called "dumb buffer". This is a buffer that we can
  383. * memory-map via mmap() and every driver supports this. We can use it for
  384. * unaccelerated software rendering on the CPU.
  385. * * We can use libgbm to create buffers available for hardware-acceleration.
  386. * libgbm is an abstraction layer that creates these buffers for each
  387. * available DRM driver. As there is no generic API for this, each driver
  388. * provides its own way to create these buffers.
  389. * We can then use such buffers to create OpenGL contexts with the mesa3D
  390. * library.
  391. * We use the first solution here as it is much simpler and doesn't require any
  392. * external libraries. However, if you want to use hardware-acceleration via
  393. * OpenGL, it is actually pretty easy to create such buffers with libgbm and
  394. * libEGL. But this is beyond the scope of this document.
  395. *
  396. * So what we do is requesting a new dumb-buffer from the driver. We specify the
  397. * same size as the current mode that we selected for the connector.
  398. * Then we request the driver to prepare this buffer for memory mapping. After
  399. * that we perform the actual mmap() call. So we can now access the framebuffer
  400. * memory directly via the dev->map memory map.
  401. */
  402. static int modeset_create_fb(int fd, struct modeset_dev *dev)
  403. {
  404. struct drm_mode_create_dumb creq;
  405. struct drm_mode_destroy_dumb dreq;
  406. struct drm_mode_map_dumb mreq;
  407. int ret;
  408. /* create dumb buffer */
  409. memset(&creq, 0, sizeof(creq));
  410. creq.width = dev->width;
  411. creq.height = dev->height;
  412. creq.bpp = 32;
  413. ret = drmIoctl(fd, DRM_IOCTL_MODE_CREATE_DUMB, &creq);
  414. if (ret < 0) {
  415. fprintf(stderr, "cannot create dumb buffer (%d): %m\n",
  416. errno);
  417. return -errno;
  418. }
  419. dev->stride = creq.pitch;
  420. dev->size = creq.size;
  421. dev->handle = creq.handle;
  422. /* create framebuffer object for the dumb-buffer */
  423. ret = drmModeAddFB(fd, dev->width, dev->height, 32, 32, dev->stride,
  424. dev->handle, &dev->fb);
  425. if (ret) {
  426. fprintf(stderr, "cannot create framebuffer (%d): %m\n",
  427. errno);
  428. ret = -errno;
  429. goto err_destroy;
  430. }
  431. drmMsg("[%s,%d]: dev->fb=%d\n",__FUNCTION__,__LINE__, dev->fb);
  432. /* prepare buffer for memory mapping */
  433. memset(&mreq, 0, sizeof(mreq));
  434. mreq.handle = dev->handle;
  435. ret = drmIoctl(fd, DRM_IOCTL_MODE_MAP_DUMB, &mreq);
  436. if (ret) {
  437. fprintf(stderr, "cannot map dumb buffer (%d): %m\n",
  438. errno);
  439. ret = -errno;
  440. goto err_fb;
  441. }
  442. /* perform actual memory mapping */
  443. dev->map = mmap(0, dev->size, PROT_READ | PROT_WRITE, MAP_SHARED,
  444. fd, mreq.offset);
  445. if (dev->map == MAP_FAILED) {
  446. fprintf(stderr, "cannot mmap dumb buffer (%d): %m\n",
  447. errno);
  448. ret = -errno;
  449. goto err_fb;
  450. }
  451. /* clear the framebuffer to 0 */
  452. memset(dev->map, 0, dev->size);
  453. return 0;
  454. err_fb:
  455. drmModeRmFB(fd, dev->fb);
  456. err_destroy:
  457. memset(&dreq, 0, sizeof(dreq));
  458. dreq.handle = dev->handle;
  459. drmIoctl(fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
  460. return ret;
  461. }
  462. /*
  463. * Finally! We have a connector with a suitable CRTC. We know which mode we want
  464. * to use and we have a framebuffer of the correct size that we can write to.
  465. * There is nothing special left to do. We only have to program the CRTC to
  466. * connect each new framebuffer to each selected connector for each combination
  467. * that we saved in the global modeset_list.
  468. * This is done with a call to drmModeSetCrtc().
  469. *
  470. * So we are ready for our main() function. First we check whether the user
  471. * specified a DRM device on the command line, otherwise we use the default
  472. * /dev/dri/card0. Then we open the device via modeset_open(). modeset_prepare()
  473. * prepares all connectors and we can loop over "modeset_list" and call
  474. * drmModeSetCrtc() on every CRTC/connector combination.
  475. *
  476. * But printing empty black pages is boring so we have another helper function
  477. * modeset_draw() that draws some colors into the framebuffer for 5 seconds and
  478. * then returns. And then we have all the cleanup functions which correctly free
  479. * all devices again after we used them. All these functions are described below
  480. * the main() function.
  481. *
  482. * As a side note: drmModeSetCrtc() actually takes a list of connectors that we
  483. * want to control with this CRTC. We pass only one connector, though. As
  484. * explained earlier, if we used multiple connectors, then all connectors would
  485. * have the same controlling framebuffer so the output would be cloned. This is
  486. * most often not what you want so we avoid explaining this feature here.
  487. * Furthermore, all connectors will have to run with the same mode, which is
  488. * also often not guaranteed. So instead, we only use one connector per CRTC.
  489. *
  490. * Before calling drmModeSetCrtc() we also save the current CRTC configuration.
  491. * This is used in modeset_cleanup() to restore the CRTC to the same mode as was
  492. * before we changed it.
  493. * If we don't do this, the screen will stay blank after we exit until another
  494. * application performs modesetting itself.
  495. */
  496. int main(int argc, char **argv)
  497. {
  498. int ret, fd;
  499. const char *card;
  500. struct modeset_dev *iter;
  501. /* check which DRM device to open */
  502. if (argc > 1)
  503. card = argv[1];
  504. else
  505. card = "/dev/dri/card0";
  506. fprintf(stderr, "using card '%s'\n", card);
  507. /* open the DRM device */
  508. ret = modeset_open(&fd, card);
  509. if (ret)
  510. goto out_return;
  511. /* prepare all connectors and CRTCs */
  512. ret = modeset_prepare(fd);
  513. if (ret)
  514. goto out_close;
  515. /* perform actual modesetting on each found connector+CRTC */
  516. for (iter = modeset_list; iter; iter = iter->next) {
  517. drmMsg("[%s,%d]: !!!!!!!!!!!errno=%m. iter->fb=%d \n",__FUNCTION__,__LINE__,iter->fb);
  518. iter->saved_crtc = drmModeGetCrtc(fd, iter->crtc);
  519. ret = drmModeSetCrtc(fd, iter->crtc, iter->fb, 0, 0,
  520. &iter->conn, 1, &iter->mode);
  521. if (ret) {
  522. fprintf(stderr, "cannot set CRTC for connector %u (%d): %m\n",
  523. iter->conn, errno);
  524. modeset_cleanup(fd);
  525. }
  526. }
  527. /* draw some colors for 5seconds */
  528. modeset_draw();
  529. /* cleanup everything */
  530. modeset_cleanup(fd);
  531. ret = 0;
  532. out_close:
  533. close(fd);
  534. out_return:
  535. if (ret) {
  536. errno = -ret;
  537. fprintf(stderr, "modeset failed with error %d: %m\n", errno);
  538. } else {
  539. fprintf(stderr, "exiting\n");
  540. }
  541. return ret;
  542. }
  543. /*
  544. * A short helper function to compute a changing color value. No need to
  545. * understand it.
  546. */
  547. static uint8_t next_color(bool *up, uint8_t cur, unsigned int mod)
  548. {
  549. uint8_t next;
  550. next = cur + (*up ? 1 : -1) * (rand() % mod);
  551. if ((*up && next < cur) || (!*up && next > cur)) {
  552. *up = !*up;
  553. next = cur;
  554. }
  555. return next;
  556. }
  557. /*
  558. * modeset_draw(): This draws a solid color into all configured framebuffers.
  559. * Every 100ms the color changes to a slightly different color so we get some
  560. * kind of smoothly changing color-gradient.
  561. *
  562. * The color calculation can be ignored as it is pretty boring. So the
  563. * interesting stuff is iterating over "modeset_list" and then through all lines
  564. * and width. We then set each pixel individually to the current color.
  565. *
  566. * We do this 50 times as we sleep 100ms after each redraw round. This makes
  567. * 50*100ms = 5000ms = 5s so it takes about 5seconds to finish this loop.
  568. *
  569. * Please note that we draw directly into the framebuffer. This means that you
  570. * will see flickering as the monitor might refresh while we redraw the screen.
  571. * To avoid this you would need to use two framebuffers and a call to
  572. * drmModeSetCrtc() to switch between both buffers.
  573. * You can also use drmModePageFlip() to do a vsync'ed pageflip. But this is
  574. * beyond the scope of this document.
  575. */
  576. static void modeset_draw(void)
  577. {
  578. uint8_t r, g, b;
  579. bool r_up, g_up, b_up;
  580. unsigned int i, j, k, off;
  581. struct modeset_dev *iter;
  582. srand(time(NULL));
  583. r = rand() % 0xff;
  584. g = rand() % 0xff;
  585. b = rand() % 0xff;
  586. r_up = g_up = b_up = true;
  587. for (i = 0; i < 50; ++i) {
  588. r = next_color(&r_up, r, 20);
  589. g = next_color(&g_up, g, 10);
  590. b = next_color(&b_up, b, 5);
  591. for (iter = modeset_list; iter; iter = iter->next) {
  592. for (j = 0; j < iter->height; ++j) {
  593. for (k = 0; k < iter->width; ++k) {
  594. off = iter->stride * j + k * 4;
  595. *(uint32_t*)&iter->map[off] =
  596. (r << 16) | (g << 8) | b;
  597. }
  598. }
  599. }
  600. usleep(100000);
  601. }
  602. }
  603. /*
  604. * modeset_cleanup(fd): This cleans up all the devices we created during
  605. * modeset_prepare(). It resets the CRTCs to their saved states and deallocates
  606. * all memory.
  607. * It should be pretty obvious how all of this works.
  608. */
  609. static void modeset_cleanup(int fd)
  610. {
  611. struct modeset_dev *iter;
  612. struct drm_mode_destroy_dumb dreq;
  613. int ret = -1;
  614. while (modeset_list) {
  615. /* remove from global list */
  616. iter = modeset_list;
  617. modeset_list = iter->next;
  618. /* restore saved CRTC configuration */
  619. ret = drmModeSetCrtc(fd,
  620. iter->saved_crtc->crtc_id,
  621. iter->saved_crtc->buffer_id,
  622. iter->saved_crtc->x,
  623. iter->saved_crtc->y,
  624. &iter->conn,
  625. 1,
  626. &iter->saved_crtc->mode);
  627. if (ret)
  628. fprintf(stderr, "cannot set CRTC for connector %u (%d): %m\n",
  629. iter->conn, errno);
  630. drmModeFreeCrtc(iter->saved_crtc);
  631. /* unmap buffer */
  632. munmap(iter->map, iter->size);
  633. /* delete framebuffer */
  634. drmModeRmFB(fd, iter->fb);
  635. /* delete dumb buffer */
  636. memset(&dreq, 0, sizeof(dreq));
  637. dreq.handle = iter->handle;
  638. drmIoctl(fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
  639. /* free allocated memory */
  640. free(iter);
  641. }
  642. }
  643. /*
  644. * I hope this was a short but easy overview of the DRM modesetting API. The DRM
  645. * API offers much more capabilities including:
  646. * - double-buffering or tripple-buffering (or whatever you want)
  647. * - vsync'ed page-flips
  648. * - hardware-accelerated rendering (for example via OpenGL)
  649. * - output cloning
  650. * - graphics-clients plus authentication
  651. * - DRM planes/overlays/sprites
  652. * - ...
  653. * If you are interested in these topics, I can currently only redirect you to
  654. * existing implementations, including:
  655. * - plymouth (which uses dumb-buffers like this example; very easy to understand)
  656. * - kmscon (which uses libuterm to do this)
  657. * - wayland (very sophisticated DRM renderer; hard to understand fully as it
  658. * uses more complicated techniques like DRM planes)
  659. * - xserver (very hard to understand as it is split across many files/projects)
  660. *
  661. * But understanding how modesetting (as described in this document) works, is
  662. * essential to understand all further DRM topics.
  663. *
  664. * Any feedback is welcome. Feel free to use this code freely for your own
  665. * documentation or projects.
  666. *
  667. * - Hosted on http://github.com/dvdhrm/docs
  668. * - Written by David Rheinsberg <david.rheinsberg@gmail.com>
  669. */