• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2013 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Brad Volkin <bradley.d.volkin@intel.com>
25  *
26  */
27 
28 #include "i915_drv.h"
29 
30 /**
31  * DOC: batch buffer command parser
32  *
33  * Motivation:
34  * Certain OpenGL features (e.g. transform feedback, performance monitoring)
35  * require userspace code to submit batches containing commands such as
36  * MI_LOAD_REGISTER_IMM to access various registers. Unfortunately, some
37  * generations of the hardware will noop these commands in "unsecure" batches
38  * (which includes all userspace batches submitted via i915) even though the
39  * commands may be safe and represent the intended programming model of the
40  * device.
41  *
42  * The software command parser is similar in operation to the command parsing
43  * done in hardware for unsecure batches. However, the software parser allows
44  * some operations that would be noop'd by hardware, if the parser determines
45  * the operation is safe, and submits the batch as "secure" to prevent hardware
46  * parsing.
47  *
48  * Threats:
49  * At a high level, the hardware (and software) checks attempt to prevent
50  * granting userspace undue privileges. There are three categories of privilege.
51  *
52  * First, commands which are explicitly defined as privileged or which should
53  * only be used by the kernel driver. The parser rejects such commands
54  *
55  * Second, commands which access registers. To support correct/enhanced
56  * userspace functionality, particularly certain OpenGL extensions, the parser
57  * provides a whitelist of registers which userspace may safely access
58  *
59  * Third, commands which access privileged memory (i.e. GGTT, HWS page, etc).
60  * The parser always rejects such commands.
61  *
62  * The majority of the problematic commands fall in the MI_* range, with only a
63  * few specific commands on each ring (e.g. PIPE_CONTROL and MI_FLUSH_DW).
64  *
65  * Implementation:
66  * Each ring maintains tables of commands and registers which the parser uses in
67  * scanning batch buffers submitted to that ring.
68  *
69  * Since the set of commands that the parser must check for is significantly
70  * smaller than the number of commands supported, the parser tables contain only
71  * those commands required by the parser. This generally works because command
72  * opcode ranges have standard command length encodings. So for commands that
73  * the parser does not need to check, it can easily skip them. This is
74  * implemented via a per-ring length decoding vfunc.
75  *
76  * Unfortunately, there are a number of commands that do not follow the standard
77  * length encoding for their opcode range, primarily amongst the MI_* commands.
78  * To handle this, the parser provides a way to define explicit "skip" entries
79  * in the per-ring command tables.
80  *
81  * Other command table entries map fairly directly to high level categories
82  * mentioned above: rejected, register whitelist. The parser implements a number
83  * of checks, including the privileged memory checks, via a general bitmasking
84  * mechanism.
85  */
86 
87 #define STD_MI_OPCODE_MASK  0xFF800000
88 #define STD_3D_OPCODE_MASK  0xFFFF0000
89 #define STD_2D_OPCODE_MASK  0xFFC00000
90 #define STD_MFX_OPCODE_MASK 0xFFFF0000
91 
92 #define CMD(op, opm, f, lm, fl, ...)				\
93 	{							\
94 		.flags = (fl) | ((f) ? CMD_DESC_FIXED : 0),	\
95 		.cmd = { (op) & (opm), (opm) },			\
96 		.length = { (lm) },				\
97 		__VA_ARGS__					\
98 	}
99 
100 /* Convenience macros to compress the tables */
101 #define SMI STD_MI_OPCODE_MASK
102 #define S3D STD_3D_OPCODE_MASK
103 #define S2D STD_2D_OPCODE_MASK
104 #define SMFX STD_MFX_OPCODE_MASK
105 #define F true
106 #define S CMD_DESC_SKIP
107 #define R CMD_DESC_REJECT
108 #define W CMD_DESC_REGISTER
109 #define B CMD_DESC_BITMASK
110 
111 /*            Command                          Mask   Fixed Len   Action
112 	      ---------------------------------------------------------- */
113 static const struct drm_i915_cmd_descriptor gen7_common_cmds[] = {
114 	CMD(  MI_NOOP,                          SMI,    F,  1,      S  ),
115 	CMD(  MI_USER_INTERRUPT,                SMI,    F,  1,      R  ),
116 	CMD(  MI_WAIT_FOR_EVENT,                SMI,    F,  1,      R  ),
117 	CMD(  MI_ARB_CHECK,                     SMI,    F,  1,      S  ),
118 	CMD(  MI_REPORT_HEAD,                   SMI,    F,  1,      S  ),
119 	CMD(  MI_SUSPEND_FLUSH,                 SMI,    F,  1,      S  ),
120 	CMD(  MI_SEMAPHORE_MBOX,                SMI,   !F,  0xFF,   R  ),
121 	CMD(  MI_STORE_DWORD_INDEX,             SMI,   !F,  0xFF,   R  ),
122 	CMD(  MI_LOAD_REGISTER_IMM(1),          SMI,   !F,  0xFF,   W,
123 	      .reg = { .offset = 1, .mask = 0x007FFFFC, .step = 2 }    ),
124 	CMD(  MI_STORE_REGISTER_MEM,            SMI,    F,  3,     W | B,
125 	      .reg = { .offset = 1, .mask = 0x007FFFFC },
126 	      .bits = {{
127 			.offset = 0,
128 			.mask = MI_GLOBAL_GTT,
129 			.expected = 0,
130 	      }},						       ),
131 	CMD(  MI_LOAD_REGISTER_MEM,             SMI,    F,  3,     W | B,
132 	      .reg = { .offset = 1, .mask = 0x007FFFFC },
133 	      .bits = {{
134 			.offset = 0,
135 			.mask = MI_GLOBAL_GTT,
136 			.expected = 0,
137 	      }},						       ),
138 	/*
139 	 * MI_BATCH_BUFFER_START requires some special handling. It's not
140 	 * really a 'skip' action but it doesn't seem like it's worth adding
141 	 * a new action. See i915_parse_cmds().
142 	 */
143 	CMD(  MI_BATCH_BUFFER_START,            SMI,   !F,  0xFF,   S  ),
144 };
145 
146 static const struct drm_i915_cmd_descriptor gen7_render_cmds[] = {
147 	CMD(  MI_FLUSH,                         SMI,    F,  1,      S  ),
148 	CMD(  MI_ARB_ON_OFF,                    SMI,    F,  1,      R  ),
149 	CMD(  MI_PREDICATE,                     SMI,    F,  1,      S  ),
150 	CMD(  MI_TOPOLOGY_FILTER,               SMI,    F,  1,      S  ),
151 	CMD(  MI_SET_APPID,                     SMI,    F,  1,      S  ),
152 	CMD(  MI_DISPLAY_FLIP,                  SMI,   !F,  0xFF,   R  ),
153 	CMD(  MI_SET_CONTEXT,                   SMI,   !F,  0xFF,   R  ),
154 	CMD(  MI_URB_CLEAR,                     SMI,   !F,  0xFF,   S  ),
155 	CMD(  MI_STORE_DWORD_IMM,               SMI,   !F,  0x3F,   B,
156 	      .bits = {{
157 			.offset = 0,
158 			.mask = MI_GLOBAL_GTT,
159 			.expected = 0,
160 	      }},						       ),
161 	CMD(  MI_UPDATE_GTT,                    SMI,   !F,  0xFF,   R  ),
162 	CMD(  MI_CLFLUSH,                       SMI,   !F,  0x3FF,  B,
163 	      .bits = {{
164 			.offset = 0,
165 			.mask = MI_GLOBAL_GTT,
166 			.expected = 0,
167 	      }},						       ),
168 	CMD(  MI_REPORT_PERF_COUNT,             SMI,   !F,  0x3F,   B,
169 	      .bits = {{
170 			.offset = 1,
171 			.mask = MI_REPORT_PERF_COUNT_GGTT,
172 			.expected = 0,
173 	      }},						       ),
174 	CMD(  MI_CONDITIONAL_BATCH_BUFFER_END,  SMI,   !F,  0xFF,   B,
175 	      .bits = {{
176 			.offset = 0,
177 			.mask = MI_GLOBAL_GTT,
178 			.expected = 0,
179 	      }},						       ),
180 	CMD(  GFX_OP_3DSTATE_VF_STATISTICS,     S3D,    F,  1,      S  ),
181 	CMD(  PIPELINE_SELECT,                  S3D,    F,  1,      S  ),
182 	CMD(  MEDIA_VFE_STATE,			S3D,   !F,  0xFFFF, B,
183 	      .bits = {{
184 			.offset = 2,
185 			.mask = MEDIA_VFE_STATE_MMIO_ACCESS_MASK,
186 			.expected = 0,
187 	      }},						       ),
188 	CMD(  GPGPU_OBJECT,                     S3D,   !F,  0xFF,   S  ),
189 	CMD(  GPGPU_WALKER,                     S3D,   !F,  0xFF,   S  ),
190 	CMD(  GFX_OP_3DSTATE_SO_DECL_LIST,      S3D,   !F,  0x1FF,  S  ),
191 	CMD(  GFX_OP_PIPE_CONTROL(5),           S3D,   !F,  0xFF,   B,
192 	      .bits = {{
193 			.offset = 1,
194 			.mask = (PIPE_CONTROL_MMIO_WRITE | PIPE_CONTROL_NOTIFY),
195 			.expected = 0,
196 	      },
197 	      {
198 			.offset = 1,
199 		        .mask = (PIPE_CONTROL_GLOBAL_GTT_IVB |
200 				 PIPE_CONTROL_STORE_DATA_INDEX),
201 			.expected = 0,
202 			.condition_offset = 1,
203 			.condition_mask = PIPE_CONTROL_POST_SYNC_OP_MASK,
204 	      }},						       ),
205 };
206 
207 static const struct drm_i915_cmd_descriptor hsw_render_cmds[] = {
208 	CMD(  MI_SET_PREDICATE,                 SMI,    F,  1,      S  ),
209 	CMD(  MI_RS_CONTROL,                    SMI,    F,  1,      S  ),
210 	CMD(  MI_URB_ATOMIC_ALLOC,              SMI,    F,  1,      S  ),
211 	CMD(  MI_SET_APPID,                     SMI,    F,  1,      S  ),
212 	CMD(  MI_RS_CONTEXT,                    SMI,    F,  1,      S  ),
213 	CMD(  MI_LOAD_SCAN_LINES_INCL,          SMI,   !F,  0x3F,   R  ),
214 	CMD(  MI_LOAD_SCAN_LINES_EXCL,          SMI,   !F,  0x3F,   R  ),
215 	CMD(  MI_LOAD_REGISTER_REG,             SMI,   !F,  0xFF,   R  ),
216 	CMD(  MI_RS_STORE_DATA_IMM,             SMI,   !F,  0xFF,   S  ),
217 	CMD(  MI_LOAD_URB_MEM,                  SMI,   !F,  0xFF,   S  ),
218 	CMD(  MI_STORE_URB_MEM,                 SMI,   !F,  0xFF,   S  ),
219 	CMD(  GFX_OP_3DSTATE_DX9_CONSTANTF_VS,  S3D,   !F,  0x7FF,  S  ),
220 	CMD(  GFX_OP_3DSTATE_DX9_CONSTANTF_PS,  S3D,   !F,  0x7FF,  S  ),
221 
222 	CMD(  GFX_OP_3DSTATE_BINDING_TABLE_EDIT_VS,  S3D,   !F,  0x1FF,  S  ),
223 	CMD(  GFX_OP_3DSTATE_BINDING_TABLE_EDIT_GS,  S3D,   !F,  0x1FF,  S  ),
224 	CMD(  GFX_OP_3DSTATE_BINDING_TABLE_EDIT_HS,  S3D,   !F,  0x1FF,  S  ),
225 	CMD(  GFX_OP_3DSTATE_BINDING_TABLE_EDIT_DS,  S3D,   !F,  0x1FF,  S  ),
226 	CMD(  GFX_OP_3DSTATE_BINDING_TABLE_EDIT_PS,  S3D,   !F,  0x1FF,  S  ),
227 };
228 
229 static const struct drm_i915_cmd_descriptor gen7_video_cmds[] = {
230 	CMD(  MI_ARB_ON_OFF,                    SMI,    F,  1,      R  ),
231 	CMD(  MI_SET_APPID,                     SMI,    F,  1,      S  ),
232 	CMD(  MI_STORE_DWORD_IMM,               SMI,   !F,  0xFF,   B,
233 	      .bits = {{
234 			.offset = 0,
235 			.mask = MI_GLOBAL_GTT,
236 			.expected = 0,
237 	      }},						       ),
238 	CMD(  MI_UPDATE_GTT,                    SMI,   !F,  0x3F,   R  ),
239 	CMD(  MI_FLUSH_DW,                      SMI,   !F,  0x3F,   B,
240 	      .bits = {{
241 			.offset = 0,
242 			.mask = MI_FLUSH_DW_NOTIFY,
243 			.expected = 0,
244 	      },
245 	      {
246 			.offset = 1,
247 			.mask = MI_FLUSH_DW_USE_GTT,
248 			.expected = 0,
249 			.condition_offset = 0,
250 			.condition_mask = MI_FLUSH_DW_OP_MASK,
251 	      },
252 	      {
253 			.offset = 0,
254 			.mask = MI_FLUSH_DW_STORE_INDEX,
255 			.expected = 0,
256 			.condition_offset = 0,
257 			.condition_mask = MI_FLUSH_DW_OP_MASK,
258 	      }},						       ),
259 	CMD(  MI_CONDITIONAL_BATCH_BUFFER_END,  SMI,   !F,  0xFF,   B,
260 	      .bits = {{
261 			.offset = 0,
262 			.mask = MI_GLOBAL_GTT,
263 			.expected = 0,
264 	      }},						       ),
265 	/*
266 	 * MFX_WAIT doesn't fit the way we handle length for most commands.
267 	 * It has a length field but it uses a non-standard length bias.
268 	 * It is always 1 dword though, so just treat it as fixed length.
269 	 */
270 	CMD(  MFX_WAIT,                         SMFX,   F,  1,      S  ),
271 };
272 
273 static const struct drm_i915_cmd_descriptor gen7_vecs_cmds[] = {
274 	CMD(  MI_ARB_ON_OFF,                    SMI,    F,  1,      R  ),
275 	CMD(  MI_SET_APPID,                     SMI,    F,  1,      S  ),
276 	CMD(  MI_STORE_DWORD_IMM,               SMI,   !F,  0xFF,   B,
277 	      .bits = {{
278 			.offset = 0,
279 			.mask = MI_GLOBAL_GTT,
280 			.expected = 0,
281 	      }},						       ),
282 	CMD(  MI_UPDATE_GTT,                    SMI,   !F,  0x3F,   R  ),
283 	CMD(  MI_FLUSH_DW,                      SMI,   !F,  0x3F,   B,
284 	      .bits = {{
285 			.offset = 0,
286 			.mask = MI_FLUSH_DW_NOTIFY,
287 			.expected = 0,
288 	      },
289 	      {
290 			.offset = 1,
291 			.mask = MI_FLUSH_DW_USE_GTT,
292 			.expected = 0,
293 			.condition_offset = 0,
294 			.condition_mask = MI_FLUSH_DW_OP_MASK,
295 	      },
296 	      {
297 			.offset = 0,
298 			.mask = MI_FLUSH_DW_STORE_INDEX,
299 			.expected = 0,
300 			.condition_offset = 0,
301 			.condition_mask = MI_FLUSH_DW_OP_MASK,
302 	      }},						       ),
303 	CMD(  MI_CONDITIONAL_BATCH_BUFFER_END,  SMI,   !F,  0xFF,   B,
304 	      .bits = {{
305 			.offset = 0,
306 			.mask = MI_GLOBAL_GTT,
307 			.expected = 0,
308 	      }},						       ),
309 };
310 
311 static const struct drm_i915_cmd_descriptor gen7_blt_cmds[] = {
312 	CMD(  MI_DISPLAY_FLIP,                  SMI,   !F,  0xFF,   R  ),
313 	CMD(  MI_STORE_DWORD_IMM,               SMI,   !F,  0x3FF,  B,
314 	      .bits = {{
315 			.offset = 0,
316 			.mask = MI_GLOBAL_GTT,
317 			.expected = 0,
318 	      }},						       ),
319 	CMD(  MI_UPDATE_GTT,                    SMI,   !F,  0x3F,   R  ),
320 	CMD(  MI_FLUSH_DW,                      SMI,   !F,  0x3F,   B,
321 	      .bits = {{
322 			.offset = 0,
323 			.mask = MI_FLUSH_DW_NOTIFY,
324 			.expected = 0,
325 	      },
326 	      {
327 			.offset = 1,
328 			.mask = MI_FLUSH_DW_USE_GTT,
329 			.expected = 0,
330 			.condition_offset = 0,
331 			.condition_mask = MI_FLUSH_DW_OP_MASK,
332 	      },
333 	      {
334 			.offset = 0,
335 			.mask = MI_FLUSH_DW_STORE_INDEX,
336 			.expected = 0,
337 			.condition_offset = 0,
338 			.condition_mask = MI_FLUSH_DW_OP_MASK,
339 	      }},						       ),
340 	CMD(  COLOR_BLT,                        S2D,   !F,  0x3F,   S  ),
341 	CMD(  SRC_COPY_BLT,                     S2D,   !F,  0x3F,   S  ),
342 };
343 
344 static const struct drm_i915_cmd_descriptor hsw_blt_cmds[] = {
345 	CMD(  MI_LOAD_SCAN_LINES_INCL,          SMI,   !F,  0x3F,   R  ),
346 	CMD(  MI_LOAD_SCAN_LINES_EXCL,          SMI,   !F,  0x3F,   R  ),
347 };
348 
349 /*
350  * For Gen9 we can still rely on the h/w to enforce cmd security, and only
351  * need to re-enforce the register access checks. We therefore only need to
352  * teach the cmdparser how to find the end of each command, and identify
353  * register accesses. The table doesn't need to reject any commands, and so
354  * the only commands listed here are:
355  *   1) Those that touch registers
356  *   2) Those that do not have the default 8-bit length
357  *
358  * Note that the default MI length mask chosen for this table is 0xFF, not
359  * the 0x3F used on older devices. This is because the vast majority of MI
360  * cmds on Gen9 use a standard 8-bit Length field.
361  * All the Gen9 blitter instructions are standard 0xFF length mask, and
362  * none allow access to non-general registers, so in fact no BLT cmds are
363  * included in the table at all.
364  *
365  */
366 static const struct drm_i915_cmd_descriptor gen9_blt_cmds[] = {
367 	CMD(  MI_NOOP,                          SMI,    F,  1,      S  ),
368 	CMD(  MI_USER_INTERRUPT,                SMI,    F,  1,      S  ),
369 	CMD(  MI_WAIT_FOR_EVENT,                SMI,    F,  1,      S  ),
370 	CMD(  MI_FLUSH,                         SMI,    F,  1,      S  ),
371 	CMD(  MI_ARB_CHECK,                     SMI,    F,  1,      S  ),
372 	CMD(  MI_REPORT_HEAD,                   SMI,    F,  1,      S  ),
373 	CMD(  MI_ARB_ON_OFF,                    SMI,    F,  1,      S  ),
374 	CMD(  MI_SUSPEND_FLUSH,                 SMI,    F,  1,      S  ),
375 	CMD(  MI_LOAD_SCAN_LINES_INCL,          SMI,   !F,  0x3F,   S  ),
376 	CMD(  MI_LOAD_SCAN_LINES_EXCL,          SMI,   !F,  0x3F,   S  ),
377 	CMD(  MI_STORE_DWORD_IMM,               SMI,   !F,  0x3FF,  S  ),
378 	CMD(  MI_LOAD_REGISTER_IMM(1),          SMI,   !F,  0xFF,   W,
379 	      .reg = { .offset = 1, .mask = 0x007FFFFC, .step = 2 }    ),
380 	CMD(  MI_UPDATE_GTT,                    SMI,   !F,  0x3FF,  S  ),
381 	CMD(  MI_STORE_REGISTER_MEM_GEN8,       SMI,    F,  4,      W,
382 	      .reg = { .offset = 1, .mask = 0x007FFFFC }               ),
383 	CMD(  MI_FLUSH_DW,                      SMI,   !F,  0x3F,   S  ),
384 	CMD(  MI_LOAD_REGISTER_MEM_GEN8,        SMI,    F,  4,      W,
385 	      .reg = { .offset = 1, .mask = 0x007FFFFC }               ),
386 	CMD(  MI_LOAD_REGISTER_REG,             SMI,    !F,  0xFF,  W,
387 	      .reg = { .offset = 1, .mask = 0x007FFFFC, .step = 1 }    ),
388 
389 	/*
390 	 * We allow BB_START but apply further checks. We just sanitize the
391 	 * basic fields here.
392 	 */
393 	CMD( MI_BATCH_BUFFER_START_GEN8,       SMI,    !F,  0xFF,  B,
394 	     .bits = {{
395 			.offset = 0,
396 			.mask = ~SMI,
397 			.expected = (MI_BATCH_PPGTT_HSW | 1),
398 	      }},					     ),
399 };
400 
401 #undef CMD
402 #undef SMI
403 #undef S3D
404 #undef S2D
405 #undef SMFX
406 #undef F
407 #undef S
408 #undef R
409 #undef W
410 #undef B
411 
412 static const struct drm_i915_cmd_table gen7_render_cmd_table[] = {
413 	{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
414 	{ gen7_render_cmds, ARRAY_SIZE(gen7_render_cmds) },
415 };
416 
417 static const struct drm_i915_cmd_table hsw_render_ring_cmd_table[] = {
418 	{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
419 	{ gen7_render_cmds, ARRAY_SIZE(gen7_render_cmds) },
420 	{ hsw_render_cmds, ARRAY_SIZE(hsw_render_cmds) },
421 };
422 
423 static const struct drm_i915_cmd_table gen7_video_cmd_table[] = {
424 	{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
425 	{ gen7_video_cmds, ARRAY_SIZE(gen7_video_cmds) },
426 };
427 
428 static const struct drm_i915_cmd_table hsw_vebox_cmd_table[] = {
429 	{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
430 	{ gen7_vecs_cmds, ARRAY_SIZE(gen7_vecs_cmds) },
431 };
432 
433 static const struct drm_i915_cmd_table gen7_blt_cmd_table[] = {
434 	{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
435 	{ gen7_blt_cmds, ARRAY_SIZE(gen7_blt_cmds) },
436 };
437 
438 static const struct drm_i915_cmd_table hsw_blt_ring_cmd_table[] = {
439 	{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
440 	{ gen7_blt_cmds, ARRAY_SIZE(gen7_blt_cmds) },
441 	{ hsw_blt_cmds, ARRAY_SIZE(hsw_blt_cmds) },
442 };
443 
444 static const struct drm_i915_cmd_table gen9_blt_cmd_table[] = {
445 	{ gen9_blt_cmds, ARRAY_SIZE(gen9_blt_cmds) },
446 };
447 
448 
449 /*
450  * Register whitelists, sorted by increasing register offset.
451  */
452 
453 /*
454  * An individual whitelist entry granting access to register addr.  If
455  * mask is non-zero the argument of immediate register writes will be
456  * AND-ed with mask, and the command will be rejected if the result
457  * doesn't match value.
458  *
459  * Registers with non-zero mask are only allowed to be written using
460  * LRI.
461  */
462 struct drm_i915_reg_descriptor {
463 	u32 addr;
464 	u32 mask;
465 	u32 value;
466 };
467 
468 /* Convenience macro for adding 32-bit registers. */
469 #define REG32(address, ...)                             \
470 	{ .addr = address, __VA_ARGS__ }
471 
472 /*
473  * Convenience macro for adding 64-bit registers.
474  *
475  * Some registers that userspace accesses are 64 bits. The register
476  * access commands only allow 32-bit accesses. Hence, we have to include
477  * entries for both halves of the 64-bit registers.
478  */
479 #define REG64(addr)                                     \
480 	REG32(addr), REG32(addr + sizeof(u32))
481 
482 #define REG64_IDX(_reg, idx) \
483 	{ .addr = _reg(idx) }, \
484 	{ .addr = _reg ## _UDW(idx) }
485 
486 static const struct drm_i915_reg_descriptor gen7_render_regs[] = {
487 	REG64(GPGPU_THREADS_DISPATCHED),
488 	REG64(HS_INVOCATION_COUNT),
489 	REG64(DS_INVOCATION_COUNT),
490 	REG64(IA_VERTICES_COUNT),
491 	REG64(IA_PRIMITIVES_COUNT),
492 	REG64(VS_INVOCATION_COUNT),
493 	REG64(GS_INVOCATION_COUNT),
494 	REG64(GS_PRIMITIVES_COUNT),
495 	REG64(CL_INVOCATION_COUNT),
496 	REG64(CL_PRIMITIVES_COUNT),
497 	REG64(PS_INVOCATION_COUNT),
498 	REG64(PS_DEPTH_COUNT),
499 	REG32(OACONTROL), /* Only allowed for LRI and SRM. See below. */
500 	REG64(MI_PREDICATE_SRC0),
501 	REG64(MI_PREDICATE_SRC1),
502 	REG32(GEN7_3DPRIM_END_OFFSET),
503 	REG32(GEN7_3DPRIM_START_VERTEX),
504 	REG32(GEN7_3DPRIM_VERTEX_COUNT),
505 	REG32(GEN7_3DPRIM_INSTANCE_COUNT),
506 	REG32(GEN7_3DPRIM_START_INSTANCE),
507 	REG32(GEN7_3DPRIM_BASE_VERTEX),
508 	REG32(GEN7_GPGPU_DISPATCHDIMX),
509 	REG32(GEN7_GPGPU_DISPATCHDIMY),
510 	REG32(GEN7_GPGPU_DISPATCHDIMZ),
511 	REG64(GEN7_SO_NUM_PRIMS_WRITTEN(0)),
512 	REG64(GEN7_SO_NUM_PRIMS_WRITTEN(1)),
513 	REG64(GEN7_SO_NUM_PRIMS_WRITTEN(2)),
514 	REG64(GEN7_SO_NUM_PRIMS_WRITTEN(3)),
515 	REG64(GEN7_SO_PRIM_STORAGE_NEEDED(0)),
516 	REG64(GEN7_SO_PRIM_STORAGE_NEEDED(1)),
517 	REG64(GEN7_SO_PRIM_STORAGE_NEEDED(2)),
518 	REG64(GEN7_SO_PRIM_STORAGE_NEEDED(3)),
519 	REG32(GEN7_SO_WRITE_OFFSET(0)),
520 	REG32(GEN7_SO_WRITE_OFFSET(1)),
521 	REG32(GEN7_SO_WRITE_OFFSET(2)),
522 	REG32(GEN7_SO_WRITE_OFFSET(3)),
523 	REG32(GEN7_L3SQCREG1),
524 	REG32(GEN7_L3CNTLREG2),
525 	REG32(GEN7_L3CNTLREG3),
526 	REG32(HSW_SCRATCH1,
527 	      .mask = ~HSW_SCRATCH1_L3_DATA_ATOMICS_DISABLE,
528 	      .value = 0),
529 	REG32(HSW_ROW_CHICKEN3,
530 	      .mask = ~(HSW_ROW_CHICKEN3_L3_GLOBAL_ATOMICS_DISABLE << 16 |
531                         HSW_ROW_CHICKEN3_L3_GLOBAL_ATOMICS_DISABLE),
532 	      .value = 0),
533 };
534 
535 static const struct drm_i915_reg_descriptor gen7_blt_regs[] = {
536 	REG32(BCS_SWCTRL),
537 };
538 
539 static const struct drm_i915_reg_descriptor gen9_blt_regs[] = {
540 	REG64_IDX(RING_TIMESTAMP, RENDER_RING_BASE),
541 	REG64_IDX(RING_TIMESTAMP, BSD_RING_BASE),
542 	REG32(BCS_SWCTRL),
543 	REG64_IDX(RING_TIMESTAMP, BLT_RING_BASE),
544 	REG64_IDX(BCS_GPR, 0),
545 	REG64_IDX(BCS_GPR, 1),
546 	REG64_IDX(BCS_GPR, 2),
547 	REG64_IDX(BCS_GPR, 3),
548 	REG64_IDX(BCS_GPR, 4),
549 	REG64_IDX(BCS_GPR, 5),
550 	REG64_IDX(BCS_GPR, 6),
551 	REG64_IDX(BCS_GPR, 7),
552 	REG64_IDX(BCS_GPR, 8),
553 	REG64_IDX(BCS_GPR, 9),
554 	REG64_IDX(BCS_GPR, 10),
555 	REG64_IDX(BCS_GPR, 11),
556 	REG64_IDX(BCS_GPR, 12),
557 	REG64_IDX(BCS_GPR, 13),
558 	REG64_IDX(BCS_GPR, 14),
559 	REG64_IDX(BCS_GPR, 15),
560 };
561 
562 #undef REG64
563 #undef REG32
564 
gen7_render_get_cmd_length_mask(u32 cmd_header)565 static u32 gen7_render_get_cmd_length_mask(u32 cmd_header)
566 {
567 	u32 client = (cmd_header & INSTR_CLIENT_MASK) >> INSTR_CLIENT_SHIFT;
568 	u32 subclient =
569 		(cmd_header & INSTR_SUBCLIENT_MASK) >> INSTR_SUBCLIENT_SHIFT;
570 
571 	if (client == INSTR_MI_CLIENT)
572 		return 0x3F;
573 	else if (client == INSTR_RC_CLIENT) {
574 		if (subclient == INSTR_MEDIA_SUBCLIENT)
575 			return 0xFFFF;
576 		else
577 			return 0xFF;
578 	}
579 
580 	DRM_DEBUG_DRIVER("CMD: Abnormal rcs cmd length! 0x%08X\n", cmd_header);
581 	return 0;
582 }
583 
gen7_bsd_get_cmd_length_mask(u32 cmd_header)584 static u32 gen7_bsd_get_cmd_length_mask(u32 cmd_header)
585 {
586 	u32 client = (cmd_header & INSTR_CLIENT_MASK) >> INSTR_CLIENT_SHIFT;
587 	u32 subclient =
588 		(cmd_header & INSTR_SUBCLIENT_MASK) >> INSTR_SUBCLIENT_SHIFT;
589 	u32 op = (cmd_header & INSTR_26_TO_24_MASK) >> INSTR_26_TO_24_SHIFT;
590 
591 	if (client == INSTR_MI_CLIENT)
592 		return 0x3F;
593 	else if (client == INSTR_RC_CLIENT) {
594 		if (subclient == INSTR_MEDIA_SUBCLIENT) {
595 			if (op == 6)
596 				return 0xFFFF;
597 			else
598 				return 0xFFF;
599 		} else
600 			return 0xFF;
601 	}
602 
603 	DRM_DEBUG_DRIVER("CMD: Abnormal bsd cmd length! 0x%08X\n", cmd_header);
604 	return 0;
605 }
606 
gen7_blt_get_cmd_length_mask(u32 cmd_header)607 static u32 gen7_blt_get_cmd_length_mask(u32 cmd_header)
608 {
609 	u32 client = (cmd_header & INSTR_CLIENT_MASK) >> INSTR_CLIENT_SHIFT;
610 
611 	if (client == INSTR_MI_CLIENT)
612 		return 0x3F;
613 	else if (client == INSTR_BC_CLIENT)
614 		return 0xFF;
615 
616 	DRM_DEBUG_DRIVER("CMD: Abnormal blt cmd length! 0x%08X\n", cmd_header);
617 	return 0;
618 }
619 
gen9_blt_get_cmd_length_mask(u32 cmd_header)620 static u32 gen9_blt_get_cmd_length_mask(u32 cmd_header)
621 {
622 	u32 client = (cmd_header & INSTR_CLIENT_MASK) >> INSTR_CLIENT_SHIFT;
623 
624 	if (client == INSTR_MI_CLIENT || client == INSTR_BC_CLIENT)
625 		return 0xFF;
626 
627 	DRM_DEBUG_DRIVER("CMD: Abnormal blt cmd length! 0x%08X\n", cmd_header);
628 	return 0;
629 }
630 
validate_cmds_sorted(struct intel_engine_cs * ring,const struct drm_i915_cmd_table * cmd_tables,int cmd_table_count)631 static bool validate_cmds_sorted(struct intel_engine_cs *ring,
632 				 const struct drm_i915_cmd_table *cmd_tables,
633 				 int cmd_table_count)
634 {
635 	int i;
636 	bool ret = true;
637 
638 	if (!cmd_tables || cmd_table_count == 0)
639 		return true;
640 
641 	for (i = 0; i < cmd_table_count; i++) {
642 		const struct drm_i915_cmd_table *table = &cmd_tables[i];
643 		u32 previous = 0;
644 		int j;
645 
646 		for (j = 0; j < table->count; j++) {
647 			const struct drm_i915_cmd_descriptor *desc =
648 				&table->table[j];
649 			u32 curr = desc->cmd.value & desc->cmd.mask;
650 
651 			if (curr < previous) {
652 				DRM_ERROR("CMD: table not sorted ring=%d table=%d entry=%d cmd=0x%08X prev=0x%08X\n",
653 					  ring->id, i, j, curr, previous);
654 				ret = false;
655 			}
656 
657 			previous = curr;
658 		}
659 	}
660 
661 	return ret;
662 }
663 
check_sorted(int ring_id,const struct drm_i915_reg_descriptor * reg_table,int reg_count)664 static bool check_sorted(int ring_id,
665 			 const struct drm_i915_reg_descriptor *reg_table,
666 			 int reg_count)
667 {
668 	int i;
669 	u32 previous = 0;
670 	bool ret = true;
671 
672 	for (i = 0; i < reg_count; i++) {
673 		u32 curr = reg_table[i].addr;
674 
675 		if (curr < previous) {
676 			DRM_ERROR("CMD: table not sorted ring=%d entry=%d reg=0x%08X prev=0x%08X\n",
677 				  ring_id, i, curr, previous);
678 			ret = false;
679 		}
680 
681 		previous = curr;
682 	}
683 
684 	return ret;
685 }
686 
validate_regs_sorted(struct intel_engine_cs * ring)687 static bool validate_regs_sorted(struct intel_engine_cs *ring)
688 {
689 	return check_sorted(ring->id, ring->reg_table, ring->reg_count);
690 }
691 
692 struct cmd_node {
693 	const struct drm_i915_cmd_descriptor *desc;
694 	struct hlist_node node;
695 };
696 
697 /*
698  * Different command ranges have different numbers of bits for the opcode. For
699  * example, MI commands use bits 31:23 while 3D commands use bits 31:16. The
700  * problem is that, for example, MI commands use bits 22:16 for other fields
701  * such as GGTT vs PPGTT bits. If we include those bits in the mask then when
702  * we mask a command from a batch it could hash to the wrong bucket due to
703  * non-opcode bits being set. But if we don't include those bits, some 3D
704  * commands may hash to the same bucket due to not including opcode bits that
705  * make the command unique. For now, we will risk hashing to the same bucket.
706  *
707  * If we attempt to generate a perfect hash, we should be able to look at bits
708  * 31:29 of a command from a batch buffer and use the full mask for that
709  * client. The existing INSTR_CLIENT_MASK/SHIFT defines can be used for this.
710  */
711 #define CMD_HASH_MASK STD_MI_OPCODE_MASK
712 
init_hash_table(struct intel_engine_cs * ring,const struct drm_i915_cmd_table * cmd_tables,int cmd_table_count)713 static int init_hash_table(struct intel_engine_cs *ring,
714 			   const struct drm_i915_cmd_table *cmd_tables,
715 			   int cmd_table_count)
716 {
717 	int i, j;
718 
719 	hash_init(ring->cmd_hash);
720 
721 	for (i = 0; i < cmd_table_count; i++) {
722 		const struct drm_i915_cmd_table *table = &cmd_tables[i];
723 
724 		for (j = 0; j < table->count; j++) {
725 			const struct drm_i915_cmd_descriptor *desc =
726 				&table->table[j];
727 			struct cmd_node *desc_node =
728 				kmalloc(sizeof(*desc_node), GFP_KERNEL);
729 
730 			if (!desc_node)
731 				return -ENOMEM;
732 
733 			desc_node->desc = desc;
734 			hash_add(ring->cmd_hash, &desc_node->node,
735 				 desc->cmd.value & CMD_HASH_MASK);
736 		}
737 	}
738 
739 	return 0;
740 }
741 
fini_hash_table(struct intel_engine_cs * ring)742 static void fini_hash_table(struct intel_engine_cs *ring)
743 {
744 	struct hlist_node *tmp;
745 	struct cmd_node *desc_node;
746 	int i;
747 
748 	hash_for_each_safe(ring->cmd_hash, i, tmp, desc_node, node) {
749 		hash_del(&desc_node->node);
750 		kfree(desc_node);
751 	}
752 }
753 
754 /**
755  * i915_cmd_parser_init_ring() - set cmd parser related fields for a ringbuffer
756  * @ring: the ringbuffer to initialize
757  *
758  * Optionally initializes fields related to batch buffer command parsing in the
759  * struct intel_engine_cs based on whether the platform requires software
760  * command parsing.
761  *
762  * Return: non-zero if initialization fails
763  */
i915_cmd_parser_init_ring(struct intel_engine_cs * ring)764 int i915_cmd_parser_init_ring(struct intel_engine_cs *ring)
765 {
766 	const struct drm_i915_cmd_table *cmd_tables;
767 	int cmd_table_count;
768 	int ret;
769 
770 	if (!IS_GEN7(ring->dev) && !(IS_GEN9(ring->dev) && ring->id == BCS))
771 		return 0;
772 
773 	switch (ring->id) {
774 	case RCS:
775 		if (IS_HASWELL(ring->dev)) {
776 			cmd_tables = hsw_render_ring_cmd_table;
777 			cmd_table_count =
778 				ARRAY_SIZE(hsw_render_ring_cmd_table);
779 		} else {
780 			cmd_tables = gen7_render_cmd_table;
781 			cmd_table_count = ARRAY_SIZE(gen7_render_cmd_table);
782 		}
783 
784 		ring->reg_table = gen7_render_regs;
785 		ring->reg_count = ARRAY_SIZE(gen7_render_regs);
786 
787 		ring->get_cmd_length_mask = gen7_render_get_cmd_length_mask;
788 		break;
789 	case VCS:
790 		cmd_tables = gen7_video_cmd_table;
791 		cmd_table_count = ARRAY_SIZE(gen7_video_cmd_table);
792 		ring->get_cmd_length_mask = gen7_bsd_get_cmd_length_mask;
793 		break;
794 	case BCS:
795 		ring->get_cmd_length_mask = gen7_blt_get_cmd_length_mask;
796 		if (IS_GEN9(ring->dev)) {
797 			cmd_tables = gen9_blt_cmd_table;
798 			cmd_table_count = ARRAY_SIZE(gen9_blt_cmd_table);
799 			ring->get_cmd_length_mask =
800 				gen9_blt_get_cmd_length_mask;
801 
802 			/* BCS Engine unsafe without parser */
803 			ring->requires_cmd_parser = 1;
804 		}
805 		else if (IS_HASWELL(ring->dev)) {
806 			cmd_tables = hsw_blt_ring_cmd_table;
807 			cmd_table_count = ARRAY_SIZE(hsw_blt_ring_cmd_table);
808 		} else {
809 			cmd_tables = gen7_blt_cmd_table;
810 			cmd_table_count = ARRAY_SIZE(gen7_blt_cmd_table);
811 		}
812 
813 		if (IS_GEN9(ring->dev)) {
814 			ring->reg_table = gen9_blt_regs;
815 			ring->reg_count = ARRAY_SIZE(gen9_blt_regs);
816 		} else {
817 			ring->reg_table = gen7_blt_regs;
818 			ring->reg_count = ARRAY_SIZE(gen7_blt_regs);
819 		}
820 
821 		break;
822 	case VECS:
823 		cmd_tables = hsw_vebox_cmd_table;
824 		cmd_table_count = ARRAY_SIZE(hsw_vebox_cmd_table);
825 		/* VECS can use the same length_mask function as VCS */
826 		ring->get_cmd_length_mask = gen7_bsd_get_cmd_length_mask;
827 		break;
828 	default:
829 		DRM_ERROR("CMD: cmd_parser_init with unknown ring: %d\n",
830 			  ring->id);
831 		BUG();
832 	}
833 
834 	BUG_ON(!validate_cmds_sorted(ring, cmd_tables, cmd_table_count));
835 	BUG_ON(!validate_regs_sorted(ring));
836 
837 	WARN_ON(!hash_empty(ring->cmd_hash));
838 
839 	ret = init_hash_table(ring, cmd_tables, cmd_table_count);
840 	if (ret) {
841 		DRM_ERROR("CMD: cmd_parser_init failed!\n");
842 		fini_hash_table(ring);
843 		return ret;
844 	}
845 
846 	ring->using_cmd_parser = true;
847 
848 	return 0;
849 }
850 
851 /**
852  * i915_cmd_parser_fini_ring() - clean up cmd parser related fields
853  * @ring: the ringbuffer to clean up
854  *
855  * Releases any resources related to command parsing that may have been
856  * initialized for the specified ring.
857  */
i915_cmd_parser_fini_ring(struct intel_engine_cs * ring)858 void i915_cmd_parser_fini_ring(struct intel_engine_cs *ring)
859 {
860 	if (!ring->using_cmd_parser)
861 		return;
862 
863 	fini_hash_table(ring);
864 }
865 
866 static const struct drm_i915_cmd_descriptor*
find_cmd_in_table(struct intel_engine_cs * ring,u32 cmd_header)867 find_cmd_in_table(struct intel_engine_cs *ring,
868 		  u32 cmd_header)
869 {
870 	struct cmd_node *desc_node;
871 
872 	hash_for_each_possible(ring->cmd_hash, desc_node, node,
873 			       cmd_header & CMD_HASH_MASK) {
874 		const struct drm_i915_cmd_descriptor *desc = desc_node->desc;
875 		u32 masked_cmd = desc->cmd.mask & cmd_header;
876 		u32 masked_value = desc->cmd.value & desc->cmd.mask;
877 
878 		if (masked_cmd == masked_value)
879 			return desc;
880 	}
881 
882 	return NULL;
883 }
884 
885 /*
886  * Returns a pointer to a descriptor for the command specified by cmd_header.
887  *
888  * The caller must supply space for a default descriptor via the default_desc
889  * parameter. If no descriptor for the specified command exists in the ring's
890  * command parser tables, this function fills in default_desc based on the
891  * ring's default length encoding and returns default_desc.
892  */
893 static const struct drm_i915_cmd_descriptor*
find_cmd(struct intel_engine_cs * ring,u32 cmd_header,struct drm_i915_cmd_descriptor * default_desc)894 find_cmd(struct intel_engine_cs *ring,
895 	 u32 cmd_header,
896 	 struct drm_i915_cmd_descriptor *default_desc)
897 {
898 	const struct drm_i915_cmd_descriptor *desc;
899 	u32 mask;
900 
901 	desc = find_cmd_in_table(ring, cmd_header);
902 	if (desc)
903 		return desc;
904 
905 	mask = ring->get_cmd_length_mask(cmd_header);
906 	if (!mask)
907 		return NULL;
908 
909 	BUG_ON(!default_desc);
910 	default_desc->flags = CMD_DESC_SKIP;
911 	default_desc->length.mask = mask;
912 
913 	return default_desc;
914 }
915 
916 static const struct drm_i915_reg_descriptor *
find_reg(const struct drm_i915_reg_descriptor * table,int count,u32 addr)917 find_reg(const struct drm_i915_reg_descriptor *table,
918 	 int count, u32 addr)
919 {
920 	if (table) {
921 		int i;
922 
923 		for (i = 0; i < count; i++) {
924 			if (table[i].addr == addr)
925 				return &table[i];
926 		}
927 	}
928 
929 	return NULL;
930 }
931 
vmap_batch(struct drm_i915_gem_object * obj,unsigned start,unsigned len)932 static u32 *vmap_batch(struct drm_i915_gem_object *obj,
933 		       unsigned start, unsigned len)
934 {
935 	int i;
936 	void *addr = NULL;
937 	struct sg_page_iter sg_iter;
938 	int first_page = start >> PAGE_SHIFT;
939 	int last_page = (len + start + 4095) >> PAGE_SHIFT;
940 	int npages = last_page - first_page;
941 	struct page **pages;
942 
943 	pages = drm_malloc_ab(npages, sizeof(*pages));
944 	if (pages == NULL) {
945 		DRM_DEBUG_DRIVER("Failed to get space for pages\n");
946 		goto finish;
947 	}
948 
949 	i = 0;
950 	for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents, first_page) {
951 		pages[i++] = sg_page_iter_page(&sg_iter);
952 		if (i == npages)
953 			break;
954 	}
955 
956 	addr = vmap(pages, i, 0, PAGE_KERNEL);
957 	if (addr == NULL) {
958 		DRM_DEBUG_DRIVER("Failed to vmap pages\n");
959 		goto finish;
960 	}
961 
962 finish:
963 	if (pages)
964 		drm_free_large(pages);
965 	return (u32*)addr;
966 }
967 
968 /* Returns a vmap'd pointer to dest_obj, which the caller must unmap */
copy_batch(struct drm_i915_gem_object * dest_obj,struct drm_i915_gem_object * src_obj,u32 batch_start_offset,u32 batch_len)969 static u32 *copy_batch(struct drm_i915_gem_object *dest_obj,
970 		       struct drm_i915_gem_object *src_obj,
971 		       u32 batch_start_offset,
972 		       u32 batch_len)
973 {
974 	int needs_clflush = 0;
975 	void *src_base, *src;
976 	void *dst = NULL;
977 	int ret;
978 
979 	if (batch_len > dest_obj->base.size ||
980 	    batch_len + batch_start_offset > src_obj->base.size)
981 		return ERR_PTR(-E2BIG);
982 
983 	if (WARN_ON(dest_obj->pages_pin_count == 0))
984 		return ERR_PTR(-ENODEV);
985 
986 	ret = i915_gem_obj_prepare_shmem_read(src_obj, &needs_clflush);
987 	if (ret) {
988 		DRM_DEBUG_DRIVER("CMD: failed to prepare shadow batch\n");
989 		return ERR_PTR(ret);
990 	}
991 
992 	src_base = vmap_batch(src_obj, batch_start_offset, batch_len);
993 	if (!src_base) {
994 		DRM_DEBUG_DRIVER("CMD: Failed to vmap batch\n");
995 		ret = -ENOMEM;
996 		goto unpin_src;
997 	}
998 
999 	ret = i915_gem_object_set_to_cpu_domain(dest_obj, true);
1000 	if (ret) {
1001 		DRM_DEBUG_DRIVER("CMD: Failed to set shadow batch to CPU\n");
1002 		goto unmap_src;
1003 	}
1004 
1005 	dst = vmap_batch(dest_obj, 0, batch_len);
1006 	if (!dst) {
1007 		DRM_DEBUG_DRIVER("CMD: Failed to vmap shadow batch\n");
1008 		ret = -ENOMEM;
1009 		goto unmap_src;
1010 	}
1011 
1012 	src = src_base + offset_in_page(batch_start_offset);
1013 	if (needs_clflush)
1014 		drm_clflush_virt_range(src, batch_len);
1015 
1016 	memcpy(dst, src, batch_len);
1017 
1018 unmap_src:
1019 	vunmap(src_base);
1020 unpin_src:
1021 	i915_gem_object_unpin_pages(src_obj);
1022 
1023 	return ret ? ERR_PTR(ret) : dst;
1024 }
1025 
check_cmd(const struct intel_engine_cs * ring,const struct drm_i915_cmd_descriptor * desc,const u32 * cmd,u32 length,bool * oacontrol_set)1026 static int check_cmd(const struct intel_engine_cs *ring,
1027 		      const struct drm_i915_cmd_descriptor *desc,
1028 		      const u32 *cmd, u32 length,
1029 		      bool *oacontrol_set)
1030 {
1031 	if (desc->flags & CMD_DESC_REJECT) {
1032 		DRM_DEBUG_DRIVER("CMD: Rejected command: 0x%08X\n", *cmd);
1033 		return false;
1034 	}
1035 
1036 	if (desc->flags & CMD_DESC_REGISTER) {
1037 		/*
1038 		 * Get the distance between individual register offset
1039 		 * fields if the command can perform more than one
1040 		 * access at a time.
1041 		 */
1042 		const u32 step = desc->reg.step ? desc->reg.step : length;
1043 		u32 offset;
1044 
1045 		for (offset = desc->reg.offset; offset < length;
1046 		     offset += step) {
1047 			const u32 reg_addr = cmd[offset] & desc->reg.mask;
1048 			const struct drm_i915_reg_descriptor *reg =
1049 				find_reg(ring->reg_table, ring->reg_count,
1050 					 reg_addr);
1051 
1052 			if (!reg) {
1053 				DRM_DEBUG_DRIVER("CMD: Rejected register 0x%08X in command: 0x%08X (ring=%d)\n",
1054 						 reg_addr, *cmd, ring->id);
1055 				return false;
1056 			}
1057 
1058 			/*
1059 			 * OACONTROL requires some special handling for
1060 			 * writes. We want to make sure that any batch which
1061 			 * enables OA also disables it before the end of the
1062 			 * batch. The goal is to prevent one process from
1063 			 * snooping on the perf data from another process. To do
1064 			 * that, we need to check the value that will be written
1065 			 * to the register. Hence, limit OACONTROL writes to
1066 			 * only MI_LOAD_REGISTER_IMM commands.
1067 			 */
1068 			if (reg_addr == OACONTROL) {
1069 				if (desc->cmd.value == MI_LOAD_REGISTER_MEM) {
1070 					DRM_DEBUG_DRIVER("CMD: Rejected LRM to OACONTROL\n");
1071 					return false;
1072 				}
1073 
1074 				if (desc->cmd.value == MI_LOAD_REGISTER_IMM(1))
1075 					*oacontrol_set = (cmd[offset + 1] != 0);
1076 			}
1077 
1078 			/*
1079 			 * Check the value written to the register against the
1080 			 * allowed mask/value pair given in the whitelist entry.
1081 			 */
1082 			if (reg->mask) {
1083 				if (desc->cmd.value == MI_LOAD_REGISTER_MEM) {
1084 					DRM_DEBUG_DRIVER("CMD: Rejected LRM to masked register 0x%08X\n",
1085 							 reg_addr);
1086 					return false;
1087 				}
1088 
1089 				if (desc->cmd.value == MI_LOAD_REGISTER_IMM(1) &&
1090 				    (offset + 2 > length ||
1091 				     (cmd[offset + 1] & reg->mask) != reg->value)) {
1092 					DRM_DEBUG_DRIVER("CMD: Rejected LRI to masked register 0x%08X\n",
1093 							 reg_addr);
1094 					return false;
1095 				}
1096 			}
1097 		}
1098 	}
1099 
1100 	if (desc->flags & CMD_DESC_BITMASK) {
1101 		int i;
1102 
1103 		for (i = 0; i < MAX_CMD_DESC_BITMASKS; i++) {
1104 			u32 dword;
1105 
1106 			if (desc->bits[i].mask == 0)
1107 				break;
1108 
1109 			if (desc->bits[i].condition_mask != 0) {
1110 				u32 offset =
1111 					desc->bits[i].condition_offset;
1112 				u32 condition = cmd[offset] &
1113 					desc->bits[i].condition_mask;
1114 
1115 				if (condition == 0)
1116 					continue;
1117 			}
1118 
1119 			dword = cmd[desc->bits[i].offset] &
1120 				desc->bits[i].mask;
1121 
1122 			if (dword != desc->bits[i].expected) {
1123 				DRM_DEBUG_DRIVER("CMD: Rejected command 0x%08X for bitmask 0x%08X (exp=0x%08X act=0x%08X) (ring=%d)\n",
1124 						 *cmd,
1125 						 desc->bits[i].mask,
1126 						 desc->bits[i].expected,
1127 						 dword, ring->id);
1128 				return false;
1129 			}
1130 		}
1131 	}
1132 
1133 	return true;
1134 }
1135 
check_bbstart(struct intel_context * ctx,u32 * cmd,u64 offset,u32 length,u32 batch_len,u64 batch_start,u64 shadow_batch_start)1136 static int check_bbstart(struct intel_context *ctx,
1137 			 u32 *cmd, u64 offset, u32 length,
1138 			 u32 batch_len,
1139 			 u64 batch_start,
1140 			 u64 shadow_batch_start)
1141 {
1142 
1143 	u64 jump_offset, jump_target;
1144 	u32 target_cmd_offset, target_cmd_index;
1145 
1146 	/* For igt compatibility on older platforms */
1147 	if (CMDPARSER_USES_GGTT(ctx->i915)) {
1148 		DRM_DEBUG("CMD: Rejecting BB_START for ggtt based submission\n");
1149 		return -EACCES;
1150 	}
1151 
1152 	if (length != 3) {
1153 		DRM_DEBUG("CMD: Recursive BB_START with bad length(%u)\n",
1154 				 length);
1155 		return -EINVAL;
1156 	}
1157 
1158 	jump_target = *(u64*)(cmd+1);
1159 	jump_offset = jump_target - batch_start;
1160 
1161 	/*
1162 	 * Any underflow of jump_target is guaranteed to be outside the range
1163 	 * of a u32, so >= test catches both too large and too small
1164 	 */
1165 	if (jump_offset >= batch_len) {
1166 		DRM_DEBUG("CMD: BB_START to 0x%llx jumps out of BB\n",
1167 			  jump_target);
1168 		return -EINVAL;
1169 	}
1170 
1171 	/*
1172 	 * This cannot overflow a u32 because we already checked jump_offset
1173 	 * is within the BB, and the batch_len is a u32
1174 	 */
1175 	target_cmd_offset = lower_32_bits(jump_offset);
1176 	target_cmd_index = target_cmd_offset / sizeof(u32);
1177 
1178 	*(u64*)(cmd + 1) = shadow_batch_start + target_cmd_offset;
1179 
1180 	if (target_cmd_index == offset)
1181 		return 0;
1182 
1183 	if (ctx->jump_whitelist_cmds <= target_cmd_index) {
1184 		DRM_DEBUG("CMD: Rejecting BB_START - truncated whitelist array\n");
1185 		return -EINVAL;
1186 	} else if (!test_bit(target_cmd_index, ctx->jump_whitelist)) {
1187 		DRM_DEBUG("CMD: BB_START to 0x%llx not a previously executed cmd\n",
1188 			  jump_target);
1189 		return -EINVAL;
1190 	}
1191 
1192 	return 0;
1193 }
1194 
init_whitelist(struct intel_context * ctx,u32 batch_len)1195 static void init_whitelist(struct intel_context *ctx, u32 batch_len)
1196 {
1197 	const u32 batch_cmds = DIV_ROUND_UP(batch_len, sizeof(u32));
1198 	const u32 exact_size = BITS_TO_LONGS(batch_cmds);
1199 	u32 next_size = BITS_TO_LONGS(roundup_pow_of_two(batch_cmds));
1200 	unsigned long *next_whitelist;
1201 
1202 	if (CMDPARSER_USES_GGTT(ctx->i915))
1203 		return;
1204 
1205 	if (batch_cmds <= ctx->jump_whitelist_cmds) {
1206 		bitmap_zero(ctx->jump_whitelist, batch_cmds);
1207 		return;
1208 	}
1209 
1210 again:
1211 	next_whitelist = kcalloc(next_size, sizeof(long), GFP_KERNEL);
1212 	if (next_whitelist) {
1213 		kfree(ctx->jump_whitelist);
1214 		ctx->jump_whitelist = next_whitelist;
1215 		ctx->jump_whitelist_cmds =
1216 			next_size * BITS_PER_BYTE * sizeof(long);
1217 		return;
1218 	}
1219 
1220 	if (next_size > exact_size) {
1221 		next_size = exact_size;
1222 		goto again;
1223 	}
1224 
1225 	DRM_DEBUG("CMD: Failed to extend whitelist. BB_START may be disallowed\n");
1226 	bitmap_zero(ctx->jump_whitelist, ctx->jump_whitelist_cmds);
1227 
1228 	return;
1229 }
1230 
1231 #define LENGTH_BIAS 2
1232 
1233 /**
1234  * i915_parse_cmds() - parse a submitted batch buffer for privilege violations
1235  * @ctx: the context in which the batch is to execute
1236  * @ring: the ring on which the batch is to execute
1237  * @batch_obj: the batch buffer in question
1238  * @user_batch_start: Canonical base address of original user batch
1239  * @batch_start_offset: byte offset in the batch at which execution starts
1240  * @batch_len: length of the commands in batch_obj
1241  * @shadow_batch_obj: copy of the batch buffer in question
1242  * @shadow_batch_start: Canonical base address of shadow_batch_obj
1243  *
1244  * Parses the specified batch buffer looking for privilege violations as
1245  * described in the overview.
1246  *
1247  * Return: non-zero if the parser finds violations or otherwise fails; -EACCES
1248  * if the batch appears legal but should use hardware parsing
1249  */
i915_parse_cmds(struct intel_context * ctx,struct intel_engine_cs * ring,struct drm_i915_gem_object * batch_obj,u64 user_batch_start,u32 batch_start_offset,u32 batch_len,struct drm_i915_gem_object * shadow_batch_obj,u64 shadow_batch_start)1250 int i915_parse_cmds(struct intel_context *ctx,
1251 		    struct intel_engine_cs *ring,
1252 		    struct drm_i915_gem_object *batch_obj,
1253 		    u64 user_batch_start,
1254 		    u32 batch_start_offset,
1255 		    u32 batch_len,
1256 		    struct drm_i915_gem_object *shadow_batch_obj,
1257 		    u64 shadow_batch_start)
1258 {
1259 	u32 *cmd, *batch_base, *batch_end, offset = 0;
1260 	struct drm_i915_cmd_descriptor default_desc = { 0 };
1261 	bool oacontrol_set = false; /* OACONTROL tracking. See check_cmd() */
1262 	int ret = 0;
1263 
1264 	batch_base = copy_batch(shadow_batch_obj, batch_obj,
1265 				batch_start_offset, batch_len);
1266 	if (IS_ERR(batch_base)) {
1267 		DRM_DEBUG_DRIVER("CMD: Failed to copy batch\n");
1268 		return PTR_ERR(batch_base);
1269 	}
1270 
1271 	init_whitelist(ctx, batch_len);
1272 
1273 	/*
1274 	 * We use the batch length as size because the shadow object is as
1275 	 * large or larger and copy_batch() will write MI_NOPs to the extra
1276 	 * space. Parsing should be faster in some cases this way.
1277 	 */
1278 	batch_end = batch_base + (batch_len / sizeof(*batch_end));
1279 
1280 	cmd = batch_base;
1281 	while (cmd < batch_end) {
1282 		const struct drm_i915_cmd_descriptor *desc;
1283 		u32 length;
1284 
1285 		if (*cmd == MI_BATCH_BUFFER_END)
1286 			break;
1287 
1288 		desc = find_cmd(ring, *cmd, &default_desc);
1289 		if (!desc) {
1290 			DRM_DEBUG_DRIVER("CMD: Unrecognized command: 0x%08X\n",
1291 					 *cmd);
1292 			ret = -EINVAL;
1293 			break;
1294 		}
1295 
1296 		if (desc->flags & CMD_DESC_FIXED)
1297 			length = desc->length.fixed;
1298 		else
1299 			length = ((*cmd & desc->length.mask) + LENGTH_BIAS);
1300 
1301 		if ((batch_end - cmd) < length) {
1302 			DRM_DEBUG_DRIVER("CMD: Command length exceeds batch length: 0x%08X length=%u batchlen=%td\n",
1303 					 *cmd,
1304 					 length,
1305 					 batch_end - cmd);
1306 			ret = -EINVAL;
1307 			break;
1308 		}
1309 
1310 		if (!check_cmd(ring, desc, cmd, length, &oacontrol_set)) {
1311 			ret = CMDPARSER_USES_GGTT(ring->dev) ? -EINVAL : -EACCES;
1312 			break;
1313 		}
1314 
1315 		if (desc->cmd.value == MI_BATCH_BUFFER_START) {
1316 			ret = check_bbstart(ctx, cmd, offset, length,
1317 					    batch_len, user_batch_start,
1318 					    shadow_batch_start);
1319 			break;
1320 		}
1321 
1322 		if (ctx->jump_whitelist_cmds > offset)
1323 			set_bit(offset, ctx->jump_whitelist);
1324 
1325 		cmd += length;
1326 		offset += length;
1327 	}
1328 
1329 	if (oacontrol_set) {
1330 		DRM_DEBUG_DRIVER("CMD: batch set OACONTROL but did not clear it\n");
1331 		ret = -EINVAL;
1332 	}
1333 
1334 	if (cmd >= batch_end) {
1335 		DRM_DEBUG_DRIVER("CMD: Got to the end of the buffer w/o a BBE cmd!\n");
1336 		ret = -EINVAL;
1337 	}
1338 
1339 	vunmap(batch_base);
1340 
1341 	return ret;
1342 }
1343 
1344 /**
1345  * i915_cmd_parser_get_version() - get the cmd parser version number
1346  *
1347  * The cmd parser maintains a simple increasing integer version number suitable
1348  * for passing to userspace clients to determine what operations are permitted.
1349  *
1350  * Return: the current version number of the cmd parser
1351  */
i915_cmd_parser_get_version(struct drm_i915_private * dev_priv)1352 int i915_cmd_parser_get_version(struct drm_i915_private *dev_priv)
1353 {
1354 	/*
1355 	 * Command parser version history
1356 	 *
1357 	 * 1. Initial version. Checks batches and reports violations, but leaves
1358 	 *    hardware parsing enabled (so does not allow new use cases).
1359 	 * 2. Allow access to the MI_PREDICATE_SRC0 and
1360 	 *    MI_PREDICATE_SRC1 registers.
1361 	 * 3. Allow access to the GPGPU_THREADS_DISPATCHED register.
1362 	 * 4. L3 atomic chicken bits of HSW_SCRATCH1 and HSW_ROW_CHICKEN3.
1363 	 * 5. GPGPU dispatch compute indirect registers.
1364 	 * 10. Gen9 only - Supports the new ppgtt based BLIT parser
1365 	 */
1366 	return CMDPARSER_USES_GGTT(dev_priv) ? 5 : 10;
1367 }
1368