static int get_device_property()

in src/nccl_ofi_topo.cpp [1047:1108]


static int get_device_property(unsigned domain, unsigned bus,
			       unsigned dev, unsigned func,
			       const char *prop_name, char *prop)
{
	static char const *const path_format = "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/%s";
	int ret = 0;
	FILE *file;
	ssize_t path_len;
	char *path = NULL;

        if ((path_len = snprintf(NULL, 0, path_format, domain, bus, dev, func, prop_name)) < 0) {
		NCCL_OFI_WARN("Failed to determine device property path length of property %s. ERROR: %s",
			      prop_name, strerror(errno));
		ret = -errno;
		goto error;
	}
	path = (char *)malloc(path_len + 1);
	if (!path) {
		NCCL_OFI_WARN("Device property file path malloc failed: %s", strerror(errno));
		ret = -ENOMEM;
		goto error;
	}

	/* Create file path */
	if (snprintf(path, path_len + 1, path_format, domain, bus, dev, func, prop_name) < 0) {
		NCCL_OFI_WARN("Failed to create device property path for property %s. ERROR: %s",
			      prop_name, strerror(errno));
		ret = -errno;
		goto error;
	}

	/* Open file and read property */
	if ((file = fopen(path, "r")) != NULL) {
		char *rc = fgets(prop, MAX_DEV_PROPERTY_LENGTH + 1, file);
		if (feof(file) && !rc) {
			/* No bytes has been read. Let caller decide
			 * whether this is an error or not. */
			prop[0] = '\0';
		} else if (ferror(file)) {
			NCCL_OFI_WARN("Failed to read device property file %s. ERROR: %s",
				      path, strerror(errno));
			ret = -errno;
			goto exit;
		}
	} else {
		NCCL_OFI_WARN("Failed to open device property file %s. ERROR: %s",
			      path, strerror(errno));
		ret = -errno;
		goto error;
	}

 exit:
	if (fclose(file)) {
		NCCL_OFI_WARN("Failed to close device property file %s. ERROR: %s",
			      path, strerror(errno));
		ret = -errno;
	}
 error:
	if (path) free(path);

	return ret;
}