1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Code to build software firmware node graph for atomisp2 connected sensors
4  * from ACPI tables.
5  *
6  * Copyright (C) 2023 Hans de Goede <hdegoede@redhat.com>
7  *
8  * Based on drivers/media/pci/intel/ipu3/cio2-bridge.c written by:
9  * Dan Scally <djrscally@gmail.com>
10  */
11 
12 #include <linux/acpi.h>
13 #include <linux/clk.h>
14 #include <linux/device.h>
15 #include <linux/dmi.h>
16 #include <linux/property.h>
17 #include <media/v4l2-fwnode.h>
18 
19 #include "atomisp_cmd.h"
20 #include "atomisp_csi2.h"
21 #include "atomisp_internal.h"
22 
23 #define NODE_SENSOR(_HID, _PROPS)		\
24 	((const struct software_node) {		\
25 		.name = _HID,			\
26 		.properties = _PROPS,		\
27 	})
28 
29 #define NODE_PORT(_PORT, _SENSOR_NODE)		\
30 	((const struct software_node) {		\
31 		.name = _PORT,			\
32 		.parent = _SENSOR_NODE,		\
33 	})
34 
35 #define NODE_ENDPOINT(_EP, _PORT, _PROPS)	\
36 	((const struct software_node) {		\
37 		.name = _EP,			\
38 		.parent = _PORT,		\
39 		.properties = _PROPS,		\
40 	})
41 
42 #define PMC_CLK_RATE_19_2MHZ			19200000
43 
44 /*
45  * 79234640-9e10-4fea-a5c1-b5aa8b19756f
46  * This _DSM GUID returns information about the GPIO lines mapped to a sensor.
47  * Function number 1 returns a count of the GPIO lines that are mapped.
48  * Subsequent functions return 32 bit ints encoding information about the GPIO.
49  */
50 static const guid_t intel_sensor_gpio_info_guid =
51 	GUID_INIT(0x79234640, 0x9e10, 0x4fea,
52 		  0xa5, 0xc1, 0xb5, 0xaa, 0x8b, 0x19, 0x75, 0x6f);
53 
54 #define INTEL_GPIO_DSM_TYPE_SHIFT			0
55 #define INTEL_GPIO_DSM_TYPE_MASK			GENMASK(7, 0)
56 #define INTEL_GPIO_DSM_PIN_SHIFT			8
57 #define INTEL_GPIO_DSM_PIN_MASK				GENMASK(15, 8)
58 #define INTEL_GPIO_DSM_SENSOR_ON_VAL_SHIFT		24
59 #define INTEL_GPIO_DSM_SENSOR_ON_VAL_MASK		GENMASK(31, 24)
60 
61 #define INTEL_GPIO_DSM_TYPE(x) \
62 	(((x) & INTEL_GPIO_DSM_TYPE_MASK) >> INTEL_GPIO_DSM_TYPE_SHIFT)
63 #define INTEL_GPIO_DSM_PIN(x) \
64 	(((x) & INTEL_GPIO_DSM_PIN_MASK) >> INTEL_GPIO_DSM_PIN_SHIFT)
65 #define INTEL_GPIO_DSM_SENSOR_ON_VAL(x) \
66 	(((x) & INTEL_GPIO_DSM_SENSOR_ON_VAL_MASK) >> INTEL_GPIO_DSM_SENSOR_ON_VAL_SHIFT)
67 
68 /*
69  * 822ace8f-2814-4174-a56b-5f029fe079ee
70  * This _DSM GUID returns a string from the sensor device, which acts as a
71  * module identifier.
72  */
73 static const guid_t intel_sensor_module_guid =
74 	GUID_INIT(0x822ace8f, 0x2814, 0x4174,
75 		  0xa5, 0x6b, 0x5f, 0x02, 0x9f, 0xe0, 0x79, 0xee);
76 
77 /*
78  * dc2f6c4f-045b-4f1d-97b9-882a6860a4be
79  * This _DSM GUID returns a package with n*2 strings, with each set of 2 strings
80  * forming a key, value pair for settings like e.g. "CsiLanes" = "1".
81  */
82 static const guid_t atomisp_dsm_guid =
83 	GUID_INIT(0xdc2f6c4f, 0x045b, 0x4f1d,
84 		  0x97, 0xb9, 0x88, 0x2a, 0x68, 0x60, 0xa4, 0xbe);
85 
86 /*
87  * Extend this array with ACPI Hardware IDs of sensors known to be working
88  * plus the default number of links + link-frequencies.
89  *
90  * Do not add an entry for a sensor that is not actually supported,
91  * or which have not yet been converted to work without atomisp_gmin
92  * power-management and with v4l2-async probing.
93  */
94 static const struct atomisp_csi2_sensor_config supported_sensors[] = {
95 	/* GalaxyCore GC0310 */
96 	{ "INT0310", 1 },
97 	/* Omnivision OV2680 */
98 	{ "OVTI2680", 1 },
99 };
100 
101 /*
102  * gmin_cfg parsing code. This is a cleaned up version of the gmin_cfg parsing
103  * code from atomisp_gmin_platform.c.
104  * Once all sensors are moved to v4l2-async probing atomisp_gmin_platform.c can
105  * be removed and the duplication of this code goes away.
106  */
107 struct gmin_cfg_var {
108 	const char *acpi_dev_name;
109 	const char *key;
110 	const char *val;
111 };
112 
113 static struct gmin_cfg_var lenovo_ideapad_miix_310_vars[] = {
114 	/* _DSM contains the wrong CsiPort! */
115 	{ "OVTI2680:01", "CsiPort", "0" },
116 	{}
117 };
118 
119 static const struct dmi_system_id gmin_cfg_dmi_overrides[] = {
120 	{
121 		/* Lenovo Ideapad Miix 310 */
122 		.matches = {
123 			DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"),
124 			DMI_MATCH(DMI_PRODUCT_VERSION, "MIIX 310-10"),
125 		},
126 		.driver_data = lenovo_ideapad_miix_310_vars,
127 	},
128 	{}
129 };
130 
131 static char *gmin_cfg_get_dsm(struct acpi_device *adev, const char *key)
132 {
133 	union acpi_object *obj, *key_el, *val_el;
134 	char *val = NULL;
135 	int i;
136 
137 	obj = acpi_evaluate_dsm_typed(adev->handle, &atomisp_dsm_guid, 0, 0,
138 				      NULL, ACPI_TYPE_PACKAGE);
139 	if (!obj)
140 		return NULL;
141 
142 	for (i = 0; i < obj->package.count - 1; i += 2) {
143 		key_el = &obj->package.elements[i + 0];
144 		val_el = &obj->package.elements[i + 1];
145 
146 		if (key_el->type != ACPI_TYPE_STRING || val_el->type != ACPI_TYPE_STRING)
147 			break;
148 
149 		if (!strcmp(key_el->string.pointer, key)) {
150 			val = kstrdup(val_el->string.pointer, GFP_KERNEL);
151 			if (!val)
152 				break;
153 
154 			acpi_handle_info(adev->handle, "Using DSM entry %s=%s\n", key, val);
155 			break;
156 		}
157 	}
158 
159 	ACPI_FREE(obj);
160 	return val;
161 }
162 
163 static char *gmin_cfg_get_dmi_override(struct acpi_device *adev, const char *key)
164 {
165 	const struct dmi_system_id *id;
166 	struct gmin_cfg_var *gv;
167 
168 	id = dmi_first_match(gmin_cfg_dmi_overrides);
169 	if (!id)
170 		return NULL;
171 
172 	for (gv = id->driver_data; gv->acpi_dev_name; gv++) {
173 		if (strcmp(gv->acpi_dev_name, acpi_dev_name(adev)))
174 			continue;
175 
176 		if (strcmp(key, gv->key))
177 			continue;
178 
179 		acpi_handle_info(adev->handle, "Using DMI entry %s=%s\n", key, gv->val);
180 		return kstrdup(gv->val, GFP_KERNEL);
181 	}
182 
183 	return NULL;
184 }
185 
186 static char *gmin_cfg_get(struct acpi_device *adev, const char *key)
187 {
188 	char *val;
189 
190 	val = gmin_cfg_get_dmi_override(adev, key);
191 	if (val)
192 		return val;
193 
194 	return gmin_cfg_get_dsm(adev, key);
195 }
196 
197 static int gmin_cfg_get_int(struct acpi_device *adev, const char *key, int default_val)
198 {
199 	char *str_val;
200 	long int_val;
201 	int ret;
202 
203 	str_val = gmin_cfg_get(adev, key);
204 	if (!str_val)
205 		goto out_use_default;
206 
207 	ret = kstrtoul(str_val, 0, &int_val);
208 	kfree(str_val);
209 	if (ret)
210 		goto out_use_default;
211 
212 	return int_val;
213 
214 out_use_default:
215 	acpi_handle_info(adev->handle, "Using default %s=%d\n", key, default_val);
216 	return default_val;
217 }
218 
219 static int atomisp_csi2_get_pmc_clk_nr_from_acpi_pr0(struct acpi_device *adev)
220 {
221 	/* ACPI_PATH_SEGMENT_LENGTH is guaranteed to be big enough for name + 0 term. */
222 	char name[ACPI_PATH_SEGMENT_LENGTH];
223 	struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
224 	struct acpi_buffer b_name = { sizeof(name), name };
225 	union acpi_object *package, *element;
226 	int i, ret = -ENOENT;
227 	acpi_handle rhandle;
228 	acpi_status status;
229 	u8 clock_num;
230 
231 	status = acpi_evaluate_object_typed(adev->handle, "_PR0", NULL, &buffer, ACPI_TYPE_PACKAGE);
232 	if (ACPI_FAILURE(status))
233 		return -ENOENT;
234 
235 	package = buffer.pointer;
236 	for (i = 0; i < package->package.count; i++) {
237 		element = &package->package.elements[i];
238 
239 		if (element->type != ACPI_TYPE_LOCAL_REFERENCE)
240 			continue;
241 
242 		rhandle = element->reference.handle;
243 		if (!rhandle)
244 			continue;
245 
246 		acpi_get_name(rhandle, ACPI_SINGLE_NAME, &b_name);
247 
248 		if (str_has_prefix(name, "CLK") && !kstrtou8(&name[3], 10, &clock_num) &&
249 		    clock_num <= 4) {
250 			ret = clock_num;
251 			break;
252 		}
253 	}
254 
255 	ACPI_FREE(buffer.pointer);
256 
257 	if (ret < 0)
258 		acpi_handle_warn(adev->handle, "Could not find PMC clk in _PR0\n");
259 
260 	return ret;
261 }
262 
263 static int atomisp_csi2_set_pmc_clk_freq(struct acpi_device *adev, int clock_num)
264 {
265 	struct clk *clk;
266 	char name[14];
267 	int ret;
268 
269 	if (clock_num < 0)
270 		return 0;
271 
272 	snprintf(name, sizeof(name), "pmc_plt_clk_%d", clock_num);
273 
274 	clk = clk_get(NULL, name);
275 	if (IS_ERR(clk)) {
276 		ret = PTR_ERR(clk);
277 		acpi_handle_err(adev->handle, "Error getting clk %s:%d\n", name, ret);
278 		return ret;
279 	}
280 
281 	/*
282 	 * The firmware might enable the clock at boot, to change
283 	 * the rate we must ensure the clock is disabled.
284 	 */
285 	ret = clk_prepare_enable(clk);
286 	if (!ret)
287 		clk_disable_unprepare(clk);
288 	if (!ret)
289 		ret = clk_set_rate(clk, PMC_CLK_RATE_19_2MHZ);
290 	if (ret)
291 		acpi_handle_err(adev->handle, "Error setting clk-rate for %s:%d\n", name, ret);
292 
293 	clk_put(clk);
294 	return ret;
295 }
296 
297 static int atomisp_csi2_get_port(struct acpi_device *adev, int clock_num)
298 {
299 	int port;
300 
301 	/*
302 	 * Compare clock-number to the PMC-clock used for CsiPort 1
303 	 * in the CHT/BYT reference designs.
304 	 */
305 	if (IS_ISP2401)
306 		port = clock_num == 4 ? 1 : 0;
307 	else
308 		port = clock_num == 0 ? 1 : 0;
309 
310 	/* Intel DSM or DMI quirk overrides _PR0 CLK derived default */
311 	return gmin_cfg_get_int(adev, "CsiPort", port);
312 }
313 
314 /* Note this always returns 1 to continue looping so that res_count is accurate */
315 static int atomisp_csi2_handle_acpi_gpio_res(struct acpi_resource *ares, void *_data)
316 {
317 	struct atomisp_csi2_acpi_gpio_parsing_data *data = _data;
318 	struct acpi_resource_gpio *agpio;
319 	const char *name;
320 	bool active_low;
321 	unsigned int i;
322 	u32 settings = 0;
323 	u16 pin;
324 
325 	if (!acpi_gpio_get_io_resource(ares, &agpio))
326 		return 1; /* Not a GPIO, continue the loop */
327 
328 	data->res_count++;
329 
330 	pin = agpio->pin_table[0];
331 	for (i = 0; i < data->settings_count; i++) {
332 		if (INTEL_GPIO_DSM_PIN(data->settings[i]) == pin) {
333 			settings = data->settings[i];
334 			break;
335 		}
336 	}
337 
338 	if (i == data->settings_count) {
339 		acpi_handle_warn(data->adev->handle,
340 				 "Could not find DSM GPIO settings for pin %u\n", pin);
341 		return 1;
342 	}
343 
344 	switch (INTEL_GPIO_DSM_TYPE(settings)) {
345 	case 0:
346 		name = "reset-gpios";
347 		break;
348 	case 1:
349 		name = "powerdown-gpios";
350 		break;
351 	default:
352 		acpi_handle_warn(data->adev->handle, "Unknown GPIO type 0x%02lx for pin %u\n",
353 				 INTEL_GPIO_DSM_TYPE(settings), pin);
354 		return 1;
355 	}
356 
357 	/*
358 	 * Both reset and power-down need to be logical false when the sensor
359 	 * is on (sensor should not be in reset and not be powered-down). So
360 	 * when the sensor-on-value (which is the physical pin value) is high,
361 	 * then the signal is active-low.
362 	 */
363 	active_low = INTEL_GPIO_DSM_SENSOR_ON_VAL(settings);
364 
365 	i = data->map_count;
366 	if (i == CSI2_MAX_ACPI_GPIOS)
367 		return 1;
368 
369 	/* res_count is already incremented */
370 	data->map->params[i].crs_entry_index = data->res_count - 1;
371 	data->map->params[i].active_low = active_low;
372 	data->map->mapping[i].name = name;
373 	data->map->mapping[i].data = &data->map->params[i];
374 	data->map->mapping[i].size = 1;
375 	data->map_count++;
376 
377 	acpi_handle_info(data->adev->handle, "%s crs %d %s pin %u active-%s\n", name,
378 			 data->res_count - 1, agpio->resource_source.string_ptr,
379 			 pin, active_low ? "low" : "high");
380 
381 	return 1;
382 }
383 
384 /*
385  * Helper function to create an ACPI GPIO lookup table for sensor reset and
386  * powerdown signals on Intel Bay Trail (BYT) and Cherry Trail (CHT) devices,
387  * including setting the correct polarity for the GPIO.
388  *
389  * This uses the "79234640-9e10-4fea-a5c1-b5aa8b19756f" DSM method directly
390  * on the sensor device's ACPI node. This is different from later Intel
391  * hardware which has a separate INT3472 acpi_device with this info.
392  *
393  * This function must be called before creating the sw-noded describing
394  * the fwnode graph endpoint. And sensor drivers used on these devices
395  * must return -EPROBE_DEFER when there is no endpoint description yet.
396  * Together this guarantees that the GPIO lookups are in place before
397  * the sensor driver tries to get GPIOs with gpiod_get().
398  *
399  * Note this code uses the same DSM GUID as the int3472_gpio_guid in
400  * the INT3472 discrete.c code and there is some overlap, but there are
401  * enough differences that it is difficult to share the code.
402  */
403 static int atomisp_csi2_add_gpio_mappings(struct atomisp_csi2_sensor *sensor,
404 					  struct acpi_device *adev)
405 {
406 	struct atomisp_csi2_acpi_gpio_parsing_data data = { };
407 	LIST_HEAD(resource_list);
408 	union acpi_object *obj;
409 	unsigned int i, j;
410 	int ret;
411 
412 	obj = acpi_evaluate_dsm_typed(adev->handle, &intel_sensor_module_guid,
413 				      0x00, 1, NULL, ACPI_TYPE_STRING);
414 	if (obj) {
415 		acpi_handle_info(adev->handle, "Sensor module id: '%s'\n", obj->string.pointer);
416 		ACPI_FREE(obj);
417 	}
418 
419 	/*
420 	 * First get the GPIO-settings count and then get count GPIO-settings
421 	 * values. Note the order of these may differ from the order in which
422 	 * the GPIOs are listed on the ACPI resources! So we first store them all
423 	 * and then enumerate the ACPI resources and match them up by pin number.
424 	 */
425 	obj = acpi_evaluate_dsm_typed(adev->handle,
426 				      &intel_sensor_gpio_info_guid, 0x00, 1,
427 				      NULL, ACPI_TYPE_INTEGER);
428 	if (!obj) {
429 		acpi_handle_err(adev->handle, "No _DSM entry for GPIO pin count\n");
430 		return -EIO;
431 	}
432 
433 	data.settings_count = obj->integer.value;
434 	ACPI_FREE(obj);
435 
436 	if (data.settings_count > CSI2_MAX_ACPI_GPIOS) {
437 		acpi_handle_err(adev->handle, "Too many GPIOs %u > %u\n", data.settings_count, CSI2_MAX_ACPI_GPIOS);
438 		return -EOVERFLOW;
439 	}
440 
441 	for (i = 0; i < data.settings_count; i++) {
442 		/*
443 		 * i + 2 because the index of this _DSM function is 1-based
444 		 * and the first function is just a count.
445 		 */
446 		obj = acpi_evaluate_dsm_typed(adev->handle,
447 					      &intel_sensor_gpio_info_guid,
448 					      0x00, i + 2,
449 					      NULL, ACPI_TYPE_INTEGER);
450 		if (!obj) {
451 			acpi_handle_err(adev->handle, "No _DSM entry for pin %u\n", i);
452 			return -EIO;
453 		}
454 
455 		data.settings[i] = obj->integer.value;
456 		ACPI_FREE(obj);
457 	}
458 
459 	/* Since we match up by pin-number the pin-numbers must be unique */
460 	for (i = 0; i < data.settings_count; i++) {
461 		for (j = i + 1; j < data.settings_count; j++) {
462 			if (INTEL_GPIO_DSM_PIN(data.settings[i]) !=
463 			    INTEL_GPIO_DSM_PIN(data.settings[j]))
464 				continue;
465 
466 			acpi_handle_err(adev->handle, "Duplicate pin number %lu\n",
467 					INTEL_GPIO_DSM_PIN(data.settings[i]));
468 			return -EIO;
469 		}
470 	}
471 
472 	/* Now parse the ACPI resources and build the lookup table */
473 	data.adev = adev;
474 	data.map = &sensor->gpio_map;
475 	ret = acpi_dev_get_resources(adev, &resource_list,
476 				     atomisp_csi2_handle_acpi_gpio_res, &data);
477 	if (ret < 0)
478 		return ret;
479 
480 	acpi_dev_free_resource_list(&resource_list);
481 
482 	if (data.map_count != data.settings_count ||
483 	    data.res_count != data.settings_count)
484 		acpi_handle_warn(adev->handle, "ACPI GPIO resources vs DSM GPIO-info count mismatch (dsm: %d res: %d map %d\n",
485 				 data.settings_count, data.res_count, data.map_count);
486 
487 	ret = acpi_dev_add_driver_gpios(adev, data.map->mapping);
488 	if (ret)
489 		acpi_handle_err(adev->handle, "Error adding driver GPIOs: %d\n", ret);
490 
491 	return ret;
492 }
493 
494 static const struct atomisp_csi2_property_names prop_names = {
495 	.clock_frequency = "clock-frequency",
496 	.rotation = "rotation",
497 	.bus_type = "bus-type",
498 	.data_lanes = "data-lanes",
499 	.remote_endpoint = "remote-endpoint",
500 	.link_frequencies = "link-frequencies",
501 };
502 
503 static void atomisp_csi2_create_fwnode_properties(struct atomisp_csi2_sensor *sensor,
504 						  struct atomisp_csi2_bridge *bridge,
505 						  const struct atomisp_csi2_sensor_config *cfg)
506 {
507 	sensor->prop_names = prop_names;
508 
509 	sensor->local_ref[0] = SOFTWARE_NODE_REFERENCE(&sensor->swnodes[SWNODE_CSI2_ENDPOINT]);
510 	sensor->remote_ref[0] = SOFTWARE_NODE_REFERENCE(&sensor->swnodes[SWNODE_SENSOR_ENDPOINT]);
511 
512 	sensor->dev_properties[0] = PROPERTY_ENTRY_U32(sensor->prop_names.clock_frequency,
513 						       PMC_CLK_RATE_19_2MHZ);
514 	sensor->dev_properties[1] = PROPERTY_ENTRY_U32(sensor->prop_names.rotation, 0);
515 
516 	sensor->ep_properties[0] = PROPERTY_ENTRY_U32(sensor->prop_names.bus_type,
517 						      V4L2_FWNODE_BUS_TYPE_CSI2_DPHY);
518 	sensor->ep_properties[1] = PROPERTY_ENTRY_U32_ARRAY_LEN(sensor->prop_names.data_lanes,
519 								bridge->data_lanes,
520 								sensor->lanes);
521 	sensor->ep_properties[2] = PROPERTY_ENTRY_REF_ARRAY(sensor->prop_names.remote_endpoint,
522 							    sensor->local_ref);
523 	if (cfg->nr_link_freqs > 0)
524 		sensor->ep_properties[3] =
525 			PROPERTY_ENTRY_U64_ARRAY_LEN(sensor->prop_names.link_frequencies,
526 						     cfg->link_freqs, cfg->nr_link_freqs);
527 
528 	sensor->csi2_properties[0] = PROPERTY_ENTRY_U32_ARRAY_LEN(sensor->prop_names.data_lanes,
529 								  bridge->data_lanes,
530 								  sensor->lanes);
531 	sensor->csi2_properties[1] = PROPERTY_ENTRY_REF_ARRAY(sensor->prop_names.remote_endpoint,
532 							      sensor->remote_ref);
533 }
534 
535 static void atomisp_csi2_init_swnode_names(struct atomisp_csi2_sensor *sensor)
536 {
537 	snprintf(sensor->node_names.remote_port,
538 		 sizeof(sensor->node_names.remote_port),
539 		 SWNODE_GRAPH_PORT_NAME_FMT, sensor->port);
540 	snprintf(sensor->node_names.port,
541 		 sizeof(sensor->node_names.port),
542 		 SWNODE_GRAPH_PORT_NAME_FMT, 0); /* Always port 0 */
543 	snprintf(sensor->node_names.endpoint,
544 		 sizeof(sensor->node_names.endpoint),
545 		 SWNODE_GRAPH_ENDPOINT_NAME_FMT, 0); /* And endpoint 0 */
546 }
547 
548 static void atomisp_csi2_init_swnode_group(struct atomisp_csi2_sensor *sensor)
549 {
550 	struct software_node *nodes = sensor->swnodes;
551 
552 	sensor->group[SWNODE_SENSOR] = &nodes[SWNODE_SENSOR];
553 	sensor->group[SWNODE_SENSOR_PORT] = &nodes[SWNODE_SENSOR_PORT];
554 	sensor->group[SWNODE_SENSOR_ENDPOINT] = &nodes[SWNODE_SENSOR_ENDPOINT];
555 	sensor->group[SWNODE_CSI2_PORT] = &nodes[SWNODE_CSI2_PORT];
556 	sensor->group[SWNODE_CSI2_ENDPOINT] = &nodes[SWNODE_CSI2_ENDPOINT];
557 }
558 
559 static void atomisp_csi2_create_connection_swnodes(struct atomisp_csi2_bridge *bridge,
560 						   struct atomisp_csi2_sensor *sensor)
561 {
562 	struct software_node *nodes = sensor->swnodes;
563 
564 	atomisp_csi2_init_swnode_names(sensor);
565 
566 	nodes[SWNODE_SENSOR] = NODE_SENSOR(sensor->name,
567 					   sensor->dev_properties);
568 	nodes[SWNODE_SENSOR_PORT] = NODE_PORT(sensor->node_names.port,
569 					      &nodes[SWNODE_SENSOR]);
570 	nodes[SWNODE_SENSOR_ENDPOINT] = NODE_ENDPOINT(sensor->node_names.endpoint,
571 						      &nodes[SWNODE_SENSOR_PORT],
572 						      sensor->ep_properties);
573 	nodes[SWNODE_CSI2_PORT] = NODE_PORT(sensor->node_names.remote_port,
574 					    &bridge->csi2_node);
575 	nodes[SWNODE_CSI2_ENDPOINT] = NODE_ENDPOINT(sensor->node_names.endpoint,
576 						    &nodes[SWNODE_CSI2_PORT],
577 						    sensor->csi2_properties);
578 
579 	atomisp_csi2_init_swnode_group(sensor);
580 }
581 
582 static void atomisp_csi2_unregister_sensors(struct atomisp_csi2_bridge *bridge)
583 {
584 	struct atomisp_csi2_sensor *sensor;
585 	unsigned int i;
586 
587 	for (i = 0; i < bridge->n_sensors; i++) {
588 		sensor = &bridge->sensors[i];
589 		software_node_unregister_node_group(sensor->group);
590 		acpi_dev_remove_driver_gpios(sensor->adev);
591 		acpi_dev_put(sensor->adev);
592 	}
593 }
594 
595 static int atomisp_csi2_connect_sensor(const struct atomisp_csi2_sensor_config *cfg,
596 				       struct atomisp_csi2_bridge *bridge,
597 				       struct atomisp_device *isp)
598 {
599 	struct fwnode_handle *fwnode, *primary;
600 	struct atomisp_csi2_sensor *sensor;
601 	struct acpi_device *adev;
602 	int ret, clock_num;
603 
604 	for_each_acpi_dev_match(adev, cfg->hid, NULL, -1) {
605 		if (!adev->status.enabled)
606 			continue;
607 
608 		if (bridge->n_sensors >= ATOMISP_CAMERA_NR_PORTS) {
609 			dev_err(isp->dev, "Exceeded available CSI2 ports\n");
610 			ret = -EOVERFLOW;
611 			goto err_put_adev;
612 		}
613 
614 		sensor = &bridge->sensors[bridge->n_sensors];
615 
616 		/*
617 		 * ACPI takes care of turning the PMC clock on and off, but on BYT
618 		 * the clock defaults to 25 MHz instead of the expected 19.2 MHz.
619 		 * Get the PMC-clock number from ACPI _PR0 method and set it to 19.2 MHz.
620 		 * The PMC-clock number is also used to determine the default CSI port.
621 		 */
622 		clock_num = atomisp_csi2_get_pmc_clk_nr_from_acpi_pr0(adev);
623 
624 		ret = atomisp_csi2_set_pmc_clk_freq(adev, clock_num);
625 		if (ret)
626 			goto err_put_adev;
627 
628 		sensor->port = atomisp_csi2_get_port(adev, clock_num);
629 		if (sensor->port >= ATOMISP_CAMERA_NR_PORTS) {
630 			acpi_handle_err(adev->handle, "Invalid port: %d\n", sensor->port);
631 			ret = -EINVAL;
632 			goto err_put_adev;
633 		}
634 
635 		sensor->lanes = gmin_cfg_get_int(adev, "CsiLanes", cfg->lanes);
636 		if (sensor->lanes > CSI2_MAX_LANES) {
637 			acpi_handle_err(adev->handle, "Invalid number of lanes: %d\n", sensor->lanes);
638 			ret = -EINVAL;
639 			goto err_put_adev;
640 		}
641 
642 		ret = atomisp_csi2_add_gpio_mappings(sensor, adev);
643 		if (ret)
644 			goto err_put_adev;
645 
646 		snprintf(sensor->name, sizeof(sensor->name), "%s-%u",
647 			 cfg->hid, sensor->port);
648 
649 		atomisp_csi2_create_fwnode_properties(sensor, bridge, cfg);
650 		atomisp_csi2_create_connection_swnodes(bridge, sensor);
651 
652 		ret = software_node_register_node_group(sensor->group);
653 		if (ret)
654 			goto err_remove_mappings;
655 
656 		fwnode = software_node_fwnode(&sensor->swnodes[SWNODE_SENSOR]);
657 		if (!fwnode) {
658 			ret = -ENODEV;
659 			goto err_free_swnodes;
660 		}
661 
662 		sensor->adev = acpi_dev_get(adev);
663 
664 		primary = acpi_fwnode_handle(adev);
665 		primary->secondary = fwnode;
666 
667 		bridge->n_sensors++;
668 	}
669 
670 	return 0;
671 
672 err_free_swnodes:
673 	software_node_unregister_node_group(sensor->group);
674 err_remove_mappings:
675 	acpi_dev_remove_driver_gpios(adev);
676 err_put_adev:
677 	acpi_dev_put(adev);
678 	return ret;
679 }
680 
681 static int atomisp_csi2_connect_sensors(struct atomisp_csi2_bridge *bridge,
682 					struct atomisp_device *isp)
683 {
684 	unsigned int i;
685 	int ret;
686 
687 	for (i = 0; i < ARRAY_SIZE(supported_sensors); i++) {
688 		const struct atomisp_csi2_sensor_config *cfg = &supported_sensors[i];
689 
690 		ret = atomisp_csi2_connect_sensor(cfg, bridge, isp);
691 		if (ret)
692 			goto err_unregister_sensors;
693 	}
694 
695 	return 0;
696 
697 err_unregister_sensors:
698 	atomisp_csi2_unregister_sensors(bridge);
699 	return ret;
700 }
701 
702 int atomisp_csi2_bridge_init(struct atomisp_device *isp)
703 {
704 	struct atomisp_csi2_bridge *bridge;
705 	struct device *dev = isp->dev;
706 	struct fwnode_handle *fwnode;
707 	int i, ret;
708 
709 	/*
710 	 * This function is intended to run only once and then leave
711 	 * the created nodes attached even after a rmmod, therefore:
712 	 * 1. The bridge memory is leaked deliberately on success
713 	 * 2. If a secondary fwnode is already set exit early.
714 	 */
715 	fwnode = dev_fwnode(dev);
716 	if (fwnode && fwnode->secondary)
717 		return 0;
718 
719 	bridge = kzalloc(sizeof(*bridge), GFP_KERNEL);
720 	if (!bridge)
721 		return -ENOMEM;
722 
723 	strscpy(bridge->csi2_node_name, "atomisp-csi2", sizeof(bridge->csi2_node_name));
724 	bridge->csi2_node.name = bridge->csi2_node_name;
725 
726 	ret = software_node_register(&bridge->csi2_node);
727 	if (ret < 0) {
728 		dev_err(dev, "Failed to register the CSI2 HID node\n");
729 		goto err_free_bridge;
730 	}
731 
732 	/*
733 	 * Map the lane arrangement, which is fixed for the ISP2 (meaning we
734 	 * only need one, rather than one per sensor). We include it as a
735 	 * member of the bridge struct rather than a global variable so
736 	 * that it survives if the module is unloaded along with the rest of
737 	 * the struct.
738 	 */
739 	for (i = 0; i < CSI2_MAX_LANES; i++)
740 		bridge->data_lanes[i] = i + 1;
741 
742 	ret = atomisp_csi2_connect_sensors(bridge, isp);
743 	if (ret || bridge->n_sensors == 0)
744 		goto err_unregister_csi2;
745 
746 	fwnode = software_node_fwnode(&bridge->csi2_node);
747 	if (!fwnode) {
748 		dev_err(dev, "Error getting fwnode from csi2 software_node\n");
749 		ret = -ENODEV;
750 		goto err_unregister_sensors;
751 	}
752 
753 	set_secondary_fwnode(dev, fwnode);
754 
755 	return 0;
756 
757 err_unregister_sensors:
758 	atomisp_csi2_unregister_sensors(bridge);
759 err_unregister_csi2:
760 	software_node_unregister(&bridge->csi2_node);
761 err_free_bridge:
762 	kfree(bridge);
763 
764 	return ret;
765 }
766 
767 /******* V4L2 sub-device asynchronous registration callbacks***********/
768 
769 struct sensor_async_subdev {
770 	struct v4l2_async_subdev asd;
771 	int port;
772 };
773 
774 #define to_sensor_asd(a)	container_of(a, struct sensor_async_subdev, asd)
775 #define notifier_to_atomisp(n)	container_of(n, struct atomisp_device, notifier)
776 
777 /* .bound() notifier callback when a match is found */
778 static int atomisp_notifier_bound(struct v4l2_async_notifier *notifier,
779 				  struct v4l2_subdev *sd,
780 				  struct v4l2_async_subdev *asd)
781 {
782 	struct atomisp_device *isp = notifier_to_atomisp(notifier);
783 	struct sensor_async_subdev *s_asd = to_sensor_asd(asd);
784 
785 	if (s_asd->port >= ATOMISP_CAMERA_NR_PORTS) {
786 		dev_err(isp->dev, "port %d not supported\n", s_asd->port);
787 		return -EINVAL;
788 	}
789 
790 	if (isp->sensor_subdevs[s_asd->port]) {
791 		dev_err(isp->dev, "port %d already has a sensor attached\n", s_asd->port);
792 		return -EBUSY;
793 	}
794 
795 	isp->sensor_subdevs[s_asd->port] = sd;
796 	return 0;
797 }
798 
799 /* The .unbind callback */
800 static void atomisp_notifier_unbind(struct v4l2_async_notifier *notifier,
801 				    struct v4l2_subdev *sd,
802 				    struct v4l2_async_subdev *asd)
803 {
804 	struct atomisp_device *isp = notifier_to_atomisp(notifier);
805 	struct sensor_async_subdev *s_asd = to_sensor_asd(asd);
806 
807 	isp->sensor_subdevs[s_asd->port] = NULL;
808 }
809 
810 /* .complete() is called after all subdevices have been located */
811 static int atomisp_notifier_complete(struct v4l2_async_notifier *notifier)
812 {
813 	struct atomisp_device *isp = notifier_to_atomisp(notifier);
814 
815 	return atomisp_register_device_nodes(isp);
816 }
817 
818 static const struct v4l2_async_notifier_operations atomisp_async_ops = {
819 	.bound = atomisp_notifier_bound,
820 	.unbind = atomisp_notifier_unbind,
821 	.complete = atomisp_notifier_complete,
822 };
823 
824 int atomisp_csi2_bridge_parse_firmware(struct atomisp_device *isp)
825 {
826 	int i, mipi_port, ret;
827 
828 	v4l2_async_nf_init(&isp->notifier);
829 	isp->notifier.ops = &atomisp_async_ops;
830 
831 	for (i = 0; i < ATOMISP_CAMERA_NR_PORTS; i++) {
832 		struct v4l2_fwnode_endpoint vep = {
833 			.bus_type = V4L2_MBUS_CSI2_DPHY,
834 		};
835 		struct sensor_async_subdev *s_asd;
836 		struct fwnode_handle *ep;
837 
838 		ep = fwnode_graph_get_endpoint_by_id(dev_fwnode(isp->dev), i, 0,
839 						     FWNODE_GRAPH_ENDPOINT_NEXT);
840 		if (!ep)
841 			continue;
842 
843 		ret = v4l2_fwnode_endpoint_parse(ep, &vep);
844 		if (ret)
845 			goto err_parse;
846 
847 		if (vep.base.port >= ATOMISP_CAMERA_NR_PORTS) {
848 			dev_err(isp->dev, "port %d not supported\n", vep.base.port);
849 			ret = -EINVAL;
850 			goto err_parse;
851 		}
852 
853 		mipi_port = atomisp_port_to_mipi_port(isp, vep.base.port);
854 		isp->sensor_lanes[mipi_port] = vep.bus.mipi_csi2.num_data_lanes;
855 
856 		s_asd = v4l2_async_nf_add_fwnode_remote(&isp->notifier, ep,
857 							struct sensor_async_subdev);
858 		if (IS_ERR(s_asd)) {
859 			ret = PTR_ERR(s_asd);
860 			goto err_parse;
861 		}
862 
863 		s_asd->port = vep.base.port;
864 
865 		fwnode_handle_put(ep);
866 		continue;
867 
868 err_parse:
869 		fwnode_handle_put(ep);
870 		return ret;
871 	}
872 
873 	return 0;
874 }
875