interplane.Get Omega
Read in your language

omega-gpu-driver

aien-dev/omega-gpu-driver

Brought by drakestapleton

branch main Branches Tags History

omega-gpu-driver / tests / uvme_check.py

398 lines · 19119 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Independent fake-kernel CUSE byte oracle; real processes, sockets and eventfd.
4No NVIDIA, VFIO, /dev/cuse, privileged ioctl, or device word is executed.
5"""
6import argparse
7import hashlib
8import multiprocessing as mp
9import os
10from pathlib import Path
11import selectors
12import signal
13import socket
14import struct
15import subprocess
16import sys
17import tempfile
18import time
19import traceback
20sys.dont_write_bytecode = True
21import uvms_check as service
22
23ROOT = Path(__file__).resolve().parents[1]
24PREFIX = ['taskset', '-c', '10-14', 'nice', '-n', '10']
25OMC = ROOT.parent/'omega-mv-vfioirq/seed/out/omc'
26PIN = '78122a72a7bb7129271088b30093e8b3b9b52f8d'
27SHA = '734bf4f3f858d56288902700cf581cdbaa4a24d1b3254a2beea014aaccf0fa38'
28QUEUE = 'b06b3f9a3dd1e74a3099350760cb3d26a3f33577'
29SIZES = {805306369:16,37:40,38:20,23:16,33:9264,34:24,25:32,39:8}
30MUTANTS = {
31 'endpoint': [
32 ('if ne size add need 72', 'if lt size add need 72'),
33 ('i = epfind epget 40 8\nif eq i 8\nepbegin -9 0\nret\nend\nif ne epget 48', 'i = ulong 0\nif eq i 8\nepbegin -9 0\nret\nend\nif ne epget 48'),
34 ('put epclnt base 0', 'put epclnt base get epclnt base'),
35 ('r = fclose get epdevice 0', 'r = long 0'),
36 ('r = send fd epwire add off pos sub n pos 0', 'r = write fd epwire add off pos sub n pos'),
37 ],
38 'notify': [('put unbytes 0 1', 'put unbytes 0 2'), ('put unlive 0 2', 'put unlive 0 0')],
39}
40
41def compile_omega(tmp, target='endpoint', mutation=None):
42 if hashlib.sha256(OMC.read_bytes()).hexdigest() != SHA:
43 raise AssertionError('compiler binary pin mismatch')
44 actual = subprocess.check_output(['git','-C',str(OMC.parents[2]),'rev-parse','HEAD'],text=True).strip()
45 if actual != PIN:
46 raise AssertionError('compiler source pin mismatch')
47 def dep(path):
48 return subprocess.check_output(['git','-C',str(ROOT.parent/'DriverOmega'),'show',QUEUE+':'+path],text=True)
49 queue = dep('gsp/irqqueue.om')
50 queue = queue[queue.index('note Explicit model-only UVM command queue'):]
51 units = ['fmt','pt','fault']
52 parts = ['om2', 'abstract unirq ulong'] + [(ROOT/'uvm'/f'{u}.om').read_text() for u in units]
53 parts += [queue, dep('gsp/irqcmd.om')]
54 for u in service.UNITS + ['notify'] + (['endpoint'] if target == 'endpoint' else []):
55 text = (ROOT/'uvm'/f'{u}.om').read_text()
56 if u == 'notify':
57 text = text.replace('abstract unirq ulong\n', '')
58 if mutation and u == mutation[0]:
59 if text.count(mutation[1]) != 1:
60 raise AssertionError(f'mutant site count {u}: {text.count(mutation[1])}')
61 text = text.replace(mutation[1],mutation[2])
62 parts.append(text)
63 if target == 'notify':
64 parts.append((ROOT/'tests/uvme_notify.om').read_text())
65 src = '\n'.join(parts)
66 out = tmp/(target+('-mutant' if mutation else ''))
67 p = subprocess.run(PREFIX+[str(OMC)],input=src.encode(),capture_output=True,timeout=120)
68 if p.returncode:
69 import re
70 m = re.search(r'line (\d+)',p.stderr.decode())
71 context = ''
72 if m:
73 n = int(m[1]); context = '\n'.join(f'{i+1}: {x}' for i,x in enumerate(src.splitlines()) if n-5 <= i <= n+2)
74 raise AssertionError(f'compile rc={p.returncode}: {p.stderr.decode()}\n{context}')
75 out.write_bytes(p.stdout); out.chmod(0o755)
76 if not mutation:
77 print(f'{target} SOURCE sha256={hashlib.sha256(src.encode()).hexdigest()} BINARY sha256={hashlib.sha256(p.stdout).hexdigest()}',flush=True)
78 return out
79
80def abi(tmp):
81 out = tmp/'offsets'
82 subprocess.run(PREFIX+['cc','-std=c11','-Wall','-Wextra','-Werror',str(ROOT/'tests/uvme_offsets.c'),'-o',str(out)],check=True)
83 p = subprocess.run(PREFIX+[str(out)],capture_output=True,text=True,check=True)
84 expected = '''fuse_in_header 40
85fuse_in_header.unique 8
86fuse_in_header.pid 32
87fuse_in_header.total_extlen 36
88fuse_out_header 16
89fuse_out_header.error 4
90fuse_out_header.unique 8
91cuse_init_in 16
92cuse_init_out 72
93cuse_init_out.flags 12
94cuse_init_out.max_read 16
95cuse_init_out.spare 32
96fuse_open_in 8
97fuse_open_out 16
98fuse_open_out.open_flags 8
99fuse_release_in 24
100fuse_flush_in 24
101fuse_ioctl_in 32
102fuse_ioctl_in.flags 8
103fuse_ioctl_in.cmd 12
104fuse_ioctl_in.arg 16
105fuse_ioctl_in.in_size 24
106fuse_ioctl_in.out_size 28
107fuse_ioctl_out 16
108fuse_ioctl_out.flags 4
109fuse_ioctl_out.in_iovs 8
110fuse_ioctl_out.out_iovs 12
111fuse_ioctl_iovec 16
112fuse_ioctl_iovec.len 8
113flags 1 2 4 33
114'''
115 assert p.stdout == expected, (p.stdout,expected)
116 print('CUSE ABI PASS sizeof/offsetof measured by host cc; header-sha256='+hashlib.sha256(Path('/usr/include/linux/fuse.h').read_bytes()).hexdigest(),flush=True)
117
118def packet(op, seq, body=b'', pid=None, ext=0):
119 return struct.pack('<IIQQIIIHH',40+len(body),op,seq,0,os.getuid(),os.getgid(),os.getpid() if pid is None else pid,ext,0)+body
120
121def reply(seq, body=b'', error=0):
122 return struct.pack('<IiQ',16+len(body),error,seq)+body
123
124def same_reply(got,want):
125 assert got == want, f'expected={want[:80].hex()} observed={got[:80].hex()} lengths={len(want)},{len(got)}'
126
127def ioctl_body(fh, cmd, data=None, flags=2, arg=65536, ins=None, outs=None):
128 n = 0 if data is None else len(data)
129 return struct.pack('<QIIQII',fh,flags,cmd,arg,n if ins is None else ins,n if outs is None else outs)+(data or b'')
130
131class Server:
132 def __init__(self, binary):
133 self.sock, child = socket.socketpair(socket.AF_UNIX,socket.SOCK_SEQPACKET)
134 self.sock.settimeout(8)
135 blocked=signal.pthread_sigmask(signal.SIG_UNBLOCK,{signal.SIGPIPE})
136 try:
137 self.p = subprocess.Popen(PREFIX+[str(binary),'--fake'],stdin=child,stdout=child,stderr=subprocess.PIPE,close_fds=True,start_new_session=True,restore_signals=True)
138 finally:
139 signal.pthread_sigmask(signal.SIG_SETMASK,blocked)
140 child.close(); self.seq = 0; self.frames = self.bytes = 0
141 def raw(self, data):
142 self.sock.sendall(data)
143 got = self.sock.recv(16384)
144 if not got:
145 rc=self.p.wait(timeout=2)
146 raise AssertionError(f'endpoint closed rc={rc} stderr={self.p.stderr.read().decode()}')
147 self.frames += 1; self.bytes += len(got)
148 return got
149 def call(self, op, body=b'', error=0, output=b'', pid=None, ext=0):
150 self.seq += 1
151 got = self.raw(packet(op,self.seq,body,pid,ext))
152 want = reply(self.seq,output,error)
153 same_reply(got,want)
154 return got
155 def init(self):
156 self.call(14,bytes(8),error=-71)
157 self.call(4096,struct.pack('<4I',8,39,0,1),error=-71)
158 self.call(4096,struct.pack('<4I',7,15,0,1),error=-71)
159 out = struct.pack('<8I',7,39,0,1,9264,9264,0,0)+bytes(40)+b'DEVNAME=omega-uvm-test\0'
160 self.call(4096,struct.pack('<4I',7,39,0,1),output=out)
161 self.call(4096,struct.pack('<4I',7,39,0,1),error=-16)
162 def opened(self):
163 self.seq += 1
164 data = self.raw(packet(14,self.seq,bytes(8)))
165 same_reply(data[:16],reply(self.seq,bytes(16))[:16])
166 fh, flags, padding = struct.unpack('<QII',data[16:])
167 assert fh and flags == 33 and padding == 0
168 return fh
169 def children(self):
170 p = Path(f'/proc/{self.p.pid}/task/{self.p.pid}/children')
171 return [int(x) for x in p.read_text().split()]
172 def descriptors(self):
173 kids = self.children()
174 assert kids
175 for pid in kids:
176 links = [os.readlink(p) for p in Path(f'/proc/{pid}/fd').iterdir()]
177 # stderr, one private socket, and an eventfd only. No CUSE channel/sibling sockets.
178 assert len(links) == 3, (pid,links)
179 assert sum(x.startswith('socket:') for x in links) == 1, (pid,links)
180 assert sum(x == 'anon_inode:[eventfd]' for x in links) == 1, (pid,links)
181 def close(self):
182 self.sock.shutdown(socket.SHUT_RDWR); self.sock.close()
183 try:
184 rc = self.p.wait(timeout=8)
185 except subprocess.TimeoutExpired:
186 os.killpg(self.p.pid,signal.SIGKILL); self.p.wait(); raise
187 err = self.p.stderr.read(); self.p.stderr.close()
188 assert rc == 0, (rc,err)
189 assert not Path(f'/proc/{self.p.pid}').exists()
190 def abort(self):
191 self.sock.close()
192 try:
193 os.killpg(self.p.pid,signal.SIGKILL)
194 except ProcessLookupError:
195 pass
196 self.p.wait()
197 self.p.stderr.close()
198
199class Client:
200 def __init__(self, conn, index):
201 self.conn = conn; self.seq = 1000000+index*10000; self.model = service.Model(); self.frames = 0
202 self.seq += 1; data = self.exchange(packet(14,self.seq,bytes(8)))
203 same_reply(data[:16],reply(self.seq,bytes(16))[:16])
204 self.fh,flags,padding = struct.unpack('<QII',data[16:]); assert flags == 33 and padding == 0
205 self.model.objects[23] = (service.BASE+self.fh*service.WIN,service.WIN)
206 def exchange(self,data):
207 self.conn.send(('frame',data)); out = self.conn.recv(); self.frames += 1
208 if not isinstance(out,bytes): raise AssertionError(out)
209 return out
210 def ioctl(self,cmd,data):
211 size=SIZES[cmd]; assert len(data)==size
212 self.seq += 1
213 got = self.exchange(packet(39,self.seq,ioctl_body(self.fh,cmd)))
214 want = reply(self.seq,struct.pack('<4i',0,4,1,1)+struct.pack('<4Q',65536,size,65536,size))
215 assert got == want, ('retry',cmd,got.hex(),want.hex())
216 self.seq += 1
217 # A different task ID must still use the SAME file-description namespace.
218 got = self.exchange(packet(39,self.seq,ioctl_body(self.fh,cmd,data),pid=os.getpid()+1))
219 self.model.ioctl(cmd,size,data)
220 want = reply(self.seq,bytes(16)+self.model.ioout)
221 same_reply(got,want)
222 def release(self):
223 self.seq += 1
224 got = self.exchange(packet(18,self.seq,struct.pack('<QIIQ',self.fh,0,0,0),pid=0))
225 assert got == reply(self.seq)
226
227
228def client_process(conn,index,barrier):
229 try:
230 c=Client(conn,index)
231 uuid=bytes(range(1,17))
232 reg=bytearray(40); reg[:16]=uuid; struct.pack_into('<III',reg,24,7,11,0)
233 vs=bytearray(32); vs[:16]=uuid; struct.pack_into('<III',vs,16,7,11,19)
234 def mapping(va):
235 b=bytearray(9264); struct.pack_into('<QQQ',b,0,va,service.PAGE,0); b[24:40]=uuid
236 struct.pack_into('<QIII',b,9240,1,7,11,23); return b
237 c.ioctl(39,bytes(8)) # semantic refusal before initialization, not outer ioctl failure
238 c.ioctl(805306369,bytes(16)); c.ioctl(805306369,bytes(16))
239 c.ioctl(37,reg); c.ioctl(25,vs)
240 for _ in range(12): c.ioctl(23,bytes(16))
241 c.ioctl(39,bytes(8))
242 va=service.BASE+index*service.PAGE
243 c.ioctl(33,mapping(va))
244 barrier.wait(timeout=12)
245 c.ioctl(34,struct.pack('<3Q',service.BASE+(1-index)*service.PAGE,service.PAGE,0)) # peer VA must not resolve
246 c.ioctl(34,struct.pack('<3Q',va,service.PAGE,0))
247 barrier.wait(timeout=12)
248 c.ioctl(33,mapping(service.BASE)) # identical VA/UUID/RM handle on distinct opens
249 barrier.wait(timeout=12)
250 if index==0: c.ioctl(34,struct.pack('<3Q',service.BASE,service.PAGE,0))
251 barrier.wait(timeout=12)
252 if index==1:
253 c.ioctl(33,mapping(service.BASE)) # still BUSY: peer free did not remove this mapping
254 c.ioctl(34,struct.pack('<3Q',service.BASE,service.PAGE,0))
255 c.ioctl(38,uuid+bytes(4)); c.ioctl(39,bytes(8)); c.release()
256 conn.send(('done',(c.fh,c.frames)))
257 except BaseException:
258 conn.send(('error',traceback.format_exc()))
259 finally:
260 conn.close()
261
262
263def concurrent_clients(s):
264 ctx=mp.get_context('fork'); barrier=ctx.Barrier(2); workers=[]; mux=selectors.DefaultSelector(); done=[]
265 for index in range(2):
266 parent,child=ctx.Pipe()
267 p=ctx.Process(target=client_process,args=(child,index,barrier)); p.start(); child.close()
268 workers.append((p,parent)); mux.register(parent.fileno(),selectors.EVENT_READ,parent)
269 deadline=time.monotonic()+35
270 try:
271 while len(done)<2:
272 if time.monotonic()>deadline: raise AssertionError('concurrent clients timed out')
273 for key,_ in mux.select(1):
274 conn=key.data; op,data=conn.recv()
275 if op=='frame': conn.send(s.raw(data))
276 elif op=='done':
277 done.append(data); mux.unregister(conn.fileno())
278 else: raise AssertionError(data)
279 for p,conn in workers:
280 p.join(5); assert p.exitcode==0, p.exitcode
281 assert len({x[0] for x in done})==2
282 assert not s.children(), s.children()
283 return done
284 finally:
285 mux.close()
286 for p,conn in workers:
287 conn.close()
288 if p.is_alive(): p.terminate(); p.join(5)
289
290
291def endpoint_suite(binary, quiet=False):
292 s=Server(binary)
293 try:
294 s.init()
295 done=concurrent_clients(s)
296 a=s.opened(); apid=s.children()[0]; b=s.opened()
297 assert a not in [x[0] for x in done] and b>a
298 # This deliberately exceeds the in-flight frame deadline, with no partial request.
299 time.sleep(5.1)
300 s.descriptors()
301 # Kernel may abandon a copyin attempt; no global pending retry state is held.
302 for fh in (a,b):
303 s.call(39,ioctl_body(fh,39),output=struct.pack('<4i',0,4,1,1)+struct.pack('<4Q',65536,8,65536,8))
304 for flags in (0,1,3,4,8,16,32):
305 s.call(39,ioctl_body(a,39,flags=flags),error=-22)
306 for cmd in (0,999,4294967295): s.call(39,ioctl_body(a,cmd),error=-22)
307 for cmd,size in SIZES.items():
308 for data in (bytes(1),bytes(size+1)):
309 s.call(39,ioctl_body(a,cmd,data),error=-22)
310 s.call(39,ioctl_body(a,cmd,bytes(size),outs=size+1),error=-22)
311 s.call(39,ioctl_body(a,cmd,bytes(size))+b'x',error=-22)
312 for addr in (0,281474976710656,18446744073709551615,281474976710655):
313 s.call(39,ioctl_body(a,39,arg=addr),error=-14)
314 s.call(39,ioctl_body(a,39)+b'x',error=-22)
315 s.call(39,bytes(31),error=-22)
316 s.call(14,bytes(8),error=-71,ext=1)
317 s.call(25,struct.pack('<QIIQ',a,0,0,0))
318 s.call(25,struct.pack('<QIIQ',999,0,0,0),error=-9)
319 # Kill one actual private worker: EPIPE/EOF must not kill parent or another client.
320 kids=s.children(); assert len(kids)==2
321 status=dict(line.split(':',1) for line in Path(f'/proc/{s.p.pid}/status').read_text().splitlines() if ':' in line)
322 pipebit=1 << (signal.SIGPIPE-1)
323 assert all(not (int(status[k].strip(),16) & pipebit) for k in ('SigIgn','SigBlk','SigCgt')), status
324 death=os.pidfd_open(apid)
325 try:
326 os.kill(apid,signal.SIGKILL)
327 with selectors.DefaultSelector() as deathwait:
328 deathwait.register(death,selectors.EVENT_READ)
329 assert deathwait.select(5), 'worker exit barrier failed'
330 finally:
331 os.close(death)
332 s.call(39,ioctl_body(a,39,bytes(8)),error=-5)
333 s.call(39,ioctl_body(a,39),error=-9)
334 m=service.Model(); m.ioctl(39,8,bytes(8))
335 s.call(39,ioctl_body(b,39,bytes(8)),output=bytes(16)+m.ioout)
336 s.call(18,struct.pack('<QIIQ',b,0,0,0),pid=0)
337 s.call(18,struct.pack('<QIIQ',b,0,0,0),error=-9,pid=0)
338 for fh,_ in done: s.call(39,ioctl_body(fh,39),error=-9)
339 # Fill and release the bounded handle table; replacements never reuse handles.
340 handles=[s.opened() for _ in range(8)]
341 s.call(14,bytes(8),error=-24)
342 for fh in handles: s.call(18,struct.pack('<QIIQ',fh,0,0,0),pid=0)
343 assert not s.children()
344 # Leave two open: connection EOF must close/reap both workers.
345 s.opened(); s.opened(); survivors=s.children(); s.close()
346 assert all(not Path(f'/proc/{pid}').exists() for pid in survivors), survivors
347 if not quiet: print(f'CUSE FAKE PASS {s.frames} frames {s.bytes} reply bytes; 2 concurrent client processes; per-open isolation, lifecycle, worker death, ABI negatives',flush=True)
348 except BaseException:
349 s.abort(); raise
350
351
352def notification(binary, quiet=False):
353 p=subprocess.run(PREFIX+[str(binary)],capture_output=True,timeout=10)
354 assert p.returncode==0 and not p.stdout and not p.stderr, (p.returncode,p.stdout,p.stderr)
355 if not quiet: print('NOTIFICATION PASS typed eventfd wake/coalescing, ring dedup, PTE plus invalidate/replay order, overflow refusal, empty poll, stale token, no reopen; no VFIO',flush=True)
356
357
358def main():
359 parser=argparse.ArgumentParser()
360 parser.add_argument('--mutants',action='store_true')
361 parser.add_argument('--emit-dir',type=Path,help='retain passed Omega and kernel-consumer binaries; never opens a device')
362 args=parser.parse_args()
363 print('COMPILER source='+PIN+' sha256='+SHA+' dependency=omega-mv#1045',flush=True)
364 with tempfile.TemporaryDirectory(prefix='uvme-') as td:
365 tmp=Path(td); abi(tmp)
366 kernel=tmp/'kernel-client'
367 subprocess.run(PREFIX+['cc','-D_GNU_SOURCE','-std=c11','-Wall','-Wextra','-Werror',str(ROOT/'tests/uvme_kernel.c'),'-o',str(kernel)],check=True)
368 print('KERNEL CONSUMER BUILD PASS; execution NOT_RUN (no authorized CUSE node)',flush=True)
369 endpoint=compile_omega(tmp); endpoint_suite(endpoint)
370 notify=compile_omega(tmp,'notify'); notification(notify)
371 # A corrupted output byte is rejected independently of implementation mutants.
372 expected=reply(1,bytes(16)); wrong=bytearray(expected); wrong[-1]=1
373 try:
374 same_reply(bytes(wrong),expected)
375 except AssertionError:
376 print('NEGATIVE CONTROL PASS altered response byte rejected by the live comparator',flush=True)
377 else:
378 raise AssertionError('altered response byte accepted')
379 if args.mutants:
380 for unit,pairs in MUTANTS.items():
381 for index,(old,new) in enumerate(pairs,1):
382 binary=compile_omega(tmp,'endpoint' if unit=='endpoint' else 'notify',(unit,old,new))
383 try:
384 (endpoint_suite if unit=='endpoint' else notification)(binary,quiet=True)
385 except (AssertionError,OSError,EOFError,subprocess.TimeoutExpired) as e:
386 if unit=='endpoint' and index==5:
387 assert 'endpoint closed rc=-13 ' in str(e), ('not a demonstrated SIGPIPE kill',str(e))
388 print(f'MUTANT KILLED {unit}:{index} {str(e).splitlines()[0][:160]}',flush=True)
389 else: raise AssertionError(f'MUTANT SURVIVED {unit}:{index}')
390 if args.emit_dir:
391 args.emit_dir.mkdir(parents=True,exist_ok=True)
392 for path in (endpoint,notify,kernel):
393 dest=args.emit_dir/path.name
394 dest.write_bytes(path.read_bytes()); dest.chmod(0o755)
395 print('ARTIFACTS '+str(args.emit_dir),flush=True)
396 print('UVME PASS host fake-kernel and eventfd; real CUSE ioctl hop NOT_RUN; chip NOT_RUN',flush=True)
397
398if __name__=='__main__': main()