xref: /linux/drivers/media/i2c/cvs/core.c (revision fab183d632628381b466a41479489541ac0e29a0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2026 Intel Corporation
4  */
5 
6 #include <linux/acpi.h>
7 #include <linux/cleanup.h>
8 #include <linux/delay.h>
9 #include <linux/device.h>
10 #include <linux/gpio/consumer.h>
11 #include <linux/i2c.h>
12 #include <linux/init.h>
13 #include <linux/interrupt.h>
14 #include <linux/jiffies.h>
15 #include <linux/module.h>
16 #include <linux/pci.h>
17 #include <linux/platform_device.h>
18 #include <linux/pm_runtime.h>
19 #include <linux/slab.h>
20 #include <linux/time64.h>
21 #include <linux/workqueue.h>
22 
23 #include <media/ipu-bridge.h>
24 #include <media/ipu6-pci-table.h>
25 
26 #include "icvs.h"
27 
28 /* Command timeouts determined experimentally */
29 #define CMD_TIMEOUT (5 * HZ)
30 #define FW_READY_DELAY_MS 100
31 
32 #define PCI_DEVICE_ID_INTEL_IPU7		0x645d	/* MTL / LNL */
33 #define PCI_DEVICE_ID_INTEL_IPU7P5		0xb05d	/* ARL / PTL */
34 #define PCI_DEVICE_ID_INTEL_IPU8		0xd719	/* NVL */
35 
36 /*
37  * IPU7 PCI device IDs not covered by ipu6_pci_tbl in ipu6-pci-table.h.
38  * Once the IPU6 driver gains support for IPU7, this table can be dropped.
39  */
40 static const struct pci_device_id icvs_ipu7_tbl[] = {
41 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IPU7) },
42 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IPU7P5) },
43 	{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IPU8) },
44 	{ }
45 };
46 
47 static const struct acpi_gpio_params gpio_wake = { 0, 0, false };
48 static const struct acpi_gpio_params gpio_rst  = { 1, 0, false };
49 static const struct acpi_gpio_params gpio_req  = { 2, 0, false };
50 static const struct acpi_gpio_params gpio_resp = { 3, 0, false };
51 static const struct acpi_gpio_mapping icvs_acpi_gpios[] = {
52 	{ "wake-gpio", &gpio_wake, 1 },
53 	{ "rst-gpio",  &gpio_rst,  1 },
54 	{ "req-gpio",  &gpio_req,  1 },
55 	{ "resp-gpio", &gpio_resp, 1 },
56 	{ }
57 };
58 
59 static const struct acpi_gpio_params lgpio_req  = { 0, 0, false };
60 static const struct acpi_gpio_params lgpio_resp = { 1, 0, false };
61 static const struct acpi_gpio_mapping icvs_acpi_lgpios[] = {
62 	{ "req-gpio",  &lgpio_req,  1 },
63 	{ "resp-gpio", &lgpio_resp, 1 },
64 	{ }
65 };
66 
67 /* Device quirk table */
68 static const struct icvs_device_quirk cvs_quirk_table[] = {
69 	{ 0x2ac1, 0x20d0, ICVS_NO_MIPI_CONFIG |
70 			  ICVS_NO_CAPS |
71 			  ICVS_NO_FW_UPDATE
72 	},	/* Lattice NX33 */
73 	{ 0x06CB, 0x0701, ICVS_SKIP_FW_RESET |
74 			  ICVS_HOST_SENSOR_PWR_CTRL |
75 			  ICVS_HOST_PRIV_CTRL |
76 			  ICVS_FW_BUF_SIZE_256 |
77 			  ICVS_FW_HEADER_SIZE_256
78 	},	/* Synaptics SVP7xxx */
79 	{ }
80 };
81 
82 /**
83  * cvs_set_quirks - Match device VID/PID and set quirks
84  * @ctx: CVS device context
85  * @vid: Vendor ID
86  * @pid: Product ID
87  *
88  * Searches the quirk table for a matching VID/PID and populates ctx->quirks
89  * with the corresponding quirk flags.
90  * If no match is found, quirks is set to 0.
91  */
cvs_set_quirks(struct icvs * ctx,u16 vid,u16 pid)92 static void cvs_set_quirks(struct icvs *ctx, u16 vid, u16 pid)
93 {
94 	ctx->quirks = 0;
95 
96 	for (unsigned int i = 0; i < ARRAY_SIZE(cvs_quirk_table); i++) {
97 		if (cvs_quirk_table[i].vid == vid &&
98 		    cvs_quirk_table[i].pid == pid) {
99 			ctx->quirks = cvs_quirk_table[i].quirks;
100 			dev_info(cvs_dev(ctx),
101 				 "Quirks: 0x%lx (VID:0x%04x PID:0x%04x)\n",
102 				 ctx->quirks, vid, pid);
103 			return;
104 		}
105 	}
106 
107 	dev_info(cvs_dev(ctx),
108 		 "No quirks for device (VID:0x%04x PID:0x%04x)\n", vid, pid);
109 }
110 
111 /* I2C transport helpers */
112 
113 /**
114  * cvs_read_i2c - Issue a read-type command and fetch device response
115  * @ctx: CVS device context
116  * @cmd_id: Command identifier (big endian)
117  * @resp: Destination buffer for response payload
118  * @size: Size of payload to read into @resp (without prefix)
119  *
120  * Sends @cmd_id and reads back the response in a single I2C transaction.
121  * When the device prepends a 4-byte protocol prefix, the combined
122  * prefix+payload is read into a temporary buffer and only the payload is
123  * copied to @resp, avoiding any dependency on the layout of the caller's
124  * buffer.
125  *
126  * Return: 0 on success or negative errno.
127  */
cvs_read_i2c(struct icvs * ctx,__be16 cmd_id,void * resp,size_t size)128 static int cvs_read_i2c(struct icvs *ctx, __be16 cmd_id, void *resp,
129 			size_t size)
130 {
131 	size_t prefix_size = ctx->prefix ? sizeof(u32) : 0;
132 	size_t read_size = size + prefix_size;
133 	struct i2c_client *i2c = ctx->i2c_client;
134 	u8 *buf __free(kfree) = NULL;
135 	int cnt;
136 
137 	if (!resp || !size)
138 		return -EINVAL;
139 
140 	cnt = i2c_master_send(i2c, (const char *)&cmd_id, sizeof(cmd_id));
141 	if (cnt != sizeof(cmd_id))
142 		return cnt < 0 ? cnt : -EIO;
143 
144 	buf = kmalloc(read_size, GFP_KERNEL);
145 	if (!buf)
146 		return -ENOMEM;
147 
148 	cnt = i2c_master_recv(i2c, buf, read_size);
149 	if (cnt != read_size) {
150 		dev_dbg(cvs_dev(ctx), "recv cmd 0x%04x short read (%d/%zu)\n",
151 			be16_to_cpu(cmd_id), cnt, read_size);
152 		return cnt < 0 ? cnt : -EIO;
153 	}
154 
155 	memcpy(resp, buf + prefix_size, size);
156 
157 	return 0;
158 }
159 
160 /**
161  * cvs_write_i2c - Write a raw command buffer to the device over I2C
162  * @ctx: CVS device context
163  * @data: Buffer containing command + payload
164  * @size: Total bytes to write
165  *
166  * Return: 0 on success or negative errno.
167  */
cvs_write_i2c(struct icvs * ctx,const void * data,int size)168 static int cvs_write_i2c(struct icvs *ctx, const void *data, int size)
169 {
170 	struct i2c_client *i2c = ctx->i2c_client;
171 	int cnt;
172 
173 	if (size < 0 || !data)
174 		return -EINVAL;
175 
176 	cnt = i2c_master_send(i2c, data, size);
177 	if (cnt != size) {
178 		dev_dbg(cvs_dev(ctx), "send short (%d/%d)\n", cnt, size);
179 		return cnt < 0 ? cnt : -EIO;
180 	}
181 
182 	return 0;
183 }
184 
185 /**
186  * cvs_checksum - Simple additive checksum helper
187  * @data: 32-bit aligned data buffer
188  * @len: Length in bytes (multiple of 4)
189  *
190  * Return: 32-bit additive checksum of the dwords in @data.
191  */
cvs_checksum(const void * data,size_t len)192 static u32 cvs_checksum(const void *data, size_t len)
193 {
194 	const u32 *words = data;
195 	u32 csum = 0;
196 
197 	if (WARN_ON_ONCE(len % sizeof(u32)))
198 		return 0;
199 
200 	for (unsigned int i = 0; i < len / sizeof(u32); i++)
201 		csum += words[i];
202 
203 	return csum;
204 }
205 
206 /**
207  * cvs_schedule_and_wait - Schedule polling work then wait for completion
208  * @ctx: CVS device context
209  * @work_delay_ms: Delay in milliseconds before polling work executes
210  * @wait_jiffies: Timeout (jiffies) to wait for cmd completion
211  *
212  * Queues ctx->work to run after @work_delay_ms and then waits up to
213  * @wait_jiffies for ctx->cmd_completion.
214  *
215  * Return: 0 on success, -ETIMEDOUT on timeout, negative errno on error.
216  */
cvs_schedule_and_wait(struct icvs * ctx,unsigned int work_delay_ms,unsigned long wait_jiffies)217 static int cvs_schedule_and_wait(struct icvs *ctx, unsigned int work_delay_ms,
218 				 unsigned long wait_jiffies)
219 {
220 	int ret;
221 
222 	schedule_delayed_work(&ctx->work, msecs_to_jiffies(work_delay_ms));
223 	ret = wait_for_completion_killable_timeout(&ctx->cmd_completion,
224 						   wait_jiffies);
225 	if (ret < 0)
226 		return ret;
227 	if (!ret)
228 		return -ETIMEDOUT;
229 
230 	return 0;
231 }
232 
233 /**
234  * cvs_wait_wake_or_sleep - Wait for wake IRQ or sleep fallback
235  * @ctx: CVS device context
236  * @timeout_jiffies: Timeout (jiffies) for wake event on full-cap devices
237  * @sleep_ms: Milliseconds to sleep on light-cap devices
238  *
239  * For full capability devices (ICVS_FULLCAP) waits interruptibly on
240  * ctx->hostwake_event until ctx->hostwake_event_arg becomes true or
241  * @timeout_jiffies elapses. The flag is cleared after the wait.
242  * For light capability devices performs a blocking msleep(@sleep_ms).
243  *
244  * Return codes normalized for caller switch handling:
245  *	<0		: error / interrupted
246  *	-ETIMEDOUT	: timeout (wake event not observed)
247  *	0		: success (wake observed OR light-cap sleep elapsed)
248  *
249  * Return: negative errno, -ETIMEDOUT on timeout, 0 on success.
250  */
cvs_wait_wake_or_sleep(struct icvs * ctx,unsigned long timeout_jiffies,unsigned int sleep_ms)251 static int cvs_wait_wake_or_sleep(struct icvs *ctx,
252 				  unsigned long timeout_jiffies,
253 				  unsigned int sleep_ms)
254 {
255 	int ret;
256 
257 	if (ctx->res == ICVS_FULLCAP) {
258 		ret = wait_event_interruptible_timeout(ctx->hostwake_event,
259 						       ctx->hostwake_event_arg,
260 						       timeout_jiffies);
261 		ctx->hostwake_event_arg = false;
262 		if (ret < 0)
263 			return ret;
264 		if (!ret)
265 			return -ETIMEDOUT;
266 		return 0;
267 	}
268 
269 	msleep(sleep_ms);
270 
271 	return 0; /* treat sleep path as success */
272 }
273 
274 /**
275  * cvs_config_mipi - Send a HOST_SET_MIPI_CONFIG command
276  * @ctx: CVS device context
277  * @c: Command container with conf field populated
278  * @len: Length of original command structure (unused except for symmetry)
279  *
280  * Packages @c->param.conf into a cvs_mipi_data_packet including size and
281  * checksum, then writes it to the device.
282  *
283  * Firmware note: the CVS firmware expects the MIPI configuration to be
284  * sent as a single transaction, including all relevant parameters and checksum.
285  *
286  * Return: 0 on success, NO_MIPI_CONFIG or negative errno from I2C write.
287  */
cvs_config_mipi(struct icvs * ctx,struct icvs_cmd * c,size_t len)288 static int cvs_config_mipi(struct icvs *ctx, struct icvs_cmd *c, size_t len)
289 {
290 	struct icvs_mipi_data_packet pkt = {
291 		.cmd_id = c->cmd_id,
292 		.size = sizeof(c->param.conf),
293 		.crc = cvs_checksum(&c->param.conf, sizeof(c->param.conf)),
294 		.conf = c->param.conf,
295 	};
296 
297 	if (ctx->quirks & ICVS_NO_MIPI_CONFIG)
298 		return 0;
299 
300 	return cvs_write_i2c(ctx, &pkt, sizeof(pkt));
301 }
302 
303 /**
304  * cvs_get_device_state - Query current device state bitfield
305  * @ctx: CVS device context
306  * @state: Returned state value
307  *
308  * Issues GET_DEV_STATE and fills @state.
309  *
310  * Return: 0 on success or negative errno.
311  */
cvs_get_device_state(struct icvs * ctx,u8 * state)312 static int cvs_get_device_state(struct icvs *ctx, u8 *state)
313 {
314 	struct icvs_resp n = {
315 		.cmd_id = cpu_to_be16(ICVS_GET_DEV_STATE),
316 	};
317 	int ret;
318 
319 	ret = cvs_read_i2c(ctx, n.cmd_id, &n.resp.state, sizeof(n.resp.state));
320 	if (ret)
321 		return ret;
322 
323 	*state = n.resp.state;
324 
325 	return 0;
326 }
327 
328 /**
329  * cvs_get_device_caps - Read protocol capabilities
330  * @ctx: CVS device context
331  * @caps: Capability structure to populate
332  *
333  * Return: 0 on success or negative errno.
334  */
cvs_get_device_caps(struct icvs * ctx,struct icvs_dev_capabilities * caps)335 static int cvs_get_device_caps(struct icvs *ctx,
336 			       struct icvs_dev_capabilities *caps)
337 {
338 	struct icvs_resp n = {
339 		.cmd_id = cpu_to_be16(ICVS_GET_DEV_CAPABILITY),
340 	};
341 	int ret;
342 
343 	if (ctx->quirks & ICVS_NO_CAPS)
344 		return 0;
345 
346 	ret = cvs_read_i2c(ctx, n.cmd_id, &n.resp.cap, sizeof(n.resp.cap));
347 	if (ret)
348 		return ret;
349 
350 	*caps = n.resp.cap;
351 
352 	return 0;
353 }
354 
355 /**
356  * cvs_hw_init - Probe device for prefix support and apply quirks
357  * @ctx: CVS device context
358  *
359  * Sends GET_DEV_VID_PID and probes for a 32-bit prefix.
360  * If it matches ICVS_PREFIX_VAL, sets ctx->prefix for subsequent reads.
361  * Then reads VID/PID and applies matching quirks.
362  * GET_DEV_VID_PID is supported by all protocol versions.
363  *
364  * Return: 0 on success or negative errno.
365  */
cvs_hw_init(struct icvs * ctx)366 static int cvs_hw_init(struct icvs *ctx)
367 {
368 	struct icvs_resp n = { };
369 	__be16 cmd = cpu_to_be16(ICVS_GET_DEV_VID_PID);
370 	u32 resp;
371 	int ret;
372 
373 	/*
374 	 * Clear prefix so cvs_read_i2c always reads exactly sizeof(u32) bytes
375 	 * here, regardless of any value left over from a previous call (e.g.
376 	 * on resume).
377 	 */
378 	ctx->prefix = false;
379 	ret = cvs_read_i2c(ctx, cmd, &resp, sizeof(resp));
380 	if (ret)
381 		return ret;
382 
383 	ctx->prefix = resp == ICVS_PREFIX_VAL;
384 
385 	/* Now read VID/PID to apply quirks */
386 	ret = cvs_read_i2c(ctx, cmd,
387 			   &n.resp.vid_pid, sizeof(n.resp.vid_pid));
388 	if (ret)
389 		return ret;
390 
391 	cvs_set_quirks(ctx, n.resp.vid_pid.v_id, n.resp.vid_pid.p_id);
392 
393 	return 0;
394 }
395 
396 /**
397  * cvs_irq_handler - Wake IRQ handler (full capability devices)
398  * @irq: IRQ number
399  * @dev_id: Device context pointer
400  *
401  * Sets a waitqueue flag and wakes up sleeping waiters.
402  *
403  * Return: IRQ_HANDLED always.
404  */
cvs_irq_handler(int irq,void * dev_id)405 static irqreturn_t cvs_irq_handler(int irq, void *dev_id)
406 {
407 	struct icvs *ctx = dev_id;
408 
409 	ctx->hostwake_event_arg = true;
410 	wake_up_interruptible(&ctx->hostwake_event);
411 
412 	return IRQ_HANDLED;
413 }
414 
415 /**
416  * cvs_reset - Toggle reset GPIO for full capability devices
417  * @ctx: CVS device context
418  *
419  * Drives reset low briefly then high if device resources indicate full
420  * capability. Light devices have no reset line.
421  */
cvs_reset(struct icvs * ctx)422 static void cvs_reset(struct icvs *ctx)
423 {
424 	if (ctx->quirks & ICVS_SKIP_FW_RESET)
425 		return;
426 
427 	if (ctx->res == ICVS_FULLCAP) {
428 		gpiod_set_value(ctx->rst, 0);
429 		fsleep(2000);
430 		gpiod_set_value(ctx->rst, 1);
431 	}
432 }
433 
434 /**
435  * cvs_recv - Delayed work handler polling for command completion
436  * @work: Embedded delayed_work member
437  *
438  * Re-reads device state; if device_busy remains set, re-schedules itself.
439  * Otherwise stores state into wq_resp and completes the command.
440  */
cvs_recv(struct work_struct * work)441 static void cvs_recv(struct work_struct *work)
442 {
443 	struct icvs *ctx = container_of(work, struct icvs, work.work);
444 	u8 state = 0;
445 	int ret;
446 
447 	ret = cvs_get_device_state(ctx, &state);
448 	if (ret < 0) {
449 		dev_dbg(cvs_dev(ctx), "state read failed: %d\n", ret);
450 		return;
451 	}
452 
453 	if (state & ICVS_DEV_STATE_BUSY) {
454 		dev_dbg(cvs_dev(ctx), "device busy, reschedule\n");
455 		schedule_delayed_work(&ctx->work,
456 				      msecs_to_jiffies(FW_READY_DELAY_MS));
457 		return;
458 	}
459 
460 	ctx->wq_resp.resp.state = state;
461 	complete(&ctx->cmd_completion);
462 }
463 
464 /**
465  * cvs_send - Common command submission path
466  * @ctx: CVS device context
467  * @cmd: Command buffer (icvs_cmd) with cmd_id and param populated
468  * @len: Buffer length
469  *
470  * Dispatches a set of supported commands:
471  * - ICVS_SET_DEV_HOST_ID,
472  * - ICVS_HOST_SENSOR_OWNER,
473  * - ICVS_HOST_SET_MIPI_CONFIG
474  * - ICVS_FW_LOADER_*
475  *
476  * For I2C based commands it sets big-endian cmd ids, writes to the device
477  * and waits (via delayed work) for completion or timeout.
478  * GPIO based ownership toggles are handled locally.
479  *
480  * Caller must hold ctx->lock when invoking this function and check for i2c
481  * bus availability.
482  *
483  * Return: 0 on success, negative errno, -EINVAL for unsupported command
484  * or status from device in ctx->wq_resp.
485  */
cvs_send(struct icvs * ctx,struct icvs_cmd * cmd,size_t len)486 int cvs_send(struct icvs *ctx, struct icvs_cmd *cmd, size_t len)
487 {
488 	int ret, status = 0;
489 
490 	lockdep_assert_held(&ctx->lock);
491 
492 	dev_dbg(cvs_dev(ctx), "send cmd = 0x%04x", be16_to_cpu(cmd->cmd_id));
493 
494 	reinit_completion(&ctx->cmd_completion);
495 
496 	switch (be16_to_cpu(cmd->cmd_id)) {
497 	case ICVS_SET_DEV_HOST_ID:
498 		cmd->cmd_id = cpu_to_be16(ICVS_SET_DEV_HOST_ID);
499 		ret = cvs_write_i2c(ctx, cmd, len);
500 		if (ret < 0)
501 			break;
502 
503 		ret = cvs_schedule_and_wait(ctx, FW_READY_DELAY_MS,
504 					    CMD_TIMEOUT);
505 		if (ret < 0)
506 			break;
507 
508 		status = ctx->wq_resp.resp.state &
509 			  ICVS_DEV_STATE_ERROR ? -EINVAL : 0;
510 		break;
511 	case ICVS_HOST_SENSOR_OWNER:
512 		gpiod_set_value_cansleep(ctx->req, cmd->param.param);
513 		fsleep(FW_READY_DELAY_MS * USEC_PER_MSEC);
514 		ret = gpiod_get_value_cansleep(ctx->resp);
515 		status = cmd->param.param == ret ? 0 : -EINVAL;
516 		ret = 0; /* success */
517 		break;
518 	case ICVS_HOST_SET_MIPI_CONFIG:
519 		cmd->cmd_id = cpu_to_be16(ICVS_HOST_SET_MIPI_CONFIG);
520 		ret = cvs_config_mipi(ctx, cmd, len);
521 		if (ret < 0)
522 			break;
523 
524 		ret = cvs_schedule_and_wait(ctx, FW_READY_DELAY_MS,
525 					    CMD_TIMEOUT);
526 		status = (ctx->wq_resp.resp.state &
527 			  ICVS_DEV_STATE_ERROR) ? -EINVAL : 0;
528 		break;
529 	case ICVS_FW_LOADER_START:
530 		cmd->cmd_id = cpu_to_be16(ICVS_FW_LOADER_START);
531 		ret = cvs_write_i2c(ctx, cmd, len);
532 		if (ret < 0)
533 			break;
534 
535 		ret = cvs_wait_wake_or_sleep(ctx, CMD_TIMEOUT,
536 					     FW_READY_DELAY_MS);
537 		if (ret)
538 			break;
539 
540 		ret = cvs_schedule_and_wait(ctx, FW_READY_DELAY_MS,
541 					    CMD_TIMEOUT);
542 		status = (ctx->wq_resp.resp.state &
543 			  ICVS_DEV_STATE_DOWNLOAD) ? 0 : -EINVAL;
544 		break;
545 	case ICVS_FW_LOADER_DATA:
546 		/* Quirk for older protocols */
547 		if (ctx->caps.protocol_version_major >= 2 &&
548 		    ctx->caps.protocol_version_minor >= 2) {
549 			cmd->cmd_id = cpu_to_be16(ICVS_FW_LOADER_DATA);
550 			ret = cvs_write_i2c(ctx, cmd, len);
551 		} else {
552 			ret = cvs_write_i2c(ctx, &cmd->param,
553 					    len - sizeof(cmd->cmd_id));
554 		}
555 
556 		if (ret < 0)
557 			return ret;
558 
559 		ret = cvs_wait_wake_or_sleep(ctx, FW_READY_DELAY_MS,
560 					     FW_READY_DELAY_MS);
561 		if (ret)
562 			break;
563 
564 		ret = cvs_schedule_and_wait(ctx, FW_READY_DELAY_MS,
565 					    CMD_TIMEOUT);
566 		status = ctx->wq_resp.resp.state &
567 			  ICVS_DEV_STATE_ERROR ? -EINVAL : 0;
568 		break;
569 	case ICVS_FW_LOADER_END:
570 		cmd->cmd_id = cpu_to_be16(ICVS_FW_LOADER_END);
571 		ret = cvs_write_i2c(ctx, cmd, len);
572 		if (ret < 0)
573 			break;
574 
575 		ret = cvs_wait_wake_or_sleep(ctx, CMD_TIMEOUT,
576 					     FW_READY_DELAY_MS);
577 		if (ret)
578 			break;
579 
580 		ret = cvs_schedule_and_wait(ctx, FW_READY_DELAY_MS,
581 					    CMD_TIMEOUT);
582 		status = !(ctx->wq_resp.resp.state &
583 			   ICVS_DEV_STATE_DOWNLOAD) ? 0 : -EINVAL;
584 		break;
585 	default:
586 		ret = -EINVAL;
587 		break;
588 	}
589 
590 	if (ret < 0)
591 		return ret;
592 
593 	return ctx->wq_resp.status = status;
594 }
595 
596 /**
597  * cvs_set_link_owner - Switch CSI-2 link ownership between host and device
598  * @ctx: CVS device context
599  * @owner: Desired owner (ICVS_CSI_LINK_HOST or ICVS_CSI_LINK_CVS)
600  *
601  * Called from runtime PM callbacks to claim or release the CSI-2 link.
602  * Also callable directly for error recovery paths.
603  *
604  * Return: 0 on success or negative errno.
605  */
cvs_set_link_owner(struct icvs * ctx,enum icvs_csi_link_owner owner)606 int cvs_set_link_owner(struct icvs *ctx, enum icvs_csi_link_owner owner)
607 {
608 	struct icvs_cmd cmd = {
609 		.cmd_id = cpu_to_be16(ICVS_HOST_SENSOR_OWNER),
610 		.param.param = owner,
611 	};
612 	size_t cmd_size = sizeof(cmd.cmd_id) + sizeof(cmd.param.param);
613 
614 	guard(mutex)(&ctx->lock);
615 	return cvs_send(ctx, &cmd, cmd_size);
616 }
617 
618 /**
619  * cvs_configure_dev_caps - Configure device capability ownership bits
620  * @ctx: CVS device context
621  *
622  * Tells the CVS device which of its features (privacy LED, RGB camera
623  * power-up, vision sensing) are controlled by the host, then sends
624  * SET_DEV_HOST_ID.
625  *
626  * Return: 0 on success or negative errno.
627  */
cvs_configure_dev_caps(struct icvs * ctx)628 static int cvs_configure_dev_caps(struct icvs *ctx)
629 {
630 	struct icvs_cmd cmd = { .cmd_id = cpu_to_be16(ICVS_SET_DEV_HOST_ID) };
631 	size_t sz = sizeof(cmd.cmd_id) + sizeof(cmd.param.host_id);
632 
633 	if (ctx->quirks & ICVS_NO_CAPS)
634 		return 0;
635 
636 	if (ctx->quirks & ICVS_HOST_VISION_SENSING)
637 		cmd.param.host_id |= ICVS_HOST_ID_VISION_SENSING;
638 	if (ctx->quirks & ICVS_HOST_PRIV_CTRL)
639 		cmd.param.host_id |= ICVS_HOST_ID_PRIVACY_LED;
640 	if (ctx->quirks & ICVS_HOST_SENSOR_PWR_CTRL)
641 		cmd.param.host_id |= ICVS_HOST_ID_RGBCAMERA_PWRUP;
642 
643 	guard(mutex)(&ctx->lock);
644 	return cvs_send(ctx, &cmd, sz);
645 }
646 
647 /**
648  * cvs_core_probe - Shared probe path for I2C & platform instantiation
649  * @dev: Parent device
650  * @i2c: I2C client (NULL for platform devices)
651  *
652  * Discovers IPU, parses ACPI resources, sets up GPIOs/IRQs, initializes
653  * sub-device (CSI) and host identifier, and exposes sysfs firmware interface.
654  *
655  * Return: 0 on success or negative errno.
656  */
cvs_core_probe(struct device * dev,struct i2c_client * i2c)657 static int cvs_core_probe(struct device *dev, struct i2c_client *i2c)
658 {
659 	struct pci_dev *ipu = NULL;
660 	struct icvs *ctx;
661 	int ret;
662 
663 	/* Locate IPU device */
664 	for (unsigned int i = 0; !ipu && ipu6_pci_tbl[i].vendor; i++)
665 		ipu = pci_get_device(ipu6_pci_tbl[i].vendor,
666 				     ipu6_pci_tbl[i].device, NULL);
667 	for (unsigned int i = 0; !ipu && icvs_ipu7_tbl[i].vendor; i++)
668 		ipu = pci_get_device(icvs_ipu7_tbl[i].vendor,
669 				     icvs_ipu7_tbl[i].device, NULL);
670 	if (!ipu)
671 		return -ENODEV;
672 
673 	ret = ipu_bridge_init(&ipu->dev, ipu_bridge_parse_ssdb);
674 	if (ret < 0)
675 		goto err_put_ipu;
676 
677 	if (!dev_fwnode(dev)) {
678 		ret = -ENXIO;
679 		goto err_put_ipu;
680 	}
681 
682 	ctx = devm_kzalloc(dev, sizeof(*ctx), GFP_KERNEL);
683 	if (!ctx) {
684 		ret = -ENOMEM;
685 		goto err_put_ipu;
686 	}
687 
688 	ctx->i2c_client = i2c;
689 
690 	ret = gpiod_count(dev, NULL);
691 	switch (ret) {
692 	case ICVS_GPIO_SYNC:
693 		ctx->res = ICVS_LIGHTCAP;
694 		break;
695 	case ICVS_GPIO_ASYNC:
696 		ctx->res = ICVS_FULLCAP;
697 		break;
698 	default:
699 		dev_err(dev, "unexpected GPIO count %d\n", ret);
700 		ret = -EINVAL;
701 		goto err_put_ipu;
702 	}
703 
704 	ret = devm_acpi_dev_add_driver_gpios(dev,
705 					     ctx->res == ICVS_FULLCAP ?
706 					     icvs_acpi_gpios :
707 					     icvs_acpi_lgpios);
708 	if (ret) {
709 		dev_err_probe(dev, ret, "failed to add ACPI GPIOs\n");
710 		goto err_put_ipu;
711 	}
712 
713 	ctx->req = devm_gpiod_get(dev, "req", GPIOD_OUT_HIGH);
714 	if (IS_ERR(ctx->req)) {
715 		ret = dev_err_probe(dev, PTR_ERR(ctx->req),
716 				    "failed to get req GPIO\n");
717 		goto err_put_ipu;
718 	}
719 
720 	ctx->resp = devm_gpiod_get(dev, "resp", GPIOD_IN);
721 	if (IS_ERR(ctx->resp)) {
722 		ret = dev_err_probe(dev, PTR_ERR(ctx->resp),
723 				    "failed to get resp GPIO\n");
724 		goto err_put_ipu;
725 	}
726 
727 	if (ctx->res == ICVS_FULLCAP) {
728 		struct gpio_desc *wake;
729 
730 		ctx->rst = devm_gpiod_get(dev, "rst", GPIOD_OUT_HIGH);
731 		if (IS_ERR(ctx->rst)) {
732 			ret = dev_err_probe(dev, PTR_ERR(ctx->rst),
733 					    "failed to get rst GPIO\n");
734 			goto err_put_ipu;
735 		}
736 
737 		wake = devm_gpiod_get(dev, "wake", GPIOD_IN);
738 		if (IS_ERR(wake)) {
739 			ret = dev_err_probe(dev, PTR_ERR(wake),
740 					    "failed to get wake GPIO\n");
741 			goto err_put_ipu;
742 		}
743 
744 		ctx->irq = gpiod_to_irq(wake);
745 		if (ctx->irq < 0) {
746 			ret = dev_err_probe(dev, ctx->irq,
747 					    "failed to get wake IRQ\n");
748 			goto err_put_ipu;
749 		}
750 
751 		ret = devm_request_threaded_irq(dev, ctx->irq, NULL,
752 						cvs_irq_handler,
753 						IRQF_ONESHOT | IRQF_NO_SUSPEND,
754 						"cvs_wake", ctx);
755 		if (ret) {
756 			dev_err_probe(dev, ret, "failed to request IRQ\n");
757 			goto err_put_ipu;
758 		}
759 	}
760 
761 	ret = devm_mutex_init(dev, &ctx->lock);
762 	if (ret)
763 		goto err_put_ipu;
764 
765 	init_completion(&ctx->cmd_completion);
766 	init_waitqueue_head(&ctx->hostwake_event);
767 	INIT_DELAYED_WORK(&ctx->work, cvs_recv);
768 
769 	if (i2c) {
770 		ret = cvs_hw_init(ctx);
771 		if (ret) {
772 			dev_err(dev, "HW init failed (%d)\n", ret);
773 			/*
774 			 * Fallback to GPIO-only mode.
775 			 * Some BIOS show the device on the I2C bus, however,
776 			 * the device is not accessible via I2C.
777 			 */
778 			ctx->i2c_client = NULL;
779 			goto fail_i2c;
780 		}
781 
782 		ret = cvs_get_device_caps(ctx, &ctx->caps);
783 		if (ret) {
784 			dev_err_probe(dev, ret, "get caps failed\n");
785 			goto err_put_ipu;
786 		}
787 
788 		ret = cvs_configure_dev_caps(ctx);
789 		if (ret) {
790 			dev_err_probe(dev, ret,
791 				      "configure dev caps failed\n");
792 			goto err_put_ipu;
793 		}
794 	}
795 
796 fail_i2c:
797 	ret = cvs_csi_init(ctx, dev, i2c);
798 	if (ret) {
799 		dev_err_probe(dev, ret, "CSI init failed\n");
800 		goto err_put_ipu;
801 	}
802 
803 	dev_set_drvdata(dev, ctx);
804 	pm_runtime_set_autosuspend_delay(dev, 1000);
805 	pm_runtime_use_autosuspend(dev);
806 	pm_runtime_enable(dev);
807 	pm_runtime_idle(dev);
808 
809 	/*
810 	 * Create a PM runtime device link with IPU as consumer and CVS as
811 	 * supplier. When the IPU runtime-resumes to start streaming, the PM
812 	 * framework automatically resumes CVS first, triggering
813 	 * cvs_runtime_resume() which hands CSI-2 link ownership to the host.
814 	 */
815 	ctx->ipu_link = device_link_add(&ipu->dev, dev,
816 					DL_FLAG_PM_RUNTIME |
817 					DL_FLAG_RPM_ACTIVE |
818 					DL_FLAG_STATELESS);
819 	if (!ctx->ipu_link) {
820 		dev_err(dev, "IPU device link failed\n");
821 		ret = -ENODEV;
822 		goto err_csi_remove;
823 	}
824 
825 	if (has_acpi_companion(dev))
826 		acpi_dev_clear_dependencies(ACPI_COMPANION(dev));
827 
828 	put_device(&ipu->dev);
829 
830 	return 0;
831 
832 err_csi_remove:
833 	if (ctx->ipu_link)
834 		device_link_del(ctx->ipu_link);
835 	cvs_csi_remove(ctx);
836 	pm_runtime_dont_use_autosuspend(dev);
837 	pm_runtime_disable(dev);
838 	pm_runtime_set_suspended(dev);
839 
840 err_put_ipu:
841 	put_device(&ipu->dev);
842 
843 	return ret;
844 }
845 
846 /**
847  * cvs_probe - I2C driver probe entry
848  * @i2c: I2C client
849  *
850  * Return: 0 on success or negative errno.
851  */
cvs_probe(struct i2c_client * i2c)852 static int cvs_probe(struct i2c_client *i2c)
853 {
854 	return cvs_core_probe(&i2c->dev, i2c);
855 }
856 
857 /**
858  * cvs_core_remove - Shared remove logic
859  * @dev: Device
860  */
cvs_core_remove(struct device * dev)861 static void cvs_core_remove(struct device *dev)
862 {
863 	struct icvs *ctx = dev_get_drvdata(dev);
864 
865 	cancel_delayed_work_sync(&ctx->work);
866 	cvs_csi_remove(ctx);
867 
868 	if (ctx->ipu_link)
869 		device_link_del(ctx->ipu_link);
870 
871 	pm_runtime_put_noidle(dev);
872 	pm_runtime_disable(dev);
873 	pm_runtime_set_suspended(dev);
874 
875 	cvs_reset(ctx);
876 }
877 
878 /**
879  * cvs_remove - I2C driver remove
880  * @client: I2C client
881  */
cvs_remove(struct i2c_client * client)882 static void cvs_remove(struct i2c_client *client)
883 {
884 	cvs_core_remove(&client->dev);
885 }
886 
887 /**
888  * cvs_suspend - System suspend callback
889  * @dev: Device
890  *
891  * Return: 0.
892  */
cvs_suspend(struct device * dev)893 static int __maybe_unused cvs_suspend(struct device *dev)
894 {
895 	struct icvs *ctx = dev_get_drvdata(dev);
896 
897 	cancel_delayed_work_sync(&ctx->work);
898 
899 	return 0;
900 }
901 
902 /**
903  * cvs_resume - System resume callback
904  * @dev: Device
905  *
906  * Re-validates I2C link prefix and re-sends host id if transport available.
907  *
908  * Return: 0 on success or negative errno if I2C check fails.
909  */
cvs_resume(struct device * dev)910 static int __maybe_unused cvs_resume(struct device *dev)
911 {
912 	struct icvs *ctx = dev_get_drvdata(dev);
913 	int ret;
914 
915 	if (ctx->i2c_client) {
916 		ret = cvs_hw_init(ctx);
917 		if (ret)
918 			return ret;
919 		return cvs_configure_dev_caps(ctx);
920 	}
921 
922 	return 0;
923 }
924 
925 /**
926  * cvs_runtime_resume - Runtime PM resume: claim CSI-2 link ownership
927  * @dev: Device
928  *
929  * Triggered automatically when the IPU (consumer) runtime-resumes, because
930  * a DL_FLAG_PM_RUNTIME device link makes CVS the supplier. Transfers CSI-2
931  * link ownership to the host so the IPU can start receiving sensor frames.
932  *
933  * Return: 0 on success or negative errno.
934  */
cvs_runtime_resume(struct device * dev)935 static int __maybe_unused cvs_runtime_resume(struct device *dev)
936 {
937 	struct icvs *ctx = dev_get_drvdata(dev);
938 
939 	return cvs_set_link_owner(ctx, ICVS_CSI_LINK_HOST);
940 }
941 
942 /**
943  * cvs_runtime_suspend - Runtime PM suspend: release CSI-2 link ownership
944  * @dev: Device
945  *
946  * Called when the streaming reference is dropped by cvs_csi_disable_streams
947  * via pm_runtime_put_autosuspend. Returns CSI-2 link ownership to CVS firmware.
948  *
949  * Return: 0 on success or negative errno.
950  */
cvs_runtime_suspend(struct device * dev)951 static int __maybe_unused cvs_runtime_suspend(struct device *dev)
952 {
953 	struct icvs *ctx = dev_get_drvdata(dev);
954 
955 	return cvs_set_link_owner(ctx, ICVS_CSI_LINK_CVS);
956 }
957 
958 static const struct dev_pm_ops __maybe_unused cvs_pm_ops = {
959 	SET_SYSTEM_SLEEP_PM_OPS(cvs_suspend, cvs_resume)
960 	SET_RUNTIME_PM_OPS(cvs_runtime_suspend, cvs_runtime_resume, NULL)
961 };
962 
963 static const struct acpi_device_id intel_cvs_acpi_match[] = {
964 	{ "INTC10DE" }, /* LNL */
965 	{ "INTC10E0" }, /* ARL */
966 	{ "INTC10E1" }, /* PTL */
967 	{ "INTC10FA" }, /* NVL */
968 	{ }
969 };
970 MODULE_DEVICE_TABLE(acpi, intel_cvs_acpi_match);
971 
972 static struct i2c_driver cvs_driver = {
973 	.driver = {
974 		.name = "intel_cvs",
975 		.acpi_match_table = intel_cvs_acpi_match,
976 		.pm = pm_ptr(&cvs_pm_ops),
977 	},
978 	.probe = cvs_probe,
979 	.remove = cvs_remove,
980 };
981 
cvs_platform_probe(struct platform_device * pdev)982 static int cvs_platform_probe(struct platform_device *pdev)
983 {
984 	return cvs_core_probe(&pdev->dev, NULL);
985 }
986 
cvs_platform_remove(struct platform_device * pdev)987 static void cvs_platform_remove(struct platform_device *pdev)
988 {
989 	cvs_core_remove(&pdev->dev);
990 }
991 
992 /*
993  * Platform driver structure.
994  *
995  * Some platforms may instantiate the CVS device as a platform device
996  * without I2C support. This driver binding allows such platforms to use the
997  * CVS core functionality (GPIOs, CSI sub-device) without I2C.
998  */
999 static struct platform_driver cvs_platform_driver = {
1000 	.driver = {
1001 		.name = "cvs_platform",
1002 		.acpi_match_table = intel_cvs_acpi_match,
1003 		.pm = pm_ptr(&cvs_pm_ops),
1004 	},
1005 	.probe = cvs_platform_probe,
1006 	.remove = cvs_platform_remove,
1007 };
1008 
1009 /**
1010  * cvs_init - Module init registering I2C and platform drivers
1011  *
1012  * Return: 0 on success or negative errno.
1013  */
cvs_init(void)1014 static int __init cvs_init(void)
1015 {
1016 	int ret;
1017 
1018 	ret = i2c_add_driver(&cvs_driver);
1019 	if (ret)
1020 		return ret;
1021 
1022 	ret = platform_driver_register(&cvs_platform_driver);
1023 	if (ret) {
1024 		i2c_del_driver(&cvs_driver);
1025 		return ret;
1026 	}
1027 
1028 	return 0;
1029 }
1030 
1031 /**
1032  * cvs_exit - Module exit unregistering drivers
1033  */
cvs_exit(void)1034 static void __exit cvs_exit(void)
1035 {
1036 	platform_driver_unregister(&cvs_platform_driver);
1037 	i2c_del_driver(&cvs_driver);
1038 }
1039 module_init(cvs_init);
1040 module_exit(cvs_exit);
1041 
1042 MODULE_IMPORT_NS("INTEL_IPU_BRIDGE");
1043 MODULE_AUTHOR("Miguel Vadillo <miguel.vadillo@intel.com>");
1044 MODULE_DESCRIPTION("Intel Vision Sensing Controller driver");
1045 MODULE_LICENSE("GPL");
1046