1# P2P channel selection test cases
2# Copyright (c) 2014, Jouni Malinen <j@w1.fi>
3#
4# This software may be distributed under the terms of the BSD license.
5# See README for more details.
6
7from remotehost import remote_compatible
8import logging
9logger = logging.getLogger()
10import os
11import subprocess
12import time
13
14import hostapd
15import hwsim_utils
16from tshark import run_tshark
17from wpasupplicant import WpaSupplicant
18from hwsim import HWSimRadio
19from p2p_utils import *
20from utils import *
21
22def set_country(country, dev=None):
23    subprocess.call(['iw', 'reg', 'set', country])
24    time.sleep(0.1)
25    if dev:
26        for i in range(10):
27            ev = dev.wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=15)
28            if ev is None:
29                raise Exception("No regdom change event seen")
30            if "type=COUNTRY alpha2=" + country in ev:
31                return
32        raise Exception("No matching regdom event seen for set_country(%s)" % country)
33
34def test_p2p_channel_5ghz(dev):
35    """P2P group formation with 5 GHz preference"""
36    try:
37        set_country("US", dev[0])
38        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
39                                               r_dev=dev[1], r_intent=0,
40                                               test_data=False)
41        check_grpform_results(i_res, r_res)
42        freq = int(i_res['freq'])
43        if freq < 5000:
44            raise Exception("Unexpected channel %d MHz - did not follow 5 GHz preference" % freq)
45        remove_group(dev[0], dev[1])
46    finally:
47        set_country("00")
48        dev[1].flush_scan_cache()
49
50def test_p2p_channel_5ghz_no_vht(dev):
51    """P2P group formation with 5 GHz preference when VHT channels are disallowed"""
52    try:
53        set_country("US", dev[0])
54        dev[0].global_request("P2P_SET disallow_freq 5180-5240")
55        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
56                                               r_dev=dev[1], r_intent=0,
57                                               test_data=False)
58        check_grpform_results(i_res, r_res)
59        freq = int(i_res['freq'])
60        if freq < 5000:
61            raise Exception("Unexpected channel %d MHz - did not follow 5 GHz preference" % freq)
62        remove_group(dev[0], dev[1])
63    finally:
64        set_country("00")
65        dev[0].global_request("P2P_SET disallow_freq ")
66        dev[1].flush_scan_cache()
67
68def test_p2p_channel_random_social(dev):
69    """P2P group formation with 5 GHz preference but all 5 GHz channels disabled"""
70    try:
71        set_country("US", dev[0])
72        dev[0].global_request("SET p2p_oper_channel 11")
73        dev[0].global_request("P2P_SET disallow_freq 5000-6000,2462")
74        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
75                                               r_dev=dev[1], r_intent=0,
76                                               test_data=False)
77        check_grpform_results(i_res, r_res)
78        freq = int(i_res['freq'])
79        if freq not in [2412, 2437, 2462]:
80            raise Exception("Unexpected channel %d MHz - did not pick random social channel" % freq)
81        remove_group(dev[0], dev[1])
82    finally:
83        set_country("00")
84        dev[0].global_request("P2P_SET disallow_freq ")
85        dev[1].flush_scan_cache()
86
87def test_p2p_channel_random(dev):
88    """P2P group formation with 5 GHz preference but all 5 GHz channels and all social channels disabled"""
89    try:
90        set_country("US", dev[0])
91        dev[0].global_request("SET p2p_oper_channel 11")
92        dev[0].global_request("P2P_SET disallow_freq 5000-6000,2412,2437,2462")
93        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
94                                               r_dev=dev[1], r_intent=0,
95                                               test_data=False)
96        check_grpform_results(i_res, r_res)
97        freq = int(i_res['freq'])
98        if freq > 2500 or freq in [2412, 2437, 2462]:
99            raise Exception("Unexpected channel %d MHz" % freq)
100        remove_group(dev[0], dev[1])
101    finally:
102        set_country("00")
103        dev[0].global_request("P2P_SET disallow_freq ")
104        dev[1].flush_scan_cache()
105
106def test_p2p_channel_random_social_with_op_class_change(dev, apdev, params):
107    """P2P group formation using random social channel with oper class change needed"""
108    try:
109        set_country("US", dev[0])
110        logger.info("Start group on 5 GHz")
111        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
112                                               r_dev=dev[1], r_intent=0,
113                                               test_data=False)
114        check_grpform_results(i_res, r_res)
115        freq = int(i_res['freq'])
116        if freq < 5000:
117            raise Exception("Unexpected channel %d MHz - did not pick 5 GHz preference" % freq)
118        remove_group(dev[0], dev[1])
119
120        logger.info("Disable 5 GHz and try to re-start group based on 5 GHz preference")
121        dev[0].global_request("SET p2p_oper_reg_class 115")
122        dev[0].global_request("SET p2p_oper_channel 36")
123        dev[0].global_request("P2P_SET disallow_freq 5000-6000")
124        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
125                                               r_dev=dev[1], r_intent=0,
126                                               test_data=False)
127        check_grpform_results(i_res, r_res)
128        freq = int(i_res['freq'])
129        if freq not in [2412, 2437, 2462]:
130            raise Exception("Unexpected channel %d MHz - did not pick random social channel" % freq)
131        remove_group(dev[0], dev[1])
132
133        out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
134                         "wifi_p2p.public_action.subtype == 0")
135        if out is not None:
136            last = None
137            for l in out.splitlines():
138                if "Operating Channel:" not in l:
139                    continue
140                last = l
141            if last is None:
142                raise Exception("Could not find GO Negotiation Request")
143            if "Operating Class 81" not in last:
144                raise Exception("Unexpected operating class: " + last.strip())
145    finally:
146        set_country("00")
147        dev[0].global_request("P2P_SET disallow_freq ")
148        dev[0].global_request("SET p2p_oper_reg_class 0")
149        dev[0].global_request("SET p2p_oper_channel 0")
150        dev[1].flush_scan_cache()
151
152def test_p2p_channel_avoid(dev):
153    """P2P and avoid frequencies driver event"""
154    try:
155        set_country("US", dev[0])
156        if "OK" not in dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES 5000-6000,2412,2437,2462"):
157            raise Exception("Could not simulate driver event")
158        ev = dev[0].wait_event(["CTRL-EVENT-AVOID-FREQ"], timeout=10)
159        if ev is None:
160            raise Exception("No CTRL-EVENT-AVOID-FREQ event")
161        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
162                                               r_dev=dev[1], r_intent=0,
163                                               test_data=False)
164        check_grpform_results(i_res, r_res)
165        freq = int(i_res['freq'])
166        if freq > 2500 or freq in [2412, 2437, 2462]:
167            raise Exception("Unexpected channel %d MHz" % freq)
168
169        if "OK" not in dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES"):
170            raise Exception("Could not simulate driver event(2)")
171        ev = dev[0].wait_event(["CTRL-EVENT-AVOID-FREQ"], timeout=10)
172        if ev is None:
173            raise Exception("No CTRL-EVENT-AVOID-FREQ event")
174        ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
175                                      "AP-CSA-FINISHED"], timeout=1)
176        if ev is not None:
177            raise Exception("Unexpected + " + ev + " event")
178
179        if "OK" not in dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES " + str(freq)):
180            raise Exception("Could not simulate driver event(3)")
181        ev = dev[0].wait_event(["CTRL-EVENT-AVOID-FREQ"], timeout=10)
182        if ev is None:
183            raise Exception("No CTRL-EVENT-AVOID-FREQ event")
184        ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
185                                      "AP-CSA-FINISHED"],
186                                     timeout=10)
187        if ev is None:
188            raise Exception("No P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED event")
189        remove_group(dev[0], dev[1])
190    finally:
191        set_country("00")
192        dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES")
193        dev[1].flush_scan_cache()
194
195def test_p2p_channel_avoid2(dev):
196    """P2P and avoid frequencies driver event on 5 GHz"""
197    try:
198        set_country("US", dev[0])
199        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
200                                               r_dev=dev[1], r_intent=0,
201                                               test_data=False,
202                                               i_max_oper_chwidth=80,
203                                               i_ht40=True, i_vht=True)
204        check_grpform_results(i_res, r_res)
205        freq = int(i_res['freq'])
206        if freq < 5000:
207            raise Exception("Unexpected channel %d MHz" % freq)
208
209        if "OK" not in dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES " + str(freq)):
210            raise Exception("Could not simulate driver event(2)")
211        ev = dev[0].wait_event(["CTRL-EVENT-AVOID-FREQ"], timeout=10)
212        if ev is None:
213            raise Exception("No CTRL-EVENT-AVOID-FREQ event")
214        ev = dev[0].wait_group_event(["CTRL-EVENT-CHANNEL-SWITCH"], timeout=10)
215        if ev is None:
216            raise Exception("No channel switch event seen")
217        if "ch_width=80 MHz" not in ev:
218            raise Exception("Could not move to a VHT80 channel")
219        ev = dev[0].wait_group_event(["AP-CSA-FINISHED"], timeout=1)
220        if ev is None:
221            raise Exception("No AP-CSA-FINISHED event seen")
222        remove_group(dev[0], dev[1])
223    finally:
224        set_country("00")
225        dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES")
226        dev[1].flush_scan_cache()
227
228def test_p2p_channel_avoid3(dev):
229    """P2P and avoid frequencies driver event on 5 GHz"""
230    try:
231        dev[0].global_request("SET p2p_pref_chan 128:44")
232        set_country("CO", dev[0])
233        form(dev[0], dev[1])
234        set_country("CO", dev[0])
235        [i_res, r_res] = invite_from_go(dev[0], dev[1], terminate=False,
236                                        extra="ht40 vht")
237        freq = int(i_res['freq'])
238        if freq != 5220:
239            raise Exception("Unexpected channel %d MHz" % freq)
240
241        if "OK" not in dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES 5180-5320,5500-5640"):
242            raise Exception("Could not simulate driver event(2)")
243        ev = dev[0].wait_event(["CTRL-EVENT-AVOID-FREQ"], timeout=10)
244        if ev is None:
245            raise Exception("No CTRL-EVENT-AVOID-FREQ event")
246        ev = dev[0].wait_group_event(["CTRL-EVENT-CHANNEL-SWITCH"], timeout=10)
247        if ev is None:
248            raise Exception("No channel switch event seen")
249        if "ch_width=80 MHz" not in ev:
250            raise Exception("Could not move to a VHT80 channel")
251        ev = dev[0].wait_group_event(["AP-CSA-FINISHED"], timeout=1)
252        if ev is None:
253            raise Exception("No AP-CSA-FINISHED event seen")
254        remove_group(dev[0], dev[1])
255    finally:
256        set_country("00")
257        dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES")
258        dev[0].global_request("SET p2p_pref_chan ")
259        dev[1].flush_scan_cache()
260
261def test_p2p_channel_avoid4(dev):
262    """P2P and avoid frequencies preventing 80 MHz on channel 149"""
263    try:
264        set_country("US", dev[0])
265        if "OK" not in dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES 5180-5320,5785-5825"):
266            raise Exception("Could not simulate driver event")
267        ev = dev[0].wait_event(["CTRL-EVENT-AVOID-FREQ"], timeout=10)
268        if ev is None:
269            raise Exception("No CTRL-EVENT-AVOID-FREQ event")
270        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
271                                               r_dev=dev[1], r_intent=0,
272                                               test_data=False,
273                                               i_max_oper_chwidth=80,
274                                               i_ht40=True, i_vht=True)
275        check_grpform_results(i_res, r_res)
276        freq = int(i_res['freq'])
277        if freq not in [5745, 5765]:
278            raise Exception("Unexpected channel %d MHz" % freq)
279
280        sig = dev[1].group_request("SIGNAL_POLL").splitlines()
281        if "WIDTH=40 MHz" not in sig:
282            raise Exception("Unexpected channel width: " + str(sig))
283        remove_group(dev[0], dev[1])
284    finally:
285        set_country("00")
286        dev[0].request("DRIVER_EVENT AVOID_FREQUENCIES")
287        dev[1].flush_scan_cache()
288
289@remote_compatible
290def test_autogo_following_bss(dev, apdev):
291    """P2P autonomous GO operate on the same channel as station interface"""
292    if dev[0].get_mcc() > 1:
293        logger.info("test mode: MCC")
294
295    dev[0].global_request("SET p2p_no_group_iface 0")
296
297    channels = {3: "2422", 5: "2432", 9: "2452"}
298    for key in channels:
299        hapd = hostapd.add_ap(apdev[0], {"ssid": 'ap-test',
300                                         "channel": str(key)})
301        dev[0].connect("ap-test", key_mgmt="NONE",
302                       scan_freq=str(channels[key]))
303        res_go = autogo(dev[0])
304        if res_go['freq'] != channels[key]:
305            raise Exception("Group operation channel is not the same as on connected station interface")
306        hwsim_utils.test_connectivity(dev[0], hapd)
307        dev[0].remove_group(res_go['ifname'])
308
309@remote_compatible
310def test_go_neg_with_bss_connected(dev, apdev):
311    """P2P channel selection: GO negotiation when station interface is connected"""
312
313    dev[0].flush_scan_cache()
314    dev[1].flush_scan_cache()
315    dev[0].global_request("SET p2p_no_group_iface 0")
316
317    hapd = hostapd.add_ap(apdev[0],
318                          {"ssid": 'bss-2.4ghz', "channel": '5'})
319    dev[0].connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2432")
320    #dev[0] as GO
321    [i_res, r_res] = go_neg_pbc(i_dev=dev[0], i_intent=10, r_dev=dev[1],
322                                r_intent=1)
323    check_grpform_results(i_res, r_res)
324    if i_res['role'] != "GO":
325       raise Exception("GO not selected according to go_intent")
326    if i_res['freq'] != "2432":
327       raise Exception("Group formed on a different frequency than BSS")
328    hwsim_utils.test_connectivity(dev[0], hapd)
329    dev[0].remove_group(i_res['ifname'])
330    dev[1].wait_go_ending_session()
331
332    if dev[0].get_mcc() > 1:
333        logger.info("Skip as-client case due to MCC being enabled")
334        return
335
336    #dev[0] as client
337    [i_res2, r_res2] = go_neg_pbc(i_dev=dev[0], i_intent=1, r_dev=dev[1],
338                                  r_intent=10)
339    check_grpform_results(i_res2, r_res2)
340    if i_res2['role'] != "client":
341       raise Exception("GO not selected according to go_intent")
342    if i_res2['freq'] != "2432":
343       raise Exception("Group formed on a different frequency than BSS")
344    hwsim_utils.test_connectivity(dev[0], hapd)
345    dev[1].remove_group(r_res2['ifname'])
346    dev[0].wait_go_ending_session()
347    dev[0].request("DISCONNECT")
348    hapd.disable()
349    dev[0].flush_scan_cache()
350    dev[1].flush_scan_cache()
351
352def test_autogo_with_bss_on_disallowed_chan(dev, apdev):
353    """P2P channel selection: Autonomous GO with BSS on a disallowed channel"""
354
355    with HWSimRadio(n_channels=2) as (radio, iface):
356        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
357        wpas.interface_add(iface)
358
359        wpas.global_request("SET p2p_no_group_iface 0")
360
361        if wpas.get_mcc() < 2:
362           raise Exception("New radio does not support MCC")
363
364        try:
365            hapd = hostapd.add_ap(apdev[0], {"ssid": 'bss-2.4ghz',
366                                             "channel": '1'})
367            wpas.global_request("P2P_SET disallow_freq 2412")
368            wpas.connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2412")
369            res = autogo(wpas)
370            if res['freq'] == "2412":
371               raise Exception("GO set on a disallowed channel")
372            hwsim_utils.test_connectivity(wpas, hapd)
373        finally:
374            wpas.global_request("P2P_SET disallow_freq ")
375
376def test_go_neg_with_bss_on_disallowed_chan(dev, apdev):
377    """P2P channel selection: GO negotiation with station interface on a disallowed channel"""
378
379    with HWSimRadio(n_channels=2) as (radio, iface):
380        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
381        wpas.interface_add(iface)
382
383        wpas.global_request("SET p2p_no_group_iface 0")
384
385        if wpas.get_mcc() < 2:
386           raise Exception("New radio does not support MCC")
387
388        try:
389            hapd = hostapd.add_ap(apdev[0],
390                                  {"ssid": 'bss-2.4ghz', "channel": '1'})
391            # make sure PBC overlap from old test cases is not maintained
392            dev[1].flush_scan_cache()
393            wpas.connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2412")
394            wpas.global_request("P2P_SET disallow_freq 2412")
395
396            #wpas as GO
397            [i_res, r_res] = go_neg_pbc(i_dev=wpas, i_intent=10, r_dev=dev[1],
398                                        r_intent=1)
399            check_grpform_results(i_res, r_res)
400            if i_res['role'] != "GO":
401               raise Exception("GO not selected according to go_intent")
402            if i_res['freq'] == "2412":
403               raise Exception("Group formed on a disallowed channel")
404            hwsim_utils.test_connectivity(wpas, hapd)
405            wpas.remove_group(i_res['ifname'])
406            dev[1].wait_go_ending_session()
407            dev[1].flush_scan_cache()
408
409            wpas.dump_monitor()
410            dev[1].dump_monitor()
411
412            #wpas as client
413            [i_res2, r_res2] = go_neg_pbc(i_dev=wpas, i_intent=1, r_dev=dev[1],
414                                          r_intent=10)
415            check_grpform_results(i_res2, r_res2)
416            if i_res2['role'] != "client":
417               raise Exception("GO not selected according to go_intent")
418            if i_res2['freq'] == "2412":
419               raise Exception("Group formed on a disallowed channel")
420            hwsim_utils.test_connectivity(wpas, hapd)
421            dev[1].remove_group(r_res2['ifname'])
422            wpas.wait_go_ending_session()
423            ev = dev[1].wait_global_event(["P2P-GROUP-REMOVED"], timeout=5)
424            if ev is None:
425                raise Exception("Group removal not indicated")
426            wpas.request("DISCONNECT")
427            hapd.disable()
428        finally:
429            wpas.global_request("P2P_SET disallow_freq ")
430
431def test_autogo_force_diff_channel(dev, apdev):
432    """P2P autonomous GO and station interface operate on different channels"""
433    with HWSimRadio(n_channels=2) as (radio, iface):
434        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
435        wpas.interface_add(iface)
436
437        if wpas.get_mcc() < 2:
438           raise Exception("New radio does not support MCC")
439
440        wpas.global_request("SET p2p_no_group_iface 0")
441
442        hapd = hostapd.add_ap(apdev[0],
443                              {"ssid": 'ap-test', "channel": '1'})
444        wpas.connect("ap-test", key_mgmt="NONE", scan_freq="2412")
445        wpas.dump_monitor()
446        channels = {2: 2417, 5: 2432, 9: 2452}
447        for key in channels:
448            res_go = autogo(wpas, channels[key])
449            wpas.dump_monitor()
450            hwsim_utils.test_connectivity(wpas, hapd)
451            if int(res_go['freq']) == 2412:
452                raise Exception("Group operation channel is: 2412 excepted: " + res_go['freq'])
453            wpas.remove_group(res_go['ifname'])
454            wpas.dump_monitor()
455
456def test_go_neg_forced_freq_diff_than_bss_freq(dev, apdev):
457    """P2P channel selection: GO negotiation with forced freq different than station interface"""
458    with HWSimRadio(n_channels=2) as (radio, iface):
459        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
460        wpas.interface_add(iface)
461
462        if wpas.get_mcc() < 2:
463           raise Exception("New radio does not support MCC")
464
465        # Clear possible PBC session overlap from previous test case
466        dev[1].flush_scan_cache()
467
468        wpas.global_request("SET p2p_no_group_iface 0")
469
470        hapd = hostapd.add_ap(apdev[0],
471                              {"country_code": 'US',
472                               "ssid": 'bss-5ghz', "hw_mode": 'a',
473                               "channel": '40'})
474        wpas.connect("bss-5ghz", key_mgmt="NONE", scan_freq="5200")
475
476        # GO and peer force the same freq, different than BSS freq,
477        # wpas to become GO
478        [i_res, r_res] = go_neg_pbc(i_dev=dev[1], i_intent=1, i_freq=5180,
479                                    r_dev=wpas, r_intent=14, r_freq=5180,
480                                    timeout=60)
481        check_grpform_results(i_res, r_res)
482        if i_res['freq'] != "5180":
483           raise Exception("P2P group formed on unexpected frequency: " + i_res['freq'])
484        if r_res['role'] != "GO":
485           raise Exception("GO not selected according to go_intent")
486        hwsim_utils.test_connectivity(wpas, hapd)
487        wpas.remove_group(r_res['ifname'])
488        dev[1].wait_go_ending_session()
489        dev[1].flush_scan_cache()
490
491        # GO and peer force the same freq, different than BSS freq, wpas to
492        # become client
493        [i_res2, r_res2] = go_neg_pbc(i_dev=dev[1], i_intent=14, i_freq=2422,
494                                      r_dev=wpas, r_intent=1, r_freq=2422,
495                                      timeout=60)
496        check_grpform_results(i_res2, r_res2)
497        if i_res2['freq'] != "2422":
498           raise Exception("P2P group formed on unexpected frequency: " + i_res2['freq'])
499        if r_res2['role'] != "client":
500           raise Exception("GO not selected according to go_intent")
501        hwsim_utils.test_connectivity(wpas, hapd)
502
503        hapd.request("DISABLE")
504        wpas.request("DISCONNECT")
505        wpas.request("ABORT_SCAN")
506        wpas.wait_disconnected()
507        subprocess.call(['iw', 'reg', 'set', '00'])
508        wpas.flush_scan_cache()
509
510@remote_compatible
511def test_go_pref_chan_bss_on_diff_chan(dev, apdev):
512    """P2P channel selection: Station on different channel than GO configured pref channel"""
513
514    dev[0].global_request("SET p2p_no_group_iface 0")
515
516    try:
517        hapd = hostapd.add_ap(apdev[0], {"ssid": 'bss-2.4ghz',
518                                         "channel": '1'})
519        dev[0].global_request("SET p2p_pref_chan 81:2")
520        dev[0].connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2412")
521        res = autogo(dev[0])
522        if res['freq'] != "2412":
523           raise Exception("GO channel did not follow BSS")
524        hwsim_utils.test_connectivity(dev[0], hapd)
525    finally:
526        dev[0].global_request("SET p2p_pref_chan ")
527
528def test_go_pref_chan_bss_on_disallowed_chan(dev, apdev):
529    """P2P channel selection: Station interface on different channel than GO configured pref channel, and station channel is disallowed"""
530    with HWSimRadio(n_channels=2) as (radio, iface):
531        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
532        wpas.interface_add(iface)
533
534        if wpas.get_mcc() < 2:
535           raise Exception("New radio does not support MCC")
536
537        wpas.global_request("SET p2p_no_group_iface 0")
538
539        try:
540            hapd = hostapd.add_ap(apdev[0], {"ssid": 'bss-2.4ghz',
541                                             "channel": '1'})
542            wpas.global_request("P2P_SET disallow_freq 2412")
543            wpas.global_request("SET p2p_pref_chan 81:2")
544            wpas.connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2412")
545            res2 = autogo(wpas)
546            if res2['freq'] != "2417":
547               raise Exception("GO channel did not follow pref_chan configuration")
548            hwsim_utils.test_connectivity(wpas, hapd)
549        finally:
550            wpas.global_request("P2P_SET disallow_freq ")
551            wpas.global_request("SET p2p_pref_chan ")
552
553@remote_compatible
554def test_no_go_freq(dev, apdev):
555    """P2P channel selection: no GO freq"""
556    try:
557       dev[0].global_request("SET p2p_no_go_freq 2412")
558       # dev[0] as client, channel 1 is ok
559       [i_res, r_res] = go_neg_pbc(i_dev=dev[0], i_intent=1,
560                                   r_dev=dev[1], r_intent=14, r_freq=2412)
561       check_grpform_results(i_res, r_res)
562       if i_res['freq'] != "2412":
563          raise Exception("P2P group not formed on forced freq")
564
565       dev[1].remove_group(r_res['ifname'])
566       dev[0].wait_go_ending_session()
567       dev[0].flush_scan_cache()
568
569       fail = False
570       # dev[0] as GO, channel 1 is not allowed
571       try:
572          dev[0].global_request("SET p2p_no_go_freq 2412")
573          [i_res2, r_res2] = go_neg_pbc(i_dev=dev[0], i_intent=14,
574                                        r_dev=dev[1], r_intent=1, r_freq=2412)
575          check_grpform_results(i_res2, r_res2)
576          fail = True
577       except:
578           pass
579       if fail:
580           raise Exception("GO set on a disallowed freq")
581    finally:
582       dev[0].global_request("SET p2p_no_go_freq ")
583
584@remote_compatible
585def test_go_neg_peers_force_diff_freq(dev, apdev):
586    """P2P channel selection when peers for different frequency"""
587    try:
588       [i_res2, r_res2] = go_neg_pbc(i_dev=dev[0], i_intent=14, i_freq=5180,
589                                     r_dev=dev[1], r_intent=0, r_freq=5200)
590    except Exception as e:
591        return
592    raise Exception("Unexpected group formation success")
593
594@remote_compatible
595def test_autogo_random_channel(dev, apdev):
596    """P2P channel selection: GO instantiated on random channel 1, 6, 11"""
597    freqs = []
598    go_freqs = ["2412", "2437", "2462"]
599    for i in range(0, 20):
600        result = autogo(dev[0])
601        if result['freq'] not in go_freqs:
602           raise Exception("Unexpected frequency selected: " + result['freq'])
603        if result['freq'] not in freqs:
604            freqs.append(result['freq'])
605        if len(freqs) == 3:
606            break
607        dev[0].remove_group(result['ifname'])
608    if i == 20:
609       raise Exception("GO created 20 times and not all social channels were selected. freqs not selected: " + str(list(set(go_freqs) - set(freqs))))
610
611@remote_compatible
612def test_p2p_autogo_pref_chan_disallowed(dev, apdev):
613    """P2P channel selection: GO preferred channels are disallowed"""
614    try:
615       dev[0].global_request("SET p2p_pref_chan 81:1,81:3,81:6,81:9,81:11")
616       dev[0].global_request("P2P_SET disallow_freq 2412,2422,2437,2452,2462")
617       for i in range(0, 5):
618           res = autogo(dev[0])
619           if res['freq'] in ["2412", "2422", "2437", "2452", "2462"]:
620               raise Exception("GO channel is disallowed")
621           dev[0].remove_group(res['ifname'])
622    finally:
623       dev[0].global_request("P2P_SET disallow_freq ")
624       dev[0].global_request("SET p2p_pref_chan ")
625
626def test_p2p_autogo_pref_chan_not_in_regulatory(dev, apdev):
627    """P2P channel selection: GO preferred channel not allowed in the regulatory rules"""
628    try:
629        set_country("US", dev[0])
630        dev[0].global_request("SET p2p_pref_chan 124:149")
631        res = autogo(dev[0], persistent=True)
632        if res['freq'] != "5745":
633            raise Exception("Unexpected channel selected: " + res['freq'])
634        dev[0].remove_group(res['ifname'])
635
636        netw = dev[0].list_networks(p2p=True)
637        if len(netw) != 1:
638            raise Exception("Unexpected number of network blocks: " + str(netw))
639        id = netw[0]['id']
640
641        set_country("JP", dev[0])
642        res = autogo(dev[0], persistent=id)
643        if res['freq'] == "5745":
644            raise Exception("Unexpected channel selected(2): " + res['freq'])
645        dev[0].remove_group(res['ifname'])
646    finally:
647        dev[0].global_request("SET p2p_pref_chan ")
648        clear_regdom_dev(dev)
649
650def run_autogo(dev, param):
651    if "OK" not in dev.global_request("P2P_GROUP_ADD " + param):
652        raise Exception("P2P_GROUP_ADD failed: " + param)
653    ev = dev.wait_global_event(["P2P-GROUP-STARTED"], timeout=10)
654    if ev is None:
655        raise Exception("GO start up timed out")
656    res = dev.group_form_result(ev)
657    dev.remove_group()
658    return res
659
660def _test_autogo_ht_vht(dev):
661    res = run_autogo(dev[0], "ht40")
662
663    res = run_autogo(dev[0], "vht")
664
665    res = run_autogo(dev[0], "freq=2")
666    freq = int(res['freq'])
667    if freq < 2412 or freq > 2462:
668        raise Exception("Unexpected freq=2 channel: " + str(freq))
669
670    res = run_autogo(dev[0], "freq=5")
671    freq = int(res['freq'])
672    if freq < 5000 or freq >= 6000:
673        raise Exception("Unexpected freq=5 channel: " + str(freq))
674
675    res = run_autogo(dev[0], "freq=5 ht40 vht")
676    logger.info(str(res))
677    freq = int(res['freq'])
678    if freq < 5000 or freq >= 6000:
679        raise Exception("Unexpected freq=5 ht40 vht channel: " + str(freq))
680
681def test_autogo_ht_vht(dev):
682    """P2P autonomous GO with HT/VHT parameters"""
683    try:
684        set_country("US", dev[0])
685        _test_autogo_ht_vht(dev)
686    finally:
687        clear_regdom_dev(dev)
688
689def test_p2p_listen_chan_optimize(dev, apdev):
690    """P2P listen channel optimization"""
691    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
692    wpas.interface_add("wlan5")
693    addr5 = wpas.p2p_dev_addr()
694    try:
695        if "OK" not in wpas.global_request("SET p2p_optimize_listen_chan 1"):
696            raise Exception("Failed to set p2p_optimize_listen_chan")
697        wpas.p2p_listen()
698        if not dev[0].discover_peer(addr5):
699            raise Exception("Could not discover peer")
700        peer = dev[0].get_peer(addr5)
701        lfreq = peer['listen_freq']
702        wpas.p2p_stop_find()
703        dev[0].p2p_stop_find()
704
705        channel = "1" if lfreq != '2412' else "6"
706        freq = "2412" if lfreq != '2412' else "2437"
707        params = {"ssid": "test-open", "channel": channel}
708        hapd = hostapd.add_ap(apdev[0], params)
709
710        id = wpas.connect("test-open", key_mgmt="NONE", scan_freq=freq)
711        wpas.p2p_listen()
712
713        if "OK" not in dev[0].global_request("P2P_FLUSH"):
714            raise Exception("P2P_FLUSH failed")
715        if not dev[0].discover_peer(addr5):
716            raise Exception("Could not discover peer")
717        peer = dev[0].get_peer(addr5)
718        lfreq2 = peer['listen_freq']
719        if lfreq == lfreq2:
720            raise Exception("Listen channel did not change")
721        if lfreq2 != freq:
722            raise Exception("Listen channel not on AP's operating channel")
723        wpas.p2p_stop_find()
724        dev[0].p2p_stop_find()
725
726        wpas.request("DISCONNECT")
727        wpas.wait_disconnected()
728
729        # for larger coverage, cover case of current channel matching
730        wpas.select_network(id)
731        wpas.wait_connected()
732        wpas.request("DISCONNECT")
733        wpas.wait_disconnected()
734
735        lchannel = "1" if channel != "1" else "6"
736        lfreq3 = "2412" if channel != "1" else "2437"
737        if "OK" not in wpas.global_request("P2P_SET listen_channel " + lchannel):
738            raise Exception("Failed to set listen channel")
739
740        wpas.select_network(id)
741        wpas.wait_connected()
742        wpas.p2p_listen()
743
744        if "OK" not in dev[0].global_request("P2P_FLUSH"):
745            raise Exception("P2P_FLUSH failed")
746        if not dev[0].discover_peer(addr5):
747            raise Exception("Could not discover peer")
748        peer = dev[0].get_peer(addr5)
749        lfreq4 = peer['listen_freq']
750        if lfreq4 != lfreq3:
751            raise Exception("Unexpected Listen channel after configuration")
752        wpas.p2p_stop_find()
753        dev[0].p2p_stop_find()
754    finally:
755        wpas.global_request("SET p2p_optimize_listen_chan 0")
756
757def test_p2p_channel_5ghz_only(dev):
758    """P2P GO start with only 5 GHz band allowed"""
759    try:
760        set_country("US", dev[0])
761        dev[0].global_request("P2P_SET disallow_freq 2400-2500")
762        res = autogo(dev[0])
763        freq = int(res['freq'])
764        if freq < 5000:
765            raise Exception("Unexpected channel %d MHz" % freq)
766        dev[0].remove_group()
767    finally:
768        dev[0].global_request("P2P_SET disallow_freq ")
769        clear_regdom_dev(dev)
770
771def test_p2p_channel_5ghz_165_169_us(dev):
772    """P2P GO and 5 GHz channels 165 (allowed) and 169 (disallowed) in US"""
773    try:
774        set_country("US", dev[0])
775        res = dev[0].p2p_start_go(freq=5825)
776        if res['freq'] != "5825":
777            raise Exception("Unexpected frequency: " + res['freq'])
778        dev[0].remove_group()
779
780        res = dev[0].global_request("P2P_GROUP_ADD freq=5845")
781        if "FAIL" not in res:
782            raise Exception("GO on channel 169 allowed unexpectedly")
783    finally:
784        clear_regdom_dev(dev)
785
786def wait_go_down_up(dev):
787    ev = dev.wait_group_event(["AP-DISABLED"], timeout=5)
788    if ev is None:
789        raise Exception("AP-DISABLED not seen after P2P-REMOVE-AND-REFORM-GROUP")
790    ev = dev.wait_group_event(["AP-ENABLED"], timeout=5)
791    if ev is None:
792        raise Exception("AP-ENABLED not seen after P2P-REMOVE-AND-REFORM-GROUP")
793
794def test_p2p_go_move_reg_change(dev, apdev):
795    """P2P GO move due to regulatory change"""
796    try:
797        set_country("US")
798        dev[0].global_request("P2P_SET disallow_freq 2400-5000,5700-6000")
799        res = autogo(dev[0])
800        freq1 = int(res['freq'])
801        if freq1 < 5000:
802            raise Exception("Unexpected channel %d MHz" % freq1)
803        dev[0].dump_monitor()
804
805        dev[0].global_request("P2P_SET disallow_freq ")
806
807        # GO move is not allowed while waiting for initial client connection
808        connect_cli(dev[0], dev[1], freq=freq1)
809        dev[1].remove_group()
810        ev = dev[1].wait_global_event(["P2P-GROUP-REMOVED"], timeout=5)
811        if ev is None:
812            raise Exception("P2P-GROUP-REMOVED not reported on client")
813        dev[1].dump_monitor()
814        dev[0].dump_monitor()
815
816        freq = dev[0].get_group_status_field('freq')
817        if int(freq) < 5000:
818            raise Exception("Unexpected freq after initial client: " + freq)
819        dev[0].dump_monitor()
820
821        dev[0].request("NOTE Setting country=BD")
822        set_country("BD")
823        dev[0].request("NOTE Waiting for GO channel change")
824        ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
825                                      "AP-CSA-FINISHED"],
826                                     timeout=10)
827        if ev is None:
828            raise Exception("P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED not seen")
829        if "P2P-REMOVE-AND-REFORM-GROUP" in ev:
830            wait_go_down_up(dev[0])
831
832        freq2 = dev[0].get_group_status_field('freq')
833        if freq1 == freq2:
834            raise Exception("Unexpected freq after group reform=" + freq2)
835
836        dev[0].remove_group()
837    finally:
838        dev[0].global_request("P2P_SET disallow_freq ")
839        set_country("00")
840
841def test_p2p_go_move_active(dev, apdev):
842    """P2P GO stays in freq although SCM is possible"""
843    with HWSimRadio(n_channels=2) as (radio, iface):
844        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
845        wpas.interface_add(iface)
846
847        if wpas.get_mcc() < 2:
848            raise Exception("New radio does not support MCC")
849
850        ndev = [wpas, dev[1]]
851        _test_p2p_go_move_active(ndev, apdev)
852
853def _test_p2p_go_move_active(dev, apdev):
854    dev[0].global_request("SET p2p_no_group_iface 0")
855    try:
856        dev[0].global_request("P2P_SET disallow_freq 2430-6000")
857        hapd = hostapd.add_ap(apdev[0], {"ssid": 'ap-test',
858                                         "channel": '11'})
859        dev[0].connect("ap-test", key_mgmt="NONE",
860                       scan_freq="2462")
861
862        res = autogo(dev[0])
863        freq = int(res['freq'])
864        if freq > 2430:
865            raise Exception("Unexpected channel %d MHz" % freq)
866
867        # GO move is not allowed while waiting for initial client connection
868        connect_cli(dev[0], dev[1], freq=freq)
869        dev[1].remove_group()
870
871        freq = dev[0].get_group_status_field('freq')
872        if int(freq) > 2430:
873            raise Exception("Unexpected freq after initial client: " + freq)
874
875        dev[0].dump_monitor()
876        dev[0].global_request("P2P_SET disallow_freq ")
877
878        ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
879                                      "AP-CSA-FINISHED"],
880                                     timeout=10)
881        if ev is not None:
882            raise Exception("Unexpected P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED seen")
883
884        dev[0].remove_group()
885    finally:
886        dev[0].global_request("P2P_SET disallow_freq ")
887
888def test_p2p_go_move_scm(dev, apdev):
889    """P2P GO move due to SCM operation preference"""
890    with HWSimRadio(n_channels=2) as (radio, iface):
891        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
892        wpas.interface_add(iface)
893
894        if wpas.get_mcc() < 2:
895            raise Exception("New radio does not support MCC")
896
897        ndev = [wpas, dev[1]]
898        _test_p2p_go_move_scm(ndev, apdev)
899
900def _test_p2p_go_move_scm(dev, apdev):
901    dev[0].global_request("SET p2p_no_group_iface 0")
902    try:
903        dev[0].global_request("P2P_SET disallow_freq 2430-6000")
904        hapd = hostapd.add_ap(apdev[0], {"ssid": 'ap-test',
905                                         "channel": '11'})
906        dev[0].connect("ap-test", key_mgmt="NONE",
907                       scan_freq="2462")
908
909        dev[0].global_request("SET p2p_go_freq_change_policy 0")
910        res = autogo(dev[0])
911        freq = int(res['freq'])
912        if freq > 2430:
913            raise Exception("Unexpected channel %d MHz" % freq)
914
915        # GO move is not allowed while waiting for initial client connection
916        connect_cli(dev[0], dev[1], freq=freq)
917        dev[1].remove_group()
918
919        freq = dev[0].get_group_status_field('freq')
920        if int(freq) > 2430:
921            raise Exception("Unexpected freq after initial client: " + freq)
922
923        dev[0].dump_monitor()
924        dev[0].global_request("P2P_SET disallow_freq ")
925
926        ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
927                                      "AP-CSA-FINISHED"], timeout=3)
928        if ev is None:
929            raise Exception("P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED not seen")
930        if "P2P-REMOVE-AND-REFORM-GROUP" in ev:
931            wait_go_down_up(dev[0])
932
933        freq = dev[0].get_group_status_field('freq')
934        if freq != '2462':
935            raise Exception("Unexpected freq after group reform=" + freq)
936
937        dev[0].remove_group()
938    finally:
939        dev[0].global_request("P2P_SET disallow_freq ")
940        dev[0].global_request("SET p2p_go_freq_change_policy 2")
941
942def test_p2p_go_move_scm_peer_supports(dev, apdev):
943    """P2P GO move due to SCM operation preference (peer supports)"""
944    with HWSimRadio(n_channels=2) as (radio, iface):
945        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
946        wpas.interface_add(iface)
947
948        if wpas.get_mcc() < 2:
949            raise Exception("New radio does not support MCC")
950
951        ndev = [wpas, dev[1]]
952        _test_p2p_go_move_scm_peer_supports(ndev, apdev)
953
954def _test_p2p_go_move_scm_peer_supports(dev, apdev):
955    try:
956        dev[0].global_request("SET p2p_go_freq_change_policy 1")
957        set_country("US", dev[0])
958
959        dev[0].global_request("SET p2p_no_group_iface 0")
960        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
961                                               r_dev=dev[1], r_intent=0,
962                                               test_data=False)
963        check_grpform_results(i_res, r_res)
964        freq = int(i_res['freq'])
965        if freq < 5000:
966            raise Exception("Unexpected channel %d MHz - did not follow 5 GHz preference" % freq)
967
968        hapd = hostapd.add_ap(apdev[0], {"ssid": 'ap-test',
969                                         "channel": '11'})
970        logger.info('Connecting client to to an AP on channel 11')
971        dev[0].connect("ap-test", key_mgmt="NONE",
972                       scan_freq="2462")
973
974        ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
975                                      "AP-CSA-FINISHED"], timeout=3)
976        if ev is None:
977            raise Exception("P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED not seen")
978        if "P2P-REMOVE-AND-REFORM-GROUP" in ev:
979            wait_go_down_up(dev[0])
980
981        freq = dev[0].get_group_status_field('freq')
982        if freq != '2462':
983            raise Exception("Unexpected freq after group reform=" + freq)
984
985        dev[0].remove_group()
986    finally:
987        dev[0].global_request("SET p2p_go_freq_change_policy 2")
988        disable_hapd(hapd)
989        clear_regdom_dev(dev, 1)
990
991def test_p2p_go_move_scm_peer_does_not_support(dev, apdev):
992    """No P2P GO move due to SCM operation (peer does not supports)"""
993    with HWSimRadio(n_channels=2) as (radio, iface):
994        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
995        wpas.interface_add(iface)
996
997        if wpas.get_mcc() < 2:
998            raise Exception("New radio does not support MCC")
999
1000        ndev = [wpas, dev[1]]
1001        _test_p2p_go_move_scm_peer_does_not_support(ndev, apdev)
1002
1003def _test_p2p_go_move_scm_peer_does_not_support(dev, apdev):
1004    try:
1005        dev[0].global_request("SET p2p_go_freq_change_policy 1")
1006        set_country("US", dev[0])
1007
1008        dev[0].global_request("SET p2p_no_group_iface 0")
1009        if "OK" not in dev[1].request("DRIVER_EVENT AVOID_FREQUENCIES 2400-2500"):
1010            raise Exception("Could not simulate driver event")
1011        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
1012                                               r_dev=dev[1], r_intent=0,
1013                                               test_data=False)
1014        check_grpform_results(i_res, r_res)
1015        freq = int(i_res['freq'])
1016        if freq < 5000:
1017            raise Exception("Unexpected channel %d MHz - did not follow 5 GHz preference" % freq)
1018
1019        hapd = hostapd.add_ap(apdev[0], {"ssid": 'ap-test',
1020                                         "channel": '11'})
1021        logger.info('Connecting client to to an AP on channel 11')
1022        dev[0].connect("ap-test", key_mgmt="NONE",
1023                       scan_freq="2462")
1024
1025        ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
1026                                      "AP-CSA-FINISHED"],
1027                                     timeout=10)
1028        if ev is not None:
1029            raise Exception("Unexpected P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED seen")
1030
1031        dev[0].remove_group()
1032    finally:
1033        dev[0].global_request("SET p2p_go_freq_change_policy 2")
1034        dev[1].request("DRIVER_EVENT AVOID_FREQUENCIES")
1035        disable_hapd(hapd)
1036        clear_regdom_dev(dev, 2)
1037
1038def test_p2p_go_move_scm_multi(dev, apdev):
1039    """P2P GO move due to SCM operation preference multiple times"""
1040    with HWSimRadio(n_channels=2) as (radio, iface):
1041        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
1042        wpas.interface_add(iface)
1043
1044        if wpas.get_mcc() < 2:
1045            raise Exception("New radio does not support MCC")
1046
1047        ndev = [wpas, dev[1]]
1048        _test_p2p_go_move_scm_multi(ndev, apdev)
1049
1050def _test_p2p_go_move_scm_multi(dev, apdev):
1051    dev[0].request("SET p2p_no_group_iface 0")
1052    try:
1053        dev[0].global_request("P2P_SET disallow_freq 2430-6000")
1054        hapd = hostapd.add_ap(apdev[0], {"ssid": 'ap-test-1',
1055                                         "channel": '11'})
1056        dev[0].connect("ap-test-1", key_mgmt="NONE",
1057                       scan_freq="2462")
1058
1059        dev[0].global_request("SET p2p_go_freq_change_policy 0")
1060        res = autogo(dev[0])
1061        freq = int(res['freq'])
1062        if freq > 2430:
1063            raise Exception("Unexpected channel %d MHz" % freq)
1064
1065        # GO move is not allowed while waiting for initial client connection
1066        connect_cli(dev[0], dev[1], freq=freq)
1067        dev[1].remove_group()
1068
1069        freq = dev[0].get_group_status_field('freq')
1070        if int(freq) > 2430:
1071            raise Exception("Unexpected freq after initial client: " + freq)
1072
1073        dev[0].dump_monitor()
1074        dev[0].global_request("P2P_SET disallow_freq ")
1075
1076        ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
1077                                      "AP-CSA-FINISHED"], timeout=3)
1078        if ev is None:
1079            raise Exception("P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED not seen")
1080        if "P2P-REMOVE-AND-REFORM-GROUP" in ev:
1081            wait_go_down_up(dev[0])
1082
1083        freq = dev[0].get_group_status_field('freq')
1084        if freq != '2462':
1085            raise Exception("Unexpected freq after group reform=" + freq)
1086
1087        hapd = hostapd.add_ap(apdev[0], {"ssid": 'ap-test-2',
1088                                         "channel": '6'})
1089        dev[0].connect("ap-test-2", key_mgmt="NONE",
1090                       scan_freq="2437")
1091
1092        ev = dev[0].wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
1093                                      "AP-CSA-FINISHED"], timeout=5)
1094        if ev is None:
1095            raise Exception("(2) P2P-REMOVE-AND-REFORM-GROUP or AP-CSA-FINISHED not seen")
1096        if "P2P-REMOVE-AND-REFORM-GROUP" in ev:
1097            wait_go_down_up(dev[0])
1098
1099        freq = dev[0].get_group_status_field('freq')
1100        if freq != '2437':
1101            raise Exception("(2) Unexpected freq after group reform=" + freq)
1102
1103        dev[0].remove_group()
1104    finally:
1105        dev[0].global_request("P2P_SET disallow_freq ")
1106        dev[0].global_request("SET p2p_go_freq_change_policy 2")
1107
1108def test_p2p_delay_go_csa(dev, apdev, params):
1109    """P2P GO CSA delayed when inviting a P2P Device to an active P2P Group"""
1110    with HWSimRadio(n_channels=2) as (radio, iface):
1111        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
1112        wpas.interface_add(iface)
1113
1114        wpas.global_request("SET p2p_no_group_iface 0")
1115
1116        if wpas.get_mcc() < 2:
1117           raise Exception("New radio does not support MCC")
1118
1119        addr0 = wpas.p2p_dev_addr()
1120        addr1 = dev[1].p2p_dev_addr()
1121
1122        try:
1123            dev[1].p2p_listen()
1124            if not wpas.discover_peer(addr1, social=True):
1125                raise Exception("Peer " + addr1 + " not found")
1126            wpas.p2p_stop_find()
1127
1128            hapd = hostapd.add_ap(apdev[0], {"ssid": 'bss-2.4ghz',
1129                                             "channel": '1'})
1130
1131            wpas.connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2412")
1132
1133            wpas.global_request("SET p2p_go_freq_change_policy 0")
1134            wpas.dump_monitor()
1135
1136            logger.info("Start GO on channel 6")
1137            res = autogo(wpas, freq=2437)
1138            if res['freq'] != "2437":
1139               raise Exception("GO set on a freq=%s instead of 2437" % res['freq'])
1140
1141            # Start find on dev[1] to run scans with dev[2] in parallel
1142            dev[1].p2p_find(social=True)
1143
1144            # Use another client device to stop the initial client connection
1145            # timeout on the GO
1146            if not dev[2].discover_peer(addr0, social=True):
1147                raise Exception("Peer2 did not find the GO")
1148            dev[2].p2p_stop_find()
1149            pin = dev[2].wps_read_pin()
1150            wpas.p2p_go_authorize_client(pin)
1151            dev[2].global_request("P2P_CONNECT " + addr0 + " " + pin + " join freq=2437")
1152            ev = dev[2].wait_global_event(["P2P-GROUP-STARTED"], timeout=10)
1153            if ev is None:
1154                raise Exception("Peer2 did not get connected")
1155
1156            if not dev[1].discover_peer(addr0, social=True):
1157                raise Exception("Peer did not find the GO")
1158
1159            pin = dev[1].wps_read_pin()
1160            dev[1].global_request("P2P_CONNECT " + addr0 + " " + pin + " join auth")
1161            dev[1].p2p_listen()
1162
1163            # Force P2P GO channel switch on successful invitation signaling
1164            wpas.group_request("SET p2p_go_csa_on_inv 1")
1165
1166            logger.info("Starting invitation")
1167            wpas.p2p_go_authorize_client(pin)
1168            wpas.global_request("P2P_INVITE group=" + wpas.group_ifname + " peer=" + addr1)
1169            ev = dev[1].wait_global_event(["P2P-INVITATION-RECEIVED",
1170                                           "P2P-GROUP-STARTED"], timeout=10)
1171
1172            if ev is None:
1173                raise Exception("Timeout on invitation on peer")
1174            if "P2P-INVITATION-RECEIVED" in ev:
1175                raise Exception("Unexpected request to accept pre-authorized invitation")
1176
1177            # A P2P GO move is not expected at this stage, as during the
1178            # invitation signaling, the P2P GO includes only its current
1179            # operating channel in the channel list, and as the invitation
1180            # response can only include channels that were also in the
1181            # invitation request channel list, the group common channels
1182            # includes only the current P2P GO operating channel.
1183            ev = wpas.wait_group_event(["P2P-REMOVE-AND-REFORM-GROUP",
1184                                        "AP-CSA-FINISHED"], timeout=1)
1185            if ev is not None:
1186                raise Exception("Unexpected + " + ev + " event")
1187
1188        finally:
1189            wpas.global_request("SET p2p_go_freq_change_policy 2")
1190
1191def test_p2p_channel_vht80(dev):
1192    """P2P group formation with VHT 80 MHz"""
1193    try:
1194        set_country("FI", dev[0])
1195        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
1196                                               i_freq=5180,
1197                                               i_max_oper_chwidth=80,
1198                                               i_ht40=True, i_vht=True,
1199                                               r_dev=dev[1], r_intent=0,
1200                                               test_data=False)
1201        check_grpform_results(i_res, r_res)
1202        freq = int(i_res['freq'])
1203        if freq < 5000:
1204            raise Exception("Unexpected channel %d MHz - did not follow 5 GHz preference" % freq)
1205        sig = dev[1].group_request("SIGNAL_POLL").splitlines()
1206        if "FREQUENCY=5180" not in sig:
1207            raise Exception("Unexpected SIGNAL_POLL value(1): " + str(sig))
1208        if "WIDTH=80 MHz" not in sig:
1209            raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
1210        remove_group(dev[0], dev[1])
1211    finally:
1212        set_country("00")
1213        dev[1].flush_scan_cache()
1214
1215def test_p2p_channel_vht80p80(dev):
1216    """P2P group formation and VHT 80+80 MHz channel"""
1217    try:
1218        set_country("US", dev[0])
1219        [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
1220                                               i_freq=5180,
1221                                               i_freq2=5775,
1222                                               i_max_oper_chwidth=160,
1223                                               i_ht40=True, i_vht=True,
1224                                               r_dev=dev[1], r_intent=0,
1225                                               test_data=False)
1226        check_grpform_results(i_res, r_res)
1227        freq = int(i_res['freq'])
1228        if freq < 5000:
1229            raise Exception("Unexpected channel %d MHz - did not follow 5 GHz preference" % freq)
1230        sig = dev[1].group_request("SIGNAL_POLL").splitlines()
1231        if "FREQUENCY=5180" not in sig:
1232            raise Exception("Unexpected SIGNAL_POLL value(1): " + str(sig))
1233        if "WIDTH=80+80 MHz" not in sig:
1234            raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
1235        if "CENTER_FRQ1=5210" not in sig:
1236            raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
1237        if "CENTER_FRQ2=5775" not in sig:
1238            raise Exception("Unexpected SIGNAL_POLL value(4): " + str(sig))
1239        remove_group(dev[0], dev[1])
1240    finally:
1241        set_country("00")
1242        dev[1].flush_scan_cache()
1243
1244def test_p2p_channel_vht80p80_autogo(dev):
1245    """P2P autonomous GO and VHT 80+80 MHz channel"""
1246    run_p2p_channel_vht80p80_autogo(dev)
1247
1248def test_p2p_channel_vht80p80_autogo_persistent(dev):
1249    """P2P autonomous GO and VHT 80+80 MHz channel (persistent group)"""
1250    run_p2p_channel_vht80p80_autogo(dev, persistent=True)
1251
1252def run_p2p_channel_vht80p80_autogo(dev, persistent=False):
1253    addr0 = dev[0].p2p_dev_addr()
1254
1255    try:
1256        set_country("US", dev[0])
1257
1258        if persistent:
1259            res = dev[0].p2p_start_go(persistent=True)
1260            dev[0].remove_group()
1261
1262            networks = dev[0].list_networks(p2p=True)
1263            if len(networks) != 1:
1264                raise Exception("Unexpected number of networks")
1265            if "[P2P-PERSISTENT]" not in networks[0]['flags']:
1266                raise Exception("Not the persistent group data")
1267            id = networks[0]['id']
1268
1269        cmd = "P2P_GROUP_ADD vht freq=5180 freq2=5775"
1270        if persistent:
1271            cmd += " persistent=" + id
1272        if "OK" not in dev[0].global_request(cmd):
1273            raise Exception("Could not start GO")
1274        ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
1275        if ev is None:
1276            raise Exception("GO start up timed out")
1277        dev[0].group_form_result(ev)
1278
1279        pin = dev[1].wps_read_pin()
1280        dev[0].p2p_go_authorize_client(pin)
1281
1282        dev[1].global_request("P2P_CONNECT " + addr0 + " " + pin + " join freq=5180")
1283        ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=10)
1284        if ev is None:
1285            raise Exception("Peer did not get connected")
1286
1287        dev[1].group_form_result(ev)
1288        sig = dev[1].group_request("SIGNAL_POLL").splitlines()
1289        if "FREQUENCY=5180" not in sig:
1290            raise Exception("Unexpected SIGNAL_POLL value(1): " + str(sig))
1291        if "WIDTH=80+80 MHz" not in sig:
1292            raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
1293        if "CENTER_FRQ1=5210" not in sig:
1294            raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
1295        if "CENTER_FRQ2=5775" not in sig:
1296            raise Exception("Unexpected SIGNAL_POLL value(4): " + str(sig))
1297        remove_group(dev[0], dev[1])
1298    finally:
1299        set_country("00")
1300        dev[1].flush_scan_cache()
1301
1302def test_p2p_channel_vht80_autogo(dev):
1303    """P2P autonomous GO and VHT 80 MHz channel"""
1304    addr0 = dev[0].p2p_dev_addr()
1305
1306    try:
1307        set_country("US", dev[0])
1308        if "OK" not in dev[0].global_request("P2P_GROUP_ADD vht freq=5180 max_oper_chwidth=80"):
1309            raise Exception("Could not start GO")
1310        ev = dev[0].wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
1311        if ev is None:
1312            raise Exception("GO start up timed out")
1313        dev[0].group_form_result(ev)
1314
1315        pin = dev[1].wps_read_pin()
1316        dev[0].p2p_go_authorize_client(pin)
1317
1318        dev[1].global_request("P2P_CONNECT " + addr0 + " " + pin + " join freq=5180")
1319        ev = dev[1].wait_global_event(["P2P-GROUP-STARTED"], timeout=10)
1320        if ev is None:
1321            raise Exception("Peer did not get connected")
1322
1323        dev[1].group_form_result(ev)
1324        sig = dev[1].group_request("SIGNAL_POLL").splitlines()
1325        if "FREQUENCY=5180" not in sig:
1326            raise Exception("Unexpected SIGNAL_POLL value(1): " + str(sig))
1327        if "WIDTH=80 MHz" not in sig:
1328            raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
1329        remove_group(dev[0], dev[1])
1330    finally:
1331        set_country("00")
1332        dev[1].flush_scan_cache()
1333
1334def test_p2p_channel_vht80p80_persistent(dev):
1335    """P2P persistent group re-invocation and VHT 80+80 MHz channel"""
1336    addr0 = dev[0].p2p_dev_addr()
1337    form(dev[0], dev[1])
1338
1339    try:
1340        set_country("US", dev[0])
1341        invite(dev[0], dev[1], extra="vht freq=5745 freq2=5210")
1342        [go_res, cli_res] = check_result(dev[0], dev[1])
1343
1344        sig = dev[1].group_request("SIGNAL_POLL").splitlines()
1345        if "FREQUENCY=5745" not in sig:
1346            raise Exception("Unexpected SIGNAL_POLL value(1): " + str(sig))
1347        if "WIDTH=80+80 MHz" not in sig:
1348            raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
1349        if "CENTER_FRQ1=5775" not in sig:
1350            raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
1351        if "CENTER_FRQ2=5210" not in sig:
1352            raise Exception("Unexpected SIGNAL_POLL value(4): " + str(sig))
1353        remove_group(dev[0], dev[1])
1354    finally:
1355        set_country("00")
1356        dev[1].flush_scan_cache()
1357
1358def test_p2p_channel_drv_pref_go_neg(dev):
1359    """P2P GO Negotiation with GO device channel preference"""
1360    dev[0].global_request("SET get_pref_freq_list_override 3:2417 4:2422")
1361    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
1362                                           r_dev=dev[1], r_intent=0,
1363                                           test_data=False)
1364    check_grpform_results(i_res, r_res)
1365    freq = int(i_res['freq'])
1366    if freq != 2417:
1367        raise Exception("Unexpected channel selected: %d" % freq)
1368    remove_group(dev[0], dev[1])
1369
1370def test_p2p_channel_drv_pref_go_neg2(dev):
1371    """P2P GO Negotiation with P2P client device channel preference"""
1372    dev[0].global_request("SET get_pref_freq_list_override 3:2417,2422")
1373    dev[1].global_request("SET get_pref_freq_list_override 4:2422")
1374    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
1375                                           r_dev=dev[1], r_intent=0,
1376                                           test_data=False)
1377    check_grpform_results(i_res, r_res)
1378    freq = int(i_res['freq'])
1379    if freq != 2422:
1380        raise Exception("Unexpected channel selected: %d" % freq)
1381    remove_group(dev[0], dev[1])
1382
1383def test_p2p_channel_drv_pref_go_neg3(dev):
1384    """P2P GO Negotiation with GO device channel preference"""
1385    dev[1].global_request("SET get_pref_freq_list_override 3:2417,2427 4:2422")
1386    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=0,
1387                                           r_dev=dev[1], r_intent=15,
1388                                           test_data=False)
1389    check_grpform_results(i_res, r_res)
1390    freq = int(i_res['freq'])
1391    if freq != 2417:
1392        raise Exception("Unexpected channel selected: %d" % freq)
1393    remove_group(dev[0], dev[1])
1394
1395def test_p2p_channel_drv_pref_go_neg4(dev):
1396    """P2P GO Negotiation with P2P client device channel preference"""
1397    dev[0].global_request("SET get_pref_freq_list_override 3:2417,2422,5180")
1398    dev[1].global_request("P2P_SET override_pref_op_chan 115:36")
1399    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
1400                                           r_dev=dev[1], r_intent=0,
1401                                           test_data=False)
1402    check_grpform_results(i_res, r_res)
1403    freq = int(i_res['freq'])
1404    if freq != 2417:
1405        raise Exception("Unexpected channel selected: %d" % freq)
1406    remove_group(dev[0], dev[1])
1407
1408def test_p2p_channel_drv_pref_go_neg5(dev):
1409    """P2P GO Negotiation with P2P client device channel preference"""
1410    dev[0].global_request("SET get_pref_freq_list_override 3:2417")
1411    dev[1].global_request("SET get_pref_freq_list_override 4:2422")
1412    dev[1].global_request("P2P_SET override_pref_op_chan 115:36")
1413    [i_res, r_res] = go_neg_pin_authorized(i_dev=dev[0], i_intent=15,
1414                                           r_dev=dev[1], r_intent=0,
1415                                           test_data=False)
1416    check_grpform_results(i_res, r_res)
1417    freq = int(i_res['freq'])
1418    if freq != 2417:
1419        raise Exception("Unexpected channel selected: %d" % freq)
1420    remove_group(dev[0], dev[1])
1421
1422def test_p2p_channel_drv_pref_autogo(dev):
1423    """P2P autonomous GO with driver channel preference"""
1424    dev[0].global_request("SET get_pref_freq_list_override 3:2417,2422,5180")
1425    res_go = autogo(dev[0])
1426    if res_go['freq'] != "2417":
1427        raise Exception("Unexpected operating frequency: " + res_go['freq'])
1428
1429def test_p2p_channel_disable_6ghz(dev):
1430    """P2P with 6 GHz disabled"""
1431    try:
1432        dev[0].global_request("SET p2p_6ghz_disable 1")
1433        dev[1].p2p_listen()
1434        dev[0].discover_peer(dev[1].p2p_dev_addr(), social=False)
1435
1436        autogo(dev[1])
1437        connect_cli(dev[1], dev[0])
1438    finally:
1439        dev[0].global_request("SET p2p_6ghz_disable 0")
1440