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 / rme_check.py

259 lines · 14712 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Independent model/vendor oracles and fake CUSE kernel. No device node is opened.
3Run ONLY inside the repository's device-hiding bwrap safety boundary.
4"""
5import argparse, hashlib, os, random, select, signal, socket, struct, subprocess, tempfile
6from pathlib import Path
7ROOT=Path(__file__).resolve().parents[1]
8OMC=Path(os.environ.get('RM_OMC',str(ROOT.parents[1]/'omega-mv/seed/out/omc')))
9SHA=dict(line.split('=',1) for line in (ROOT/'rm/omc.pin').read_text().splitlines() if line and not line.startswith('#'))['OMC_SHA256']
10OGKM=Path(os.environ.get('OGKM',str(Path.home()/'workspace/_ext/open-gpu-kernel-modules-580.173.02')))
11UNITS=['chan/params.om','gsp/rpc.om','rm/ioctl.om','rm/handles.om','rm/memory.om','rm/model.om','rm/uvmclient.om','rm/dispatch.om','rm/import.om','rm/endpoint.om']
12SIZES={43:32,42:32,41:16,78:56,79:32,87:64,88:48,74:184,200:4608,201:4,206:16,207:16,210:72}
13CLASSES={65:0,128:56,8320:4,37105:56,41068:20,36967:12,51567:368,52928:0}
14PARENTS={128:65,8320:128,37105:128,41068:128,36967:41068,51567:41068,52928:51567}
15STATUS={0:0,1:31,2:51,3:54,4:52,5:81,6:86}
16TOKEN=0xc36f0108;SCHED=0xa06c0101
17
18def build(tmp, mutation=None, trace=False):
19 if hashlib.sha256(OMC.read_bytes()).hexdigest()!=SHA: raise RuntimeError('RM compiler pin mismatch')
20 parts=['om2']
21 for unit in UNITS:
22 text=(ROOT/unit).read_text()
23 if trace and unit=='rm/endpoint.om':text=text.split('fn main to int\n',1)[0]
24 if mutation and unit==mutation[0]:
25 old,new=mutation[1:]
26 if text.count(old)!=1: raise RuntimeError(f'mutation site {unit}: {text.count(old)}')
27 text=text.replace(old,new)
28 parts.append(text)
29 if trace: parts.append((ROOT/'tests/rme_trace.om').read_text())
30 src='\n'.join(parts);(tmp/'rme.om').write_text(src)
31 p=subprocess.run([str(OMC)],input=src.encode(),capture_output=True)
32 if p.returncode:
33 import re
34 msg=p.stderr.decode();m=re.search(r'line (\d+)',msg)
35 if m:
36 n=int(m[1]);msg+='\n'+'\n'.join(f'{j+1}: {s}' for j,s in enumerate(src.splitlines()) if n-6<=j<=n+3)
37 raise RuntimeError(msg)
38 binary=tmp/'rme';binary.write_bytes(p.stdout);binary.chmod(0o700)
39 return binary
40
41def cc(tmp,name):
42 inc=['src/common/sdk/nvidia/inc','kernel-open/common/inc','src/nvidia/arch/nvalloc/unix/include','src/common/inc']
43 out=tmp/name
44 subprocess.run(['cc','-std=c11','-O1','-Wall','-Wextra','-Werror',*[f'-I{OGKM/p}' for p in inc],str(ROOT/'tests'/f'{name}.c'),'-o',str(out)],check=True)
45 return out
46
47def layout(tmp):
48 text=subprocess.check_output([str(cc(tmp,'rme_offsets'))],text=True)
49 expected={'alloc':32,'alloc.ptr':16,'alloc.size':24,'alloc.status':28,'control':32,'control.ptr':16,'control.size':24,'control.status':28,'free':16,'free.status':12,'map':56,'map.fd':48,'map.status':40,'unmap':32,'unmap.status':24,'mapdma':64,'mapdma.status':56,'unmapdma':48,'unmapdma.status':40,'heap':184,'heap.status':20,'card':72,'register':4,'event':16,'event.status':12,'version':72,'xfer':16}
50 expected.update({'gr':32,'gr.ptr':8,'classes':16,'gid':268,'idv2':32})
51 got={line.split()[0]:int(line.split()[1]) for line in text.splitlines() if len(line.split())==2}
52 assert got==expected,(got,expected)
53 assert 'escapes 43 42 41 78 79 87 88 74 200 201 206 210\n' in text
54 assert 'status 31 51 54 52 81 86\n' in text
55 print('RM vendor 580.173.02 layout oracle PASS')
56
57class Server:
58 def __init__(self,binary):
59 self.sock,child=socket.socketpair(socket.AF_UNIX,socket.SOCK_SEQPACKET);self.sock.settimeout(8)
60 self.proc=subprocess.Popen([str(binary),'--fake','--host-model',str(ROOT/'rm/host-model.fixture')],stdin=child,stdout=child,stderr=subprocess.PIPE,start_new_session=True);child.close();self.seq=0
61 self.frame(4096,struct.pack('<IIII',7,31,0,1))
62 def frame(self,op,body=b'',error=0):
63 self.seq+=1;self.sock.send(struct.pack('<IIQQIIII',40+len(body),op,self.seq,0,os.getuid(),os.getgid(),os.getpid(),0)+body)
64 data=self.sock.recv(16384);assert len(data)>=16
65 n,err,seq=struct.unpack_from('<IiQ',data);assert (n,err,seq)==(len(data),error,self.seq),(op,n,err,error)
66 return data[16:]
67 def open(self): return struct.unpack_from('<Q',self.frame(14,bytes(8)))[0]
68 def release(self,fh,error=0):return self.frame(18,struct.pack('<QIIQ',fh,0,0,0),error)
69 def raw(self,fh,cmd,ins=b'',outs=None,arg=0x100000,flags=2,error=0):
70 if outs is None:outs=len(ins)
71 return self.frame(39,struct.pack('<QIIQII',fh,flags,cmd,arg,len(ins),outs)+ins,error)
72 def ioctl(self,fh,nr,header,params=b''):
73 cmd=0xc0004600|(len(header)<<16)|nr
74 retry=self.raw(fh,cmd)
75 assert struct.unpack_from('<IIII',retry)==(0,4,1,1)
76 assert struct.unpack_from('<QQQQ',retry,16)==(0x100000,len(header),0x100000,len(header))
77 out=self.raw(fh,cmd,header)
78 if params:
79 assert struct.unpack_from('<IIII',out)==(0,4,2,2)
80 ptr=struct.unpack_from('<Q',header,16)[0]
81 assert struct.unpack_from('<QQQQQQQQ',out,16)==(0x100000,len(header),ptr,len(params),0x100000,len(header),ptr,len(params))
82 out=self.raw(fh,cmd,header+params)
83 assert out[:16]==bytes(16)
84 assert len(out)==16+len(header)+len(params)
85 return out[16:]
86 def alloc(self,fh,cli,par,obj,cls,params=None):
87 if params is None:params=bytes(CLASSES.get(cls,0))
88 h=struct.pack('<IIIIQII',cli,par,obj,cls,0x200000 if params else 0,len(params),0xdeadbeef)
89 out=self.ioctl(fh,43,h,params)
90 return struct.unpack_from('<I',out,28)[0],struct.unpack_from('<I',out,8)[0]
91 def free(self,fh,cli,par,obj):
92 out=self.ioctl(fh,41,struct.pack('<IIII',cli,par,obj,0xdeadbeef));return struct.unpack_from('<I',out,12)[0]
93 def ctrl(self,fh,cli,obj,cmd,params):
94 out=self.ioctl(fh,42,struct.pack('<IIIIQII',cli,obj,cmd,0,0x200000 if params else 0,len(params),0xdeadbeef),params)
95 return struct.unpack_from('<I',out,28)[0],out[32:]
96 def close(self):
97 self.sock.close()
98 try:self.proc.wait(timeout=8)
99 except subprocess.TimeoutExpired:os.killpg(self.proc.pid,signal.SIGKILL);self.proc.wait();raise
100 assert self.proc.returncode==0,self.proc.stderr.read()
101 def abort(self):
102 self.sock.close()
103 if self.proc.poll() is None:os.killpg(self.proc.pid,signal.SIGKILL)
104 self.proc.wait()
105
106class Model:
107 """Independent tree-of-objects specification; no slots, byte codecs or RM routing reuse."""
108 def __init__(self):self.nodes={};self.seen=set();self.roots=0
109 def alloc(self,cli,par,obj,cls):
110 if cls not in CLASSES:return 86,obj
111 if cls==65:
112 if (cli,par,obj)!=(0,0,0):return 31,obj
113 self.roots+=1;cli=obj=self.roots;par=obj
114 else:
115 parent=self.nodes.get((cli,par))
116 if parent is None or parent[1]!=PARENTS[cls]:return 54,obj
117 if obj==0:return 31,obj
118 if (cli,obj) in self.seen:return 52,obj
119 if len(self.seen)==64:return 81,obj
120 self.nodes[cli,obj]=(par,cls);self.seen.add((cli,obj));return 0,obj
121 def free(self,cli,par,obj):
122 node=self.nodes.get((cli,obj))
123 if node is None:return 51
124 if node[0]!=par:return 54
125 dead={obj}
126 while True:
127 more={o for (c,o),(p,_) in self.nodes.items() if c==cli and p in dead}
128 if more<=dead:break
129 dead|=more
130 self.nodes={key:value for key,value in self.nodes.items() if key[0]!=cli or key[1] not in dead}
131 return 0
132
133def exercise(binary,red=False):
134 s=Server(binary)
135 try:
136 a=s.open();b=s.open();m=Model()
137 def alloc(cli,par,obj,cls):
138 expected=m.alloc(cli,par,obj,cls);observed=s.alloc(a,cli,par,obj,cls)
139 if red:expected=(31,0)
140 assert observed==expected,('alloc',cli,par,obj,cls,observed,expected)
141 return observed[1]
142 def free(cli,par,obj):
143 expected=m.free(cli,par,obj);observed=s.free(a,cli,par,obj)
144 assert observed==expected,('free',cli,par,obj,observed,expected)
145 root=alloc(0,0,0,65);dev=alloc(root,root,100,128)
146 alloc(root,dev,101,8320);alloc(root,dev,102,41068)
147 alloc(root,101,103,128) # Wrong class parent.
148 assert s.alloc(b,root,dev,100,8320)[0]==54 # per-open isolation.
149 root2=alloc(0,0,0,65);alloc(root2,root2,200,128)
150 alloc(root2,dev,201,8320) # cross-client parent.
151 assert s.ctrl(a,root,102,SCHED,b'\1\0\0')[0]==0
152 assert s.ctrl(a,root,101,SCHED,b'\1\0\0')[0]==54
153 assert s.ctrl(a,root2,102,SCHED,b'\1\0\0')[0]==51
154 free(root,root,dev);free(root,dev,101);free(root,dev,dev);alloc(root,root,100,128)
155 # Explicit events remain refused; host memory rejects unknown ownership.
156 for nr in (206,207):
157 out=s.ioctl(a,nr,bytes(16))
158 assert struct.unpack_from('<I',out,12)[0]==86
159 s.raw(a,0xc00446c9,bytes(4),error=-9)
160 s.raw(a,0xc01046ff,bytes(16),error=-22)
161 s.raw(a,0xc01f462b,bytes(31),error=-22)
162 s.raw(a,0xc021462b,bytes(33),error=-22)
163 s.raw(a,0x8020462b,bytes(32),error=-22)
164 s.raw(a,0xc020472b,bytes(32),error=-22)
165 s.raw(a,0xc020462b,bytes(32),arg=0,error=-14)
166 s.raw(a,0xc020462b,bytes(32),flags=0,error=-22)
167 h=struct.pack('<IIIIQII',root,root,999,128,0x200000,4097,0)
168 s.raw(a,0xc020462b,h,error=-22)
169 h=struct.pack('<IIIIQII',root,root,999,128,0xffffffffffffffff,56,0)
170 s.raw(a,0xc020462b,h,error=-14)
171 rng=random.Random(2718)
172 # Hundreds of interleaved valid/invalid tree mutations, including exhausted tombstones.
173 for _ in range(320):
174 cli=rng.choice([root,root2,999]);par=rng.choice([root,root2,200,201,999]);obj=rng.randrange(200,240)
175 if rng.randrange(3):alloc(cli,par,obj,rng.choice([128,8320,41068]))
176 else:free(cli,par,obj)
177 for obj in range(300,370):alloc(root2,200,obj,8320)
178 free(root2,root2,root2);free(root2,root2,root2)
179 opened=[s.open() for _ in range(6)];s.frame(14,bytes(8),error=-24)
180 s.release(a);s.release(a,error=-9);s.raw(a,0xc0104629,bytes(16),error=-9)
181 fresh=s.open();assert fresh not in [a,b,*opened]
182 assert s.alloc(fresh,root,root,100,128)[0]==54
183 s.close()
184 except BaseException:s.abort();raise
185
186MUTANTS=[
187 ('stale-handle','rm/handles.om','if rmseen t cli obj','if false'),
188 ('wrong-parent','rm/handles.om','if not rmparent cls get t add mul p 5 4','if false'),
189 ('size-off-by-one','rm/ioctl.om','if ne cmd or or ulong 3221225472 shl n 16 or ulong 17920 nr','if false'),
190 ('cascade-skip','rm/handles.om','if rmchild t cli get t add k 3','if false'),
191 ('status-map','rm/ioctl.om','if eq code 2\nret 51','if eq code 2\nret 31'),
192 ('cross-client','rm/handles.om','if eq get t add k 2 cli\nret j','if true\nret j'),
193 ('unknown-escape','rm/ioctl.om','if eq n 0\nret 0','if eq n 0\nret 16'),
194 ('double-free','rm/handles.om','if eq s 64\nret 2','if eq s 64\nret 0'),
195 ('oversized-payload','rm/endpoint.om','if gt p 4096','if gt p 8192'),
196 ('control-object-class','rm/dispatch.om','if ne cls 41068','if false'),
197]
198def workers(binary):
199 s=Server(binary)
200 try:
201 a=s.open()
202 children=Path(f'/proc/{s.proc.pid}/task/{s.proc.pid}/children')
203 first=set(map(int,children.read_text().split()));assert len(first)==1
204 b=s.open()
205 second=set(map(int,children.read_text().split()))-first;assert len(second)==1
206 assert s.alloc(a,0,0,0,65)==(0,1)
207 assert s.alloc(b,0,0,0,65)==(0,1)
208 # A worker owns stderr and its private channel only: no fake kernel socket or sibling endpoint.
209 for pid in first|second:
210 fds=list(Path(f'/proc/{pid}/fd').iterdir())
211 assert len(fds)==2,[(str(fd),os.readlink(fd)) for fd in fds]
212 dead=second.pop();pidfd=os.pidfd_open(dead)
213 try:
214 os.kill(dead,signal.SIGKILL)
215 assert select.select([pidfd],[],[],8)[0],'worker death was not observed'
216 finally:os.close(pidfd)
217 s.raw(b,0xc0104629,bytes(16),error=-5)
218 s.raw(b,0xc0104629,bytes(16),error=-9)
219 assert s.alloc(a,1,1,100,128)==(0,100)
220 s.close()
221 except BaseException:s.abort();raise
222 print('RM worker fd isolation / dead-worker SIGPIPE / surviving peer PASS')
223
224def routing(tmp):
225 folder=tmp/'route';folder.mkdir()
226 trace=build(folder,trace=True)
227 data=subprocess.check_output([str(trace)],timeout=8)
228 expected=struct.pack('<IIII',0,1,103,1)
229 expected+=struct.pack('<IIIIIIII',1,0,1,65,0,120,0,0)
230 expected+=struct.pack('<II',1,0)+b'aien-ogd'+bytes(104)
231 expected+=struct.pack('<III',81,1,64)
232 assert data==expected,(data.hex(),expected.hex())
233 print('RM GSP frame publication / refusal rollback PASS (host model, not firmware completion)')
234def main():
235 p=argparse.ArgumentParser();p.add_argument('--mutants',action='store_true');p.add_argument('--build',action='store_true');args=p.parse_args()
236 assert os.environ.get('AIEN_TEST_CPUS')=='10-14','required CPU safety boundary'
237 assert not Path('/dev/nvidiactl').exists() and not Path('/dev/cuse').exists(),'device-hiding bwrap required'
238 with tempfile.TemporaryDirectory(prefix='ogd-rme-') as d:
239 tmp=Path(d);binary=build(tmp)
240 print(f'RM compiler SHA256 {SHA}')
241 print(f'RM endpoint source SHA256 {hashlib.sha256((tmp/"rme.om").read_bytes()).hexdigest()}')
242 print(f'RM endpoint ELF SHA256 {hashlib.sha256(binary.read_bytes()).hexdigest()}')
243 if args.build:print('RM endpoint compile PASS');return
244 layout(tmp);exercise(binary);print('RM handle differential / fake CUSE kernel PASS')
245 try:exercise(binary,red=True)
246 except AssertionError:print('RM independent model red control PASS (deliberate mismatch rejected)')
247 else:raise AssertionError('red control accepted mismatch')
248 consumer=cc(tmp,'rme_consumer');subprocess.run([str(consumer),str(binary),str(ROOT/'rm/host-model.fixture')],check=True,timeout=30)
249 routing(tmp)
250 workers(binary)
251 if args.mutants:
252 for name,unit,old,new in MUTANTS:
253 with tempfile.TemporaryDirectory(dir=tmp) as md:
254 mutant=build(Path(md),(unit,old,new))
255 try:exercise(mutant)
256 except (AssertionError,ConnectionError,socket.timeout):print(f'RM mutant {name} KILLED')
257 else:raise AssertionError(f'survived behavior mutant {name}')
258 print('RM endpoint HOST_EXERCISED PASS; CHIP/LIVE_RM/VFIO NOT_RUN')
259if __name__=='__main__':main()