drm_vblank.c 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  1. /*
  2. * drm_irq.c IRQ and vblank support
  3. *
  4. * \author Rickard E. (Rik) Faith <faith@valinux.com>
  5. * \author Gareth Hughes <gareth@valinux.com>
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a
  8. * copy of this software and associated documentation files (the "Software"),
  9. * to deal in the Software without restriction, including without limitation
  10. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  11. * and/or sell copies of the Software, and to permit persons to whom the
  12. * Software is furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice (including the next
  15. * paragraph) shall be included in all copies or substantial portions of the
  16. * Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  21. * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  22. * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  23. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  24. * OTHER DEALINGS IN THE SOFTWARE.
  25. */
  26. #include <linux/export.h>
  27. #include <linux/kthread.h>
  28. #include <linux/moduleparam.h>
  29. #include <drm/drm_crtc.h>
  30. #include <drm/drm_drv.h>
  31. #include <drm/drm_framebuffer.h>
  32. #include <drm/drm_managed.h>
  33. #include <drm/drm_modeset_helper_vtables.h>
  34. #include <drm/drm_print.h>
  35. #include <drm/drm_vblank.h>
  36. #include "drm_internal.h"
  37. #include "drm_trace.h"
  38. /**
  39. * DOC: vblank handling
  40. *
  41. * From the computer's perspective, every time the monitor displays
  42. * a new frame the scanout engine has "scanned out" the display image
  43. * from top to bottom, one row of pixels at a time. The current row
  44. * of pixels is referred to as the current scanline.
  45. *
  46. * In addition to the display's visible area, there's usually a couple of
  47. * extra scanlines which aren't actually displayed on the screen.
  48. * These extra scanlines don't contain image data and are occasionally used
  49. * for features like audio and infoframes. The region made up of these
  50. * scanlines is referred to as the vertical blanking region, or vblank for
  51. * short.
  52. *
  53. * For historical reference, the vertical blanking period was designed to
  54. * give the electron gun (on CRTs) enough time to move back to the top of
  55. * the screen to start scanning out the next frame. Similar for horizontal
  56. * blanking periods. They were designed to give the electron gun enough
  57. * time to move back to the other side of the screen to start scanning the
  58. * next scanline.
  59. *
  60. * ::
  61. *
  62. *
  63. * physical → ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽
  64. * top of | |
  65. * display | |
  66. * | New frame |
  67. * | |
  68. * |↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓|
  69. * |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| ← Scanline,
  70. * |↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓| updates the
  71. * | | frame as it
  72. * | | travels down
  73. * | | ("scan out")
  74. * | Old frame |
  75. * | |
  76. * | |
  77. * | |
  78. * | | physical
  79. * | | bottom of
  80. * vertical |⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽| ← display
  81. * blanking ┆xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx┆
  82. * region → ┆xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx┆
  83. * ┆xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx┆
  84. * start of → ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽
  85. * new frame
  86. *
  87. * "Physical top of display" is the reference point for the high-precision/
  88. * corrected timestamp.
  89. *
  90. * On a lot of display hardware, programming needs to take effect during the
  91. * vertical blanking period so that settings like gamma, the image buffer
  92. * buffer to be scanned out, etc. can safely be changed without showing
  93. * any visual artifacts on the screen. In some unforgiving hardware, some of
  94. * this programming has to both start and end in the same vblank. To help
  95. * with the timing of the hardware programming, an interrupt is usually
  96. * available to notify the driver when it can start the updating of registers.
  97. * The interrupt is in this context named the vblank interrupt.
  98. *
  99. * The vblank interrupt may be fired at different points depending on the
  100. * hardware. Some hardware implementations will fire the interrupt when the
  101. * new frame start, other implementations will fire the interrupt at different
  102. * points in time.
  103. *
  104. * Vertical blanking plays a major role in graphics rendering. To achieve
  105. * tear-free display, users must synchronize page flips and/or rendering to
  106. * vertical blanking. The DRM API offers ioctls to perform page flips
  107. * synchronized to vertical blanking and wait for vertical blanking.
  108. *
  109. * The DRM core handles most of the vertical blanking management logic, which
  110. * involves filtering out spurious interrupts, keeping race-free blanking
  111. * counters, coping with counter wrap-around and resets and keeping use counts.
  112. * It relies on the driver to generate vertical blanking interrupts and
  113. * optionally provide a hardware vertical blanking counter.
  114. *
  115. * Drivers must initialize the vertical blanking handling core with a call to
  116. * drm_vblank_init(). Minimally, a driver needs to implement
  117. * &drm_crtc_funcs.enable_vblank and &drm_crtc_funcs.disable_vblank plus call
  118. * drm_crtc_handle_vblank() in its vblank interrupt handler for working vblank
  119. * support.
  120. *
  121. * Vertical blanking interrupts can be enabled by the DRM core or by drivers
  122. * themselves (for instance to handle page flipping operations). The DRM core
  123. * maintains a vertical blanking use count to ensure that the interrupts are not
  124. * disabled while a user still needs them. To increment the use count, drivers
  125. * call drm_crtc_vblank_get() and release the vblank reference again with
  126. * drm_crtc_vblank_put(). In between these two calls vblank interrupts are
  127. * guaranteed to be enabled.
  128. *
  129. * On many hardware disabling the vblank interrupt cannot be done in a race-free
  130. * manner, see &drm_vblank_crtc_config.disable_immediate and
  131. * &drm_driver.max_vblank_count. In that case the vblank core only disables the
  132. * vblanks after a timer has expired, which can be configured through the
  133. * ``vblankoffdelay`` module parameter.
  134. *
  135. * Drivers for hardware without support for vertical-blanking interrupts
  136. * must not call drm_vblank_init(). For such drivers, atomic helpers will
  137. * automatically generate fake vblank events as part of the display update.
  138. * This functionality also can be controlled by the driver by enabling and
  139. * disabling struct drm_crtc_state.no_vblank.
  140. */
  141. /* Retry timestamp calculation up to 3 times to satisfy
  142. * drm_timestamp_precision before giving up.
  143. */
  144. #define DRM_TIMESTAMP_MAXRETRIES 3
  145. /* Threshold in nanoseconds for detection of redundant
  146. * vblank irq in drm_handle_vblank(). 1 msec should be ok.
  147. */
  148. #define DRM_REDUNDANT_VBLIRQ_THRESH_NS 1000000
  149. static bool
  150. drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
  151. ktime_t *tvblank, bool in_vblank_irq);
  152. static unsigned int drm_timestamp_precision = 20; /* Default to 20 usecs. */
  153. static int drm_vblank_offdelay = 5000; /* Default to 5000 msecs. */
  154. module_param_named(vblankoffdelay, drm_vblank_offdelay, int, 0600);
  155. module_param_named(timestamp_precision_usec, drm_timestamp_precision, int, 0600);
  156. MODULE_PARM_DESC(vblankoffdelay, "Delay until vblank irq auto-disable [msecs] (0: never disable, <0: disable immediately)");
  157. MODULE_PARM_DESC(timestamp_precision_usec, "Max. error on timestamps [usecs]");
  158. static struct drm_vblank_crtc *
  159. drm_vblank_crtc(struct drm_device *dev, unsigned int pipe)
  160. {
  161. return &dev->vblank[pipe];
  162. }
  163. struct drm_vblank_crtc *
  164. drm_crtc_vblank_crtc(struct drm_crtc *crtc)
  165. {
  166. return drm_vblank_crtc(crtc->dev, drm_crtc_index(crtc));
  167. }
  168. EXPORT_SYMBOL(drm_crtc_vblank_crtc);
  169. static void store_vblank(struct drm_device *dev, unsigned int pipe,
  170. u32 vblank_count_inc,
  171. ktime_t t_vblank, u32 last)
  172. {
  173. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  174. assert_spin_locked(&dev->vblank_time_lock);
  175. vblank->last = last;
  176. write_seqlock(&vblank->seqlock);
  177. vblank->time = t_vblank;
  178. atomic64_add(vblank_count_inc, &vblank->count);
  179. write_sequnlock(&vblank->seqlock);
  180. }
  181. static u32 drm_max_vblank_count(struct drm_device *dev, unsigned int pipe)
  182. {
  183. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  184. return vblank->max_vblank_count ?: dev->max_vblank_count;
  185. }
  186. /*
  187. * "No hw counter" fallback implementation of .get_vblank_counter() hook,
  188. * if there is no usable hardware frame counter available.
  189. */
  190. static u32 drm_vblank_no_hw_counter(struct drm_device *dev, unsigned int pipe)
  191. {
  192. drm_WARN_ON_ONCE(dev, drm_max_vblank_count(dev, pipe) != 0);
  193. return 0;
  194. }
  195. static u32 __get_vblank_counter(struct drm_device *dev, unsigned int pipe)
  196. {
  197. if (drm_core_check_feature(dev, DRIVER_MODESET)) {
  198. struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
  199. if (drm_WARN_ON(dev, !crtc))
  200. return 0;
  201. if (crtc->funcs->get_vblank_counter)
  202. return crtc->funcs->get_vblank_counter(crtc);
  203. }
  204. return drm_vblank_no_hw_counter(dev, pipe);
  205. }
  206. /*
  207. * Reset the stored timestamp for the current vblank count to correspond
  208. * to the last vblank occurred.
  209. *
  210. * Only to be called from drm_crtc_vblank_on().
  211. *
  212. * Note: caller must hold &drm_device.vbl_lock since this reads & writes
  213. * device vblank fields.
  214. */
  215. static void drm_reset_vblank_timestamp(struct drm_device *dev, unsigned int pipe)
  216. {
  217. u32 cur_vblank;
  218. bool rc;
  219. ktime_t t_vblank;
  220. int count = DRM_TIMESTAMP_MAXRETRIES;
  221. spin_lock(&dev->vblank_time_lock);
  222. /*
  223. * sample the current counter to avoid random jumps
  224. * when drm_vblank_enable() applies the diff
  225. */
  226. do {
  227. cur_vblank = __get_vblank_counter(dev, pipe);
  228. rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
  229. } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
  230. /*
  231. * Only reinitialize corresponding vblank timestamp if high-precision query
  232. * available and didn't fail. Otherwise reinitialize delayed at next vblank
  233. * interrupt and assign 0 for now, to mark the vblanktimestamp as invalid.
  234. */
  235. if (!rc)
  236. t_vblank = 0;
  237. /*
  238. * +1 to make sure user will never see the same
  239. * vblank counter value before and after a modeset
  240. */
  241. store_vblank(dev, pipe, 1, t_vblank, cur_vblank);
  242. spin_unlock(&dev->vblank_time_lock);
  243. }
  244. /*
  245. * Call back into the driver to update the appropriate vblank counter
  246. * (specified by @pipe). Deal with wraparound, if it occurred, and
  247. * update the last read value so we can deal with wraparound on the next
  248. * call if necessary.
  249. *
  250. * Only necessary when going from off->on, to account for frames we
  251. * didn't get an interrupt for.
  252. *
  253. * Note: caller must hold &drm_device.vbl_lock since this reads & writes
  254. * device vblank fields.
  255. */
  256. static void drm_update_vblank_count(struct drm_device *dev, unsigned int pipe,
  257. bool in_vblank_irq)
  258. {
  259. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  260. u32 cur_vblank, diff;
  261. bool rc;
  262. ktime_t t_vblank;
  263. int count = DRM_TIMESTAMP_MAXRETRIES;
  264. int framedur_ns = vblank->framedur_ns;
  265. u32 max_vblank_count = drm_max_vblank_count(dev, pipe);
  266. /*
  267. * Interrupts were disabled prior to this call, so deal with counter
  268. * wrap if needed.
  269. * NOTE! It's possible we lost a full dev->max_vblank_count + 1 events
  270. * here if the register is small or we had vblank interrupts off for
  271. * a long time.
  272. *
  273. * We repeat the hardware vblank counter & timestamp query until
  274. * we get consistent results. This to prevent races between gpu
  275. * updating its hardware counter while we are retrieving the
  276. * corresponding vblank timestamp.
  277. */
  278. do {
  279. cur_vblank = __get_vblank_counter(dev, pipe);
  280. rc = drm_get_last_vbltimestamp(dev, pipe, &t_vblank, in_vblank_irq);
  281. } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
  282. if (max_vblank_count) {
  283. /* trust the hw counter when it's around */
  284. diff = (cur_vblank - vblank->last) & max_vblank_count;
  285. } else if (rc && framedur_ns) {
  286. u64 diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
  287. /*
  288. * Figure out how many vblanks we've missed based
  289. * on the difference in the timestamps and the
  290. * frame/field duration.
  291. */
  292. drm_dbg_vbl(dev, "crtc %u: Calculating number of vblanks."
  293. " diff_ns = %lld, framedur_ns = %d)\n",
  294. pipe, (long long)diff_ns, framedur_ns);
  295. diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
  296. if (diff == 0 && in_vblank_irq)
  297. drm_dbg_vbl(dev, "crtc %u: Redundant vblirq ignored\n",
  298. pipe);
  299. } else {
  300. /* some kind of default for drivers w/o accurate vbl timestamping */
  301. diff = in_vblank_irq ? 1 : 0;
  302. }
  303. /*
  304. * Within a drm_vblank_pre_modeset - drm_vblank_post_modeset
  305. * interval? If so then vblank irqs keep running and it will likely
  306. * happen that the hardware vblank counter is not trustworthy as it
  307. * might reset at some point in that interval and vblank timestamps
  308. * are not trustworthy either in that interval. Iow. this can result
  309. * in a bogus diff >> 1 which must be avoided as it would cause
  310. * random large forward jumps of the software vblank counter.
  311. */
  312. if (diff > 1 && (vblank->inmodeset & 0x2)) {
  313. drm_dbg_vbl(dev,
  314. "clamping vblank bump to 1 on crtc %u: diffr=%u"
  315. " due to pre-modeset.\n", pipe, diff);
  316. diff = 1;
  317. }
  318. drm_dbg_vbl(dev, "updating vblank count on crtc %u:"
  319. " current=%llu, diff=%u, hw=%u hw_last=%u\n",
  320. pipe, (unsigned long long)atomic64_read(&vblank->count),
  321. diff, cur_vblank, vblank->last);
  322. if (diff == 0) {
  323. drm_WARN_ON_ONCE(dev, cur_vblank != vblank->last);
  324. return;
  325. }
  326. /*
  327. * Only reinitialize corresponding vblank timestamp if high-precision query
  328. * available and didn't fail, or we were called from the vblank interrupt.
  329. * Otherwise reinitialize delayed at next vblank interrupt and assign 0
  330. * for now, to mark the vblanktimestamp as invalid.
  331. */
  332. if (!rc && !in_vblank_irq)
  333. t_vblank = 0;
  334. store_vblank(dev, pipe, diff, t_vblank, cur_vblank);
  335. }
  336. u64 drm_vblank_count(struct drm_device *dev, unsigned int pipe)
  337. {
  338. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  339. u64 count;
  340. if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
  341. return 0;
  342. count = atomic64_read(&vblank->count);
  343. /*
  344. * This read barrier corresponds to the implicit write barrier of the
  345. * write seqlock in store_vblank(). Note that this is the only place
  346. * where we need an explicit barrier, since all other access goes
  347. * through drm_vblank_count_and_time(), which already has the required
  348. * read barrier curtesy of the read seqlock.
  349. */
  350. smp_rmb();
  351. return count;
  352. }
  353. /**
  354. * drm_crtc_accurate_vblank_count - retrieve the master vblank counter
  355. * @crtc: which counter to retrieve
  356. *
  357. * This function is similar to drm_crtc_vblank_count() but this function
  358. * interpolates to handle a race with vblank interrupts using the high precision
  359. * timestamping support.
  360. *
  361. * This is mostly useful for hardware that can obtain the scanout position, but
  362. * doesn't have a hardware frame counter.
  363. */
  364. u64 drm_crtc_accurate_vblank_count(struct drm_crtc *crtc)
  365. {
  366. struct drm_device *dev = crtc->dev;
  367. unsigned int pipe = drm_crtc_index(crtc);
  368. u64 vblank;
  369. unsigned long flags;
  370. drm_WARN_ONCE(dev, drm_debug_enabled(DRM_UT_VBL) &&
  371. !crtc->funcs->get_vblank_timestamp,
  372. "This function requires support for accurate vblank timestamps.");
  373. spin_lock_irqsave(&dev->vblank_time_lock, flags);
  374. drm_update_vblank_count(dev, pipe, false);
  375. vblank = drm_vblank_count(dev, pipe);
  376. spin_unlock_irqrestore(&dev->vblank_time_lock, flags);
  377. return vblank;
  378. }
  379. EXPORT_SYMBOL(drm_crtc_accurate_vblank_count);
  380. static void __disable_vblank(struct drm_device *dev, unsigned int pipe)
  381. {
  382. if (drm_core_check_feature(dev, DRIVER_MODESET)) {
  383. struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
  384. if (drm_WARN_ON(dev, !crtc))
  385. return;
  386. if (crtc->funcs->disable_vblank)
  387. crtc->funcs->disable_vblank(crtc);
  388. }
  389. }
  390. /*
  391. * Disable vblank irq's on crtc, make sure that last vblank count
  392. * of hardware and corresponding consistent software vblank counter
  393. * are preserved, even if there are any spurious vblank irq's after
  394. * disable.
  395. */
  396. void drm_vblank_disable_and_save(struct drm_device *dev, unsigned int pipe)
  397. {
  398. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  399. unsigned long irqflags;
  400. assert_spin_locked(&dev->vbl_lock);
  401. /* Prevent vblank irq processing while disabling vblank irqs,
  402. * so no updates of timestamps or count can happen after we've
  403. * disabled. Needed to prevent races in case of delayed irq's.
  404. */
  405. spin_lock_irqsave(&dev->vblank_time_lock, irqflags);
  406. /*
  407. * Update vblank count and disable vblank interrupts only if the
  408. * interrupts were enabled. This avoids calling the ->disable_vblank()
  409. * operation in atomic context with the hardware potentially runtime
  410. * suspended.
  411. */
  412. if (!vblank->enabled)
  413. goto out;
  414. /*
  415. * Update the count and timestamp to maintain the
  416. * appearance that the counter has been ticking all along until
  417. * this time. This makes the count account for the entire time
  418. * between drm_crtc_vblank_on() and drm_crtc_vblank_off().
  419. */
  420. drm_update_vblank_count(dev, pipe, false);
  421. __disable_vblank(dev, pipe);
  422. vblank->enabled = false;
  423. out:
  424. spin_unlock_irqrestore(&dev->vblank_time_lock, irqflags);
  425. }
  426. static void vblank_disable_fn(struct timer_list *t)
  427. {
  428. struct drm_vblank_crtc *vblank = from_timer(vblank, t, disable_timer);
  429. struct drm_device *dev = vblank->dev;
  430. unsigned int pipe = vblank->pipe;
  431. unsigned long irqflags;
  432. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  433. if (atomic_read(&vblank->refcount) == 0 && vblank->enabled) {
  434. drm_dbg_core(dev, "disabling vblank on crtc %u\n", pipe);
  435. drm_vblank_disable_and_save(dev, pipe);
  436. }
  437. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  438. }
  439. static void drm_vblank_init_release(struct drm_device *dev, void *ptr)
  440. {
  441. struct drm_vblank_crtc *vblank = ptr;
  442. drm_WARN_ON(dev, READ_ONCE(vblank->enabled) &&
  443. drm_core_check_feature(dev, DRIVER_MODESET));
  444. drm_vblank_destroy_worker(vblank);
  445. del_timer_sync(&vblank->disable_timer);
  446. }
  447. /**
  448. * drm_vblank_init - initialize vblank support
  449. * @dev: DRM device
  450. * @num_crtcs: number of CRTCs supported by @dev
  451. *
  452. * This function initializes vblank support for @num_crtcs display pipelines.
  453. * Cleanup is handled automatically through a cleanup function added with
  454. * drmm_add_action_or_reset().
  455. *
  456. * Returns:
  457. * Zero on success or a negative error code on failure.
  458. */
  459. int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
  460. {
  461. int ret;
  462. unsigned int i;
  463. spin_lock_init(&dev->vbl_lock);
  464. spin_lock_init(&dev->vblank_time_lock);
  465. dev->vblank = drmm_kcalloc(dev, num_crtcs, sizeof(*dev->vblank), GFP_KERNEL);
  466. if (!dev->vblank)
  467. return -ENOMEM;
  468. dev->num_crtcs = num_crtcs;
  469. for (i = 0; i < num_crtcs; i++) {
  470. struct drm_vblank_crtc *vblank = &dev->vblank[i];
  471. vblank->dev = dev;
  472. vblank->pipe = i;
  473. init_waitqueue_head(&vblank->queue);
  474. timer_setup(&vblank->disable_timer, vblank_disable_fn, 0);
  475. seqlock_init(&vblank->seqlock);
  476. ret = drmm_add_action_or_reset(dev, drm_vblank_init_release,
  477. vblank);
  478. if (ret)
  479. return ret;
  480. ret = drm_vblank_worker_init(vblank);
  481. if (ret)
  482. return ret;
  483. }
  484. return 0;
  485. }
  486. EXPORT_SYMBOL(drm_vblank_init);
  487. /**
  488. * drm_dev_has_vblank - test if vblanking has been initialized for
  489. * a device
  490. * @dev: the device
  491. *
  492. * Drivers may call this function to test if vblank support is
  493. * initialized for a device. For most hardware this means that vblanking
  494. * can also be enabled.
  495. *
  496. * Atomic helpers use this function to initialize
  497. * &drm_crtc_state.no_vblank. See also drm_atomic_helper_check_modeset().
  498. *
  499. * Returns:
  500. * True if vblanking has been initialized for the given device, false
  501. * otherwise.
  502. */
  503. bool drm_dev_has_vblank(const struct drm_device *dev)
  504. {
  505. return dev->num_crtcs != 0;
  506. }
  507. EXPORT_SYMBOL(drm_dev_has_vblank);
  508. /**
  509. * drm_crtc_vblank_waitqueue - get vblank waitqueue for the CRTC
  510. * @crtc: which CRTC's vblank waitqueue to retrieve
  511. *
  512. * This function returns a pointer to the vblank waitqueue for the CRTC.
  513. * Drivers can use this to implement vblank waits using wait_event() and related
  514. * functions.
  515. */
  516. wait_queue_head_t *drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
  517. {
  518. return &crtc->dev->vblank[drm_crtc_index(crtc)].queue;
  519. }
  520. EXPORT_SYMBOL(drm_crtc_vblank_waitqueue);
  521. /**
  522. * drm_calc_timestamping_constants - calculate vblank timestamp constants
  523. * @crtc: drm_crtc whose timestamp constants should be updated.
  524. * @mode: display mode containing the scanout timings
  525. *
  526. * Calculate and store various constants which are later needed by vblank and
  527. * swap-completion timestamping, e.g, by
  528. * drm_crtc_vblank_helper_get_vblank_timestamp(). They are derived from
  529. * CRTC's true scanout timing, so they take things like panel scaling or
  530. * other adjustments into account.
  531. */
  532. void drm_calc_timestamping_constants(struct drm_crtc *crtc,
  533. const struct drm_display_mode *mode)
  534. {
  535. struct drm_device *dev = crtc->dev;
  536. unsigned int pipe = drm_crtc_index(crtc);
  537. struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc);
  538. int linedur_ns = 0, framedur_ns = 0;
  539. int dotclock = mode->crtc_clock;
  540. if (!drm_dev_has_vblank(dev))
  541. return;
  542. if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
  543. return;
  544. /* Valid dotclock? */
  545. if (dotclock > 0) {
  546. int frame_size = mode->crtc_htotal * mode->crtc_vtotal;
  547. /*
  548. * Convert scanline length in pixels and video
  549. * dot clock to line duration and frame duration
  550. * in nanoseconds:
  551. */
  552. linedur_ns = div_u64((u64) mode->crtc_htotal * 1000000, dotclock);
  553. framedur_ns = div_u64((u64) frame_size * 1000000, dotclock);
  554. /*
  555. * Fields of interlaced scanout modes are only half a frame duration.
  556. */
  557. if (mode->flags & DRM_MODE_FLAG_INTERLACE)
  558. framedur_ns /= 2;
  559. } else {
  560. drm_err(dev, "crtc %u: Can't calculate constants, dotclock = 0!\n",
  561. crtc->base.id);
  562. }
  563. vblank->linedur_ns = linedur_ns;
  564. vblank->framedur_ns = framedur_ns;
  565. drm_mode_copy(&vblank->hwmode, mode);
  566. drm_dbg_core(dev,
  567. "crtc %u: hwmode: htotal %d, vtotal %d, vdisplay %d\n",
  568. crtc->base.id, mode->crtc_htotal,
  569. mode->crtc_vtotal, mode->crtc_vdisplay);
  570. drm_dbg_core(dev, "crtc %u: clock %d kHz framedur %d linedur %d\n",
  571. crtc->base.id, dotclock, framedur_ns, linedur_ns);
  572. }
  573. EXPORT_SYMBOL(drm_calc_timestamping_constants);
  574. /**
  575. * drm_crtc_vblank_helper_get_vblank_timestamp_internal - precise vblank
  576. * timestamp helper
  577. * @crtc: CRTC whose vblank timestamp to retrieve
  578. * @max_error: Desired maximum allowable error in timestamps (nanosecs)
  579. * On return contains true maximum error of timestamp
  580. * @vblank_time: Pointer to time which should receive the timestamp
  581. * @in_vblank_irq:
  582. * True when called from drm_crtc_handle_vblank(). Some drivers
  583. * need to apply some workarounds for gpu-specific vblank irq quirks
  584. * if flag is set.
  585. * @get_scanout_position:
  586. * Callback function to retrieve the scanout position. See
  587. * @struct drm_crtc_helper_funcs.get_scanout_position.
  588. *
  589. * Implements calculation of exact vblank timestamps from given drm_display_mode
  590. * timings and current video scanout position of a CRTC.
  591. *
  592. * The current implementation only handles standard video modes. For double scan
  593. * and interlaced modes the driver is supposed to adjust the hardware mode
  594. * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
  595. * match the scanout position reported.
  596. *
  597. * Note that atomic drivers must call drm_calc_timestamping_constants() before
  598. * enabling a CRTC. The atomic helpers already take care of that in
  599. * drm_atomic_helper_calc_timestamping_constants().
  600. *
  601. * Returns:
  602. * Returns true on success, and false on failure, i.e. when no accurate
  603. * timestamp could be acquired.
  604. */
  605. bool
  606. drm_crtc_vblank_helper_get_vblank_timestamp_internal(
  607. struct drm_crtc *crtc, int *max_error, ktime_t *vblank_time,
  608. bool in_vblank_irq,
  609. drm_vblank_get_scanout_position_func get_scanout_position)
  610. {
  611. struct drm_device *dev = crtc->dev;
  612. unsigned int pipe = crtc->index;
  613. struct drm_vblank_crtc *vblank = &dev->vblank[pipe];
  614. struct timespec64 ts_etime, ts_vblank_time;
  615. ktime_t stime, etime;
  616. bool vbl_status;
  617. const struct drm_display_mode *mode;
  618. int vpos, hpos, i;
  619. int delta_ns, duration_ns;
  620. if (pipe >= dev->num_crtcs) {
  621. drm_err(dev, "Invalid crtc %u\n", pipe);
  622. return false;
  623. }
  624. /* Scanout position query not supported? Should not happen. */
  625. if (!get_scanout_position) {
  626. drm_err(dev, "Called from CRTC w/o get_scanout_position()!?\n");
  627. return false;
  628. }
  629. if (drm_drv_uses_atomic_modeset(dev))
  630. mode = &vblank->hwmode;
  631. else
  632. mode = &crtc->hwmode;
  633. /* If mode timing undefined, just return as no-op:
  634. * Happens during initial modesetting of a crtc.
  635. */
  636. if (mode->crtc_clock == 0) {
  637. drm_dbg_core(dev, "crtc %u: Noop due to uninitialized mode.\n",
  638. pipe);
  639. drm_WARN_ON_ONCE(dev, drm_drv_uses_atomic_modeset(dev));
  640. return false;
  641. }
  642. /* Get current scanout position with system timestamp.
  643. * Repeat query up to DRM_TIMESTAMP_MAXRETRIES times
  644. * if single query takes longer than max_error nanoseconds.
  645. *
  646. * This guarantees a tight bound on maximum error if
  647. * code gets preempted or delayed for some reason.
  648. */
  649. for (i = 0; i < DRM_TIMESTAMP_MAXRETRIES; i++) {
  650. /*
  651. * Get vertical and horizontal scanout position vpos, hpos,
  652. * and bounding timestamps stime, etime, pre/post query.
  653. */
  654. vbl_status = get_scanout_position(crtc, in_vblank_irq,
  655. &vpos, &hpos,
  656. &stime, &etime,
  657. mode);
  658. /* Return as no-op if scanout query unsupported or failed. */
  659. if (!vbl_status) {
  660. drm_dbg_core(dev,
  661. "crtc %u : scanoutpos query failed.\n",
  662. pipe);
  663. return false;
  664. }
  665. /* Compute uncertainty in timestamp of scanout position query. */
  666. duration_ns = ktime_to_ns(etime) - ktime_to_ns(stime);
  667. /* Accept result with < max_error nsecs timing uncertainty. */
  668. if (duration_ns <= *max_error)
  669. break;
  670. }
  671. /* Noisy system timing? */
  672. if (i == DRM_TIMESTAMP_MAXRETRIES) {
  673. drm_dbg_core(dev,
  674. "crtc %u: Noisy timestamp %d us > %d us [%d reps].\n",
  675. pipe, duration_ns / 1000, *max_error / 1000, i);
  676. }
  677. /* Return upper bound of timestamp precision error. */
  678. *max_error = duration_ns;
  679. /* Convert scanout position into elapsed time at raw_time query
  680. * since start of scanout at first display scanline. delta_ns
  681. * can be negative if start of scanout hasn't happened yet.
  682. */
  683. delta_ns = div_s64(1000000LL * (vpos * mode->crtc_htotal + hpos),
  684. mode->crtc_clock);
  685. /* Subtract time delta from raw timestamp to get final
  686. * vblank_time timestamp for end of vblank.
  687. */
  688. *vblank_time = ktime_sub_ns(etime, delta_ns);
  689. if (!drm_debug_enabled(DRM_UT_VBL))
  690. return true;
  691. ts_etime = ktime_to_timespec64(etime);
  692. ts_vblank_time = ktime_to_timespec64(*vblank_time);
  693. drm_dbg_vbl(dev,
  694. "crtc %u : v p(%d,%d)@ %lld.%06ld -> %lld.%06ld [e %d us, %d rep]\n",
  695. pipe, hpos, vpos,
  696. (u64)ts_etime.tv_sec, ts_etime.tv_nsec / 1000,
  697. (u64)ts_vblank_time.tv_sec, ts_vblank_time.tv_nsec / 1000,
  698. duration_ns / 1000, i);
  699. return true;
  700. }
  701. EXPORT_SYMBOL(drm_crtc_vblank_helper_get_vblank_timestamp_internal);
  702. /**
  703. * drm_crtc_vblank_helper_get_vblank_timestamp - precise vblank timestamp
  704. * helper
  705. * @crtc: CRTC whose vblank timestamp to retrieve
  706. * @max_error: Desired maximum allowable error in timestamps (nanosecs)
  707. * On return contains true maximum error of timestamp
  708. * @vblank_time: Pointer to time which should receive the timestamp
  709. * @in_vblank_irq:
  710. * True when called from drm_crtc_handle_vblank(). Some drivers
  711. * need to apply some workarounds for gpu-specific vblank irq quirks
  712. * if flag is set.
  713. *
  714. * Implements calculation of exact vblank timestamps from given drm_display_mode
  715. * timings and current video scanout position of a CRTC. This can be directly
  716. * used as the &drm_crtc_funcs.get_vblank_timestamp implementation of a kms
  717. * driver if &drm_crtc_helper_funcs.get_scanout_position is implemented.
  718. *
  719. * The current implementation only handles standard video modes. For double scan
  720. * and interlaced modes the driver is supposed to adjust the hardware mode
  721. * (taken from &drm_crtc_state.adjusted mode for atomic modeset drivers) to
  722. * match the scanout position reported.
  723. *
  724. * Note that atomic drivers must call drm_calc_timestamping_constants() before
  725. * enabling a CRTC. The atomic helpers already take care of that in
  726. * drm_atomic_helper_calc_timestamping_constants().
  727. *
  728. * Returns:
  729. * Returns true on success, and false on failure, i.e. when no accurate
  730. * timestamp could be acquired.
  731. */
  732. bool drm_crtc_vblank_helper_get_vblank_timestamp(struct drm_crtc *crtc,
  733. int *max_error,
  734. ktime_t *vblank_time,
  735. bool in_vblank_irq)
  736. {
  737. return drm_crtc_vblank_helper_get_vblank_timestamp_internal(
  738. crtc, max_error, vblank_time, in_vblank_irq,
  739. crtc->helper_private->get_scanout_position);
  740. }
  741. EXPORT_SYMBOL(drm_crtc_vblank_helper_get_vblank_timestamp);
  742. /**
  743. * drm_crtc_get_last_vbltimestamp - retrieve raw timestamp for the most
  744. * recent vblank interval
  745. * @crtc: CRTC whose vblank timestamp to retrieve
  746. * @tvblank: Pointer to target time which should receive the timestamp
  747. * @in_vblank_irq:
  748. * True when called from drm_crtc_handle_vblank(). Some drivers
  749. * need to apply some workarounds for gpu-specific vblank irq quirks
  750. * if flag is set.
  751. *
  752. * Fetches the system timestamp corresponding to the time of the most recent
  753. * vblank interval on specified CRTC. May call into kms-driver to
  754. * compute the timestamp with a high-precision GPU specific method.
  755. *
  756. * Returns zero if timestamp originates from uncorrected do_gettimeofday()
  757. * call, i.e., it isn't very precisely locked to the true vblank.
  758. *
  759. * Returns:
  760. * True if timestamp is considered to be very precise, false otherwise.
  761. */
  762. static bool
  763. drm_crtc_get_last_vbltimestamp(struct drm_crtc *crtc, ktime_t *tvblank,
  764. bool in_vblank_irq)
  765. {
  766. bool ret = false;
  767. /* Define requested maximum error on timestamps (nanoseconds). */
  768. int max_error = (int) drm_timestamp_precision * 1000;
  769. /* Query driver if possible and precision timestamping enabled. */
  770. if (crtc && crtc->funcs->get_vblank_timestamp && max_error > 0) {
  771. ret = crtc->funcs->get_vblank_timestamp(crtc, &max_error,
  772. tvblank, in_vblank_irq);
  773. }
  774. /* GPU high precision timestamp query unsupported or failed.
  775. * Return current monotonic/gettimeofday timestamp as best estimate.
  776. */
  777. if (!ret)
  778. *tvblank = ktime_get();
  779. return ret;
  780. }
  781. static bool
  782. drm_get_last_vbltimestamp(struct drm_device *dev, unsigned int pipe,
  783. ktime_t *tvblank, bool in_vblank_irq)
  784. {
  785. struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
  786. return drm_crtc_get_last_vbltimestamp(crtc, tvblank, in_vblank_irq);
  787. }
  788. /**
  789. * drm_crtc_vblank_count - retrieve "cooked" vblank counter value
  790. * @crtc: which counter to retrieve
  791. *
  792. * Fetches the "cooked" vblank count value that represents the number of
  793. * vblank events since the system was booted, including lost events due to
  794. * modesetting activity. Note that this timer isn't correct against a racing
  795. * vblank interrupt (since it only reports the software vblank counter), see
  796. * drm_crtc_accurate_vblank_count() for such use-cases.
  797. *
  798. * Note that for a given vblank counter value drm_crtc_handle_vblank()
  799. * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
  800. * provide a barrier: Any writes done before calling
  801. * drm_crtc_handle_vblank() will be visible to callers of the later
  802. * functions, if the vblank count is the same or a later one.
  803. *
  804. * See also &drm_vblank_crtc.count.
  805. *
  806. * Returns:
  807. * The software vblank counter.
  808. */
  809. u64 drm_crtc_vblank_count(struct drm_crtc *crtc)
  810. {
  811. return drm_vblank_count(crtc->dev, drm_crtc_index(crtc));
  812. }
  813. EXPORT_SYMBOL(drm_crtc_vblank_count);
  814. /**
  815. * drm_vblank_count_and_time - retrieve "cooked" vblank counter value and the
  816. * system timestamp corresponding to that vblank counter value.
  817. * @dev: DRM device
  818. * @pipe: index of CRTC whose counter to retrieve
  819. * @vblanktime: Pointer to ktime_t to receive the vblank timestamp.
  820. *
  821. * Fetches the "cooked" vblank count value that represents the number of
  822. * vblank events since the system was booted, including lost events due to
  823. * modesetting activity. Returns corresponding system timestamp of the time
  824. * of the vblank interval that corresponds to the current vblank counter value.
  825. *
  826. * This is the legacy version of drm_crtc_vblank_count_and_time().
  827. */
  828. static u64 drm_vblank_count_and_time(struct drm_device *dev, unsigned int pipe,
  829. ktime_t *vblanktime)
  830. {
  831. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  832. u64 vblank_count;
  833. unsigned int seq;
  834. if (drm_WARN_ON(dev, pipe >= dev->num_crtcs)) {
  835. *vblanktime = 0;
  836. return 0;
  837. }
  838. do {
  839. seq = read_seqbegin(&vblank->seqlock);
  840. vblank_count = atomic64_read(&vblank->count);
  841. *vblanktime = vblank->time;
  842. } while (read_seqretry(&vblank->seqlock, seq));
  843. return vblank_count;
  844. }
  845. /**
  846. * drm_crtc_vblank_count_and_time - retrieve "cooked" vblank counter value
  847. * and the system timestamp corresponding to that vblank counter value
  848. * @crtc: which counter to retrieve
  849. * @vblanktime: Pointer to time to receive the vblank timestamp.
  850. *
  851. * Fetches the "cooked" vblank count value that represents the number of
  852. * vblank events since the system was booted, including lost events due to
  853. * modesetting activity. Returns corresponding system timestamp of the time
  854. * of the vblank interval that corresponds to the current vblank counter value.
  855. *
  856. * Note that for a given vblank counter value drm_crtc_handle_vblank()
  857. * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
  858. * provide a barrier: Any writes done before calling
  859. * drm_crtc_handle_vblank() will be visible to callers of the later
  860. * functions, if the vblank count is the same or a later one.
  861. *
  862. * See also &drm_vblank_crtc.count.
  863. */
  864. u64 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc,
  865. ktime_t *vblanktime)
  866. {
  867. return drm_vblank_count_and_time(crtc->dev, drm_crtc_index(crtc),
  868. vblanktime);
  869. }
  870. EXPORT_SYMBOL(drm_crtc_vblank_count_and_time);
  871. /**
  872. * drm_crtc_next_vblank_start - calculate the time of the next vblank
  873. * @crtc: the crtc for which to calculate next vblank time
  874. * @vblanktime: pointer to time to receive the next vblank timestamp.
  875. *
  876. * Calculate the expected time of the start of the next vblank period,
  877. * based on time of previous vblank and frame duration
  878. */
  879. int drm_crtc_next_vblank_start(struct drm_crtc *crtc, ktime_t *vblanktime)
  880. {
  881. struct drm_vblank_crtc *vblank;
  882. struct drm_display_mode *mode;
  883. u64 vblank_start;
  884. if (!drm_dev_has_vblank(crtc->dev))
  885. return -EINVAL;
  886. vblank = drm_crtc_vblank_crtc(crtc);
  887. mode = &vblank->hwmode;
  888. if (!vblank->framedur_ns || !vblank->linedur_ns)
  889. return -EINVAL;
  890. if (!drm_crtc_get_last_vbltimestamp(crtc, vblanktime, false))
  891. return -EINVAL;
  892. vblank_start = DIV_ROUND_DOWN_ULL(
  893. (u64)vblank->framedur_ns * mode->crtc_vblank_start,
  894. mode->crtc_vtotal);
  895. *vblanktime = ktime_add(*vblanktime, ns_to_ktime(vblank_start));
  896. return 0;
  897. }
  898. EXPORT_SYMBOL(drm_crtc_next_vblank_start);
  899. static void send_vblank_event(struct drm_device *dev,
  900. struct drm_pending_vblank_event *e,
  901. u64 seq, ktime_t now)
  902. {
  903. struct timespec64 tv;
  904. switch (e->event.base.type) {
  905. case DRM_EVENT_VBLANK:
  906. case DRM_EVENT_FLIP_COMPLETE:
  907. tv = ktime_to_timespec64(now);
  908. e->event.vbl.sequence = seq;
  909. /*
  910. * e->event is a user space structure, with hardcoded unsigned
  911. * 32-bit seconds/microseconds. This is safe as we always use
  912. * monotonic timestamps since linux-4.15
  913. */
  914. e->event.vbl.tv_sec = tv.tv_sec;
  915. e->event.vbl.tv_usec = tv.tv_nsec / 1000;
  916. break;
  917. case DRM_EVENT_CRTC_SEQUENCE:
  918. if (seq)
  919. e->event.seq.sequence = seq;
  920. e->event.seq.time_ns = ktime_to_ns(now);
  921. break;
  922. }
  923. trace_drm_vblank_event_delivered(e->base.file_priv, e->pipe, seq);
  924. /*
  925. * Use the same timestamp for any associated fence signal to avoid
  926. * mismatch in timestamps for vsync & fence events triggered by the
  927. * same HW event. Frameworks like SurfaceFlinger in Android expects the
  928. * retire-fence timestamp to match exactly with HW vsync as it uses it
  929. * for its software vsync modeling.
  930. */
  931. drm_send_event_timestamp_locked(dev, &e->base, now);
  932. }
  933. /**
  934. * drm_crtc_arm_vblank_event - arm vblank event after pageflip
  935. * @crtc: the source CRTC of the vblank event
  936. * @e: the event to send
  937. *
  938. * A lot of drivers need to generate vblank events for the very next vblank
  939. * interrupt. For example when the page flip interrupt happens when the page
  940. * flip gets armed, but not when it actually executes within the next vblank
  941. * period. This helper function implements exactly the required vblank arming
  942. * behaviour.
  943. *
  944. * NOTE: Drivers using this to send out the &drm_crtc_state.event as part of an
  945. * atomic commit must ensure that the next vblank happens at exactly the same
  946. * time as the atomic commit is committed to the hardware. This function itself
  947. * does **not** protect against the next vblank interrupt racing with either this
  948. * function call or the atomic commit operation. A possible sequence could be:
  949. *
  950. * 1. Driver commits new hardware state into vblank-synchronized registers.
  951. * 2. A vblank happens, committing the hardware state. Also the corresponding
  952. * vblank interrupt is fired off and fully processed by the interrupt
  953. * handler.
  954. * 3. The atomic commit operation proceeds to call drm_crtc_arm_vblank_event().
  955. * 4. The event is only send out for the next vblank, which is wrong.
  956. *
  957. * An equivalent race can happen when the driver calls
  958. * drm_crtc_arm_vblank_event() before writing out the new hardware state.
  959. *
  960. * The only way to make this work safely is to prevent the vblank from firing
  961. * (and the hardware from committing anything else) until the entire atomic
  962. * commit sequence has run to completion. If the hardware does not have such a
  963. * feature (e.g. using a "go" bit), then it is unsafe to use this functions.
  964. * Instead drivers need to manually send out the event from their interrupt
  965. * handler by calling drm_crtc_send_vblank_event() and make sure that there's no
  966. * possible race with the hardware committing the atomic update.
  967. *
  968. * Caller must hold a vblank reference for the event @e acquired by a
  969. * drm_crtc_vblank_get(), which will be dropped when the next vblank arrives.
  970. */
  971. void drm_crtc_arm_vblank_event(struct drm_crtc *crtc,
  972. struct drm_pending_vblank_event *e)
  973. {
  974. struct drm_device *dev = crtc->dev;
  975. unsigned int pipe = drm_crtc_index(crtc);
  976. assert_spin_locked(&dev->event_lock);
  977. e->pipe = pipe;
  978. e->sequence = drm_crtc_accurate_vblank_count(crtc) + 1;
  979. list_add_tail(&e->base.link, &dev->vblank_event_list);
  980. }
  981. EXPORT_SYMBOL(drm_crtc_arm_vblank_event);
  982. /**
  983. * drm_crtc_send_vblank_event - helper to send vblank event after pageflip
  984. * @crtc: the source CRTC of the vblank event
  985. * @e: the event to send
  986. *
  987. * Updates sequence # and timestamp on event for the most recently processed
  988. * vblank, and sends it to userspace. Caller must hold event lock.
  989. *
  990. * See drm_crtc_arm_vblank_event() for a helper which can be used in certain
  991. * situation, especially to send out events for atomic commit operations.
  992. */
  993. void drm_crtc_send_vblank_event(struct drm_crtc *crtc,
  994. struct drm_pending_vblank_event *e)
  995. {
  996. struct drm_device *dev = crtc->dev;
  997. u64 seq;
  998. unsigned int pipe = drm_crtc_index(crtc);
  999. ktime_t now;
  1000. if (drm_dev_has_vblank(dev)) {
  1001. seq = drm_vblank_count_and_time(dev, pipe, &now);
  1002. } else {
  1003. seq = 0;
  1004. now = ktime_get();
  1005. }
  1006. e->pipe = pipe;
  1007. send_vblank_event(dev, e, seq, now);
  1008. }
  1009. EXPORT_SYMBOL(drm_crtc_send_vblank_event);
  1010. static int __enable_vblank(struct drm_device *dev, unsigned int pipe)
  1011. {
  1012. if (drm_core_check_feature(dev, DRIVER_MODESET)) {
  1013. struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
  1014. if (drm_WARN_ON(dev, !crtc))
  1015. return 0;
  1016. if (crtc->funcs->enable_vblank)
  1017. return crtc->funcs->enable_vblank(crtc);
  1018. }
  1019. return -EINVAL;
  1020. }
  1021. static int drm_vblank_enable(struct drm_device *dev, unsigned int pipe)
  1022. {
  1023. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  1024. int ret = 0;
  1025. assert_spin_locked(&dev->vbl_lock);
  1026. spin_lock(&dev->vblank_time_lock);
  1027. if (!vblank->enabled) {
  1028. /*
  1029. * Enable vblank irqs under vblank_time_lock protection.
  1030. * All vblank count & timestamp updates are held off
  1031. * until we are done reinitializing master counter and
  1032. * timestamps. Filtercode in drm_handle_vblank() will
  1033. * prevent double-accounting of same vblank interval.
  1034. */
  1035. ret = __enable_vblank(dev, pipe);
  1036. drm_dbg_core(dev, "enabling vblank on crtc %u, ret: %d\n",
  1037. pipe, ret);
  1038. if (ret) {
  1039. atomic_dec(&vblank->refcount);
  1040. } else {
  1041. drm_update_vblank_count(dev, pipe, 0);
  1042. /* drm_update_vblank_count() includes a wmb so we just
  1043. * need to ensure that the compiler emits the write
  1044. * to mark the vblank as enabled after the call
  1045. * to drm_update_vblank_count().
  1046. */
  1047. WRITE_ONCE(vblank->enabled, true);
  1048. }
  1049. }
  1050. spin_unlock(&dev->vblank_time_lock);
  1051. return ret;
  1052. }
  1053. int drm_vblank_get(struct drm_device *dev, unsigned int pipe)
  1054. {
  1055. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  1056. unsigned long irqflags;
  1057. int ret = 0;
  1058. if (!drm_dev_has_vblank(dev))
  1059. return -EINVAL;
  1060. if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
  1061. return -EINVAL;
  1062. spin_lock_irqsave(&dev->vbl_lock, irqflags);
  1063. /* Going from 0->1 means we have to enable interrupts again */
  1064. if (atomic_add_return(1, &vblank->refcount) == 1) {
  1065. ret = drm_vblank_enable(dev, pipe);
  1066. } else {
  1067. if (!vblank->enabled) {
  1068. atomic_dec(&vblank->refcount);
  1069. ret = -EINVAL;
  1070. }
  1071. }
  1072. spin_unlock_irqrestore(&dev->vbl_lock, irqflags);
  1073. return ret;
  1074. }
  1075. /**
  1076. * drm_crtc_vblank_get - get a reference count on vblank events
  1077. * @crtc: which CRTC to own
  1078. *
  1079. * Acquire a reference count on vblank events to avoid having them disabled
  1080. * while in use.
  1081. *
  1082. * Returns:
  1083. * Zero on success or a negative error code on failure.
  1084. */
  1085. int drm_crtc_vblank_get(struct drm_crtc *crtc)
  1086. {
  1087. return drm_vblank_get(crtc->dev, drm_crtc_index(crtc));
  1088. }
  1089. EXPORT_SYMBOL(drm_crtc_vblank_get);
  1090. void drm_vblank_put(struct drm_device *dev, unsigned int pipe)
  1091. {
  1092. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  1093. int vblank_offdelay = vblank->config.offdelay_ms;
  1094. if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
  1095. return;
  1096. if (drm_WARN_ON(dev, atomic_read(&vblank->refcount) == 0))
  1097. return;
  1098. /* Last user schedules interrupt disable */
  1099. if (atomic_dec_and_test(&vblank->refcount)) {
  1100. if (!vblank_offdelay)
  1101. return;
  1102. else if (vblank_offdelay < 0)
  1103. vblank_disable_fn(&vblank->disable_timer);
  1104. else if (!vblank->config.disable_immediate)
  1105. mod_timer(&vblank->disable_timer,
  1106. jiffies + ((vblank_offdelay * HZ) / 1000));
  1107. }
  1108. }
  1109. /**
  1110. * drm_crtc_vblank_put - give up ownership of vblank events
  1111. * @crtc: which counter to give up
  1112. *
  1113. * Release ownership of a given vblank counter, turning off interrupts
  1114. * if possible. Disable interrupts after &drm_vblank_crtc_config.offdelay_ms
  1115. * milliseconds.
  1116. */
  1117. void drm_crtc_vblank_put(struct drm_crtc *crtc)
  1118. {
  1119. drm_vblank_put(crtc->dev, drm_crtc_index(crtc));
  1120. }
  1121. EXPORT_SYMBOL(drm_crtc_vblank_put);
  1122. /**
  1123. * drm_wait_one_vblank - wait for one vblank
  1124. * @dev: DRM device
  1125. * @pipe: CRTC index
  1126. *
  1127. * This waits for one vblank to pass on @pipe, using the irq driver interfaces.
  1128. * It is a failure to call this when the vblank irq for @pipe is disabled, e.g.
  1129. * due to lack of driver support or because the crtc is off.
  1130. *
  1131. * This is the legacy version of drm_crtc_wait_one_vblank().
  1132. */
  1133. void drm_wait_one_vblank(struct drm_device *dev, unsigned int pipe)
  1134. {
  1135. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  1136. int ret;
  1137. u64 last;
  1138. if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
  1139. return;
  1140. ret = drm_vblank_get(dev, pipe);
  1141. if (drm_WARN(dev, ret, "vblank not available on crtc %i, ret=%i\n",
  1142. pipe, ret))
  1143. return;
  1144. last = drm_vblank_count(dev, pipe);
  1145. ret = wait_event_timeout(vblank->queue,
  1146. last != drm_vblank_count(dev, pipe),
  1147. msecs_to_jiffies(100));
  1148. drm_WARN(dev, ret == 0, "vblank wait timed out on crtc %i\n", pipe);
  1149. drm_vblank_put(dev, pipe);
  1150. }
  1151. EXPORT_SYMBOL(drm_wait_one_vblank);
  1152. /**
  1153. * drm_crtc_wait_one_vblank - wait for one vblank
  1154. * @crtc: DRM crtc
  1155. *
  1156. * This waits for one vblank to pass on @crtc, using the irq driver interfaces.
  1157. * It is a failure to call this when the vblank irq for @crtc is disabled, e.g.
  1158. * due to lack of driver support or because the crtc is off.
  1159. */
  1160. void drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
  1161. {
  1162. drm_wait_one_vblank(crtc->dev, drm_crtc_index(crtc));
  1163. }
  1164. EXPORT_SYMBOL(drm_crtc_wait_one_vblank);
  1165. /**
  1166. * drm_crtc_vblank_off - disable vblank events on a CRTC
  1167. * @crtc: CRTC in question
  1168. *
  1169. * Drivers can use this function to shut down the vblank interrupt handling when
  1170. * disabling a crtc. This function ensures that the latest vblank frame count is
  1171. * stored so that drm_vblank_on can restore it again.
  1172. *
  1173. * Drivers must use this function when the hardware vblank counter can get
  1174. * reset, e.g. when suspending or disabling the @crtc in general.
  1175. */
  1176. void drm_crtc_vblank_off(struct drm_crtc *crtc)
  1177. {
  1178. struct drm_device *dev = crtc->dev;
  1179. unsigned int pipe = drm_crtc_index(crtc);
  1180. struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc);
  1181. struct drm_pending_vblank_event *e, *t;
  1182. ktime_t now;
  1183. u64 seq;
  1184. if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
  1185. return;
  1186. /*
  1187. * Grab event_lock early to prevent vblank work from being scheduled
  1188. * while we're in the middle of shutting down vblank interrupts
  1189. */
  1190. spin_lock_irq(&dev->event_lock);
  1191. spin_lock(&dev->vbl_lock);
  1192. drm_dbg_vbl(dev, "crtc %d, vblank enabled %d, inmodeset %d\n",
  1193. pipe, vblank->enabled, vblank->inmodeset);
  1194. /* Avoid redundant vblank disables without previous
  1195. * drm_crtc_vblank_on(). */
  1196. if (drm_core_check_feature(dev, DRIVER_ATOMIC) || !vblank->inmodeset)
  1197. drm_vblank_disable_and_save(dev, pipe);
  1198. wake_up(&vblank->queue);
  1199. /*
  1200. * Prevent subsequent drm_vblank_get() from re-enabling
  1201. * the vblank interrupt by bumping the refcount.
  1202. */
  1203. if (!vblank->inmodeset) {
  1204. atomic_inc(&vblank->refcount);
  1205. vblank->inmodeset = 1;
  1206. }
  1207. spin_unlock(&dev->vbl_lock);
  1208. /* Send any queued vblank events, lest the natives grow disquiet */
  1209. seq = drm_vblank_count_and_time(dev, pipe, &now);
  1210. list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
  1211. if (e->pipe != pipe)
  1212. continue;
  1213. drm_dbg_core(dev, "Sending premature vblank event on disable: "
  1214. "wanted %llu, current %llu\n",
  1215. e->sequence, seq);
  1216. list_del(&e->base.link);
  1217. drm_vblank_put(dev, pipe);
  1218. send_vblank_event(dev, e, seq, now);
  1219. }
  1220. /* Cancel any leftover pending vblank work */
  1221. drm_vblank_cancel_pending_works(vblank);
  1222. spin_unlock_irq(&dev->event_lock);
  1223. /* Will be reset by the modeset helpers when re-enabling the crtc by
  1224. * calling drm_calc_timestamping_constants(). */
  1225. vblank->hwmode.crtc_clock = 0;
  1226. /* Wait for any vblank work that's still executing to finish */
  1227. drm_vblank_flush_worker(vblank);
  1228. }
  1229. EXPORT_SYMBOL(drm_crtc_vblank_off);
  1230. /**
  1231. * drm_crtc_vblank_reset - reset vblank state to off on a CRTC
  1232. * @crtc: CRTC in question
  1233. *
  1234. * Drivers can use this function to reset the vblank state to off at load time.
  1235. * Drivers should use this together with the drm_crtc_vblank_off() and
  1236. * drm_crtc_vblank_on() functions. The difference compared to
  1237. * drm_crtc_vblank_off() is that this function doesn't save the vblank counter
  1238. * and hence doesn't need to call any driver hooks.
  1239. *
  1240. * This is useful for recovering driver state e.g. on driver load, or on resume.
  1241. */
  1242. void drm_crtc_vblank_reset(struct drm_crtc *crtc)
  1243. {
  1244. struct drm_device *dev = crtc->dev;
  1245. struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc);
  1246. spin_lock_irq(&dev->vbl_lock);
  1247. /*
  1248. * Prevent subsequent drm_vblank_get() from enabling the vblank
  1249. * interrupt by bumping the refcount.
  1250. */
  1251. if (!vblank->inmodeset) {
  1252. atomic_inc(&vblank->refcount);
  1253. vblank->inmodeset = 1;
  1254. }
  1255. spin_unlock_irq(&dev->vbl_lock);
  1256. drm_WARN_ON(dev, !list_empty(&dev->vblank_event_list));
  1257. drm_WARN_ON(dev, !list_empty(&vblank->pending_work));
  1258. }
  1259. EXPORT_SYMBOL(drm_crtc_vblank_reset);
  1260. /**
  1261. * drm_crtc_set_max_vblank_count - configure the hw max vblank counter value
  1262. * @crtc: CRTC in question
  1263. * @max_vblank_count: max hardware vblank counter value
  1264. *
  1265. * Update the maximum hardware vblank counter value for @crtc
  1266. * at runtime. Useful for hardware where the operation of the
  1267. * hardware vblank counter depends on the currently active
  1268. * display configuration.
  1269. *
  1270. * For example, if the hardware vblank counter does not work
  1271. * when a specific connector is active the maximum can be set
  1272. * to zero. And when that specific connector isn't active the
  1273. * maximum can again be set to the appropriate non-zero value.
  1274. *
  1275. * If used, must be called before drm_vblank_on().
  1276. */
  1277. void drm_crtc_set_max_vblank_count(struct drm_crtc *crtc,
  1278. u32 max_vblank_count)
  1279. {
  1280. struct drm_device *dev = crtc->dev;
  1281. struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc);
  1282. drm_WARN_ON(dev, dev->max_vblank_count);
  1283. drm_WARN_ON(dev, !READ_ONCE(vblank->inmodeset));
  1284. vblank->max_vblank_count = max_vblank_count;
  1285. }
  1286. EXPORT_SYMBOL(drm_crtc_set_max_vblank_count);
  1287. /**
  1288. * drm_crtc_vblank_on_config - enable vblank events on a CRTC with custom
  1289. * configuration options
  1290. * @crtc: CRTC in question
  1291. * @config: Vblank configuration value
  1292. *
  1293. * See drm_crtc_vblank_on(). In addition, this function allows you to provide a
  1294. * custom vblank configuration for a given CRTC.
  1295. *
  1296. * Note that @config is copied, the pointer does not need to stay valid beyond
  1297. * this function call. For details of the parameters see
  1298. * struct drm_vblank_crtc_config.
  1299. */
  1300. void drm_crtc_vblank_on_config(struct drm_crtc *crtc,
  1301. const struct drm_vblank_crtc_config *config)
  1302. {
  1303. struct drm_device *dev = crtc->dev;
  1304. unsigned int pipe = drm_crtc_index(crtc);
  1305. struct drm_vblank_crtc *vblank = drm_crtc_vblank_crtc(crtc);
  1306. if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
  1307. return;
  1308. spin_lock_irq(&dev->vbl_lock);
  1309. drm_dbg_vbl(dev, "crtc %d, vblank enabled %d, inmodeset %d\n",
  1310. pipe, vblank->enabled, vblank->inmodeset);
  1311. vblank->config = *config;
  1312. /* Drop our private "prevent drm_vblank_get" refcount */
  1313. if (vblank->inmodeset) {
  1314. atomic_dec(&vblank->refcount);
  1315. vblank->inmodeset = 0;
  1316. }
  1317. drm_reset_vblank_timestamp(dev, pipe);
  1318. /*
  1319. * re-enable interrupts if there are users left, or the
  1320. * user wishes vblank interrupts to be enabled all the time.
  1321. */
  1322. if (atomic_read(&vblank->refcount) != 0 || !vblank->config.offdelay_ms)
  1323. drm_WARN_ON(dev, drm_vblank_enable(dev, pipe));
  1324. spin_unlock_irq(&dev->vbl_lock);
  1325. }
  1326. EXPORT_SYMBOL(drm_crtc_vblank_on_config);
  1327. /**
  1328. * drm_crtc_vblank_on - enable vblank events on a CRTC
  1329. * @crtc: CRTC in question
  1330. *
  1331. * This functions restores the vblank interrupt state captured with
  1332. * drm_crtc_vblank_off() again and is generally called when enabling @crtc. Note
  1333. * that calls to drm_crtc_vblank_on() and drm_crtc_vblank_off() can be
  1334. * unbalanced and so can also be unconditionally called in driver load code to
  1335. * reflect the current hardware state of the crtc.
  1336. *
  1337. * Note that unlike in drm_crtc_vblank_on_config(), default values are used.
  1338. */
  1339. void drm_crtc_vblank_on(struct drm_crtc *crtc)
  1340. {
  1341. const struct drm_vblank_crtc_config config = {
  1342. .offdelay_ms = drm_vblank_offdelay,
  1343. .disable_immediate = crtc->dev->vblank_disable_immediate
  1344. };
  1345. drm_crtc_vblank_on_config(crtc, &config);
  1346. }
  1347. EXPORT_SYMBOL(drm_crtc_vblank_on);
  1348. static void drm_vblank_restore(struct drm_device *dev, unsigned int pipe)
  1349. {
  1350. ktime_t t_vblank;
  1351. struct drm_vblank_crtc *vblank;
  1352. int framedur_ns;
  1353. u64 diff_ns;
  1354. u32 cur_vblank, diff = 1;
  1355. int count = DRM_TIMESTAMP_MAXRETRIES;
  1356. u32 max_vblank_count = drm_max_vblank_count(dev, pipe);
  1357. if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
  1358. return;
  1359. assert_spin_locked(&dev->vbl_lock);
  1360. assert_spin_locked(&dev->vblank_time_lock);
  1361. vblank = drm_vblank_crtc(dev, pipe);
  1362. drm_WARN_ONCE(dev,
  1363. drm_debug_enabled(DRM_UT_VBL) && !vblank->framedur_ns,
  1364. "Cannot compute missed vblanks without frame duration\n");
  1365. framedur_ns = vblank->framedur_ns;
  1366. do {
  1367. cur_vblank = __get_vblank_counter(dev, pipe);
  1368. drm_get_last_vbltimestamp(dev, pipe, &t_vblank, false);
  1369. } while (cur_vblank != __get_vblank_counter(dev, pipe) && --count > 0);
  1370. diff_ns = ktime_to_ns(ktime_sub(t_vblank, vblank->time));
  1371. if (framedur_ns)
  1372. diff = DIV_ROUND_CLOSEST_ULL(diff_ns, framedur_ns);
  1373. drm_dbg_vbl(dev,
  1374. "missed %d vblanks in %lld ns, frame duration=%d ns, hw_diff=%d\n",
  1375. diff, diff_ns, framedur_ns, cur_vblank - vblank->last);
  1376. vblank->last = (cur_vblank - diff) & max_vblank_count;
  1377. }
  1378. /**
  1379. * drm_crtc_vblank_restore - estimate missed vblanks and update vblank count.
  1380. * @crtc: CRTC in question
  1381. *
  1382. * Power manamement features can cause frame counter resets between vblank
  1383. * disable and enable. Drivers can use this function in their
  1384. * &drm_crtc_funcs.enable_vblank implementation to estimate missed vblanks since
  1385. * the last &drm_crtc_funcs.disable_vblank using timestamps and update the
  1386. * vblank counter.
  1387. *
  1388. * Note that drivers must have race-free high-precision timestamping support,
  1389. * i.e. &drm_crtc_funcs.get_vblank_timestamp must be hooked up and
  1390. * &drm_vblank_crtc_config.disable_immediate must be set to indicate the
  1391. * time-stamping functions are race-free against vblank hardware counter
  1392. * increments.
  1393. */
  1394. void drm_crtc_vblank_restore(struct drm_crtc *crtc)
  1395. {
  1396. struct drm_device *dev = crtc->dev;
  1397. unsigned int pipe = drm_crtc_index(crtc);
  1398. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  1399. drm_WARN_ON_ONCE(dev, !crtc->funcs->get_vblank_timestamp);
  1400. drm_WARN_ON_ONCE(dev, vblank->inmodeset);
  1401. drm_WARN_ON_ONCE(dev, !vblank->config.disable_immediate);
  1402. drm_vblank_restore(dev, pipe);
  1403. }
  1404. EXPORT_SYMBOL(drm_crtc_vblank_restore);
  1405. static int drm_queue_vblank_event(struct drm_device *dev, unsigned int pipe,
  1406. u64 req_seq,
  1407. union drm_wait_vblank *vblwait,
  1408. struct drm_file *file_priv)
  1409. {
  1410. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  1411. struct drm_pending_vblank_event *e;
  1412. ktime_t now;
  1413. u64 seq;
  1414. int ret;
  1415. e = kzalloc(sizeof(*e), GFP_KERNEL);
  1416. if (e == NULL) {
  1417. ret = -ENOMEM;
  1418. goto err_put;
  1419. }
  1420. e->pipe = pipe;
  1421. e->event.base.type = DRM_EVENT_VBLANK;
  1422. e->event.base.length = sizeof(e->event.vbl);
  1423. e->event.vbl.user_data = vblwait->request.signal;
  1424. e->event.vbl.crtc_id = 0;
  1425. if (drm_core_check_feature(dev, DRIVER_MODESET)) {
  1426. struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
  1427. if (crtc)
  1428. e->event.vbl.crtc_id = crtc->base.id;
  1429. }
  1430. spin_lock_irq(&dev->event_lock);
  1431. /*
  1432. * drm_crtc_vblank_off() might have been called after we called
  1433. * drm_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
  1434. * vblank disable, so no need for further locking. The reference from
  1435. * drm_vblank_get() protects against vblank disable from another source.
  1436. */
  1437. if (!READ_ONCE(vblank->enabled)) {
  1438. ret = -EINVAL;
  1439. goto err_unlock;
  1440. }
  1441. ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
  1442. &e->event.base);
  1443. if (ret)
  1444. goto err_unlock;
  1445. seq = drm_vblank_count_and_time(dev, pipe, &now);
  1446. drm_dbg_core(dev, "event on vblank count %llu, current %llu, crtc %u\n",
  1447. req_seq, seq, pipe);
  1448. trace_drm_vblank_event_queued(file_priv, pipe, req_seq);
  1449. e->sequence = req_seq;
  1450. if (drm_vblank_passed(seq, req_seq)) {
  1451. drm_vblank_put(dev, pipe);
  1452. send_vblank_event(dev, e, seq, now);
  1453. vblwait->reply.sequence = seq;
  1454. } else {
  1455. /* drm_handle_vblank_events will call drm_vblank_put */
  1456. list_add_tail(&e->base.link, &dev->vblank_event_list);
  1457. vblwait->reply.sequence = req_seq;
  1458. }
  1459. spin_unlock_irq(&dev->event_lock);
  1460. return 0;
  1461. err_unlock:
  1462. spin_unlock_irq(&dev->event_lock);
  1463. kfree(e);
  1464. err_put:
  1465. drm_vblank_put(dev, pipe);
  1466. return ret;
  1467. }
  1468. static bool drm_wait_vblank_is_query(union drm_wait_vblank *vblwait)
  1469. {
  1470. if (vblwait->request.sequence)
  1471. return false;
  1472. return _DRM_VBLANK_RELATIVE ==
  1473. (vblwait->request.type & (_DRM_VBLANK_TYPES_MASK |
  1474. _DRM_VBLANK_EVENT |
  1475. _DRM_VBLANK_NEXTONMISS));
  1476. }
  1477. /*
  1478. * Widen a 32-bit param to 64-bits.
  1479. *
  1480. * \param narrow 32-bit value (missing upper 32 bits)
  1481. * \param near 64-bit value that should be 'close' to near
  1482. *
  1483. * This function returns a 64-bit value using the lower 32-bits from
  1484. * 'narrow' and constructing the upper 32-bits so that the result is
  1485. * as close as possible to 'near'.
  1486. */
  1487. static u64 widen_32_to_64(u32 narrow, u64 near)
  1488. {
  1489. return near + (s32) (narrow - near);
  1490. }
  1491. static void drm_wait_vblank_reply(struct drm_device *dev, unsigned int pipe,
  1492. struct drm_wait_vblank_reply *reply)
  1493. {
  1494. ktime_t now;
  1495. struct timespec64 ts;
  1496. /*
  1497. * drm_wait_vblank_reply is a UAPI structure that uses 'long'
  1498. * to store the seconds. This is safe as we always use monotonic
  1499. * timestamps since linux-4.15.
  1500. */
  1501. reply->sequence = drm_vblank_count_and_time(dev, pipe, &now);
  1502. ts = ktime_to_timespec64(now);
  1503. reply->tval_sec = (u32)ts.tv_sec;
  1504. reply->tval_usec = ts.tv_nsec / 1000;
  1505. }
  1506. static bool drm_wait_vblank_supported(struct drm_device *dev)
  1507. {
  1508. return drm_dev_has_vblank(dev);
  1509. }
  1510. int drm_wait_vblank_ioctl(struct drm_device *dev, void *data,
  1511. struct drm_file *file_priv)
  1512. {
  1513. struct drm_crtc *crtc;
  1514. struct drm_vblank_crtc *vblank;
  1515. union drm_wait_vblank *vblwait = data;
  1516. int ret;
  1517. u64 req_seq, seq;
  1518. unsigned int pipe_index;
  1519. unsigned int flags, pipe, high_pipe;
  1520. if (!drm_wait_vblank_supported(dev))
  1521. return -EOPNOTSUPP;
  1522. if (vblwait->request.type & _DRM_VBLANK_SIGNAL)
  1523. return -EINVAL;
  1524. if (vblwait->request.type &
  1525. ~(_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
  1526. _DRM_VBLANK_HIGH_CRTC_MASK)) {
  1527. drm_dbg_core(dev,
  1528. "Unsupported type value 0x%x, supported mask 0x%x\n",
  1529. vblwait->request.type,
  1530. (_DRM_VBLANK_TYPES_MASK | _DRM_VBLANK_FLAGS_MASK |
  1531. _DRM_VBLANK_HIGH_CRTC_MASK));
  1532. return -EINVAL;
  1533. }
  1534. flags = vblwait->request.type & _DRM_VBLANK_FLAGS_MASK;
  1535. high_pipe = (vblwait->request.type & _DRM_VBLANK_HIGH_CRTC_MASK);
  1536. if (high_pipe)
  1537. pipe_index = high_pipe >> _DRM_VBLANK_HIGH_CRTC_SHIFT;
  1538. else
  1539. pipe_index = flags & _DRM_VBLANK_SECONDARY ? 1 : 0;
  1540. /* Convert lease-relative crtc index into global crtc index */
  1541. if (drm_core_check_feature(dev, DRIVER_MODESET)) {
  1542. pipe = 0;
  1543. drm_for_each_crtc(crtc, dev) {
  1544. if (drm_lease_held(file_priv, crtc->base.id)) {
  1545. if (pipe_index == 0)
  1546. break;
  1547. pipe_index--;
  1548. }
  1549. pipe++;
  1550. }
  1551. } else {
  1552. pipe = pipe_index;
  1553. }
  1554. if (pipe >= dev->num_crtcs)
  1555. return -EINVAL;
  1556. vblank = &dev->vblank[pipe];
  1557. /* If the counter is currently enabled and accurate, short-circuit
  1558. * queries to return the cached timestamp of the last vblank.
  1559. */
  1560. if (vblank->config.disable_immediate &&
  1561. drm_wait_vblank_is_query(vblwait) &&
  1562. READ_ONCE(vblank->enabled)) {
  1563. drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
  1564. return 0;
  1565. }
  1566. ret = drm_vblank_get(dev, pipe);
  1567. if (ret) {
  1568. drm_dbg_core(dev,
  1569. "crtc %d failed to acquire vblank counter, %d\n",
  1570. pipe, ret);
  1571. return ret;
  1572. }
  1573. seq = drm_vblank_count(dev, pipe);
  1574. switch (vblwait->request.type & _DRM_VBLANK_TYPES_MASK) {
  1575. case _DRM_VBLANK_RELATIVE:
  1576. req_seq = seq + vblwait->request.sequence;
  1577. vblwait->request.sequence = req_seq;
  1578. vblwait->request.type &= ~_DRM_VBLANK_RELATIVE;
  1579. break;
  1580. case _DRM_VBLANK_ABSOLUTE:
  1581. req_seq = widen_32_to_64(vblwait->request.sequence, seq);
  1582. break;
  1583. default:
  1584. ret = -EINVAL;
  1585. goto done;
  1586. }
  1587. if ((flags & _DRM_VBLANK_NEXTONMISS) &&
  1588. drm_vblank_passed(seq, req_seq)) {
  1589. req_seq = seq + 1;
  1590. vblwait->request.type &= ~_DRM_VBLANK_NEXTONMISS;
  1591. vblwait->request.sequence = req_seq;
  1592. }
  1593. if (flags & _DRM_VBLANK_EVENT) {
  1594. /* must hold on to the vblank ref until the event fires
  1595. * drm_vblank_put will be called asynchronously
  1596. */
  1597. return drm_queue_vblank_event(dev, pipe, req_seq, vblwait, file_priv);
  1598. }
  1599. if (req_seq != seq) {
  1600. int wait;
  1601. drm_dbg_core(dev, "waiting on vblank count %llu, crtc %u\n",
  1602. req_seq, pipe);
  1603. wait = wait_event_interruptible_timeout(vblank->queue,
  1604. drm_vblank_passed(drm_vblank_count(dev, pipe), req_seq) ||
  1605. !READ_ONCE(vblank->enabled),
  1606. msecs_to_jiffies(3000));
  1607. switch (wait) {
  1608. case 0:
  1609. /* timeout */
  1610. ret = -EBUSY;
  1611. break;
  1612. case -ERESTARTSYS:
  1613. /* interrupted by signal */
  1614. ret = -EINTR;
  1615. break;
  1616. default:
  1617. ret = 0;
  1618. break;
  1619. }
  1620. }
  1621. if (ret != -EINTR) {
  1622. drm_wait_vblank_reply(dev, pipe, &vblwait->reply);
  1623. drm_dbg_core(dev, "crtc %d returning %u to client\n",
  1624. pipe, vblwait->reply.sequence);
  1625. } else {
  1626. drm_dbg_core(dev, "crtc %d vblank wait interrupted by signal\n",
  1627. pipe);
  1628. }
  1629. done:
  1630. drm_vblank_put(dev, pipe);
  1631. return ret;
  1632. }
  1633. static void drm_handle_vblank_events(struct drm_device *dev, unsigned int pipe)
  1634. {
  1635. struct drm_crtc *crtc = drm_crtc_from_index(dev, pipe);
  1636. bool high_prec = false;
  1637. struct drm_pending_vblank_event *e, *t;
  1638. ktime_t now;
  1639. u64 seq;
  1640. assert_spin_locked(&dev->event_lock);
  1641. seq = drm_vblank_count_and_time(dev, pipe, &now);
  1642. list_for_each_entry_safe(e, t, &dev->vblank_event_list, base.link) {
  1643. if (e->pipe != pipe)
  1644. continue;
  1645. if (!drm_vblank_passed(seq, e->sequence))
  1646. continue;
  1647. drm_dbg_core(dev, "vblank event on %llu, current %llu\n",
  1648. e->sequence, seq);
  1649. list_del(&e->base.link);
  1650. drm_vblank_put(dev, pipe);
  1651. send_vblank_event(dev, e, seq, now);
  1652. }
  1653. if (crtc && crtc->funcs->get_vblank_timestamp)
  1654. high_prec = true;
  1655. trace_drm_vblank_event(pipe, seq, now, high_prec);
  1656. }
  1657. /**
  1658. * drm_handle_vblank - handle a vblank event
  1659. * @dev: DRM device
  1660. * @pipe: index of CRTC where this event occurred
  1661. *
  1662. * Drivers should call this routine in their vblank interrupt handlers to
  1663. * update the vblank counter and send any signals that may be pending.
  1664. *
  1665. * This is the legacy version of drm_crtc_handle_vblank().
  1666. */
  1667. bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
  1668. {
  1669. struct drm_vblank_crtc *vblank = drm_vblank_crtc(dev, pipe);
  1670. unsigned long irqflags;
  1671. bool disable_irq;
  1672. if (drm_WARN_ON_ONCE(dev, !drm_dev_has_vblank(dev)))
  1673. return false;
  1674. if (drm_WARN_ON(dev, pipe >= dev->num_crtcs))
  1675. return false;
  1676. spin_lock_irqsave(&dev->event_lock, irqflags);
  1677. /* Need timestamp lock to prevent concurrent execution with
  1678. * vblank enable/disable, as this would cause inconsistent
  1679. * or corrupted timestamps and vblank counts.
  1680. */
  1681. spin_lock(&dev->vblank_time_lock);
  1682. /* Vblank irq handling disabled. Nothing to do. */
  1683. if (!vblank->enabled) {
  1684. spin_unlock(&dev->vblank_time_lock);
  1685. spin_unlock_irqrestore(&dev->event_lock, irqflags);
  1686. return false;
  1687. }
  1688. drm_update_vblank_count(dev, pipe, true);
  1689. spin_unlock(&dev->vblank_time_lock);
  1690. wake_up(&vblank->queue);
  1691. /* With instant-off, we defer disabling the interrupt until after
  1692. * we finish processing the following vblank after all events have
  1693. * been signaled. The disable has to be last (after
  1694. * drm_handle_vblank_events) so that the timestamp is always accurate.
  1695. */
  1696. disable_irq = (vblank->config.disable_immediate &&
  1697. vblank->config.offdelay_ms > 0 &&
  1698. !atomic_read(&vblank->refcount));
  1699. drm_handle_vblank_events(dev, pipe);
  1700. drm_handle_vblank_works(vblank);
  1701. spin_unlock_irqrestore(&dev->event_lock, irqflags);
  1702. if (disable_irq)
  1703. vblank_disable_fn(&vblank->disable_timer);
  1704. return true;
  1705. }
  1706. EXPORT_SYMBOL(drm_handle_vblank);
  1707. /**
  1708. * drm_crtc_handle_vblank - handle a vblank event
  1709. * @crtc: where this event occurred
  1710. *
  1711. * Drivers should call this routine in their vblank interrupt handlers to
  1712. * update the vblank counter and send any signals that may be pending.
  1713. *
  1714. * This is the native KMS version of drm_handle_vblank().
  1715. *
  1716. * Note that for a given vblank counter value drm_crtc_handle_vblank()
  1717. * and drm_crtc_vblank_count() or drm_crtc_vblank_count_and_time()
  1718. * provide a barrier: Any writes done before calling
  1719. * drm_crtc_handle_vblank() will be visible to callers of the later
  1720. * functions, if the vblank count is the same or a later one.
  1721. *
  1722. * See also &drm_vblank_crtc.count.
  1723. *
  1724. * Returns:
  1725. * True if the event was successfully handled, false on failure.
  1726. */
  1727. bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
  1728. {
  1729. return drm_handle_vblank(crtc->dev, drm_crtc_index(crtc));
  1730. }
  1731. EXPORT_SYMBOL(drm_crtc_handle_vblank);
  1732. /*
  1733. * Get crtc VBLANK count.
  1734. *
  1735. * \param dev DRM device
  1736. * \param data user argument, pointing to a drm_crtc_get_sequence structure.
  1737. * \param file_priv drm file private for the user's open file descriptor
  1738. */
  1739. int drm_crtc_get_sequence_ioctl(struct drm_device *dev, void *data,
  1740. struct drm_file *file_priv)
  1741. {
  1742. struct drm_crtc *crtc;
  1743. struct drm_vblank_crtc *vblank;
  1744. int pipe;
  1745. struct drm_crtc_get_sequence *get_seq = data;
  1746. ktime_t now;
  1747. bool vblank_enabled;
  1748. int ret;
  1749. if (!drm_core_check_feature(dev, DRIVER_MODESET))
  1750. return -EOPNOTSUPP;
  1751. if (!drm_dev_has_vblank(dev))
  1752. return -EOPNOTSUPP;
  1753. crtc = drm_crtc_find(dev, file_priv, get_seq->crtc_id);
  1754. if (!crtc)
  1755. return -ENOENT;
  1756. pipe = drm_crtc_index(crtc);
  1757. vblank = drm_crtc_vblank_crtc(crtc);
  1758. vblank_enabled = READ_ONCE(vblank->config.disable_immediate) &&
  1759. READ_ONCE(vblank->enabled);
  1760. if (!vblank_enabled) {
  1761. ret = drm_crtc_vblank_get(crtc);
  1762. if (ret) {
  1763. drm_dbg_core(dev,
  1764. "crtc %d failed to acquire vblank counter, %d\n",
  1765. pipe, ret);
  1766. return ret;
  1767. }
  1768. }
  1769. drm_modeset_lock(&crtc->mutex, NULL);
  1770. if (crtc->state)
  1771. get_seq->active = crtc->state->enable;
  1772. else
  1773. get_seq->active = crtc->enabled;
  1774. drm_modeset_unlock(&crtc->mutex);
  1775. get_seq->sequence = drm_vblank_count_and_time(dev, pipe, &now);
  1776. get_seq->sequence_ns = ktime_to_ns(now);
  1777. if (!vblank_enabled)
  1778. drm_crtc_vblank_put(crtc);
  1779. return 0;
  1780. }
  1781. /*
  1782. * Queue a event for VBLANK sequence
  1783. *
  1784. * \param dev DRM device
  1785. * \param data user argument, pointing to a drm_crtc_queue_sequence structure.
  1786. * \param file_priv drm file private for the user's open file descriptor
  1787. */
  1788. int drm_crtc_queue_sequence_ioctl(struct drm_device *dev, void *data,
  1789. struct drm_file *file_priv)
  1790. {
  1791. struct drm_crtc *crtc;
  1792. struct drm_vblank_crtc *vblank;
  1793. int pipe;
  1794. struct drm_crtc_queue_sequence *queue_seq = data;
  1795. ktime_t now;
  1796. struct drm_pending_vblank_event *e;
  1797. u32 flags;
  1798. u64 seq;
  1799. u64 req_seq;
  1800. int ret;
  1801. if (!drm_core_check_feature(dev, DRIVER_MODESET))
  1802. return -EOPNOTSUPP;
  1803. if (!drm_dev_has_vblank(dev))
  1804. return -EOPNOTSUPP;
  1805. crtc = drm_crtc_find(dev, file_priv, queue_seq->crtc_id);
  1806. if (!crtc)
  1807. return -ENOENT;
  1808. flags = queue_seq->flags;
  1809. /* Check valid flag bits */
  1810. if (flags & ~(DRM_CRTC_SEQUENCE_RELATIVE|
  1811. DRM_CRTC_SEQUENCE_NEXT_ON_MISS))
  1812. return -EINVAL;
  1813. pipe = drm_crtc_index(crtc);
  1814. vblank = drm_crtc_vblank_crtc(crtc);
  1815. e = kzalloc(sizeof(*e), GFP_KERNEL);
  1816. if (e == NULL)
  1817. return -ENOMEM;
  1818. ret = drm_crtc_vblank_get(crtc);
  1819. if (ret) {
  1820. drm_dbg_core(dev,
  1821. "crtc %d failed to acquire vblank counter, %d\n",
  1822. pipe, ret);
  1823. goto err_free;
  1824. }
  1825. seq = drm_vblank_count_and_time(dev, pipe, &now);
  1826. req_seq = queue_seq->sequence;
  1827. if (flags & DRM_CRTC_SEQUENCE_RELATIVE)
  1828. req_seq += seq;
  1829. if ((flags & DRM_CRTC_SEQUENCE_NEXT_ON_MISS) && drm_vblank_passed(seq, req_seq))
  1830. req_seq = seq + 1;
  1831. e->pipe = pipe;
  1832. e->event.base.type = DRM_EVENT_CRTC_SEQUENCE;
  1833. e->event.base.length = sizeof(e->event.seq);
  1834. e->event.seq.user_data = queue_seq->user_data;
  1835. spin_lock_irq(&dev->event_lock);
  1836. /*
  1837. * drm_crtc_vblank_off() might have been called after we called
  1838. * drm_crtc_vblank_get(). drm_crtc_vblank_off() holds event_lock around the
  1839. * vblank disable, so no need for further locking. The reference from
  1840. * drm_crtc_vblank_get() protects against vblank disable from another source.
  1841. */
  1842. if (!READ_ONCE(vblank->enabled)) {
  1843. ret = -EINVAL;
  1844. goto err_unlock;
  1845. }
  1846. ret = drm_event_reserve_init_locked(dev, file_priv, &e->base,
  1847. &e->event.base);
  1848. if (ret)
  1849. goto err_unlock;
  1850. e->sequence = req_seq;
  1851. if (drm_vblank_passed(seq, req_seq)) {
  1852. drm_crtc_vblank_put(crtc);
  1853. send_vblank_event(dev, e, seq, now);
  1854. queue_seq->sequence = seq;
  1855. } else {
  1856. /* drm_handle_vblank_events will call drm_vblank_put */
  1857. list_add_tail(&e->base.link, &dev->vblank_event_list);
  1858. queue_seq->sequence = req_seq;
  1859. }
  1860. spin_unlock_irq(&dev->event_lock);
  1861. return 0;
  1862. err_unlock:
  1863. spin_unlock_irq(&dev->event_lock);
  1864. drm_crtc_vblank_put(crtc);
  1865. err_free:
  1866. kfree(e);
  1867. return ret;
  1868. }