xref: /linux/tools/testing/selftests/drivers/net/psp.py (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0
3
4"""Test suite for PSP capable drivers."""
5
6import errno
7import fcntl
8import os
9import socket
10import struct
11import termios
12import time
13
14from contextlib import contextmanager
15
16from lib.py import defer
17from lib.py import ksft_run, ksft_exit, ksft_pr
18from lib.py import ksft_true, ksft_eq, ksft_ne, ksft_gt, ksft_raises
19from lib.py import ksft_not_none
20from lib.py import ksft_variants, KsftNamedVariant
21from lib.py import KsftSkipEx, KsftFailEx
22from lib.py import NetDrvEpEnv, NetDrvContEnv
23from lib.py import Netlink, NlError, PSPFamily, RtnlFamily
24from lib.py import NetNSEnter
25from lib.py import bkg, rand_port, wait_port_listen
26from lib.py import ip
27
28TCP_ULP = 31
29
30
31def _get_outq(s):
32    one = b'\0' * 4
33    outq = fcntl.ioctl(s.fileno(), termios.TIOCOUTQ, one)
34    return struct.unpack("I", outq)[0]
35
36
37def _send_with_ack(cfg, msg):
38    cfg.comm_sock.send(msg)
39    response = cfg.comm_sock.recv(4)
40    if response != b'ack\0':
41        raise RuntimeError("Unexpected server response", response)
42
43
44def _remote_read_len(cfg):
45    cfg.comm_sock.send(b'read len\0')
46    return int(cfg.comm_sock.recv(1024)[:-1].decode('utf-8'))
47
48
49def _make_clr_conn(cfg, ipver=None):
50    _send_with_ack(cfg, b'conn clr\0')
51    remote_addr = cfg.remote_addr_v[ipver] if ipver else cfg.remote_addr
52    s = socket.create_connection((remote_addr, cfg.comm_port), )
53    return s
54
55
56def _make_psp_conn(cfg, version=0, ipver=None):
57    _send_with_ack(cfg, b'conn psp\0' + struct.pack('BB', version, version))
58    remote_addr = cfg.remote_addr_v[ipver] if ipver else cfg.remote_addr
59    s = socket.create_connection((remote_addr, cfg.comm_port), )
60    return s
61
62
63@contextmanager
64def _make_lo_conn():
65    # After tx-assoc, the client's egress is dropped, since lo has no
66    # psp_dev, so its FIN never reaches the server. Closing the server
67    # resets the unaccepted child, and the client accepts the cleartext
68    # RST because it hasn't received any PSP traffic yet.
69    with socket.create_server(("localhost", 0)) as srv, \
70         socket.create_connection(srv.getsockname()[:2]) as s:
71        yield s
72
73
74def _close_conn(cfg, s):
75    _send_with_ack(cfg, b'data close\0')
76    s.close()
77
78
79def _close_psp_conn(cfg, s):
80    _close_conn(cfg, s)
81
82
83def _spi_xchg(s, rx):
84    s.send(struct.pack('I', rx['spi']) + rx['key'])
85    tx = s.recv(4 + len(rx['key']))
86    return {
87        'spi': struct.unpack('I', tx[:4])[0],
88        'key': tx[4:]
89    }
90
91
92def _send_careful(cfg, s, rounds):
93    data = b'0123456789' * 200
94    for i in range(rounds):
95        n = 0
96        for _ in range(10): # allow 10 retries
97            try:
98                n += s.send(data[n:], socket.MSG_DONTWAIT)
99                if n == len(data):
100                    break
101            except BlockingIOError:
102                time.sleep(0.05)
103        else:
104            rlen = _remote_read_len(cfg)
105            outq = _get_outq(s)
106            report = f'sent: {i * len(data) + n} remote len: {rlen} outq: {outq}'
107            raise RuntimeError(report)
108
109    return len(data) * rounds
110
111
112def _check_data_rx(cfg, exp_len):
113    read_len = -1
114    for _ in range(30):
115        cfg.comm_sock.send(b'read len\0')
116        read_len = int(cfg.comm_sock.recv(1024)[:-1].decode('utf-8'))
117        if read_len == exp_len:
118            break
119        time.sleep(0.01)
120    ksft_eq(read_len, exp_len)
121
122
123def _recv_careful(s, target, timeout=2):
124    """Read exactly target bytes, tolerating short reads"""
125    data = b''
126    end = time.monotonic() + timeout
127    while time.monotonic() < end:
128        try:
129            data += s.recv(target - len(data), socket.MSG_DONTWAIT)
130            if len(data) == target:
131                return data
132        except BlockingIOError:
133            time.sleep(0.001)
134    raise KsftFailEx(f"short read, got {len(data)} of {target} bytes")
135
136
137def _req_echo(cfg, s):
138    """Ask the peer to echo, and check the reply arrives intact"""
139    _send_with_ack(cfg, b'data echo\0')
140    ksft_eq(_recv_careful(s, 5), b'echo\0')
141
142
143def _check_data_outq(s, exp_len, force_wait=False):
144    outq = 0
145    for _ in range(10):
146        outq = _get_outq(s)
147        if not force_wait and outq == exp_len:
148            break
149        time.sleep(0.01)
150    ksft_eq(outq, exp_len)
151
152
153def _get_stat(cfg, key):
154    return cfg.pspnl.get_stats({'dev-id': cfg.psp_dev_id})[key]
155
156#
157# Test case boiler plate
158#
159
160def _init_psp_dev(cfg, use_psp_ifindex=False):
161    if not hasattr(cfg, 'psp_dev_id'):
162        # Figure out which local device we are testing against
163        # For NetDrvContEnv: use psp_ifindex instead of ifindex
164        target_ifindex = cfg.psp_ifindex if use_psp_ifindex else cfg.ifindex
165        for dev in cfg.pspnl.dev_get({}, dump=True):
166            if dev['ifindex'] == target_ifindex:
167                cfg.psp_info = dev
168                cfg.psp_dev_id = cfg.psp_info['id']
169                break
170        else:
171            raise KsftSkipEx("No PSP devices found")
172
173    # Enable PSP if necessary
174    cap = cfg.psp_info['psp-versions-cap']
175    ena = cfg.psp_info['psp-versions-ena']
176    if cap != ena:
177        cfg.pspnl.dev_set({'id': cfg.psp_dev_id, 'psp-versions-ena': cap})
178        defer(cfg.pspnl.dev_set, {'id': cfg.psp_dev_id,
179                                  'psp-versions-ena': ena })
180
181#
182# Test cases
183#
184
185def dev_list_devices(cfg):
186    """ Dump all devices """
187    _init_psp_dev(cfg)
188
189    devices = cfg.pspnl.dev_get({}, dump=True)
190
191    found = False
192    for dev in devices:
193        found |= dev['id'] == cfg.psp_dev_id
194    ksft_true(found)
195
196
197def dev_get_device(cfg):
198    """ Get the device we intend to use """
199    _init_psp_dev(cfg)
200
201    dev = cfg.pspnl.dev_get({'id': cfg.psp_dev_id})
202    ksft_eq(dev['id'], cfg.psp_dev_id)
203
204
205def dev_get_device_bad(cfg):
206    """ Test getting device which doesn't exist """
207    raised = False
208    try:
209        cfg.pspnl.dev_get({'id': 1234567})
210    except NlError as e:
211        ksft_eq(e.nl_msg.error, -errno.ENODEV)
212        raised = True
213    ksft_true(raised)
214
215
216def dev_rotate(cfg):
217    """ Test key rotation """
218    _init_psp_dev(cfg)
219
220    prev_rotations = _get_stat(cfg, 'key-rotations')
221
222    rot = cfg.pspnl.key_rotate({"id": cfg.psp_dev_id})
223    ksft_eq(rot['id'], cfg.psp_dev_id)
224    rot = cfg.pspnl.key_rotate({"id": cfg.psp_dev_id})
225    ksft_eq(rot['id'], cfg.psp_dev_id)
226
227    cur_rotations = _get_stat(cfg, 'key-rotations')
228    ksft_eq(cur_rotations, prev_rotations + 2)
229
230
231def dev_rotate_spi(cfg):
232    """ Test key rotation and SPI check """
233    _init_psp_dev(cfg)
234
235    top_a = top_b = 0
236    with _make_lo_conn() as s:
237        assoc_a = cfg.pspnl.rx_assoc({"version": 0,
238                                     "dev-id": cfg.psp_dev_id,
239                                     "sock-fd": s.fileno()})
240        top_a = assoc_a['rx-key']['spi'] >> 31
241    rot = cfg.pspnl.key_rotate({"id": cfg.psp_dev_id})
242    with _make_lo_conn() as s:
243        ksft_eq(rot['id'], cfg.psp_dev_id)
244        assoc_b = cfg.pspnl.rx_assoc({"version": 0,
245                                    "dev-id": cfg.psp_dev_id,
246                                    "sock-fd": s.fileno()})
247        top_b = assoc_b['rx-key']['spi'] >> 31
248    ksft_ne(top_a, top_b)
249
250
251def assoc_basic(cfg):
252    """ Test creating associations """
253    _init_psp_dev(cfg)
254
255    with _make_lo_conn() as s:
256        assoc = cfg.pspnl.rx_assoc({"version": 0,
257                                  "dev-id": cfg.psp_dev_id,
258                                  "sock-fd": s.fileno()})
259        ksft_eq(assoc['dev-id'], cfg.psp_dev_id)
260        ksft_gt(assoc['rx-key']['spi'], 0)
261        ksft_eq(len(assoc['rx-key']['key']), 16)
262
263        assoc = cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
264                                  "version": 0,
265                                  "tx-key": assoc['rx-key'],
266                                  "sock-fd": s.fileno()})
267        ksft_eq(len(assoc), 0)
268
269
270def assoc_bad_dev(cfg):
271    """ Test creating associations with bad device ID """
272    _init_psp_dev(cfg)
273
274    with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
275        with ksft_raises(NlError) as cm:
276            cfg.pspnl.rx_assoc({"version": 0,
277                              "dev-id": cfg.psp_dev_id + 1234567,
278                              "sock-fd": s.fileno()})
279        ksft_eq(cm.exception.nl_msg.error, -errno.ENODEV)
280
281
282def assoc_sk_only_conn(cfg):
283    """ Test creating associations based on socket """
284    _init_psp_dev(cfg)
285
286    with _make_clr_conn(cfg) as s:
287        assoc = cfg.pspnl.rx_assoc({"version": 0,
288                                  "sock-fd": s.fileno()})
289        ksft_eq(assoc['dev-id'], cfg.psp_dev_id)
290        cfg.pspnl.tx_assoc({"version": 0,
291                          "tx-key": assoc['rx-key'],
292                          "sock-fd": s.fileno()})
293        _close_conn(cfg, s)
294
295
296def assoc_sk_only_mismatch(cfg):
297    """ Test creating associations based on socket (dev mismatch) """
298    _init_psp_dev(cfg)
299
300    with _make_clr_conn(cfg) as s:
301        with ksft_raises(NlError) as cm:
302            cfg.pspnl.rx_assoc({"version": 0,
303                              "dev-id": cfg.psp_dev_id + 1234567,
304                              "sock-fd": s.fileno()})
305        the_exception = cm.exception
306        ksft_eq(the_exception.nl_msg.extack['bad-attr'], ".dev-id")
307        ksft_eq(the_exception.nl_msg.error, -errno.EINVAL)
308        _close_conn(cfg, s)
309
310
311def assoc_sk_only_mismatch_tx(cfg):
312    """ Test creating associations based on socket (dev mismatch) """
313    _init_psp_dev(cfg)
314
315    with _make_clr_conn(cfg) as s:
316        with ksft_raises(NlError) as cm:
317            assoc = cfg.pspnl.rx_assoc({"version": 0,
318                                      "sock-fd": s.fileno()})
319            cfg.pspnl.tx_assoc({"version": 0,
320                              "tx-key": assoc['rx-key'],
321                              "dev-id": cfg.psp_dev_id + 1234567,
322                              "sock-fd": s.fileno()})
323        the_exception = cm.exception
324        ksft_eq(the_exception.nl_msg.extack['bad-attr'], ".dev-id")
325        ksft_eq(the_exception.nl_msg.error, -errno.EINVAL)
326        _close_conn(cfg, s)
327
328
329def assoc_sk_only_unconn(cfg):
330    """ Test creating associations based on socket (unconnected, should fail) """
331    _init_psp_dev(cfg)
332
333    with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
334        with ksft_raises(NlError) as cm:
335            cfg.pspnl.rx_assoc({"version": 0,
336                              "sock-fd": s.fileno()})
337        the_exception = cm.exception
338        ksft_eq(the_exception.nl_msg.extack['miss-type'], "dev-id")
339        ksft_eq(the_exception.nl_msg.error, -errno.EINVAL)
340
341
342def assoc_rx_unconnected(cfg):
343    """ Test that an Rx assoc is rejected on an unconnected socket """
344    _init_psp_dev(cfg)
345
346    with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
347        with ksft_raises(NlError) as cm:
348            cfg.pspnl.rx_assoc({"version": 0,
349                                "dev-id": cfg.psp_dev_id,
350                                "sock-fd": s.fileno()})
351        ksft_eq(cm.exception.nl_msg.error, -errno.ENOTCONN)
352        ksft_eq(cm.exception.nl_msg.extack['bad-attr'], ".sock-fd")
353
354
355def assoc_rx_listener(cfg):
356    """ Test that an Rx assoc is rejected on a listening socket """
357    _init_psp_dev(cfg)
358
359    with socket.create_server(("localhost", 0)) as s:
360        with ksft_raises(NlError) as cm:
361            cfg.pspnl.rx_assoc({"version": 0,
362                                "dev-id": cfg.psp_dev_id,
363                                "sock-fd": s.fileno()})
364        ksft_eq(cm.exception.nl_msg.error, -errno.ENOTCONN)
365        ksft_eq(cm.exception.nl_msg.extack['bad-attr'], ".sock-fd")
366
367
368def assoc_version_mismatch(cfg):
369    """ Test creating associations where Rx and Tx PSP versions do not match """
370    _init_psp_dev(cfg)
371
372    versions = list(cfg.psp_info['psp-versions-cap'])
373    if len(versions) < 2:
374        raise KsftSkipEx("Not enough PSP versions supported by the device for the test")
375
376    # Translate versions to integers
377    versions = [cfg.pspnl.consts["version"].entries[v].value for v in versions]
378
379    with _make_lo_conn() as s:
380        rx = cfg.pspnl.rx_assoc({"version": versions[0],
381                                 "dev-id": cfg.psp_dev_id,
382                                 "sock-fd": s.fileno()})
383
384        for version in versions[1:]:
385            with ksft_raises(NlError) as cm:
386                cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
387                                    "version": version,
388                                    "tx-key": rx['rx-key'],
389                                    "sock-fd": s.fileno()})
390            the_exception = cm.exception
391            ksft_eq(the_exception.nl_msg.error, -errno.EINVAL)
392
393
394def _require_tls_ulp():
395    with socket.create_server(("localhost", 0)) as srv, \
396         socket.create_connection(srv.getsockname()) as s:
397        try:
398            s.setsockopt(socket.SOL_TCP, TCP_ULP, b"tls")
399        except OSError as exc:
400            raise KsftSkipEx("kTLS not available") from exc
401
402
403def assoc_psp_ulp_exclusive(cfg):
404    """ Test that a TCP ULP cannot be attached to a PSP socket """
405    _init_psp_dev(cfg)
406    _require_tls_ulp()
407
408    with _make_clr_conn(cfg) as s:
409        try:
410            cfg.pspnl.rx_assoc({"version": 0,
411                                "dev-id": cfg.psp_dev_id,
412                                "sock-fd": s.fileno()})
413            with ksft_raises(OSError) as cm:
414                s.setsockopt(socket.SOL_TCP, TCP_ULP, b"tls")
415            ksft_eq(cm.exception.errno, errno.EINVAL)
416        finally:
417            _close_conn(cfg, s)
418
419
420def assoc_ulp_psp_exclusive(cfg):
421    """ Test that a PSP assoc cannot be added to a socket with a TCP ULP """
422    _init_psp_dev(cfg)
423    _require_tls_ulp()
424
425    with _make_clr_conn(cfg) as s:
426        try:
427            s.setsockopt(socket.SOL_TCP, TCP_ULP, b"tls")
428            with ksft_raises(NlError) as cm:
429                cfg.pspnl.rx_assoc({"version": 0,
430                                    "dev-id": cfg.psp_dev_id,
431                                    "sock-fd": s.fileno()})
432            ksft_eq(cm.exception.nl_msg.error, -errno.EINVAL)
433            ksft_eq(cm.exception.nl_msg.extack['bad-attr'], ".sock-fd")
434        finally:
435            _close_conn(cfg, s)
436
437
438def assoc_twice(cfg):
439    """ Test reusing Tx assoc for two sockets """
440    _init_psp_dev(cfg)
441
442    def rx_assoc_check(s):
443        assoc = cfg.pspnl.rx_assoc({"version": 0,
444                                  "dev-id": cfg.psp_dev_id,
445                                  "sock-fd": s.fileno()})
446        ksft_eq(assoc['dev-id'], cfg.psp_dev_id)
447        ksft_gt(assoc['rx-key']['spi'], 0)
448        ksft_eq(len(assoc['rx-key']['key']), 16)
449
450        return assoc
451
452    with _make_lo_conn() as s:
453        assoc = rx_assoc_check(s)
454        tx = cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
455                               "version": 0,
456                               "tx-key": assoc['rx-key'],
457                               "sock-fd": s.fileno()})
458        ksft_eq(len(tx), 0)
459
460        # Use the same Tx assoc second time
461        with _make_lo_conn() as s2:
462            rx_assoc_check(s2)
463            tx = cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
464                                   "version": 0,
465                                   "tx-key": assoc['rx-key'],
466                                   "sock-fd": s2.fileno()})
467            ksft_eq(len(tx), 0)
468
469
470def _data_basic_send(cfg, version, ipver):
471    """ Test basic data send """
472    _init_psp_dev(cfg)
473
474    # Version 0 is required by spec, don't let it skip
475    if version:
476        name = cfg.pspnl.consts["version"].entries_by_val[version].name
477        if name not in cfg.psp_info['psp-versions-cap']:
478            with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
479                with ksft_raises(NlError) as cm:
480                    cfg.pspnl.rx_assoc({"version": version,
481                                        "dev-id": cfg.psp_dev_id,
482                                        "sock-fd": s.fileno()})
483                ksft_eq(cm.exception.nl_msg.error, -errno.EOPNOTSUPP)
484            raise KsftSkipEx("PSP version not supported", name)
485
486    s = _make_psp_conn(cfg, version, ipver)
487
488    rx_assoc = cfg.pspnl.rx_assoc({"version": version,
489                                   "dev-id": cfg.psp_dev_id,
490                                   "sock-fd": s.fileno()})
491    rx = rx_assoc['rx-key']
492    tx = _spi_xchg(s, rx)
493
494    cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
495                        "version": version,
496                        "tx-key": tx,
497                        "sock-fd": s.fileno()})
498
499    data_len = _send_careful(cfg, s, 100)
500    _check_data_rx(cfg, data_len)
501    _req_echo(cfg, s)
502    _close_psp_conn(cfg, s)
503
504
505def __bad_xfer_do(cfg, s, tx, version='hdr0-aes-gcm-128'):
506    # Make sure we accept the ACK for the SPI before we seal with the bad assoc
507    _check_data_outq(s, 0)
508
509    cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
510                        "version": version,
511                        "tx-key": tx,
512                        "sock-fd": s.fileno()})
513
514    data_len = _send_careful(cfg, s, 20)
515    _check_data_outq(s, data_len, force_wait=True)
516    _check_data_rx(cfg, 0)
517    _close_psp_conn(cfg, s)
518
519
520def data_send_bad_key(cfg):
521    """ Test send data with bad key """
522    _init_psp_dev(cfg)
523
524    s = _make_psp_conn(cfg)
525
526    rx_assoc = cfg.pspnl.rx_assoc({"version": 0,
527                                   "dev-id": cfg.psp_dev_id,
528                                   "sock-fd": s.fileno()})
529    rx = rx_assoc['rx-key']
530    tx = _spi_xchg(s, rx)
531    tx['key'] = (tx['key'][0] ^ 0xff).to_bytes(1, 'little') + tx['key'][1:]
532    __bad_xfer_do(cfg, s, tx)
533
534
535def data_send_disconnect(cfg):
536    """ Test socket close after sending data """
537    _init_psp_dev(cfg)
538
539    with _make_psp_conn(cfg) as s:
540        assoc = cfg.pspnl.rx_assoc({"version": 0,
541                                  "sock-fd": s.fileno()})
542        tx = _spi_xchg(s, assoc['rx-key'])
543        cfg.pspnl.tx_assoc({"version": 0,
544                          "tx-key": tx,
545                          "sock-fd": s.fileno()})
546
547        data_len = _send_careful(cfg, s, 100)
548        _check_data_rx(cfg, data_len)
549
550        s.shutdown(socket.SHUT_RDWR)
551        s.close()
552
553
554def _data_mss_adjust(cfg, ipver):
555    _init_psp_dev(cfg)
556
557    # First figure out what the MSS would be without any adjustments
558    s = _make_clr_conn(cfg, ipver)
559    s.send(b"0123456789abcdef" * 1024)
560    _check_data_rx(cfg, 16 * 1024)
561    mss = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_MAXSEG)
562    _close_conn(cfg, s)
563
564    s = _make_psp_conn(cfg, 0, ipver)
565    try:
566        rx_assoc = cfg.pspnl.rx_assoc({"version": 0,
567                                     "dev-id": cfg.psp_dev_id,
568                                     "sock-fd": s.fileno()})
569        rx = rx_assoc['rx-key']
570        tx = _spi_xchg(s, rx)
571
572        rxmss = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_MAXSEG)
573        ksft_eq(mss, rxmss)
574
575        cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
576                          "version": 0,
577                          "tx-key": tx,
578                          "sock-fd": s.fileno()})
579
580        txmss = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_MAXSEG)
581        ksft_eq(mss, txmss + 40)
582
583        data_len = _send_careful(cfg, s, 100)
584        _check_data_rx(cfg, data_len)
585        _check_data_outq(s, 0)
586
587        txmss = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_MAXSEG)
588        ksft_eq(mss, txmss + 40)
589    finally:
590        _close_psp_conn(cfg, s)
591
592
593def data_stale_key(cfg):
594    """ Test send on a double-rotated key """
595    _init_psp_dev(cfg)
596
597    prev_stale = _get_stat(cfg, 'stale-events')
598    s = _make_psp_conn(cfg)
599    try:
600        rx_assoc = cfg.pspnl.rx_assoc({"version": 0,
601                                     "dev-id": cfg.psp_dev_id,
602                                     "sock-fd": s.fileno()})
603        rx = rx_assoc['rx-key']
604        tx = _spi_xchg(s, rx)
605
606        cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
607                          "version": 0,
608                          "tx-key": tx,
609                          "sock-fd": s.fileno()})
610
611        data_len = _send_careful(cfg, s, 100)
612        _check_data_rx(cfg, data_len)
613        _check_data_outq(s, 0)
614
615        cfg.pspnl.key_rotate({"id": cfg.psp_dev_id})
616        cfg.pspnl.key_rotate({"id": cfg.psp_dev_id})
617
618        cur_stale = _get_stat(cfg, 'stale-events')
619        ksft_gt(cur_stale, prev_stale)
620
621        s.send(b'0123456789' * 200)
622        _check_data_outq(s, 2000, force_wait=True)
623    finally:
624        _close_psp_conn(cfg, s)
625
626
627def __nsim_psp_rereg(cfg):
628    # The PSP dev ID will change, remember what was there before
629    before = {x['id'] for x in cfg.pspnl.dev_get({}, dump=True)}
630
631    cfg._ns.nsims[0].dfs_write('psp_rereg', '1')
632
633    after = {x['id'] for x in cfg.pspnl.dev_get({}, dump=True)}
634
635    new_devs = list(after - before)
636    ksft_eq(len(new_devs), 1)
637    cfg.psp_dev_id = list(after - before)[0]
638
639
640def removal_device_rx(cfg):
641    """ Test removing a netdev / PSD with active Rx assoc """
642
643    # We could technically devlink reload real devices, too
644    # but that kills the control socket. So test this on
645    # netdevsim only for now
646    cfg.require_nsim()
647
648    s = _make_clr_conn(cfg)
649    try:
650        rx_assoc = cfg.pspnl.rx_assoc({"version": 0,
651                                       "dev-id": cfg.psp_dev_id,
652                                       "sock-fd": s.fileno()})
653        ksft_not_none(rx_assoc)
654
655        __nsim_psp_rereg(cfg)
656    finally:
657        _close_conn(cfg, s)
658
659
660def removal_device_bi(cfg):
661    """ Test removing a netdev / PSD with active Rx/Tx assoc """
662
663    # We could technically devlink reload real devices, too
664    # but that kills the control socket. So test this on
665    # netdevsim only for now
666    cfg.require_nsim()
667
668    s = _make_clr_conn(cfg)
669    try:
670        rx_assoc = cfg.pspnl.rx_assoc({"version": 0,
671                                       "dev-id": cfg.psp_dev_id,
672                                       "sock-fd": s.fileno()})
673        cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
674                            "version": 0,
675                            "tx-key": rx_assoc['rx-key'],
676                            "sock-fd": s.fileno()})
677        __nsim_psp_rereg(cfg)
678    finally:
679        _close_conn(cfg, s)
680
681
682def _get_psp_ver_ip_variants():
683    for ver in range(4):
684        for ipv in ("4", "6"):
685            yield KsftNamedVariant(f"v{ver}_ip{ipv}", ver, ipv)
686
687
688def _get_ip_variants():
689    for ipv in ("4", "6"):
690        yield KsftNamedVariant(f"ip{ipv}", ipv)
691
692
693@ksft_variants(_get_psp_ver_ip_variants())
694def data_basic_send(cfg, version, ipver):
695    """Test basic PSP data send."""
696    cfg.require_ipver(ipver)
697    _data_basic_send(cfg, version, ipver)
698
699
700@ksft_variants(_get_ip_variants())
701def data_mss_adjust(cfg, ipver):
702    """Test MSS adjustment with PSP."""
703    cfg.require_ipver(ipver)
704    _data_mss_adjust(cfg, ipver)
705
706
707def _check_assoc_list(cfg, psp_dev_id, ifindex, nsid=None):
708    """Verify assoc-list contains device with given ifindex, no duplicates."""
709    dev_info = cfg.pspnl.dev_get({'id': psp_dev_id})
710
711    ksft_true('assoc-list' in dev_info,
712              "No assoc-list in dev_get() response after association")
713    found = False
714    for assoc in dev_info['assoc-list']:
715        if assoc['ifindex'] != ifindex:
716            continue
717        if nsid is not None and assoc['nsid'] != nsid:
718            continue
719        ksft_eq(found, False, "Duplicate assoc entry found")
720        found = True
721    ksft_eq(found, True,
722            "Associated device not found in dev_get() response")
723
724
725def _data_basic_send_netkit_psp_assoc(cfg, version, ipver):
726    """
727    Test basic data send with netkit interface associated with PSP dev.
728    """
729    _assoc_nk_guest(cfg)
730
731    # Enter guest namespace (netns) to run PSP test
732    with NetNSEnter(cfg.netns.name):
733        cfg.pspnl = PSPFamily()
734
735        sock = _make_psp_conn(cfg, version, ipver)
736
737        rx_assoc = cfg.pspnl.rx_assoc({"version": version,
738                                       "dev-id": cfg.psp_dev_id,
739                                       "sock-fd": sock.fileno()})
740        rx_key = rx_assoc['rx-key']
741        tx_key = _spi_xchg(sock, rx_key)
742
743        cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
744                            "version": version,
745                            "tx-key": tx_key,
746                            "sock-fd": sock.fileno()})
747
748        data_len = _send_careful(cfg, sock, 100)
749        _check_data_rx(cfg, data_len)
750        _req_echo(cfg, sock)
751        _close_psp_conn(cfg, sock)
752
753
754def _assoc_check_list(cfg):
755    """Test that assoc-list is correctly populated after dev-assoc."""
756    _assoc_nk_guest(cfg)
757    _check_assoc_list(cfg, cfg.psp_dev_id, cfg.nk_guest_ifindex,
758                      cfg.psp_dev_peer_nsid)
759
760
761def _get_psp_ver_ip6_variants():
762    for ver in range(4):
763        yield KsftNamedVariant(f"v{ver}_ip6", ver, "6")
764
765
766@ksft_variants(_get_psp_ver_ip6_variants())
767def data_basic_send_netkit_psp_assoc(cfg, version, ipver):
768    """Test PSP data send via netkit with dev-assoc."""
769    cfg.require_ipver(ipver)
770    _data_basic_send_netkit_psp_assoc(cfg, version, ipver)
771
772
773def _key_rotation_notify_multi_ns_netkit(cfg):
774    """ Test key rotation notifications across multiple namespaces using netkit """
775    _assoc_nk_guest(cfg)
776
777    # Create listener in guest namespace; socket stays bound to that ns
778    with NetNSEnter(cfg.netns.name):
779        peer_pspnl = PSPFamily()
780        peer_pspnl.ntf_subscribe('use')
781
782    # Create listener in main namespace
783    main_pspnl = PSPFamily()
784    main_pspnl.ntf_subscribe('use')
785
786    # Trigger key rotation on the PSP device
787    cfg.pspnl.key_rotate({"id": cfg.psp_dev_id})
788
789    # Poll both sockets from main thread
790    for pspnl, label in [(main_pspnl, "main"), (peer_pspnl, "guest")]:
791        for ntf in pspnl.poll_ntf(duration=10):
792            if ntf['msg'].get('id') == cfg.psp_dev_id:
793                break
794        else:
795            raise KsftFailEx(
796                f"No key rotation notification received"
797                f" in {label} namespace")
798
799
800def _dev_change_notify_multi_ns_netkit(cfg):
801    """ Test dev_change notifications across multiple namespaces using netkit """
802    _assoc_nk_guest(cfg)
803
804    # Create listener in guest namespace; socket stays bound to that ns
805    with NetNSEnter(cfg.netns.name):
806        peer_pspnl = PSPFamily()
807        peer_pspnl.ntf_subscribe('mgmt')
808
809    # Create listener in main namespace
810    main_pspnl = PSPFamily()
811    main_pspnl.ntf_subscribe('mgmt')
812
813    # Trigger dev_change by calling dev_set (notification is always sent)
814    cfg.pspnl.dev_set({'id': cfg.psp_dev_id,
815                       'psp-versions-ena': cfg.psp_info['psp-versions-cap']})
816
817    # Poll both sockets from main thread
818    for pspnl, label in [(main_pspnl, "main"), (peer_pspnl, "guest")]:
819        for ntf in pspnl.poll_ntf(duration=10):
820            if ntf['msg'].get('id') == cfg.psp_dev_id:
821                break
822        else:
823            raise KsftFailEx(
824                f"No dev_change notification received"
825                f" in {label} namespace")
826
827
828def _subscribe_mgmt(cfg):
829    """Listen on the mgmt group in the guest and in the main namespace."""
830    # Listener in the guest namespace; socket stays bound to that ns
831    with NetNSEnter(cfg.netns.name):
832        peer_pspnl = PSPFamily()
833        peer_pspnl.ntf_subscribe('mgmt')
834
835    main_pspnl = PSPFamily()
836    main_pspnl.ntf_subscribe('mgmt')
837
838    return main_pspnl, peer_pspnl
839
840
841def _get_dev_ntf(cfg, pspnl, label):
842    """Wait for the next notification about the PSP device under test."""
843    for ntf in pspnl.poll_ntf(duration=10):
844        if ntf['msg'].get('id') == cfg.psp_dev_id:
845            return ntf
846    raise KsftFailEx(f"No notification received in the {label} namespace")
847
848
849def _check_disassoc_ntf(cfg, main_pspnl, peer_pspnl, ifindex):
850    """Check the notifications for a netns losing its last association."""
851    ntf = _get_dev_ntf(cfg, main_pspnl, "main")
852    ksft_eq(ntf['name'], 'dev-change-ntf')
853    for assoc in ntf['msg'].get('assoc-list', []):
854        if assoc['nsid'] != cfg.psp_dev_peer_nsid:
855            continue
856        ksft_ne(assoc['ifindex'], ifindex,
857                "Disassociated device still listed in the notification")
858
859    # The device is gone as far as the disassociated namespace is concerned
860    ntf = _get_dev_ntf(cfg, peer_pspnl, "guest")
861    ksft_eq(ntf['name'], 'dev-del-ntf')
862    ksft_true('ifindex' not in ntf['msg'],
863              "ifindex reported to an associated namespace")
864
865
866def _dev_disassoc_notify_multi_ns_netkit(cfg):
867    """ Test the notifications dev-disassoc generates in both namespaces """
868    _init_psp_dev(cfg, True)
869    defer(delattr, cfg, 'psp_dev_id')
870    defer(delattr, cfg, 'psp_info')
871
872    cfg.pspnl.dev_assoc({'id': cfg.psp_dev_id,
873                         'ifindex': cfg.nk_guest_ifindex,
874                         'nsid': cfg.psp_dev_peer_nsid})
875    defer(_try_disassoc, cfg, cfg.psp_dev_id, cfg.nk_guest_ifindex,
876          cfg.psp_dev_peer_nsid)
877
878    main_pspnl, peer_pspnl = _subscribe_mgmt(cfg)
879
880    cfg.pspnl.dev_disassoc({'id': cfg.psp_dev_id,
881                            'ifindex': cfg.nk_guest_ifindex,
882                            'nsid': cfg.psp_dev_peer_nsid})
883
884    _check_disassoc_ntf(cfg, main_pspnl, peer_pspnl, cfg.nk_guest_ifindex)
885
886
887def _dev_disassoc_notify_one_of_two_netkit(cfg):
888    """Test the notifications with two netkits associated in one netns.
889
890    Disassociating the first netkit leaves the PSP device visible in the
891    guest namespace, generates a dev-change-ntf.
892    Disassociating the second one takes the device out of its view,
893    generates 'dev-del-ntf'.
894    """
895    _init_psp_dev(cfg, True)
896    defer(delattr, cfg, 'psp_dev_id')
897    defer(delattr, cfg, 'psp_info')
898
899    tmp_ifindex, _ = _add_netkit_guest(cfg, "tmp_nk_host", "tmp_nk_guest")
900
901    for ifindex in [cfg.nk_guest_ifindex, tmp_ifindex]:
902        cfg.pspnl.dev_assoc({'id': cfg.psp_dev_id, 'ifindex': ifindex,
903                             'nsid': cfg.psp_dev_peer_nsid})
904        defer(_try_disassoc, cfg, cfg.psp_dev_id, ifindex,
905              cfg.psp_dev_peer_nsid)
906
907    main_pspnl, peer_pspnl = _subscribe_mgmt(cfg)
908
909    # One of the two goes away, the device stays visible in the guest netns
910    cfg.pspnl.dev_disassoc({'id': cfg.psp_dev_id, 'ifindex': tmp_ifindex,
911                            'nsid': cfg.psp_dev_peer_nsid})
912
913    ntf = _get_dev_ntf(cfg, main_pspnl, "main")
914    ksft_eq(ntf['name'], 'dev-change-ntf')
915
916    ntf = _get_dev_ntf(cfg, peer_pspnl, "guest")
917    ksft_eq(ntf['name'], 'dev-change-ntf')
918    found = False
919    for assoc in ntf['msg'].get('assoc-list', []):
920        ksft_ne(assoc['ifindex'], tmp_ifindex,
921                "Disassociated device still listed in the notification")
922        found |= assoc['ifindex'] == cfg.nk_guest_ifindex
923    ksft_true(found, "Remaining association missing from the notification")
924
925    # And now the last one, the device disappears from the guest netns
926    cfg.pspnl.dev_disassoc({'id': cfg.psp_dev_id,
927                            'ifindex': cfg.nk_guest_ifindex,
928                            'nsid': cfg.psp_dev_peer_nsid})
929
930    _check_disassoc_ntf(cfg, main_pspnl, peer_pspnl, cfg.nk_guest_ifindex)
931
932
933def _psp_dev_get_check_netkit_psp_assoc(cfg):
934    """ Check psp dev-get output with netkit interface associated with PSP dev """
935    _assoc_nk_guest(cfg)
936
937    # Check 1: In default netns, verify dev-get has correct ifindex and assoc-list
938    dev_info = cfg.pspnl.dev_get({'id': cfg.psp_dev_id})
939    ksft_eq(dev_info['ifindex'], cfg.psp_ifindex)
940    _check_assoc_list(cfg, cfg.psp_dev_id, cfg.nk_guest_ifindex,
941                      cfg.psp_dev_peer_nsid)
942
943    # Check 2: In guest netns, verify dev-get has assoc-list with nk_guest device
944    with NetNSEnter(cfg.netns.name):
945        peer_pspnl = PSPFamily()
946
947        # Dump all devices in the guest namespace
948        peer_devices = peer_pspnl.dev_get({}, dump=True)
949
950        # Find the device with by-association flag
951        peer_dev = None
952        for dev in peer_devices:
953            if dev.get('by-association'):
954                peer_dev = dev
955                break
956
957        ksft_not_none(peer_dev, "No PSP device found with by-association flag in guest netns")
958
959        # ifindex of the main netdevice means nothing in this namespace
960        ksft_true('ifindex' not in peer_dev,
961                  "ifindex reported to an associated namespace")
962
963        # Verify assoc-list contains the nk_guest device
964        ksft_true('assoc-list' in peer_dev and len(peer_dev['assoc-list']) > 0,
965                  "Guest device should have assoc-list with local devices")
966
967        # Verify the assoc-list contains nk_guest ifindex with nsid=-1 (same namespace)
968        found = False
969        for assoc in peer_dev['assoc-list']:
970            if assoc['ifindex'] == cfg.nk_guest_ifindex:
971                ksft_eq(assoc['nsid'], -1,
972                        "nsid should be -1 (NETNSA_NSID_NOT_ASSIGNED) for same-namespace device")
973                found = True
974                break
975        ksft_true(found, "nk_guest ifindex not found in assoc-list")
976
977
978def _dev_assoc_no_nsid(cfg):
979    """ Test dev-assoc and dev-disassoc without nsid attribute """
980    _init_psp_dev(cfg, True)
981
982    # Associate without nsid - should look up ifindex in caller's netns
983    cfg.pspnl.dev_assoc({'id': cfg.psp_dev_id,
984                         'ifindex': cfg.nk_host_ifindex})
985    defer(_try_disassoc, cfg,
986          cfg.psp_dev_id, cfg.nk_host_ifindex)
987    defer(delattr, cfg, 'psp_dev_id')
988    defer(delattr, cfg, 'psp_info')
989
990    # Verify assoc-list contains the device (match by ifindex only)
991    _check_assoc_list(cfg, cfg.psp_dev_id, cfg.nk_host_ifindex)
992
993    # Disassociate without nsid - should also use caller's netns
994    cfg.pspnl.dev_disassoc({'id': cfg.psp_dev_id,
995                            'ifindex': cfg.nk_host_ifindex})
996
997    # Verify assoc-list no longer contains the device
998    dev_info = cfg.pspnl.dev_get({'id': cfg.psp_dev_id})
999    found = False
1000    if 'assoc-list' in dev_info:
1001        for assoc in dev_info['assoc-list']:
1002            if assoc['ifindex'] == cfg.nk_host_ifindex:
1003                found = True
1004                break
1005    ksft_true(not found, "Device should not be in assoc-list after disassociation")
1006
1007
1008def _add_netkit_guest(cfg, host_name, guest_name):
1009    """Create a netkit pair and move its peer into the test namespace.
1010
1011    Returns the peer's ifindex there and the defer() deleting the pair.
1012    """
1013    existing = {link['ifindex'] for link in ip("-d link show", json=True)
1014                if link.get('linkinfo', {}).get('info_kind') == 'netkit'}
1015
1016    rtnl = RtnlFamily()
1017    rtnl.newlink(
1018        {
1019            "ifname": host_name,
1020            "linkinfo": {
1021                "kind": "netkit",
1022                "data": {
1023                    "mode": "l2",
1024                    "policy": "forward",
1025                    "peer-policy": "forward",
1026                },
1027            },
1028        },
1029        flags=[Netlink.NLM_F_CREATE, Netlink.NLM_F_EXCL],
1030    )
1031    cleanup = defer(ip, f"link del {host_name}")
1032
1033    # Find the peer by diffing against existing netkit ifindexes
1034    all_links = ip("-d link show", json=True)
1035    peer = [link for link in all_links
1036            if link.get('linkinfo', {}).get('info_kind') == 'netkit'
1037            and link['ifindex'] not in existing
1038            and link['ifname'] != host_name]
1039    ksft_eq(len(peer), 1, "Failed to find the new netkit peer")
1040
1041    # Rename and move guest end into the test namespace
1042    ip(f"link set dev {peer[0]['ifname']} name {guest_name}")
1043    ip(f"link set dev {guest_name} netns {cfg.netns.name}")
1044    guest_dev = ip(f"link show dev {guest_name}", json=True, ns=cfg.netns)[0]
1045    ip(f"link set dev {guest_name} up", ns=cfg.netns)
1046
1047    return guest_dev['ifindex'], cleanup
1048
1049
1050def _psp_dev_assoc_cleanup_on_netkit_del(cfg):
1051    """Test that assoc-list is cleared when associated netkit is deleted.
1052
1053    Creates a disposable netkit pair for this test to avoid destroying
1054    the shared environment.
1055    """
1056    _init_psp_dev(cfg, True)
1057    defer(delattr, cfg, 'psp_dev_id')
1058    defer(delattr, cfg, 'psp_info')
1059
1060    tmp_host_name = "tmp_nk_host"
1061    tmp_guest_ifindex, cleanup_netkit = _add_netkit_guest(cfg, tmp_host_name,
1062                                                          "tmp_nk_guest")
1063
1064    # Associate PSP device with the temporary guest interface
1065    cfg.pspnl.dev_assoc({'id': cfg.psp_dev_id,
1066                         'ifindex': tmp_guest_ifindex,
1067                         'nsid': cfg.psp_dev_peer_nsid})
1068
1069    # Verify assoc-list contains the temporary device
1070    _check_assoc_list(cfg, cfg.psp_dev_id, tmp_guest_ifindex,
1071                      cfg.psp_dev_peer_nsid)
1072
1073    # Removing the netdevice is notified like a disassociation
1074    main_pspnl, peer_pspnl = _subscribe_mgmt(cfg)
1075
1076    # Delete the temporary netkit pair (deleting one end removes both)
1077    ip(f"link del {tmp_host_name}")
1078    cleanup_netkit.cancel()
1079
1080    # Verify assoc-list is cleared after netkit deletion
1081    dev_info = cfg.pspnl.dev_get({'id': cfg.psp_dev_id})
1082    ksft_true('assoc-list' not in dev_info
1083              or len(dev_info['assoc-list']) == 0,
1084              "assoc-list should be empty after netkit deletion")
1085
1086    _check_disassoc_ntf(cfg, main_pspnl, peer_pspnl, tmp_guest_ifindex)
1087
1088
1089def _try_disassoc(cfg, psp_dev_id, ifindex, nsid=None):
1090    """Best-effort disassociate, ignoring errors if already removed."""
1091    try:
1092        params = {'id': psp_dev_id, 'ifindex': ifindex}
1093        if nsid is not None:
1094            params['nsid'] = nsid
1095        cfg.pspnl.dev_disassoc(params)
1096    except NlError:
1097        pass
1098
1099
1100def _assoc_nk_guest(cfg):
1101    """Associate nk_guest with PSP device and register cleanup via defer()."""
1102    _init_psp_dev(cfg, True)
1103
1104    cfg.pspnl.dev_assoc({'id': cfg.psp_dev_id,
1105                         'ifindex': cfg.nk_guest_ifindex,
1106                         'nsid': cfg.psp_dev_peer_nsid})
1107    defer(_disassoc_nk_guest, cfg,
1108          cfg.psp_dev_id, cfg.nk_guest_ifindex)
1109
1110
1111def _disassoc_nk_guest(cfg, psp_dev_id, nk_guest_ifindex):
1112    """Disassociate nk_guest and reset cfg PSP state."""
1113    pspnl = PSPFamily()
1114    pspnl.dev_disassoc({'id': psp_dev_id, 'ifindex': nk_guest_ifindex,
1115                        'nsid': cfg.psp_dev_peer_nsid})
1116    cfg.pspnl = pspnl
1117    del cfg.psp_dev_id
1118    del cfg.psp_info
1119
1120
1121def _get_nsid(ns_name):
1122    """Get the nsid for a namespace."""
1123    for entry in ip("netns list-id", json=True):
1124        if entry.get("name") == str(ns_name):
1125            return entry["nsid"]
1126    raise KsftSkipEx(f"nsid not found for namespace {ns_name}")
1127
1128
1129def _setup_psp_attributes(cfg):
1130    # pylint: disable=protected-access
1131    """
1132    Set up PSP-specific attributes on the environment.
1133
1134    This sets attributes needed for PSP tests based on whether we're using
1135    netdevsim or a real NIC.
1136    """
1137    if cfg._ns is not None:
1138        # netdevsim case: PSP device is the local dev (in host namespace)
1139        cfg.psp_dev = cfg._ns.nsims[0].dev
1140        cfg.psp_ifname = cfg.psp_dev['ifname']
1141        cfg.psp_ifindex = cfg.psp_dev['ifindex']
1142
1143        # PSP peer device is the remote dev (in _netns, where psp_responder runs)
1144        cfg.psp_dev_peer = cfg._ns_peer.nsims[0].dev
1145        cfg.psp_dev_peer_ifname = cfg.psp_dev_peer['ifname']
1146        cfg.psp_dev_peer_ifindex = cfg.psp_dev_peer['ifindex']
1147    else:
1148        # Real NIC case: PSP device is the local interface
1149        cfg.psp_dev = cfg.dev
1150        cfg.psp_ifname = cfg.ifname
1151        cfg.psp_ifindex = cfg.ifindex
1152
1153        # PSP peer device is the remote interface
1154        cfg.psp_dev_peer = cfg.remote_dev
1155        cfg.psp_dev_peer_ifname = cfg.remote_ifname
1156        cfg.psp_dev_peer_ifindex = cfg.remote_ifindex
1157
1158    # Get nsid for the guest namespace (netns) where nk_guest is
1159    cfg.psp_dev_peer_nsid = _get_nsid(cfg.netns.name)
1160
1161
1162
1163def main() -> None:
1164    """ Ksft boiler plate main """
1165
1166    # Make sure LOCAL_PREFIX_V6 is set
1167    if "LOCAL_PREFIX_V6" not in os.environ:
1168        os.environ["LOCAL_PREFIX_V6"] = "2001:db8:2::"
1169
1170    try:
1171        env = NetDrvContEnv(__file__, primary_rx_redirect=True)
1172        has_cont = True
1173    except KsftSkipEx:
1174        env = NetDrvEpEnv(__file__)
1175        has_cont = False
1176
1177    with env as cfg:
1178        cfg.pspnl = PSPFamily()
1179
1180        if has_cont:
1181            _setup_psp_attributes(cfg)
1182
1183        # Set up responder and communication sock
1184        # psp_responder runs in _netns (remote namespace with psp_dev_peer)
1185        responder = cfg.remote.deploy("psp_responder")
1186
1187        cfg.comm_port = rand_port()
1188        srv = None
1189        try:
1190            with bkg(responder + f" -p {cfg.comm_port} -i {cfg.remote_ifindex}",
1191                     host=cfg.remote, exit_wait=True) as srv:
1192                wait_port_listen(cfg.comm_port, host=cfg.remote)
1193
1194                cfg.comm_sock = socket.create_connection((cfg.remote_addr,
1195                                                          cfg.comm_port),
1196                                                         timeout=1)
1197
1198                cases = [data_basic_send, data_mss_adjust]
1199
1200                if has_cont:
1201                    cases += [
1202                        _assoc_check_list,
1203                        data_basic_send_netkit_psp_assoc,
1204                        _key_rotation_notify_multi_ns_netkit,
1205                        _dev_change_notify_multi_ns_netkit,
1206                        _dev_disassoc_notify_multi_ns_netkit,
1207                        _dev_disassoc_notify_one_of_two_netkit,
1208                        _psp_dev_get_check_netkit_psp_assoc,
1209                        _dev_assoc_no_nsid,
1210                        _psp_dev_assoc_cleanup_on_netkit_del,
1211                    ]
1212
1213                ksft_run(cases=cases, globs=globals(),
1214                         case_pfx={"dev_", "data_", "assoc_", "removal_"},
1215                         args=(cfg, ))
1216
1217                cfg.comm_sock.send(b"exit\0")
1218                cfg.comm_sock.close()
1219        finally:
1220            if srv and (srv.stdout or srv.stderr):
1221                ksft_pr("")
1222                ksft_pr(f"Responder logs ({srv.ret}):")
1223            if srv and srv.stdout:
1224                ksft_pr("STDOUT:\n#  " + srv.stdout.strip().replace("\n", "\n#  "))
1225            if srv and srv.stderr:
1226                ksft_pr("STDERR:\n#  " + srv.stderr.strip().replace("\n", "\n#  "))
1227    ksft_exit()
1228
1229
1230if __name__ == "__main__":
1231    main()
1232