Debian Codegraph @

src/udev/udev-builtin-net_id.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 /*
4 * Predictable network interface device names based on:
5 * - firmware/bios-provided index numbers for on-board devices
6 * - firmware-provided pci-express hotplug slot index number
7 * - physical/geographical location of the hardware
8 * - the interface's MAC address
9 *
10 * https://systemd.io/PREDICTABLE_INTERFACE_NAMES
11 *
12 * When the code here is changed, man/systemd.net-naming-scheme.xml must be updated too.
13 */
14
15 #include <linux/if.h>
16 #include <linux/if_arp.h>
17 #include <linux/netdevice.h>
18 #include <linux/pci_regs.h>
19 #include <unistd.h>
20
21 #include "alloc-util.h"
22 #include "device-private.h"
23 #include "device-util.h"
24 #include "dirent-util.h"
25 #include "ether-addr-util.h"
26 #include "fd-util.h"
27 #include "fileio.h"
28 #include "glyph-util.h"
29 #include "netif-naming-scheme.h"
30 #include "parse-util.h"
31 #include "stdio-util.h"
32 #include "string-util.h"
33 #include "udev-builtin.h"
34
35 #define ONBOARD_14BIT_INDEX_MAX ((1U << 14) - 1)
36 #define ONBOARD_16BIT_INDEX_MAX ((1U << 16) - 1)
37
38 static int device_get_parent_skip_virtio(sd_device *dev, sd_device **ret) {
39 int r;
40
41 assert(dev);
42 assert(ret);
43
44 /* This provides the parent device, but skips intermediate virtio devices. There can only ever be one
45 * virtio bus per parent device, so we can safely ignore any virtio buses. See
46 * https://lore.kernel.org/virtualization/CAPXgP137A=CdmggtVPUZXbnpTbU9Tewq-sOjg9T8ohYktct1kQ@mail.gmail.com/ */
47
48 for (;;) {
49 r = sd_device_get_parent(dev, &dev);
50 if (r < 0)
51 return r;
52
53 r = device_in_subsystem(dev, "virtio");
54 if (r < 0)
55 return r;
56 if (r == 0) {
57 *ret = dev;
58 return 0;
59 }
60 }
61 }
62
63 static int get_matching_parent(
64 sd_device *dev,
65 char * const *parent_subsystems,
66 bool skip_virtio,
67 sd_device **ret) {
68
69 sd_device *parent;
70 int r;
71
72 assert(dev);
73
74 if (skip_virtio)
75 r = device_get_parent_skip_virtio(dev, &parent);
76 else
77 r = sd_device_get_parent(dev, &parent);
78 if (r < 0)
79 return r;
80
81 /* check if our direct parent is in an expected subsystem. */
82 r = device_in_subsystem_strv(parent, parent_subsystems);
83 if (r < 0)
84 return r;
85 if (r == 0)
86 return -ENODEV;
87
88 if (ret)
89 *ret = parent;
90 return 0;
91 }
92
93 static int get_first_syspath_component(sd_device *dev, const char *prefix, char **ret) {
94 _cleanup_free_ char *buf = NULL;
95 const char *syspath, *p, *q;
96 int r;
97
98 assert(dev);
99 assert(prefix);
100 assert(ret);
101
102 r = sd_device_get_syspath(dev, &syspath);
103 if (r < 0)
104 return r;
105
106 p = path_startswith(syspath, prefix);
107 if (!p)
108 return -EINVAL;
109
110 r = path_find_first_component(&p, /* accept_dot_dot= */ false, &q);
111 if (r < 0)
112 return r;
113
114 buf = strndup(q, r);
115 if (!buf)
116 return -ENOMEM;
117
118 *ret = TAKE_PTR(buf);
119 return r; /* return the length of the string */
120 }
121
122 static int get_virtfn_info(sd_device *pcidev, sd_device **ret_physfn_pcidev, char **ret_suffix) {
123 _cleanup_(sd_device_unrefp) sd_device *physfn_pcidev = NULL;
124 const char *syspath, *name;
125 int r;
126
127 assert(pcidev);
128 assert(ret_physfn_pcidev);
129 assert(ret_suffix);
130
131 r = sd_device_get_syspath(pcidev, &syspath);
132 if (r < 0)
133 return r;
134
135 /* Get physical function's pci device. */
136 r = sd_device_new_child(&physfn_pcidev, pcidev, "physfn");
137 if (r < 0)
138 return r;
139
140 /* Find the virtual function number by finding the right virtfn link. */
141 FOREACH_DEVICE_CHILD_WITH_SUFFIX(physfn_pcidev, child, name) {
142 const char *n, *s;
143
144 /* Only accepts e.g. virtfn0, virtfn1, and so on. */
145 n = startswith(name, "virtfn");
146 if (isempty(n) || !in_charset(n, DIGITS))
147 continue;
148
149 if (sd_device_get_syspath(child, &s) < 0)
150 continue;
151
152 if (streq(s, syspath)) {
153 char *suffix;
154
155 suffix = strjoin("v", n);
156 if (!suffix)
157 return -ENOMEM;
158
159 *ret_physfn_pcidev = sd_device_ref(physfn_pcidev);
160 *ret_suffix = suffix;
161 return 0;
162 }
163 }
164
165 return -ENOENT;
166 }
167
168 static int get_subfunc_info(sd_device *aux_dev, sd_device **ret_parent_pcidev, char **ret_suffix) {
169 sd_device *parent;
170 unsigned sfnum;
171 char *suffix;
172 int r;
173
174 assert(aux_dev);
175 assert(ret_parent_pcidev);
176 assert(ret_suffix);
177
178 /* The auxiliary device must expose an 'sfnum' attribute. This is currently used by the
179 * mlx5_core driver for sub-function (SF) auxiliary devices. The sfnum is the user-defined
180 * stable identifier passed to "devlink port add ... sfnum N". */
181 r = device_get_sysattr_unsigned_filtered(aux_dev, "sfnum", &sfnum);
182 if (r < 0)
183 return r;
184
185 /* Walk one hop up: the auxiliary device's parent must be a PCI function. It can be either
186 * the PF directly, or an SR-IOV VF — mlx5 also supports SFs hosted on VFs (VF-SF), see
187 * Documentation/networking/representors.rst in the kernel tree. The VF case is handled by
188 * the existing virtfn logic in names_pci(), so here we just return the immediate PCI
189 * parent and a single "S<sfnum>" suffix piece. */
190 r = sd_device_get_parent(aux_dev, &parent);
191 if (r < 0)
192 return r;
193
194 r = device_in_subsystem(parent, "pci");
195 if (r < 0)
196 return r;
197 if (r == 0)
198 return -ENODEV;
199
200 if (asprintf(&suffix, "S%u", sfnum) < 0)
201 return log_oom_debug();
202
203 *ret_parent_pcidev = sd_device_ref(parent);
204 *ret_suffix = suffix;
205 return 0;
206 }
207
208 static int get_port_specifier(sd_device *dev, char **ret) {
209 const char *phys_port_name;
210 unsigned dev_port;
211 char *buf;
212 int r;
213
214 assert(dev);
215 assert(ret);
216
217 /* First, try to use the kernel provided front panel port name for multiple port PCI device. */
218 r = device_get_sysattr_safe_string_filtered(dev, "phys_port_name", &phys_port_name);
219 if (r >= 0 && !isempty(phys_port_name)) {
220 if (naming_scheme_has(NAMING_SR_IOV_R)) {
221 int vf_id = -1;
222
223 /* Check if phys_port_name indicates virtual device representor. */
224 (void) sscanf(phys_port_name, "pf%*uvf%d", &vf_id);
225
226 if (vf_id >= 0) {
227 /* For VF representor append 'r<VF_NUM>'. */
228 if (asprintf(&buf, "r%d", vf_id) < 0)
229 return log_oom_debug();
230
231 *ret = buf;
232 return 1;
233 }
234 }
235
236 /* Otherwise, use phys_port_name as is. */
237 buf = strjoin("n", phys_port_name);
238 if (!buf)
239 return log_oom_debug();
240
241 *ret = buf;
242 return 1;
243 }
244
245 /* Then, try to use the kernel provided port index for the case when multiple ports on a single PCI
246 * function. */
247 r = device_get_sysattr_unsigned_filtered(dev, "dev_port", &dev_port);
248 if (r < 0)
249 return log_device_debug_errno(dev, r, "Failed to get device port index: %m");
250 if (r > 0) {
251 assert(dev_port > 0);
252 if (asprintf(&buf, "d%u", dev_port) < 0)
253 return log_oom_debug();
254
255 *ret = buf;
256 return 1;
257 }
258
259 *ret = NULL;
260 return 0;
261 }
262
263 static bool is_valid_onboard_index(unsigned idx) {
264 /* Some BIOSes report rubbish indexes that are excessively high (2^24-1 is an index VMware likes to
265 * report for example). Let's define a cut-off where we don't consider the index reliable anymore. We
266 * pick some arbitrary cut-off, which is somewhere beyond the realistic number of physical network
267 * interface a system might have. Ideally the kernel would already filter this crap for us, but it
268 * doesn't currently. The initial cut-off value (2^14-1) was too conservative for s390 PCI which
269 * allows for index values up 2^16-1 which is now enabled with the NAMING_16BIT_INDEX naming flag. */
270 return idx <= (naming_scheme_has(NAMING_16BIT_INDEX) ? ONBOARD_16BIT_INDEX_MAX : ONBOARD_14BIT_INDEX_MAX);
271 }
272
273 static int pci_get_onboard_index(sd_device *dev, unsigned *ret) {
274 unsigned idx;
275 int r;
276
277 assert(dev);
278 assert(ret);
279
280 /* ACPI _DSM — device specific method for naming a PCI or PCI Express device */
281 r = device_get_sysattr_unsigned_filtered(dev, "acpi_index", &idx);
282 if (r < 0)
283 /* SMBIOS type 41 — Onboard Devices Extended Information */
284 r = device_get_sysattr_unsigned_filtered(dev, "index", &idx);
285 if (r < 0)
286 return log_device_debug_errno(dev, r, "Could not obtain onboard index: %m");
287
288 if (idx == 0 && !naming_scheme_has(NAMING_ZERO_ACPI_INDEX))
289 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
290 "Naming scheme does not allow onboard index==0.");
291 if (!is_valid_onboard_index(idx))
292 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
293 "Not a valid onboard index: %u", idx);
294
295 *ret = idx;
296 return 0;
297 }
298
299 static int names_pci_onboard(UdevEvent *event, sd_device *pci_dev, const char *prefix, const char *suffix) {
300 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
301 _cleanup_free_ char *port = NULL;
302 unsigned idx = 0; /* avoid false maybe-uninitialized warning */
303 int r;
304
305 assert(pci_dev);
306 assert(prefix);
307
308 /* retrieve on-board index number from firmware */
309 r = pci_get_onboard_index(pci_dev, &idx);
310 if (r < 0)
311 return r;
312
313 r = get_port_specifier(dev, &port);
314 if (r < 0)
315 return r;
316
317 char str[ALTIFNAMSIZ];
318 if (snprintf_ok(str, sizeof str, "%so%u%s%s", prefix, idx, strempty(port), strempty(suffix)))
319 udev_builtin_add_property(event, "ID_NET_NAME_ONBOARD", str);
320
321 log_device_debug(dev, "PCI onboard index identifier: index=%u port=%s %s %s",
322 idx, strna(port),
323 glyph(GLYPH_ARROW_RIGHT), empty_to_na(str));
324
325 return 0;
326 }
327
328 static int names_pci_onboard_label(UdevEvent *event, sd_device *pci_dev, const char *prefix) {
329 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
330 const char *label;
331 int r;
332
333 assert(prefix);
334
335 /* retrieve on-board label from firmware */
336 r = device_get_sysattr_safe_string_filtered(pci_dev, "label", &label);
337 if (r < 0)
338 return log_device_debug_errno(pci_dev, r, "Failed to get PCI onboard label: %m");
339
340 char str[ALTIFNAMSIZ];
341 if (snprintf_ok(str, sizeof str, "%s%s",
342 naming_scheme_has(NAMING_LABEL_NOPREFIX) ? "" : prefix,
343 label))
344 udev_builtin_add_property(event, "ID_NET_LABEL_ONBOARD", str);
345
346 log_device_debug(dev, "Onboard label from PCI device: %s", label);
347 return 0;
348 }
349
350 /* read the 256 bytes PCI configuration space to check the multi-function bit */
351 static int is_pci_multifunction(sd_device *dev) {
352 _cleanup_free_ uint8_t *config = NULL;
353 const char *filename, *syspath;
354 size_t len;
355 int r;
356
357 assert(dev);
358
359 r = sd_device_get_syspath(dev, &syspath);
360 if (r < 0)
361 return r;
362
363 filename = strjoina(syspath, "/config");
364 r = read_virtual_file(filename, PCI_HEADER_TYPE + 1, (char **) &config, &len);
365 if (r < 0)
366 return r;
367 if (len < PCI_HEADER_TYPE + 1)
368 return -EINVAL;
369
370 #ifndef PCI_HEADER_TYPE_MULTIFUNC
371 #define PCI_HEADER_TYPE_MULTIFUNC 0x80
372 #endif
373
374 /* bit 0-6 header type, bit 7 multi/single function device */
375 return config[PCI_HEADER_TYPE] & PCI_HEADER_TYPE_MULTIFUNC;
376 }
377
378 static bool is_pci_ari_enabled(sd_device *dev) {
379 assert(dev);
380
381 return device_get_sysattr_bool_filtered(dev, "ari_enabled") > 0;
382 }
383
384 static bool is_pci_bridge(sd_device *dev) {
385 const char *v, *p;
386
387 assert(dev);
388
389 if (device_get_sysattr_safe_string_filtered(dev, "modalias", &v) < 0)
390 return false;
391
392 if (!startswith(v, "pci:"))
393 return false;
394
395 p = strrchr(v, 's');
396 if (!p)
397 return false;
398 if (p[1] != 'c')
399 return false;
400
401 /* PCI device subclass 04 corresponds to PCI bridge */
402 bool b = strneq(p + 2, "04", 2);
403 if (b)
404 log_device_debug(dev, "Device is a PCI bridge.");
405 return b;
406 }
407
408 static int parse_hotplug_slot_from_function_id(sd_device *dev, int slots_dirfd, uint32_t *ret) {
409 uint64_t function_id;
410 char filename[NAME_MAX+1];
411 const char *attr;
412 int r;
413
414 /* The <sysname>/function_id attribute is unique to the s390 PCI driver. If present, we know that the
415 * slot's directory name for this device is /sys/bus/pci/slots/XXXXXXXX/ where XXXXXXXX is the fixed
416 * length 8 hexadecimal character string representation of function_id. Therefore we can short cut
417 * here and just check for the existence of the slot directory. As this directory has to exist, we're
418 * emitting a debug message for the unlikely case it's not found. Note that the domain part doesn't
419 * belong to the slot name here because there's a 1-to-1 relationship between PCI function and its
420 * hotplug slot. See https://docs.kernel.org/arch/s390/pci.html for more details. */
421
422 assert(dev);
423 assert(slots_dirfd >= 0);
424 assert(ret);
425
426 if (!naming_scheme_has(NAMING_SLOT_FUNCTION_ID)) {
427 *ret = 0;
428 return 0;
429 }
430
431 if (device_get_sysattr_safe_string_filtered(dev, "function_id", &attr) < 0) {
432 *ret = 0;
433 return 0;
434 }
435
436 r = safe_atou64(attr, &function_id);
437 if (r < 0)
438 return log_device_debug_errno(dev, r, "Failed to parse function_id, ignoring: '%s'", attr);
439
440 if (function_id <= 0 || function_id > UINT32_MAX)
441 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
442 "Invalid function id (0x%"PRIx64"), ignoring.",
443 function_id);
444
445 if (!snprintf_ok(filename, sizeof(filename), "%08"PRIx64, function_id))
446 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(ENAMETOOLONG),
447 "PCI slot path is too long, ignoring.");
448
449 if (faccessat(slots_dirfd, filename, F_OK, 0) < 0)
450 return log_device_debug_errno(dev, errno, "Cannot access '%s' under pci slots, ignoring: %m", filename);
451
452 *ret = (uint32_t) function_id;
453 return 1; /* Found. We should ignore domain part. */
454 }
455
456 static int pci_get_hotplug_slot_from_address(
457 sd_device *dev,
458 sd_device *pci,
459 DIR *dir,
460 uint32_t *ret) {
461
462 const char *sysname;
463 int r;
464
465 assert(dev);
466 assert(pci);
467 assert(dir);
468 assert(ret);
469
470 r = sd_device_get_sysname(dev, &sysname);
471 if (r < 0)
472 return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
473
474 rewinddir(dir);
475 FOREACH_DIRENT_ALL(de, dir, break) {
476 _cleanup_free_ char *path = NULL;
477 const char *address;
478 uint32_t slot;
479
480 if (dot_or_dot_dot(de->d_name))
481 continue;
482
483 if (de->d_type != DT_DIR)
484 continue;
485
486 r = safe_atou32(de->d_name, &slot);
487 if (r < 0 || slot <= 0)
488 continue;
489
490 path = path_join("slots", de->d_name, "address");
491 if (!path)
492 return log_oom_debug();
493
494 if (device_get_sysattr_safe_string_filtered(pci, path, &address) < 0)
495 continue;
496
497 /* match slot address with device by stripping the function */
498 if (!startswith(sysname, address))
499 continue;
500
501 *ret = slot;
502 return 1; /* found */
503 }
504
505 *ret = 0;
506 return 0; /* not found */
507 }
508
509 static int pci_get_hotplug_slot(sd_device *dev, uint32_t *ret) {
510 _cleanup_(sd_device_unrefp) sd_device *pci = NULL;
511 _cleanup_closedir_ DIR *dir = NULL;
512 int r;
513
514 assert(dev);
515 assert(ret);
516
517 /* ACPI _SUN — slot user number */
518 r = sd_device_new_from_subsystem_sysname(&pci, "subsystem", "pci");
519 if (r < 0)
520 return log_debug_errno(r, "Failed to create sd_device object for pci subsystem: %m");
521
522 r = device_opendir(pci, "slots", &dir);
523 if (r < 0)
524 return log_device_debug_errno(dev, r, "Cannot open 'slots' subdirectory: %m");
525
526 for (sd_device *slot_dev = dev; slot_dev; ) {
527 uint32_t slot = 0; /* avoid false maybe-uninitialized warning */
528
529 r = parse_hotplug_slot_from_function_id(slot_dev, dirfd(dir), &slot);
530 if (r < 0)
531 return r;
532 if (r > 0) {
533 *ret = slot;
534 return 1; /* domain should be ignored. */
535 }
536
537 r = pci_get_hotplug_slot_from_address(slot_dev, pci, dir, &slot);
538 if (r < 0)
539 return r;
540 if (r > 0) {
541 /* We found the match between PCI device and slot. However, we won't use the slot
542 * index if the device is a PCI bridge, because it can have other child devices that
543 * will try to claim the same index and that would create name collision. */
544 if (naming_scheme_has(NAMING_BRIDGE_NO_SLOT) && is_pci_bridge(slot_dev)) {
545 if (naming_scheme_has(NAMING_BRIDGE_MULTIFUNCTION_SLOT) && is_pci_multifunction(dev) <= 0)
546 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(ESTALE),
547 "Not using slot information because the PCI device associated with "
548 "the hotplug slot is a bridge and the PCI device has a single function.");
549
550 if (!naming_scheme_has(NAMING_BRIDGE_MULTIFUNCTION_SLOT))
551 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(ESTALE),
552 "Not using slot information because the PCI device is a bridge.");
553 }
554
555 *ret = slot;
556 return 0; /* domain can be still used. */
557 }
558
559 if (sd_device_get_parent_with_subsystem_devtype(slot_dev, "pci", NULL, &slot_dev) < 0)
560 break;
561 }
562
563 return -ENOENT;
564 }
565
566 static int get_device_firmware_node_sun(sd_device *dev, uint32_t *ret) {
567 const char *attr;
568 int r;
569
570 assert(dev);
571 assert(ret);
572
573 r = device_get_sysattr_safe_string_filtered(dev, "firmware_node/sun", &attr);
574 if (r < 0)
575 return log_device_debug_errno(dev, r, "Failed to read firmware_node/sun, ignoring: %m");
576
577 uint32_t sun;
578 r = safe_atou32(attr, &sun);
579 if (r < 0)
580 return log_device_debug_errno(dev, r, "Failed to parse firmware_node/sun '%s', ignoring: %m", attr);
581 if (sun == 0)
582 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL), "firmware_node/sun == 0, ignoring.");
583
584 *ret = sun;
585 return 0;
586 }
587
588 static int pci_get_slot_from_firmware_node_sun(sd_device *dev, uint32_t *ret) {
589 sd_device *slot_dev;
590 int r;
591
592 assert(dev);
593 assert(ret);
594
595 if (!naming_scheme_has(NAMING_FIRMWARE_NODE_SUN))
596 return -EOPNOTSUPP;
597
598 /* Try getting the ACPI _SUN for the device */
599 if (get_device_firmware_node_sun(dev, ret) >= 0)
600 return 0;
601
602 r = sd_device_get_parent_with_subsystem_devtype(dev, "pci", NULL, &slot_dev);
603 if (r < 0)
604 return log_device_debug_errno(dev, r, "Failed to find parent PCI device, ignoring: %m");
605
606 if (is_pci_bridge(slot_dev) && is_pci_multifunction(dev) <= 0)
607 return log_device_debug_errno(
608 dev, SYNTHETIC_ERRNO(ESTALE),
609 "Not using slot information because the parent PCI slot is a bridge and the PCI device is not multifunction.");
610
611 /* Try getting the ACPI _SUN from the parent pcieport */
612 if (get_device_firmware_node_sun(slot_dev, ret) >= 0)
613 return 0;
614
615 return -ENOENT;
616 }
617
618 static int get_pci_slot_specifiers(
619 sd_device *dev,
620 char **ret_domain,
621 char **ret_bus_and_slot,
622 char **ret_func) {
623
624 _cleanup_free_ char *domain_spec = NULL, *bus_and_slot_spec = NULL, *func_spec = NULL;
625 unsigned domain, bus, slot, func;
626 const char *sysname;
627 int r;
628
629 assert(dev);
630 assert(ret_domain);
631 assert(ret_bus_and_slot);
632 assert(ret_func);
633
634 r = sd_device_get_sysname(dev, &sysname);
635 if (r < 0)
636 return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
637
638 r = sscanf(sysname, "%x:%x:%x.%u", &domain, &bus, &slot, &func);
639 if (r != 4)
640 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
641 "Failed to parse slot information from PCI device sysname.");
642
643 if (naming_scheme_has(NAMING_NPAR_ARI) &&
644 is_pci_ari_enabled(dev))
645 /* ARI devices support up to 256 functions on a single device ("slot"), and interpret the
646 * traditional 5-bit slot and 3-bit function number as a single 8-bit function number,
647 * where the slot makes up the upper 5 bits. */
648 func += slot * 8;
649
650 /* Include the PCI domain in the name if the ID_NET_NAME_INCLUDE_DOMAIN property says so, if it is
651 * set. If it is not set, include it if the domain is non-zero. */
652 r = device_get_property_bool(dev, "ID_NET_NAME_INCLUDE_DOMAIN");
653 if (r < 0) {
654 if (r != -ENOENT)
655 log_device_warning_errno(dev, r, "Failed to read property \"ID_NET_NAME_INCLUDE_DOMAIN\", ignoring: %m");
656
657 r = domain > 0;
658 }
659 if (r > 0 && asprintf(&domain_spec, "P%u", domain) < 0)
660 return log_oom_debug();
661
662 if (asprintf(&bus_and_slot_spec, "p%us%u", bus, slot) < 0)
663 return log_oom_debug();
664
665 if ((func > 0 || is_pci_multifunction(dev) > 0) &&
666 asprintf(&func_spec, "f%u", func) < 0)
667 return log_oom_debug();
668
669 *ret_domain = TAKE_PTR(domain_spec);
670 *ret_bus_and_slot = TAKE_PTR(bus_and_slot_spec);
671 *ret_func = TAKE_PTR(func_spec);
672 return 0;
673 }
674
675 static int names_pci_slot(UdevEvent *event, sd_device *pci_dev, const char *prefix, const char *suffix) {
676 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
677 _cleanup_free_ char *domain = NULL, *bus_and_slot = NULL, *func = NULL, *port = NULL;
678 uint32_t slot = 0; /* avoid false maybe-uninitialized warning */
679 char str[ALTIFNAMSIZ];
680 int r;
681
682 assert(pci_dev);
683 assert(prefix);
684
685 r = get_pci_slot_specifiers(pci_dev, &domain, &bus_and_slot, &func);
686 if (r < 0)
687 return r;
688
689 r = get_port_specifier(dev, &port);
690 if (r < 0)
691 return r;
692
693 /* compose a name based on the raw kernel's PCI bus, slot numbers */
694 if (snprintf_ok(str, sizeof str, "%s%s%s%s%s%s",
695 prefix, strempty(domain), bus_and_slot, strempty(func), strempty(port), strempty(suffix)))
696 udev_builtin_add_property(event, "ID_NET_NAME_PATH", str);
697
698 log_device_debug(dev, "PCI path identifier: domain=%s bus_and_slot=%s func=%s port=%s %s %s",
699 strna(domain), bus_and_slot, strna(func), strna(port),
700 glyph(GLYPH_ARROW_RIGHT), empty_to_na(str));
701
702 if (pci_get_slot_from_firmware_node_sun(pci_dev, &slot) < 0) {
703 /* If we don't find a slot using firmware_node/sun, fallback to hotplug_slot */
704 r = pci_get_hotplug_slot(pci_dev, &slot);
705 if (r < 0)
706 return r;
707 if (r > 0)
708 /* If the hotplug slot is found through the function ID, then drop the domain from the name.
709 * See comments in parse_hotplug_slot_from_function_id(). */
710 domain = mfree(domain);
711 }
712
713 if (snprintf_ok(str, sizeof str, "%s%ss%"PRIu32"%s%s%s",
714 prefix, strempty(domain), slot, strempty(func), strempty(port), strempty(suffix)))
715 udev_builtin_add_property(event, "ID_NET_NAME_SLOT", str);
716
717 log_device_debug(dev, "PCI slot identifier: domain=%s slot=%"PRIu32" func=%s port=%s %s %s",
718 strna(domain), slot, strna(func), strna(port),
719 glyph(GLYPH_ARROW_RIGHT), empty_to_na(str));
720
721 return 0;
722 }
723
724 static int names_vio(UdevEvent *event, const char *prefix) {
725 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
726 _cleanup_free_ char *s = NULL;
727 unsigned slotid;
728 int r;
729
730 assert(prefix);
731
732 /* get ibmveth/ibmvnic slot-based names. */
733
734 /* check if our direct parent is a VIO device with no other bus in-between */
735 if (get_matching_parent(dev, STRV_MAKE("vio"), /* skip_virtio= */ false, NULL) < 0)
736 return 0;
737
738 log_device_debug(dev, "Parent device is in the vio subsystem.");
739
740 /* The devices' $DEVPATH number is tied to (virtual) hardware (slot id
741 * selected in the HMC), thus this provides a reliable naming (e.g.
742 * "/devices/vio/30000002/net/eth1"); we ignore the bus number, as
743 * there should only ever be one bus, and then remove leading zeros. */
744 r = get_first_syspath_component(dev, "/sys/devices/vio/", &s);
745 if (r < 0)
746 return log_device_debug_errno(dev, r, "Failed to get VIO bus ID and slot ID: %m");
747
748 if (r != 8)
749 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
750 "VIO bus ID and slot ID have invalid length: '%s'", s);
751
752 if (!in_charset(s, HEXDIGITS))
753 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
754 "VIO bus ID and slot ID contain invalid characters: '%s'", s);
755
756 /* Parse only slot ID (the last 4 hexdigits). */
757 r = safe_atou_full(s + 4, 16, &slotid);
758 if (r < 0)
759 return log_device_debug_errno(dev, r, "Failed to parse VIO slot from '%s': %m", s);
760
761 char str[ALTIFNAMSIZ];
762 if (snprintf_ok(str, sizeof str, "%sv%u", prefix, slotid))
763 udev_builtin_add_property(event, "ID_NET_NAME_SLOT", str);
764 log_device_debug(dev, "Vio slot identifier: slotid=%u %s %s",
765 slotid, glyph(GLYPH_ARROW_RIGHT), str + strlen(prefix));
766 return 0;
767 }
768
769 static int names_platform(UdevEvent *event, const char *prefix) {
770 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
771 _cleanup_free_ char *p = NULL;
772 const char *validchars;
773 char *vendor, *model_str, *instance_str;
774 unsigned model, instance;
775 int r;
776
777 assert(prefix);
778
779 /* get ACPI path names for ARM64 platform devices */
780
781 /* check if our direct parent is a platform device with no other bus in-between */
782 if (get_matching_parent(dev, STRV_MAKE("platform"), /* skip_virtio= */ false, NULL) < 0)
783 return 0;
784
785 log_device_debug(dev, "Parent device is in the platform subsystem.");
786
787 r = get_first_syspath_component(dev, "/sys/devices/platform/", &p);
788 if (r < 0)
789 return log_device_debug_errno(dev, r, "Failed to get platform ID: %m");
790
791 /* Platform devices are named after ACPI table match, and instance id
792 * eg. "/sys/devices/platform/HISI00C2:00"
793 * The Vendor (3 or 4 char), followed by hexadecimal model number : instance id. */
794 if (r == 10 && p[7] == ':') {
795 /* 3 char vendor string */
796 vendor = strndupa_safe(p, 3);
797 model_str = strndupa_safe(p + 3, 4);
798 instance_str = strndupa_safe(p + 8, 2);
799 validchars = UPPERCASE_LETTERS;
800 } else if (r == 11 && p[8] == ':') {
801 /* 4 char vendor string */
802 vendor = strndupa_safe(p, 4);
803 model_str = strndupa_safe(p + 4, 4);
804 instance_str = strndupa_safe(p + 9, 2);
805 validchars = UPPERCASE_LETTERS DIGITS;
806 } else
807 return -EOPNOTSUPP;
808
809 if (!in_charset(vendor, validchars))
810 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
811 "Platform vendor contains invalid characters: '%s'", vendor);
812
813 ascii_strlower(vendor);
814
815 r = safe_atou_full(model_str, 16, &model);
816 if (r < 0)
817 return log_device_debug_errno(dev, r, "Failed to parse model number \"%s\": %m", model_str);
818
819 r = safe_atou_full(instance_str, 16, &instance);
820 if (r < 0)
821 return log_device_debug_errno(dev, r, "Failed to parse instance id \"%s\": %m", instance_str);
822
823 char str[ALTIFNAMSIZ];
824 if (snprintf_ok(str, sizeof str, "%sa%s%xi%u", prefix, vendor, model, instance))
825 udev_builtin_add_property(event, "ID_NET_NAME_PATH", str);
826 log_device_debug(dev, "Platform identifier: vendor=%s model=%x instance=%u %s %s",
827 vendor, model, instance, glyph(GLYPH_ARROW_RIGHT), str + strlen(prefix));
828 return 0;
829 }
830
831 static int names_devicetree_alias_prefix(UdevEvent *event, const char *prefix, const char *alias_prefix) {
832 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
833 _cleanup_(sd_device_unrefp) sd_device *aliases_dev = NULL, *ofnode_dev = NULL, *devicetree_dev = NULL;
834 const char *ofnode_path, *ofnode_syspath, *devicetree_syspath;
835 int r;
836
837 assert(prefix);
838 assert(alias_prefix);
839
840 /* Returns 1 if found, 0 if not found, negative if error */
841
842 _cleanup_free_ char *alias_prefix_0 = strjoin(alias_prefix, "0");
843 if (!alias_prefix_0)
844 return log_oom_debug();
845
846 /* check if the device itself has an of_node */
847 if (naming_scheme_has(NAMING_DEVICETREE_PORT_ALIASES)) {
848 r = sd_device_new_child(&ofnode_dev, dev, "of_node");
849 if (r < 0)
850 log_device_debug_errno(dev, r, "Failed to get device of_node, ignoring: %m");
851 }
852 if (!ofnode_dev) {
853 sd_device *parent;
854
855 /* check if our direct parent has an of_node as a fallback */
856 r = sd_device_get_parent(dev, &parent);
857 if (r < 0)
858 return log_device_debug_errno(dev, r, "Failed to get parent device: %m");
859
860 r = sd_device_new_child(&ofnode_dev, parent, "of_node");
861 if (r < 0)
862 return log_device_debug_errno(parent, r, "Failed to get device of_node: %m");
863 }
864
865 r = sd_device_get_syspath(ofnode_dev, &ofnode_syspath);
866 if (r < 0)
867 return log_device_debug_errno(ofnode_dev, r, "Failed to get syspath: %m");
868
869 /* /proc/device-tree should be a symlink to /sys/firmware/devicetree/base. */
870 r = sd_device_new_from_path(&devicetree_dev, "/proc/device-tree");
871 if (r < 0)
872 return log_debug_errno(r, "Failed to create sd-device object from '/proc/device-tree': %m");
873
874 r = sd_device_get_syspath(devicetree_dev, &devicetree_syspath);
875 if (r < 0)
876 return log_device_debug_errno(devicetree_dev, r, "Failed to get syspath: %m");
877
878 /*
879 * Example paths:
880 * devicetree_syspath = /sys/firmware/devicetree/base
881 * ofnode_syspath = /sys/firmware/devicetree/base/soc/ethernet@deadbeef
882 * ofnode_path = soc/ethernet@deadbeef
883 */
884 ofnode_path = path_startswith(ofnode_syspath, devicetree_syspath);
885 if (!ofnode_path)
886 return log_device_debug_errno(ofnode_dev, SYNTHETIC_ERRNO(EINVAL),
887 "The device '%s' is not a child device of '%s'.",
888 ofnode_syspath, devicetree_syspath);
889
890 /* Get back our leading / to match the contents of the aliases */
891 ofnode_path--;
892 assert(path_is_absolute(ofnode_path));
893
894 r = sd_device_new_child(&aliases_dev, devicetree_dev, "aliases");
895 if (r < 0)
896 return log_device_debug_errno(devicetree_dev, r,
897 "Failed to get 'aliases' child device: %m");
898
899 FOREACH_DEVICE_SYSATTR(aliases_dev, alias) {
900 const char *alias_path, *alias_index, *conflict;
901 unsigned i;
902
903 alias_index = startswith(alias, alias_prefix);
904 if (!alias_index)
905 continue;
906
907 if (device_get_sysattr_safe_string_filtered(aliases_dev, alias, &alias_path) < 0)
908 continue;
909
910 if (!path_equal(ofnode_path, alias_path))
911 continue;
912
913 /* If there's no index, we default to 0... */
914 if (isempty(alias_index)) {
915 i = 0;
916 conflict = alias_prefix_0;
917 } else {
918 r = safe_atou(alias_index, &i);
919 if (r < 0)
920 return log_device_debug_errno(dev, r,
921 "Could not get index of alias '%s': %m", alias);
922 conflict = alias_prefix;
923 }
924
925 /* ...but make sure we don't have an alias conflict */
926 if (i == 0 && device_get_sysattr_safe_string_filtered(aliases_dev, conflict, NULL) >= 0)
927 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EEXIST),
928 "DeviceTree alias conflict: '%s' and '%s' both exist.",
929 alias_prefix, alias_prefix_0);
930
931 char str[ALTIFNAMSIZ];
932 if (snprintf_ok(str, sizeof str, "%sd%u", prefix, i))
933 udev_builtin_add_property(event, "ID_NET_NAME_ONBOARD", str);
934 log_device_debug(dev, "DeviceTree identifier: alias_index=%u %s \"%s\"",
935 i, glyph(GLYPH_ARROW_RIGHT), str + strlen(prefix));
936 return 1;
937 }
938
939 return 0;
940 }
941
942 static int names_devicetree(UdevEvent *event, const char *prefix) {
943 int r;
944
945 assert(event);
946 assert(prefix);
947
948 if (!naming_scheme_has(NAMING_DEVICETREE_ALIASES))
949 return 0;
950
951 if (streq(prefix, "en"))
952 r = names_devicetree_alias_prefix(event, prefix, "ethernet");
953 else if (naming_scheme_has(NAMING_DEVICETREE_ALIASES_WLAN) &&
954 streq(prefix, "wl")) {
955 r = names_devicetree_alias_prefix(event, prefix, "wifi");
956 /* Sometimes DeviceTrees have WLAN devices with alias ethernetN, fall back to those */
957 if (r == 0)
958 r = names_devicetree_alias_prefix(event, prefix, "ethernet");
959 } else
960 return -EOPNOTSUPP; /* Unsupported interface type */
961 if (r < 0)
962 return r;
963 if (r == 0) /* Not found */
964 return -ENOENT;
965
966 return 0; /* Found */
967 };
968
969 static int names_pci(UdevEvent *event, const char *prefix) {
970 sd_device *parent, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
971 _cleanup_(sd_device_unrefp) sd_device *physfn_pcidev = NULL, *parent_pcidev = NULL;
972 _cleanup_free_ char *virtfn_suffix = NULL, *subfunc_suffix = NULL, *combined_suffix = NULL;
973 const char *suffix = NULL;
974
975 assert(prefix);
976
977 /* If the network device's direct parent is an auxiliary device that exposes a stable
978 * 'sfnum' attribute (currently mlx5_core sub-functions), peel off the SF identity into
979 * a 'S<sfnum>' suffix piece and pick up the aux device's underlying PCI function as
980 * 'parent'. The aux device is just a bump on the path; everything below — PF/VF
981 * resolution, slot/onboard lookup — proceeds the same way as for any PCI-rooted
982 * network device. */
983 if (naming_scheme_has(NAMING_SUBFUNC)) {
984 sd_device *aux;
985
986 if (get_matching_parent(dev, STRV_MAKE("auxiliary"),
987 /* skip_virtio= */ false, &aux) >= 0)
988 (void) get_subfunc_info(aux, &parent_pcidev, &subfunc_suffix);
989 }
990
991 /* SF: parent is the aux device's PCI function. Otherwise the network device's direct
992 * parent must itself be a PCI device. */
993 if (subfunc_suffix)
994 parent = parent_pcidev;
995 else if (get_matching_parent(dev, STRV_MAKE("pci"), /* skip_virtio= */ true, &parent) < 0)
996 return 0;
997
998 /* If parent is an SR-IOV VF, walk to the parent PF and add a 'v<N>' suffix piece. The
999 * onboard BIOS label is intentionally not exposed for any "child function" (VF, SF, or
1000 * VF-SF), since the label refers to the parent's physical port, not to a logical child. */
1001 bool is_child_function = !!subfunc_suffix;
1002 if (naming_scheme_has(NAMING_SR_IOV_V) &&
1003 get_virtfn_info(parent, &physfn_pcidev, &virtfn_suffix) >= 0) {
1004 parent = physfn_pcidev;
1005 is_child_function = true;
1006 }
1007 if (!is_child_function)
1008 (void) names_pci_onboard_label(event, parent, prefix);
1009
1010 /* Compose the final suffix in PF -> [VF ->] SF order, e.g. "v0", "S88", or "v0S88". */
1011 if (virtfn_suffix && subfunc_suffix) {
1012 combined_suffix = strjoin(virtfn_suffix, subfunc_suffix);
1013 if (!combined_suffix)
1014 return log_oom_debug();
1015 suffix = combined_suffix;
1016 } else
1017 suffix = virtfn_suffix ?: subfunc_suffix;
1018
1019 (void) names_pci_onboard(event, parent, prefix, suffix);
1020 (void) names_pci_slot(event, parent, prefix, suffix);
1021 return 0;
1022 }
1023
1024 static int get_usb_specifier(sd_device *dev, char **ret) {
1025 char *ports, *config, *interf, *buf;
1026 const char *sysname;
1027 int r;
1028
1029 assert(dev);
1030 assert(ret);
1031
1032 r = sd_device_get_sysname(dev, &sysname);
1033 if (r < 0)
1034 return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
1035
1036 /* get USB port number chain, configuration, interface */
1037 const char *s = strchr(sysname, '-');
1038 if (!s)
1039 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
1040 "sysname \"%s\" does not have '-' in the expected place.", sysname);
1041
1042 ports = strdupa_safe(s + 1);
1043 char *t = strchr(ports, ':');
1044 if (!t)
1045 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
1046 "sysname \"%s\" does not have ':' in the expected place.", sysname);
1047
1048 *t = '\0';
1049 config = t + 1;
1050 t = strchr(config, '.');
1051 if (!t)
1052 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
1053 "sysname \"%s\" does not have '.' in the expected place.", sysname);
1054
1055 *t = '\0';
1056 interf = t + 1;
1057
1058 /* prefix every port number in the chain with "u" */
1059 string_replace_char(ports, '.', 'u');
1060
1061 /* suppress the common config == 1 */
1062 if (streq(config, "1"))
1063 config = NULL;
1064
1065 /* suppress the interface == 0 */
1066 if (streq(interf, "0"))
1067 interf = NULL;
1068
1069 buf = strjoin("u", ports,
1070 config ? "c" : "", strempty(config),
1071 interf ? "i" : "", strempty(interf));
1072 if (!buf)
1073 return log_oom_debug();
1074
1075 log_device_debug(dev, "USB name identifier: ports=%s config=%s interface=%s %s %s",
1076 ports, strna(config), strna(interf),
1077 glyph(GLYPH_ARROW_RIGHT), buf);
1078
1079 *ret = buf;
1080 return 0;
1081 }
1082
1083 static int names_usb(UdevEvent *event, const char *prefix) {
1084 sd_device *usbdev, *pcidev, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
1085 _cleanup_free_ char *suffix = NULL;
1086 int r;
1087
1088 assert(prefix);
1089
1090 /* USB device */
1091
1092 r = sd_device_get_parent_with_subsystem_devtype(dev, "usb", "usb_interface", &usbdev);
1093 if (r < 0)
1094 return log_device_debug_errno(dev, r, "Could not find USB parent device: %m");
1095
1096 r = get_usb_specifier(usbdev, &suffix);
1097 if (r < 0)
1098 return r;
1099
1100 /* If the USB bus is on PCI bus, then suffix the USB specifier to the name based on the PCI bus. */
1101 r = sd_device_get_parent_with_subsystem_devtype(usbdev, "pci", NULL, &pcidev);
1102 if (r >= 0)
1103 return names_pci_slot(event, pcidev, prefix, suffix);
1104
1105 if (r != -ENOENT || !naming_scheme_has(NAMING_USB_HOST))
1106 return log_device_debug_errno(usbdev, r, "Failed to get parent PCI bus: %m");
1107
1108 /* Otherwise, e.g. on-chip asics that have USB ports, use the USB specifier as is. */
1109 char str[ALTIFNAMSIZ];
1110 if (snprintf_ok(str, sizeof str, "%s%s", prefix, suffix))
1111 udev_builtin_add_property(event, "ID_NET_NAME_PATH", str);
1112
1113 return 0;
1114 }
1115
1116 static int get_bcma_specifier(sd_device *dev, char **ret) {
1117 const char *sysname;
1118 char *buf = NULL;
1119 unsigned core;
1120 int r;
1121
1122 assert(dev);
1123 assert(ret);
1124
1125 r = sd_device_get_sysname(dev, &sysname);
1126 if (r < 0)
1127 return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
1128
1129 /* bus num:core num */
1130 r = sscanf(sysname, "bcma%*u:%u", &core);
1131 if (r != 1)
1132 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
1133 "Failed to parse BCMA device information.");
1134
1135 /* suppress the common core == 0 */
1136 if (core > 0 && asprintf(&buf, "b%u", core) < 0)
1137 return log_oom_debug();
1138
1139 log_device_debug(dev, "BCMA core identifier: core=%u %s \"%s\"",
1140 core, glyph(GLYPH_ARROW_RIGHT), strna(buf));
1141
1142 *ret = buf;
1143 return 0;
1144 }
1145
1146 static int names_bcma(UdevEvent *event, const char *prefix) {
1147 sd_device *bcmadev, *pcidev, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
1148 _cleanup_free_ char *suffix = NULL;
1149 int r;
1150
1151 assert(prefix);
1152
1153 r = sd_device_get_parent_with_subsystem_devtype(dev, "bcma", NULL, &bcmadev);
1154 if (r < 0)
1155 return log_device_debug_errno(dev, r, "Could not get BCMA parent device: %m");
1156
1157 r = sd_device_get_parent_with_subsystem_devtype(bcmadev, "pci", NULL, &pcidev);
1158 if (r < 0)
1159 return log_device_debug_errno(dev, r, "Could not get PCI parent device: %m");
1160
1161 r = get_bcma_specifier(bcmadev, &suffix);
1162 if (r < 0)
1163 return r;
1164
1165 return names_pci_slot(event, pcidev, prefix, suffix);
1166 }
1167
1168 static int names_ccw(UdevEvent *event, const char *prefix) {
1169 sd_device *cdev, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
1170 const char *bus_id;
1171 size_t bus_id_start, bus_id_len;
1172 int r;
1173
1174 assert(prefix);
1175
1176 /* get path names for Linux on System z network devices */
1177
1178 if (get_matching_parent(dev, STRV_MAKE("ccwgroup", "ccw"), /* skip_virtio= */ true, &cdev) < 0)
1179 return 0;
1180
1181 log_device_debug(dev, "Device is CCW.");
1182
1183 /* Retrieve bus-ID of the CCW device. The bus-ID uniquely
1184 * identifies the network device on the Linux on System z channel
1185 * subsystem. Note that the bus-ID contains lowercase characters.
1186 */
1187 r = sd_device_get_sysname(cdev, &bus_id);
1188 if (r < 0)
1189 return log_device_debug_errno(cdev, r, "Failed to get sysname: %m");
1190
1191 /* Check the length of the bus-ID. Rely on the fact that the kernel provides a correct bus-ID;
1192 * alternatively, improve this check and parse and verify each bus-ID part...
1193 */
1194 bus_id_len = strlen(bus_id);
1195 if (!IN_SET(bus_id_len, 8, 9))
1196 return log_device_debug_errno(cdev, SYNTHETIC_ERRNO(EINVAL), "Invalid bus_id: '%s'", bus_id);
1197
1198 /* Strip leading zeros from the bus id for aesthetic purposes. This
1199 * keeps the ccw names stable, yet much shorter in general case of
1200 * bus_id 0.0.0600 -> 600. This is similar to e.g. how PCI domain is
1201 * not prepended when it is zero. Preserve the last 0 for 0.0.0000.
1202 */
1203 bus_id_start = strspn(bus_id, ".0");
1204 bus_id += bus_id_start < bus_id_len ? bus_id_start : bus_id_len - 1;
1205
1206 /* Use the CCW bus-ID as network device name */
1207 char str[ALTIFNAMSIZ];
1208 if (snprintf_ok(str, sizeof str, "%sc%s", prefix, bus_id))
1209 udev_builtin_add_property(event, "ID_NET_NAME_PATH", str);
1210 log_device_debug(dev, "CCW identifier: ccw_busid=%s %s \"%s\"",
1211 bus_id, glyph(GLYPH_ARROW_RIGHT), str + strlen(prefix));
1212 return 0;
1213 }
1214
1215 /* IEEE Organizationally Unique Identifier vendor string */
1216 static int ieee_oui(UdevEvent *event, const struct hw_addr_data *hw_addr) {
1217 char str[32];
1218
1219 assert(event);
1220 assert(hw_addr);
1221
1222 if (hw_addr->length != 6)
1223 return -EOPNOTSUPP;
1224
1225 /* skip commonly misused 00:00:00 (Xerox) prefix */
1226 if (hw_addr->bytes[0] == 0 &&
1227 hw_addr->bytes[1] == 0 &&
1228 hw_addr->bytes[2] == 0)
1229 return -EINVAL;
1230
1231 xsprintf(str, "OUI:%02X%02X%02X%02X%02X%02X",
1232 hw_addr->bytes[0],
1233 hw_addr->bytes[1],
1234 hw_addr->bytes[2],
1235 hw_addr->bytes[3],
1236 hw_addr->bytes[4],
1237 hw_addr->bytes[5]);
1238
1239 return udev_builtin_hwdb_lookup(event, NULL, str, NULL);
1240 }
1241
1242 static int names_mac(UdevEvent *event, const char *prefix) {
1243 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
1244 unsigned iftype, assign_type;
1245 struct hw_addr_data hw_addr;
1246 const char *s;
1247 int r;
1248
1249 assert(prefix);
1250
1251 r = device_get_sysattr_unsigned_filtered(dev, "type", &iftype);
1252 if (r < 0)
1253 return log_device_debug_errno(dev, r, "Failed to read 'type' attribute: %m");
1254
1255 /* The persistent part of a hardware address of an InfiniBand NIC is 8 bytes long. We cannot
1256 * fit this much in an iface name.
1257 * TODO: but it can be used as alternative names?? */
1258 if (iftype == ARPHRD_INFINIBAND)
1259 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EOPNOTSUPP),
1260 "Not generating MAC name for infiniband device.");
1261
1262 /* check for NET_ADDR_PERM, skip random MAC addresses */
1263 r = device_get_sysattr_unsigned_filtered(dev, "addr_assign_type", &assign_type);
1264 if (r < 0)
1265 return log_device_debug_errno(dev, r, "Failed to read/parse addr_assign_type: %m");
1266
1267 if (assign_type != NET_ADDR_PERM)
1268 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL),
1269 "addr_assign_type=%u, MAC address is not permanent.", assign_type);
1270
1271 r = device_get_sysattr_safe_string_filtered(dev, "address", &s);
1272 if (r < 0)
1273 return log_device_debug_errno(dev, r, "Failed to read 'address' attribute: %m");
1274
1275 r = parse_hw_addr(s, &hw_addr);
1276 if (r < 0)
1277 return log_device_debug_errno(dev, r, "Failed to parse 'address' attribute: %m");
1278
1279 if (hw_addr.length != 6)
1280 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EOPNOTSUPP),
1281 "Not generating MAC name for device with MAC address of length %zu.",
1282 hw_addr.length);
1283
1284 char str[ALTIFNAMSIZ];
1285 xsprintf(str, "%sx%s", prefix, HW_ADDR_TO_STR_FULL(&hw_addr, HW_ADDR_TO_STRING_NO_COLON));
1286 udev_builtin_add_property(event, "ID_NET_NAME_MAC", str);
1287 log_device_debug(dev, "MAC address identifier: hw_addr=%s %s %s",
1288 HW_ADDR_TO_STR(&hw_addr),
1289 glyph(GLYPH_ARROW_RIGHT), str + strlen(prefix));
1290
1291 (void) ieee_oui(event, &hw_addr);
1292 return 0;
1293 }
1294
1295 static int names_netdevsim(UdevEvent *event, const char *prefix) {
1296 sd_device *netdevsimdev, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
1297 const char *phys_port_name;
1298 unsigned addr;
1299 int r;
1300
1301 assert(prefix);
1302
1303 /* get netdevsim path names */
1304
1305 if (!naming_scheme_has(NAMING_NETDEVSIM))
1306 return 0;
1307
1308 r = sd_device_get_parent_with_subsystem_devtype(dev, "netdevsim", NULL, &netdevsimdev);
1309 if (r < 0)
1310 return r;
1311
1312 r = device_get_sysnum_unsigned(netdevsimdev, &addr);
1313 if (r < 0)
1314 return log_device_debug_errno(netdevsimdev, r, "Failed to get device sysnum: %m");
1315
1316 r = device_get_sysattr_safe_string_filtered(dev, "phys_port_name", &phys_port_name);
1317 if (r < 0)
1318 return log_device_debug_errno(dev, r, "Failed to get 'phys_port_name' attribute: %m");
1319 if (isempty(phys_port_name))
1320 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EOPNOTSUPP),
1321 "The 'phys_port_name' attribute is empty.");
1322
1323 char str[ALTIFNAMSIZ];
1324 if (snprintf_ok(str, sizeof str, "%si%un%s", prefix, addr, phys_port_name))
1325 udev_builtin_add_property(event, "ID_NET_NAME_PATH", str);
1326 log_device_debug(dev, "Netdevsim identifier: address=%u, port_name=%s %s %s",
1327 addr, phys_port_name, glyph(GLYPH_ARROW_RIGHT), str + strlen(prefix));
1328 return 0;
1329 }
1330
1331 static int names_xen(UdevEvent *event, const char *prefix) {
1332 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
1333 _cleanup_free_ char *vif = NULL;
1334 const char *p;
1335 unsigned id;
1336 int r;
1337
1338 assert(prefix);
1339
1340 /* get xen vif "slot" based names. */
1341
1342 if (!naming_scheme_has(NAMING_XEN_VIF))
1343 return 0;
1344
1345 /* check if our direct parent is a Xen VIF device with no other bus in-between */
1346 if (get_matching_parent(dev, STRV_MAKE("xen"), /* skip_virtio= */ false, NULL) < 0)
1347 return 0;
1348
1349 /* Use the vif-n name to extract "n" */
1350 r = get_first_syspath_component(dev, "/sys/devices/", &vif);
1351 if (r < 0)
1352 return log_device_debug_errno(dev, r, "Failed to get Xen VIF name: %m");
1353
1354 p = startswith(vif, "vif-");
1355 if (!p)
1356 return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EINVAL), "Invalid vif name: '%s'.", vif);
1357
1358 r = safe_atou_full(p, SAFE_ATO_REFUSE_PLUS_MINUS | SAFE_ATO_REFUSE_LEADING_ZERO |
1359 SAFE_ATO_REFUSE_LEADING_WHITESPACE | 10, &id);
1360 if (r < 0)
1361 return log_device_debug_errno(dev, r, "Failed to parse vif index from '%s': %m", p);
1362
1363 char str[ALTIFNAMSIZ];
1364 if (snprintf_ok(str, sizeof str, "%sX%u", prefix, id))
1365 udev_builtin_add_property(event, "ID_NET_NAME_SLOT", str);
1366 log_device_debug(dev, "Xen identifier: id=%u %s %s",
1367 id, glyph(GLYPH_ARROW_RIGHT), str + strlen(prefix));
1368 return 0;
1369 }
1370
1371 static int get_ifname_prefix(sd_device *dev, const char **ret) {
1372 unsigned iftype;
1373 int r;
1374
1375 assert(dev);
1376 assert(ret);
1377
1378 r = device_get_sysattr_unsigned_filtered(dev, "type", &iftype);
1379 if (r < 0)
1380 return r;
1381
1382 /* handle only ARPHRD_ETHER, ARPHRD_SLIP, ARPHRD_INFINIBAND, and ARPHDR_MCTP devices */
1383 switch (iftype) {
1384 case ARPHRD_ETHER: {
1385 if (device_is_devtype(dev, "wlan") > 0)
1386 *ret = "wl";
1387 else if (device_is_devtype(dev, "wwan") > 0)
1388 *ret = "ww";
1389 else
1390 *ret = "en";
1391 return 0;
1392 }
1393 case ARPHRD_INFINIBAND:
1394 if (!naming_scheme_has(NAMING_INFINIBAND))
1395 return -EOPNOTSUPP;
1396
1397 *ret = "ib";
1398 return 0;
1399
1400 case ARPHRD_SLIP:
1401 *ret = "sl";
1402 return 0;
1403
1404 case ARPHRD_MCTP:
1405 if (!naming_scheme_has(NAMING_MCTP))
1406 return -EOPNOTSUPP;
1407
1408 *ret = "mc";
1409 return 0;
1410
1411 default:
1412 return -EOPNOTSUPP;
1413 }
1414 }
1415
1416 static int device_is_stacked(sd_device *dev) {
1417 int ifindex, iflink, r;
1418
1419 assert(dev);
1420
1421 r = sd_device_get_ifindex(dev, &ifindex);
1422 if (r < 0)
1423 return r;
1424
1425 r = device_get_sysattr_int_filtered(dev, "iflink", &iflink);
1426 if (r < 0)
1427 return r;
1428
1429 return ifindex != iflink;
1430 }
1431
1432 static int builtin_net_id(UdevEvent *event, int argc, char *argv[]) {
1433 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
1434 const char *prefix;
1435 int r;
1436
1437 /* skip stacked devices, like VLANs, ... */
1438 r = device_is_stacked(dev);
1439 if (r < 0)
1440 return log_device_debug_errno(dev, r, "Failed to check if the device is stacked: %m");
1441 if (r > 0)
1442 return 0;
1443
1444 r = get_ifname_prefix(dev, &prefix);
1445 if (r < 0) {
1446 log_device_debug_errno(dev, r, "Failed to determine prefix for network interface naming, ignoring: %m");
1447 return 0;
1448 }
1449
1450 udev_builtin_add_property(event, "ID_NET_NAMING_SCHEME", naming_scheme()->name);
1451
1452 (void) names_mac(event, prefix);
1453 (void) names_devicetree(event, prefix);
1454 (void) names_ccw(event, prefix);
1455 (void) names_vio(event, prefix);
1456 (void) names_platform(event, prefix);
1457 (void) names_netdevsim(event, prefix);
1458 (void) names_xen(event, prefix);
1459 (void) names_pci(event, prefix);
1460 (void) names_usb(event, prefix);
1461 (void) names_bcma(event, prefix);
1462
1463 return 0;
1464 }
1465
1466 static int builtin_net_id_init(void) {
1467 /* Load naming scheme here to suppress log messages in workers. */
1468 naming_scheme();
1469 return 0;
1470 }
1471
1472 const UdevBuiltin udev_builtin_net_id = {
1473 .name = "net_id",
1474 .cmd = builtin_net_id,
1475 .init = builtin_net_id_init,
1476 .help = "Network device properties",
1477 };