File: device_utils_network.go

package info (click to toggle)
incus 6.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 24,392 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (1190 lines) | stat: -rw-r--r-- 36,112 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
package device

import (
	"context"
	"errors"
	"fmt"
	"net"
	"net/netip"
	"os"
	"slices"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/mdlayher/arp"
	"github.com/mdlayher/ndp"
	"golang.org/x/sys/unix"

	deviceConfig "github.com/lxc/incus/v6/internal/server/device/config"
	pcidev "github.com/lxc/incus/v6/internal/server/device/pci"
	"github.com/lxc/incus/v6/internal/server/instance"
	"github.com/lxc/incus/v6/internal/server/instance/instancetype"
	"github.com/lxc/incus/v6/internal/server/ip"
	"github.com/lxc/incus/v6/internal/server/network"
	"github.com/lxc/incus/v6/internal/server/state"
	"github.com/lxc/incus/v6/shared/logger"
	"github.com/lxc/incus/v6/shared/revert"
	"github.com/lxc/incus/v6/shared/units"
	"github.com/lxc/incus/v6/shared/util"
	"github.com/lxc/incus/v6/shared/validate"
)

// Instances can be started in parallel, so lock the creation of VLANs.
var networkCreateSharedDeviceLock sync.Mutex

// NetworkSetDevMTU sets the MTU setting for a named network device if different from current.
func NetworkSetDevMTU(devName string, mtu uint32) error {
	curMTU, err := network.GetDevMTU(devName)
	if err != nil {
		return err
	}

	// Only try and change the MTU if the requested mac is different to current one.
	if curMTU != mtu {
		link := &ip.Link{Name: devName}
		err := link.SetMTU(mtu)
		if err != nil {
			return err
		}
	}

	return nil
}

// NetworkGetDevMAC retrieves the current MAC setting for a named network device.
func NetworkGetDevMAC(devName string) (string, error) {
	content, err := os.ReadFile(fmt.Sprintf("/sys/class/net/%s/address", devName))
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(string(content)), nil
}

// NetworkSetDevMAC sets the MAC setting for a named network device if different from current.
func NetworkSetDevMAC(devName string, mac string) error {
	curMac, err := NetworkGetDevMAC(devName)
	if err != nil {
		return err
	}

	// Only try and change the MAC if the requested mac is different to current one.
	if curMac != mac {
		hwaddr, err := net.ParseMAC(mac)
		if err != nil {
			return fmt.Errorf("Failed parsing MAC address %q: %w", mac, err)
		}

		link := &ip.Link{Name: devName}
		err = link.SetAddress(hwaddr)
		if err != nil {
			return err
		}
	}

	return nil
}

// networkRemoveInterfaceIfNeeded removes a network interface by name but only if no other instance is using it.
func networkRemoveInterfaceIfNeeded(state *state.State, nic string, current instance.Instance, parent string, vlanID string) error {
	// Check if it's used by another instance.
	instances, err := instance.LoadNodeAll(state, instancetype.Any)
	if err != nil {
		return err
	}

	for _, inst := range instances {
		if inst.Name() == current.Name() && inst.Project().Name == current.Project().Name {
			continue
		}

		for devName, dev := range inst.ExpandedDevices() {
			if dev["type"] != "nic" || dev["vlan"] != vlanID || dev["parent"] != parent {
				continue
			}

			// Check if another running instance created the device, if so, don't touch it.
			if util.IsTrue(inst.ExpandedConfig()[fmt.Sprintf("volatile.%s.last_state.created", devName)]) {
				return nil
			}
		}
	}

	return network.InterfaceRemove(nic)
}

// networkCreateVlanDeviceIfNeeded creates a VLAN device if doesn't already exist.
func networkCreateVlanDeviceIfNeeded(state *state.State, parent string, vlanDevice string, vlanID string, gvrp bool) (string, error) {
	if vlanID != "" {
		created, err := network.VLANInterfaceCreate(parent, vlanDevice, vlanID, gvrp)
		if err != nil {
			return "", err
		}

		if created {
			return "created", nil
		}

		// Check if it was created for another running instance.
		instances, err := instance.LoadNodeAll(state, instancetype.Any)
		if err != nil {
			return "", err
		}

		for _, inst := range instances {
			for devName, dev := range inst.ExpandedDevices() {
				if dev["type"] != "nic" || dev["vlan"] != vlanID || dev["parent"] != parent {
					continue
				}

				// Check if another running instance created the device, if so, mark it as created.
				if util.IsTrue(inst.ExpandedConfig()[fmt.Sprintf("volatile.%s.last_state.created", devName)]) {
					return "reused", nil
				}
			}
		}
	}

	return "existing", nil
}

// networkSnapshotPhysicalNIC records properties of the NIC to volatile so they can be restored later.
func networkSnapshotPhysicalNIC(hostName string, volatile map[string]string) error {
	// Store current MTU for restoration on detach.
	mtu, err := network.GetDevMTU(hostName)
	if err != nil {
		return err
	}

	volatile["last_state.mtu"] = fmt.Sprintf("%d", mtu)

	// Store current MAC for restoration on detach
	mac, err := NetworkGetDevMAC(hostName)
	if err != nil {
		return err
	}

	volatile["last_state.hwaddr"] = mac
	return nil
}

// networkRestorePhysicalNIC restores NIC properties from volatile to what they were before it was attached.
func networkRestorePhysicalNIC(hostName string, volatile map[string]string) error {
	// If we created the "physical" device and then it should be removed.
	if util.IsTrue(volatile["last_state.created"]) {
		return network.InterfaceRemove(hostName)
	}

	// Bring the interface down, as this is sometimes needed to change settings on the nic.
	link := &ip.Link{Name: hostName}
	err := link.SetDown()
	if err != nil {
		return fmt.Errorf("Failed to bring down \"%s\": %w", hostName, err)
	}

	// If MTU value is specified then there is an original MTU that needs restoring.
	if volatile["last_state.mtu"] != "" {
		mtuInt, err := strconv.ParseUint(volatile["last_state.mtu"], 10, 32)
		if err != nil {
			return fmt.Errorf("Failed to convert mtu for \"%s\" mtu \"%s\": %w", hostName, volatile["last_state.mtu"], err)
		}

		err = NetworkSetDevMTU(hostName, uint32(mtuInt))
		if err != nil {
			return fmt.Errorf("Failed to restore physical dev \"%s\" mtu to \"%d\": %w", hostName, mtuInt, err)
		}
	}

	// If MAC value is specified then there is an original MAC that needs restoring.
	if volatile["last_state.hwaddr"] != "" {
		err := NetworkSetDevMAC(hostName, volatile["last_state.hwaddr"])
		if err != nil {
			return fmt.Errorf("Failed to restore physical dev \"%s\" mac to \"%s\": %w", hostName, volatile["last_state.hwaddr"], err)
		}
	}

	return nil
}

// networkCreateVethPair creates and configures a veth pair. It will set the hwaddr and mtu settings
// in the supplied config to the newly created peer interface. If mtu is not specified, but parent
// is supplied in config, then the MTU of the new peer interface will inherit the parent MTU.
// Accepts the name of the host side interface as a parameter and returns the peer interface name and MTU used.
func networkCreateVethPair(hostName string, m deviceConfig.Device) (string, uint32, error) {
	var err error

	veth := &ip.Veth{
		Link: ip.Link{
			Name:   hostName,
			Up:     true,
			Master: m["vrf"],
		},
		Peer: ip.Link{
			Name: network.RandomDevName("veth"),
		},
	}

	// Set the MTU on both ends.
	// The host side should always line up with the bridge to avoid accidentally lowering the bridge MTU.
	// The instance side should use the configured MTU (if any), if not, it should match the host side.
	var instanceMTU uint32
	var parentMTU uint32

	if m["parent"] != "" {
		mtu, err := network.GetDevMTU(m["parent"])
		if err != nil {
			return "", 0, fmt.Errorf("Failed to get the parent MTU: %w", err)
		}

		parentMTU = uint32(mtu)
	}

	if m["mtu"] != "" {
		mtu, err := strconv.ParseUint(m["mtu"], 10, 32)
		if err != nil {
			return "", 0, fmt.Errorf("Invalid MTU specified: %w", err)
		}

		instanceMTU = uint32(mtu)
	}

	if instanceMTU == 0 && parentMTU > 0 {
		instanceMTU = parentMTU
	}

	if parentMTU == 0 && instanceMTU > 0 {
		parentMTU = instanceMTU
	}

	if instanceMTU > 0 {
		veth.Peer.MTU = instanceMTU
	}

	if parentMTU > 0 {
		veth.MTU = parentMTU
	}

	// Set the MAC address on peer.
	if m["hwaddr"] != "" {
		hwaddr, err := net.ParseMAC(m["hwaddr"])
		if err != nil {
			return "", 0, fmt.Errorf("Failed parsing MAC address %q: %w", m["hwaddr"], err)
		}

		veth.Peer.Address = hwaddr
	}

	// Set TX queue length on both ends.
	if m["queue.tx.length"] != "" {
		nicTXqlen, err := strconv.ParseUint(m["queue.tx.length"], 10, 32)
		if err != nil {
			return "", 0, fmt.Errorf("Invalid txqueuelen specified: %w", err)
		}

		veth.TXQueueLength = uint32(nicTXqlen)
	} else if m["parent"] != "" {
		veth.TXQueueLength, err = network.GetTXQueueLength(m["parent"])
		if err != nil {
			return "", 0, fmt.Errorf("Failed to get the parent txqueuelen: %w", err)
		}
	}

	veth.Peer.TXQueueLength = veth.TXQueueLength

	// Add and configure the interface in one operation to reduce the number of executions and to avoid
	// systemd-udevd from applying the default MACAddressPolicy=persistent policy.
	err = veth.Add()
	if err != nil {
		return "", 0, fmt.Errorf("Failed to create the veth interfaces %q and %q: %w", hostName, veth.Peer.Name, err)
	}

	return veth.Peer.Name, veth.Peer.MTU, nil
}

// networkCreateTap creates and configures a TAP device.
// Returns the MTU used.
func networkCreateTap(hostName string, m deviceConfig.Device) (uint32, error) {
	tuntap := &ip.Tuntap{
		Name:       hostName,
		Mode:       "tap",
		MultiQueue: true,
		Master:     m["vrf"],
	}

	err := tuntap.Add()
	if err != nil {
		return 0, fmt.Errorf("Failed to create the tap interfaces %q: %w", hostName, err)
	}

	reverter := revert.New()
	defer reverter.Fail()

	link := &ip.Link{Name: hostName}
	err = link.SetUp()
	if err != nil {
		return 0, fmt.Errorf("Failed to bring up the tap interface %q: %w", hostName, err)
	}

	reverter.Add(func() { _ = network.InterfaceRemove(hostName) })

	// Set the MTU on both ends.
	// The host side should always line up with the bridge to avoid accidentally lowering the bridge MTU.
	// The instance side should use the configured MTU (if any), if not, it should match the host side.
	var mtu uint32
	var instanceMTU uint32
	var parentMTU uint32

	if m["parent"] != "" {
		mtu, err := network.GetDevMTU(m["parent"])
		if err != nil {
			return 0, fmt.Errorf("Failed to get the parent MTU: %w", err)
		}

		parentMTU = uint32(mtu)
	}

	if m["mtu"] != "" {
		mtu, err := strconv.ParseUint(m["mtu"], 10, 32)
		if err != nil {
			return 0, fmt.Errorf("Invalid MTU specified: %w", err)
		}

		instanceMTU = uint32(mtu)
	}

	mtu = max(instanceMTU, parentMTU)

	err = NetworkSetDevMTU(hostName, mtu)
	if err != nil {
		return 0, fmt.Errorf("Failed to set the MTU %d: %w", mtu, err)
	}

	// Set TX queue length on both ends.
	var txqueuelen uint32
	if m["queue.tx.length"] != "" {
		nicTXqlen, err := strconv.ParseUint(m["queue.tx.length"], 10, 32)
		if err != nil {
			return 0, fmt.Errorf("Invalid txqueuelen specified: %w", err)
		}

		txqueuelen = uint32(nicTXqlen)
	} else if m["parent"] != "" {
		txqueuelen, err = network.GetTXQueueLength(m["parent"])
		if err != nil {
			return 0, fmt.Errorf("Failed to get the parent txqueuelen: %w", err)
		}
	}

	if txqueuelen > 0 {
		err = link.SetTXQueueLength(txqueuelen)
		if err != nil {
			return 0, fmt.Errorf("Failed to set the TX queue length %d: %w", txqueuelen, err)
		}
	}

	reverter.Success()

	return mtu, nil
}

// networkVethFillFromVolatile fills veth host_name and hwaddr fields from volatile if not set in device config.
func networkVethFillFromVolatile(device deviceConfig.Device, volatile map[string]string) {
	// If not configured, check if volatile data contains the most recently added host_name.
	if device["host_name"] == "" {
		device["host_name"] = volatile["host_name"]
	}

	// If not configured, check if volatile data contains the most recently added hwaddr.
	if device["hwaddr"] == "" {
		device["hwaddr"] = volatile["hwaddr"]
	}
}

// networkNICRouteAdd applies any static host-side routes configured for an instance NIC.
func networkNICRouteAdd(routeDev string, routes ...string) error {
	if !network.InterfaceExists(routeDev) {
		return fmt.Errorf("Route interface missing %q", routeDev)
	}

	reverter := revert.New()
	defer reverter.Fail()

	for _, r := range routes {
		route := r // Local var for revert.
		ipNet, err := ip.ParseIPNet(route)
		if err != nil {
			return fmt.Errorf("Invalid route %q: %w", route, err)
		}

		ipVersion := ip.FamilyV4
		if ipNet.IP.To4() == nil {
			ipVersion = ip.FamilyV6
		}

		// Add IP route (using boot proto to avoid conflicts with network defined static routes).
		r := &ip.Route{
			DevName: routeDev,
			Route:   ipNet,
			Proto:   "boot",
			Family:  ipVersion,
		}

		err = r.Add()
		if err != nil {
			return err
		}

		reverter.Add(func() {
			r := &ip.Route{
				DevName: routeDev,
				Route:   ipNet,
				Proto:   "boot",
				Family:  ipVersion,
			}

			_ = r.Flush()
		})
	}

	reverter.Success()

	return nil
}

// networkNICRouteDelete deletes any static host-side routes configured for an instance NIC.
// Logs any errors and continues to next route to remove.
func networkNICRouteDelete(routeDev string, routes ...string) {
	if routeDev == "" {
		logger.Errorf("Failed removing static route, empty route device specified")
		return
	}

	if !network.InterfaceExists(routeDev) {
		return // Routes will already be gone if device doesn't exist.
	}

	for _, r := range routes {
		route := r // Local var for revert.
		ipNet, err := ip.ParseIPNet(route)
		if err != nil {
			logger.Errorf("Failed to remove static route %q to %q: %v", route, routeDev, err)
			continue
		}

		ipVersion := ip.FamilyV4
		if ipNet.IP.To4() == nil {
			ipVersion = ip.FamilyV6
		}

		// Add IP route (using boot proto to avoid conflicts with network defined static routes).
		r := &ip.Route{
			DevName: routeDev,
			Route:   ipNet,
			Proto:   "boot",
			Family:  ipVersion,
		}

		err = r.Flush()
		if err != nil {
			logger.Errorf("Failed to remove static route %q to %q: %v", route, routeDev, err)
			continue
		}
	}
}

// networkSetupHostVethLimits applies any network rate limits to the veth device specified in the config.
func networkSetupHostVethLimits(d *deviceCommon, oldConfig deviceConfig.Device, bridged bool) error {
	var err error

	veth := d.config["host_name"]

	if veth == "" || !network.InterfaceExists(veth) {
		return fmt.Errorf("Unknown or missing host side veth device %q", veth)
	}

	// Apply max limit
	if d.config["limits.max"] != "" {
		d.config["limits.ingress"] = d.config["limits.max"]
		d.config["limits.egress"] = d.config["limits.max"]
	}

	// Parse the values
	var ingressInt int64
	if d.config["limits.ingress"] != "" {
		ingressInt, err = units.ParseBitSizeString(d.config["limits.ingress"])
		if err != nil {
			return err
		}
	}

	var egressInt int64
	if d.config["limits.egress"] != "" {
		egressInt, err = units.ParseBitSizeString(d.config["limits.egress"])
		if err != nil {
			return err
		}
	}

	// Clean any existing entry
	qdiscIngress := &ip.QdiscIngress{Qdisc: ip.Qdisc{Dev: veth, Handle: "ffff:0"}}
	err = qdiscIngress.Delete()
	if err != nil && !errors.Is(err, unix.ENOENT) {
		return err
	}

	qdiscHTB := &ip.QdiscHTB{Qdisc: ip.Qdisc{Dev: veth, Handle: "1:0", Parent: "root"}}
	err = qdiscHTB.Delete()
	if err != nil && !errors.Is(err, unix.ENOENT) {
		return err
	}

	// Apply new limits
	if d.config["limits.ingress"] != "" {
		qdiscHTB = &ip.QdiscHTB{Qdisc: ip.Qdisc{Dev: veth, Handle: "1:0", Parent: "root"}, Default: 0x10}
		err := qdiscHTB.Add()
		if err != nil {
			return fmt.Errorf("Failed to create root tc qdisc: %s", err)
		}

		classHTB := &ip.ClassHTB{Class: ip.Class{Dev: veth, Parent: "1:0", Classid: "1:10"}, Rate: fmt.Sprintf("%dbit", ingressInt)}
		err = classHTB.Add()
		if err != nil {
			return fmt.Errorf("Failed to create limit tc class: %s", err)
		}

		filter := &ip.U32Filter{Filter: ip.Filter{Dev: veth, Parent: "1:0", Protocol: "all", Flowid: "1:1"}, Value: 0, Mask: 0}
		err = filter.Add()
		if err != nil {
			return fmt.Errorf("Failed to create tc filter: %s", err)
		}
	}

	if d.config["limits.egress"] != "" {
		qdiscIngress = &ip.QdiscIngress{Qdisc: ip.Qdisc{Dev: veth, Handle: "ffff:0"}}
		err := qdiscIngress.Add()
		if err != nil {
			return fmt.Errorf("Failed to create ingress tc qdisc: %s", err)
		}

		police := &ip.ActionPolice{Rate: uint32(egressInt / 8), Burst: uint32(egressInt / 40), Mtu: 65535, Drop: true}
		filter := &ip.U32Filter{Filter: ip.Filter{Dev: veth, Parent: "ffff:0", Protocol: "all"}, Value: 0, Mask: 0, Actions: []ip.Action{police}}
		err = filter.Add()
		if err != nil {
			return fmt.Errorf("Failed to create ingress tc filter: %s", err)
		}
	}

	var networkPriority uint64
	if d.config["limits.priority"] != "" {
		networkPriority, err = strconv.ParseUint(d.config["limits.priority"], 10, 32)
		if err != nil {
			return fmt.Errorf("Failed to parse limits.priority %q: %w", d.config["limits.priority"], err)
		}
	}

	if oldConfig != nil && oldConfig["limits.priority"] != d.config["limits.priority"] {
		err = d.state.Firewall.InstanceClearNetPrio(d.inst.Project().Name, d.inst.Name(), veth)
		if err != nil {
			return err
		}
	}

	if oldConfig == nil || oldConfig["limits.priority"] != d.config["limits.priority"] {
		if networkPriority != 0 {
			if bridged && d.state.Firewall.String() == "xtables" {
				return errors.New("Failed to setup instance device network priority. The xtables firewall driver does not support required functionality.")
			}

			err = d.state.Firewall.InstanceSetupNetPrio(d.inst.Project().Name, d.inst.Name(), veth, uint32(networkPriority))
			if err != nil {
				return fmt.Errorf("Failed to setup instance device network priority: %w", err)
			}
		}
	}

	return nil
}

// networkClearHostVethLimits clears any network rate limits to the veth device specified in the config.
func networkClearHostVethLimits(d *deviceCommon) error {
	err := d.state.Firewall.InstanceClearNetPrio(d.inst.Project().Name, d.inst.Name(), d.config["host_name"])
	if err != nil {
		return err
	}

	return nil
}

// networkValidGateway validates the gateway value.
func networkValidGateway(value string) error {
	if slices.Contains([]string{"none", "auto"}, value) {
		return nil
	}

	return fmt.Errorf("Invalid gateway: %s", value)
}

// bgpAddPrefix adds external routes to the BGP server.
func bgpAddPrefix(d *deviceCommon, n network.Network, config map[string]string) error {
	// BGP is only valid when tied to a managed network.
	if config["network"] == "" {
		return nil
	}

	// Parse nexthop configuration.
	nexthopV4 := net.ParseIP(n.Config()["bgp.ipv4.nexthop"])
	if nexthopV4 == nil {
		nexthopV4 = net.ParseIP(n.Config()["volatile.network.ipv4.address"])
		if nexthopV4 == nil {
			nexthopV4 = net.ParseIP("0.0.0.0")
		}
	}

	nexthopV6 := net.ParseIP(n.Config()["bgp.ipv6.nexthop"])
	if nexthopV6 == nil {
		nexthopV6 = net.ParseIP(n.Config()["volatile.network.ipv6.address"])
		if nexthopV6 == nil {
			nexthopV6 = net.ParseIP("::")
		}
	}

	// Add the prefixes.
	bgpOwner := fmt.Sprintf("instance_%d_%s", d.inst.ID(), d.name)
	if config["ipv4.routes.external"] != "" {
		for _, prefix := range util.SplitNTrimSpace(config["ipv4.routes.external"], ",", -1, true) {
			_, prefixNet, err := net.ParseCIDR(prefix)
			if err != nil {
				return err
			}

			err = d.state.BGP.AddPrefix(*prefixNet, nexthopV4, bgpOwner)
			if err != nil {
				return err
			}
		}
	}

	if config["ipv6.routes.external"] != "" {
		for _, prefix := range util.SplitNTrimSpace(config["ipv6.routes.external"], ",", -1, true) {
			_, prefixNet, err := net.ParseCIDR(prefix)
			if err != nil {
				return err
			}

			err = d.state.BGP.AddPrefix(*prefixNet, nexthopV6, bgpOwner)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func bgpRemovePrefix(d *deviceCommon, config map[string]string) error {
	// BGP is only valid when tied to a managed network.
	if config["network"] == "" {
		return nil
	}

	// Load the network configuration.
	err := d.state.BGP.RemovePrefixByOwner(fmt.Sprintf("instance_%d_%s", d.inst.ID(), d.name))
	if err != nil {
		return err
	}

	return nil
}

// networkSRIOVParentVFInfo returns info about an SR-IOV virtual function from the parent NIC.
func networkSRIOVParentVFInfo(vfParent string, vfID int) (ip.VirtFuncInfo, error) {
	link := &ip.Link{Name: vfParent}
	vfi, err := link.GetVFInfo(vfID)
	return vfi, err
}

// networkSRIOVSetupVF configures a SR-IOV virtual function (VF) on the parent (PF) and stores original properties
// of the PF and VF devices into voltatile for restoration on detach.
// The useSpoofCheck argument controls whether to use the spoof check feature for the VF on the parent device.
// If this is false then "security.mac_filtering" must not be enabled.
// Returns VF PCI device info and IOMMU group number for VMs.
func networkSRIOVSetupVF(d deviceCommon, vfParent string, vfDevice string, vfID int, volatile map[string]string) (pcidev.Device, uint64, error) {
	var vfPCIDev pcidev.Device

	// Retrieve VF settings from parent device.
	vfInfo, err := networkSRIOVParentVFInfo(vfParent, vfID)
	if err != nil {
		return vfPCIDev, 0, err
	}

	reverter := revert.New()
	defer reverter.Fail()

	// Record properties of VF settings on the parent device.
	volatile["last_state.vf.parent"] = vfParent
	volatile["last_state.vf.hwaddr"] = vfInfo.Address.String()
	volatile["last_state.vf.id"] = fmt.Sprintf("%d", vfID)
	volatile["last_state.vf.vlan"] = fmt.Sprintf("%d", vfInfo.VLAN)
	volatile["last_state.vf.spoofcheck"] = fmt.Sprintf("%t", vfInfo.SpoofCheck)

	// Record the host interface we represents the VF device which we will move into instance.
	volatile["host_name"] = vfDevice
	volatile["last_state.created"] = "false" // Indicates don't delete device at stop time.

	// Record properties of VF device.
	err = networkSnapshotPhysicalNIC(volatile["host_name"], volatile)
	if err != nil {
		return vfPCIDev, 0, fmt.Errorf("Failed recording NIC %q settings: %w", volatile["host_name"], err)
	}

	// Get VF device's PCI Slot Name so we can unbind and rebind it from the host.
	vfPCIDev, err = network.SRIOVGetVFDevicePCISlot(vfParent, volatile["last_state.vf.id"])
	if err != nil {
		return vfPCIDev, 0, fmt.Errorf("Failed getting PCI slot for VF %q: %w", volatile["last_state.vf.id"], err)
	}

	// Unbind VF device from the host so that the settings will take effect when we rebind it.
	err = pcidev.DeviceUnbind(vfPCIDev)
	if err != nil {
		return vfPCIDev, 0, err
	}

	reverter.Add(func() { _ = pcidev.DeviceProbe(vfPCIDev) })

	// Setup VF VLAN if specified.
	if d.config["vlan"] != "" {
		link := &ip.Link{Name: vfParent}
		err := link.SetVfVlan(volatile["last_state.vf.id"], d.config["vlan"])
		if err != nil {
			return vfPCIDev, 0, fmt.Errorf("Failed setting VLAN for VF %q: %w", volatile["last_state.vf.id"], err)
		}
	}

	// Setup VF MAC spoofing protection if specified.
	// The ordering of this section is very important, as Intel cards require a very specific
	// order of setup to allow setting custom MACs when using spoof check mode.
	if util.IsTrue(d.config["security.mac_filtering"]) {
		// If no MAC specified in config, use current VF interface MAC.
		mac := d.config["hwaddr"]
		if mac == "" {
			mac = volatile["last_state.hwaddr"]
		}

		// Set MAC on VF (this combined with spoof checking prevents any other MAC being used).
		link := &ip.Link{Name: vfParent}
		err = link.SetVfAddress(volatile["last_state.vf.id"], mac)
		if err != nil {
			return vfPCIDev, 0, fmt.Errorf("Failed setting MAC for VF %q: %w", volatile["last_state.vf.id"], err)
		}

		// Now that MAC is set on VF, we can enable spoof checking.
		err = link.SetVfSpoofchk(volatile["last_state.vf.id"], true)
		if err != nil {
			return vfPCIDev, 0, fmt.Errorf("Failed enabling spoof check for VF %q: %w", volatile["last_state.vf.id"], err)
		}
	} else {
		// Try to reset VF to ensure no previous MAC restriction exists, as some devices require this
		// before being able to set a new VF MAC or disable spoofchecking. However some devices don't
		// allow it so ignore failures.
		link := &ip.Link{Name: vfParent}
		_ = link.SetVfAddress(volatile["last_state.vf.id"], "00:00:00:00:00:00")

		// Ensure spoof checking is disabled if not enabled in instance (only for real VF).
		err = link.SetVfSpoofchk(volatile["last_state.vf.id"], false)
		if err != nil && d.config["security.mac_filtering"] != "" {
			return vfPCIDev, 0, fmt.Errorf("Failed disabling spoof check for VF %q: %w", volatile["last_state.vf.id"], err)
		}

		// Set MAC on VF if specified (this should be passed through into VM when it is bound to vfio-pci).
		if d.inst.Type() == instancetype.VM {
			// If no MAC specified in config, use current VF interface MAC.
			mac := d.config["hwaddr"]
			if mac == "" {
				mac = volatile["last_state.hwaddr"]
			}

			err = link.SetVfAddress(volatile["last_state.vf.id"], mac)
			if err != nil {
				return vfPCIDev, 0, fmt.Errorf("Failed setting MAC for VF %q: %w", volatile["last_state.vf.id"], err)
			}
		}
	}

	// pciIOMMUGroup, used for VM physical passthrough.
	var pciIOMMUGroup uint64

	if d.inst.Type() == instancetype.Container {
		// Bind VF device onto the host so that the settings will take effect.
		err = networkPCIBindWaitInterface(vfPCIDev, volatile["host_name"])
		if err != nil {
			return vfPCIDev, 0, err
		}
	} else if d.inst.Type() == instancetype.VM {
		pciIOMMUGroup, err = pcidev.DeviceIOMMUGroup(vfPCIDev.SlotName)
		if err != nil {
			return vfPCIDev, 0, fmt.Errorf("Failed getting IOMMU group for VF device %q: %w", vfPCIDev.SlotName, err)
		}

		if d.config["acceleration"] != "vdpa" {
			// Register VF device with vfio-pci driver so it can be passed to VM.
			err = pcidev.DeviceDriverOverride(vfPCIDev, "vfio-pci")
			if err != nil {
				return vfPCIDev, 0, fmt.Errorf("Failed overriding driver for VF device %q: %w", vfPCIDev.SlotName, err)
			}
		} else {
			// Bind VF device onto the host so that the settings will take effect.
			err = networkPCIBindWaitInterface(vfPCIDev, volatile["host_name"])
			if err != nil {
				return vfPCIDev, 0, err
			}
		}

		// Record original driver used by VF device for restore.
		volatile["last_state.pci.driver"] = vfPCIDev.Driver
	}

	reverter.Success()

	return vfPCIDev, pciIOMMUGroup, nil
}

// networkSRIOVRestoreVF restores SR-IOV VF device settings on parent PF and on VF NIC. Used when removing a VF NIC
// from an instance. Use volatile data that was stored when the device was first added with networkSRIOVSetupVF().
// The useSpoofCheck argument controls whether to use the spoof check feature for the VF on the parent device.
func networkSRIOVRestoreVF(d deviceCommon, useSpoofCheck bool, volatile map[string]string) error {
	// Retrieve parent interface from config or volatile.
	parent := d.config["parent"]
	if parent == "" {
		parent = volatile["last_state.vf.parent"]
	}

	// Nothing to do if we don't know the original device name or the VF ID.
	if volatile["host_name"] == "" || volatile["last_state.vf.id"] == "" || parent == "" {
		return nil
	}

	reverter := revert.New()
	defer reverter.Fail()

	// Get VF device's PCI info so we can unbind and rebind it from the host.
	vfPCIDev, err := network.SRIOVGetVFDevicePCISlot(parent, volatile["last_state.vf.id"])
	if err != nil {
		return err
	}

	// Unbind VF device from the host so that the restored settings will take effect when we rebind it.
	err = pcidev.DeviceUnbind(vfPCIDev)
	if err != nil {
		return err
	}

	if d.inst.Type() == instancetype.VM {
		// Before we bind the device back to the host, ensure we restore the original driver info as it
		// should be currently set to vfio-pci.
		err = pcidev.DeviceSetDriverOverride(vfPCIDev, volatile["last_state.pci.driver"])
		if err != nil {
			return err
		}
	}

	// However we return from this function, we must try to rebind the VF so its not orphaned.
	// The OS won't let an already bound device be bound again so is safe to call twice.
	reverter.Add(func() { _ = pcidev.DeviceProbe(vfPCIDev) })

	// Reset VF VLAN if specified
	if volatile["last_state.vf.vlan"] != "" {
		link := &ip.Link{Name: parent}
		err := link.SetVfVlan(volatile["last_state.vf.id"], volatile["last_state.vf.vlan"])
		if err != nil {
			return err
		}
	}

	// Reset VF MAC spoofing protection if recorded. Do this first before resetting the MAC
	// to avoid any issues with zero MACs refusing to be set whilst spoof check is on.
	if volatile["last_state.vf.spoofcheck"] != "" {
		mode := util.IsTrue(volatile["last_state.vf.spoofcheck"])
		link := &ip.Link{Name: parent}
		err := link.SetVfSpoofchk(volatile["last_state.vf.id"], mode)
		if err != nil && d.config["security.mac_filtering"] != "" {
			return err
		}
	}

	// Reset VF MAC specified if specified.
	if volatile["last_state.vf.hwaddr"] != "" {
		link := &ip.Link{Name: parent}
		err := link.SetVfAddress(volatile["last_state.vf.id"], volatile["last_state.vf.hwaddr"])
		if err != nil {
			return err
		}
	}

	// Bind VF device onto the host so that the settings will take effect.
	err = networkPCIBindWaitInterface(vfPCIDev, volatile["host_name"])
	if err != nil {
		return err
	}

	// Restore VF interface settings.
	err = networkRestorePhysicalNIC(volatile["host_name"], volatile)
	if err != nil {
		return err
	}

	reverter.Success()

	return nil
}

// networkPCIBindWaitInterface repeatedly requests the pciDev is probed to be bound to the override driver and
// checks whether the expected network interface has appeared as the result of the device driver being bound.
func networkPCIBindWaitInterface(pciDev pcidev.Device, ifName string) error {
	var err error

	waitDuration := time.Second * 10
	waitUntil := time.Now().Add(waitDuration)

	// Keep requesting the device driver be probed in case it was not ready previously or the expected
	// interface has not appeared yet. The device can be probed multiple times safely.

	i := 0
	for {
		err = pcidev.DeviceProbe(pciDev)
		if err == nil && network.InterfaceExists(ifName) {
			return nil
		}

		if time.Now().After(waitUntil) {
			if err != nil {
				return fmt.Errorf("Failed binding interface %q after %v: %w", ifName, waitDuration, err)
			}

			return fmt.Errorf("Failed binding interface %q after %v", ifName, waitDuration)
		}

		if i <= 5 {
			// Retry more quickly early on.
			time.Sleep(time.Millisecond * time.Duration(i) * 10)
		} else {
			time.Sleep(time.Second)
		}

		i++
	}
}

// networkSRIOVSetupContainerVFNIC configures the VF NIC interface ready for moving into container.
// It configures the MAC address and MTU, then brings the interface up.
func networkSRIOVSetupContainerVFNIC(hostName string, config map[string]string) error {
	// Set the MAC address.
	if config["hwaddr"] != "" {
		hwaddr, err := net.ParseMAC(config["hwaddr"])
		if err != nil {
			return fmt.Errorf("Failed parsing MAC address %q: %w", config["hwaddr"], err)
		}

		link := &ip.Link{Name: hostName}
		err = link.SetAddress(hwaddr)
		if err != nil {
			return fmt.Errorf("Failed setting MAC address %q on %q: %w", config["hwaddr"], hostName, err)
		}
	}

	// Set the MTU.
	if config["mtu"] != "" {
		mtu, err := strconv.ParseUint(config["mtu"], 10, 32)
		if err != nil {
			return fmt.Errorf("Invalid VF MTU specified %q: %w", config["mtu"], err)
		}

		link := &ip.Link{Name: hostName}
		err = link.SetMTU(uint32(mtu))
		if err != nil {
			return fmt.Errorf("Failed setting MTU %q on %q: %w", config["mtu"], hostName, err)
		}
	}

	// Bring the interface up.
	link := &ip.Link{Name: hostName}
	err := link.SetUp()
	if err != nil {
		if config["hwaddr"] != "" {
			return fmt.Errorf("Failed to bring up VF interface %q: %w", hostName, err)
		}

		upErr := err

		// If interface fails to come up and MAC not previously set, some NICs require us to set
		// a specific MAC before being allowed to bring up the VF interface. So check if interface
		// has an empty MAC and set a random one if needed.
		vfIF, err := net.InterfaceByName(hostName)
		if err != nil {
			return fmt.Errorf("Failed getting interface info for VF %q: %w", hostName, err)
		}

		// If the VF interface has a MAC already, something else prevented bringing interface up.
		if vfIF.HardwareAddr.String() != "00:00:00:00:00:00" {
			return fmt.Errorf("Failed to bring up VF interface %q: %w", hostName, upErr)
		}

		// Try using a random MAC address and bringing interface up.
		randMAC, err := instance.DeviceNextInterfaceHWAddr()
		if err != nil {
			return fmt.Errorf("Failed generating random MAC for VF %q: %w", hostName, err)
		}

		hwaddr, err := net.ParseMAC(randMAC)
		if err != nil {
			return fmt.Errorf("Failed parsing MAC address %q: %w", randMAC, err)
		}

		link := &ip.Link{Name: hostName}
		err = link.SetAddress(hwaddr)
		if err != nil {
			return fmt.Errorf("Failed to set random MAC address %q on %q: %w", randMAC, hostName, err)
		}

		err = link.SetUp()
		if err != nil {
			return fmt.Errorf("Failed to bring up VF interface %q: %w", hostName, err)
		}
	}

	return nil
}

// isIPAvailable checks if address responds to ARP/NDP neighbour probe on the parentInterface.
// Returns true if IP is in use.
func isIPAvailable(ctx context.Context, address net.IP, parentInterface string) (bool, error) {
	deadline, ok := ctx.Deadline()
	if !ok {
		// Set default timeout of 500ms if no deadline context provided.
		var cancel context.CancelFunc
		ctx, cancel = context.WithTimeout(ctx, time.Duration(500*time.Millisecond))
		defer cancel()
		deadline, _ = ctx.Deadline()
	}

	// Handle IPv4 address.
	if address.To4() != nil {
		err := pingOverIfaceByName(deadline, address, parentInterface)
		if err != nil {
			var ne net.Error
			if errors.As(err, &ne) && ne.Timeout() {
				return false, nil
			}

			return false, err
		}

		return true, nil
	}

	// Handle IPv6 address.
	networkInterface, err := net.InterfaceByName(parentInterface)
	if err != nil {
		return false, err
	}

	conn, _, err := ndp.Listen(networkInterface, ndp.LinkLocal)
	if err != nil {
		return false, err
	}

	defer func() { _ = conn.Close() }()

	netipAddr, ok := netip.AddrFromSlice(address)
	if !ok {
		return false, errors.New("Couldn't convert address to netip")
	}

	solicitedNodeMulticast, err := ndp.SolicitedNodeMulticast(netipAddr)
	if err != nil {
		return false, err
	}

	neighbourSolicitationMessage := &ndp.NeighborSolicitation{
		TargetAddress: netipAddr,
	}

	_ = conn.SetDeadline(deadline)
	err = conn.WriteTo(neighbourSolicitationMessage, nil, solicitedNodeMulticast)
	if err != nil {
		return false, err
	}

	_ = conn.SetDeadline(deadline)
	msg, _, _, err := conn.ReadFrom()
	if err != nil {
		var cause net.Error
		if errors.As(err, &cause) && cause.Timeout() {
			return false, nil
		}

		return false, err
	}

	neighbourAdvertisement, ok := msg.(*ndp.NeighborAdvertisement)
	if ok && neighbourAdvertisement.TargetAddress == netipAddr {
		return true, nil
	}

	return false, nil
}

// networkVLANListExpand takes in a list of raw VLAN values (string) that includes
// different VLAN formats ("number" and "start-end") and convert them into a list of
// expanded VLAN values in integer.
func networkVLANListExpand(rawVLANValues []string) ([]int, error) {
	var networkVLANList []int
	for _, vlan := range rawVLANValues {
		start, count, err := validate.ParseNetworkVLANRange(vlan)
		if err != nil {
			return nil, err
		}

		for i := start; i < start+count; i++ {
			networkVLANList = append(networkVLANList, i)
		}
	}

	return networkVLANList, nil
}

// pingOverIfaceByName sends an ARP request to the given IPv4 address using the specified network interface.
// It respects the provided deadline and returns an error if resolution fails (unless due to timeout).
func pingOverIfaceByName(deadline time.Time, address net.IP, parentInterface string) error {
	// Obtain the network interface.
	ifi, err := net.InterfaceByName(parentInterface)
	if err != nil {
		return err
	}

	// Open an ARP client on that interface.
	c, err := arp.Dial(ifi)
	if err != nil {
		return err
	}

	defer func() { _ = c.Close() }()

	// Honour the caller’s deadline.
	_ = c.SetDeadline(deadline)

	// Convert to netip.Addr which arp.Client expects.
	netipAddr, ok := netip.AddrFromSlice(address.To4())
	if !ok {
		return fmt.Errorf("Invalid IPv4 address: %v", address)
	}

	// Try to resolve the IP → MAC. If it answers, the IP is in use.
	_, err = c.Resolve(netipAddr)
	if err != nil {
		return err
	}

	return nil
}