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