xref: /linux/drivers/hwmon/arctic_fan_controller.c (revision 8c13415c8a4383447c21ec832b20b3b283f0e01a)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Linux hwmon driver for ARCTIC Fan Controller
4  *
5  * USB Custom HID device with 10 fan channels.
6  * Exposes fan RPM (input) and PWM (0-255) via hwmon. Device pushes IN reports
7  * at ~1 Hz; no GET_REPORT. OUT reports set PWM duty (bytes 1-10, 0-100%).
8  * PWM is manual-only: the device does not change duty autonomously, only
9  * when it receives an OUT report from the host.
10  */
11 
12 #include <linux/completion.h>
13 #include <linux/dma-mapping.h>
14 #include <linux/err.h>
15 #include <linux/hid.h>
16 #include <linux/hwmon.h>
17 #include <linux/jiffies.h>
18 #include <linux/minmax.h>
19 #include <linux/module.h>
20 #include <linux/spinlock.h>
21 #include <linux/string.h>
22 #include <linux/unaligned.h>
23 
24 #define ARCTIC_VID			0x3904
25 #define ARCTIC_PID			0xF001
26 #define ARCTIC_NUM_FANS			10
27 #define ARCTIC_OUTPUT_REPORT_ID		0x01
28 #define ARCTIC_REPORT_LEN		32
29 #define ARCTIC_RPM_OFFSET		11	/* bytes 11-30: 10 x uint16 LE */
30 /* ACK report: device sends Report ID 0x02, 2 bytes (ID + status) after applying OUT report */
31 #define ARCTIC_ACK_REPORT_ID		0x02
32 #define ARCTIC_ACK_REPORT_LEN		2
33 /*
34  * Time to wait for ACK report after send.
35  * Measured over 500 iterations: max ~563 ms. Keep 1 s as margin.
36  */
37 #define ARCTIC_ACK_TIMEOUT_MS		1000
38 
39 struct arctic_fan_data {
40 	struct hid_device *hdev;
41 	struct device *hwmon_dev;	/* stored for explicit unregister in remove() */
42 	spinlock_t in_report_lock;	/* protects fan_rpm, ack_status, write_pending, pwm_duty */
43 	struct completion in_report_received; /* ACK (ID 0x02) received in raw_event */
44 	int ack_status;			/* 0 = OK, negative errno on device error */
45 	bool write_pending;		/* true while an OUT report ACK is in flight */
46 	u32 fan_rpm[ARCTIC_NUM_FANS];
47 	u8 pwm_duty[ARCTIC_NUM_FANS];	/* 0-255 matching sysfs range; converted to 0-100 on send */
48 	/*
49 	 * OUT report buffer passed to hid_hw_output_report(). Embedded in the
50 	 * devm_kzalloc'd struct so it is heap-allocated and passes
51 	 * usb_hcd_map_urb_for_dma(). Exclusively accessed by write(), which
52 	 * the hwmon core serializes.
53 	 */
54 	__dma_from_device_group_begin();
55 	u8 buf[ARCTIC_REPORT_LEN];
56 	__dma_from_device_group_end();
57 };
58 
59 /*
60  * Parse RPM values from the periodic status report (10 x uint16 LE at rpm_off).
61  * pwm_duty is not updated from the report: the device is manual-only, so the
62  * host cache is the authoritative source for PWM.
63  * Called from raw_event which may run in IRQ context; must not sleep.
64  */
65 static void arctic_fan_parse_report(struct arctic_fan_data *priv, u8 *buf,
66 				    int len, int rpm_off)
67 {
68 	unsigned long flags;
69 	int i;
70 
71 	if (len < rpm_off + 20)
72 		return;
73 
74 	spin_lock_irqsave(&priv->in_report_lock, flags);
75 	for (i = 0; i < ARCTIC_NUM_FANS; i++)
76 		priv->fan_rpm[i] = get_unaligned_le16(&buf[rpm_off + i * 2]);
77 	spin_unlock_irqrestore(&priv->in_report_lock, flags);
78 }
79 
80 /*
81  * raw_event: IN reports.
82  *
83  * Status report: Report ID 0x01, 32 bytes:
84  *   byte 0 = report ID, bytes 1-10 = PWM 0-100%, bytes 11-30 = 10 x RPM uint16 LE.
85  *   Device pushes these at ~1 Hz; no GET_REPORT.
86  *
87  * ACK report: Report ID 0x02, 2 bytes:
88  *   byte 0 = 0x02, byte 1 = status (0x00 = OK, 0x01 = ERROR).
89  *   Sent once after accepting and applying an OUT report (ID 0x01).
90  */
91 static int arctic_fan_raw_event(struct hid_device *hdev,
92 				struct hid_report *report, u8 *data, int size)
93 {
94 	struct arctic_fan_data *priv = hid_get_drvdata(hdev);
95 	unsigned long flags;
96 
97 	hid_dbg(hdev, "arctic_fan: raw_event id=%u size=%d\n", report->id, size);
98 
99 	if (report->id == ARCTIC_ACK_REPORT_ID && size == ARCTIC_ACK_REPORT_LEN) {
100 		spin_lock_irqsave(&priv->in_report_lock, flags);
101 		/*
102 		 * Only deliver if a write is in flight. This prevents a
103 		 * late-arriving ACK from a timed-out write from erroneously
104 		 * satisfying a subsequent write's completion wait.
105 		 */
106 		if (priv->write_pending) {
107 			priv->ack_status = data[1] == 0x00 ? 0 : -EIO;
108 			complete(&priv->in_report_received);
109 		}
110 		spin_unlock_irqrestore(&priv->in_report_lock, flags);
111 		return 0;
112 	}
113 
114 	if (report->id != ARCTIC_OUTPUT_REPORT_ID || size != ARCTIC_REPORT_LEN) {
115 		hid_dbg(hdev, "arctic_fan: raw_event id=%u size=%d ignored\n",
116 			report->id, size);
117 		return 0;
118 	}
119 
120 	arctic_fan_parse_report(priv, data, size, ARCTIC_RPM_OFFSET);
121 	return 0;
122 }
123 
124 static umode_t arctic_fan_is_visible(const void *data,
125 				     enum hwmon_sensor_types type,
126 				     u32 attr, int channel)
127 {
128 	if (type == hwmon_fan && attr == hwmon_fan_input)
129 		return 0444;
130 	if (type == hwmon_pwm && attr == hwmon_pwm_input)
131 		return 0644;
132 	return 0;
133 }
134 
135 static int arctic_fan_read(struct device *dev, enum hwmon_sensor_types type,
136 			   u32 attr, int channel, long *val)
137 {
138 	struct arctic_fan_data *priv = dev_get_drvdata(dev);
139 	unsigned long flags;
140 
141 	if (type == hwmon_fan && attr == hwmon_fan_input) {
142 		spin_lock_irqsave(&priv->in_report_lock, flags);
143 		*val = priv->fan_rpm[channel];
144 		spin_unlock_irqrestore(&priv->in_report_lock, flags);
145 		return 0;
146 	}
147 	if (type == hwmon_pwm && attr == hwmon_pwm_input) {
148 		spin_lock_irqsave(&priv->in_report_lock, flags);
149 		*val = priv->pwm_duty[channel];
150 		spin_unlock_irqrestore(&priv->in_report_lock, flags);
151 		return 0;
152 	}
153 	return -EINVAL;
154 }
155 
156 static int arctic_fan_write(struct device *dev, enum hwmon_sensor_types type,
157 			    u32 attr, int channel, long val)
158 {
159 	struct arctic_fan_data *priv = dev_get_drvdata(dev);
160 	u8 new_duty = (u8)clamp_val(val, 0, 255);
161 	unsigned long flags;
162 	unsigned long t;
163 	int i, ret;
164 
165 	/*
166 	 * Build the buffer and arm write_pending under in_report_lock so that
167 	 * reset_resume() cannot clear pwm_duty[] between the pwm_duty[] read
168 	 * and the buffer write, and raw_event() cannot deliver a stale ACK
169 	 * from a previous write into this write's completion.
170 	 *
171 	 * priv->buf is heap-allocated (embedded in the devm_kzalloc'd struct),
172 	 * satisfying usb_hcd_map_urb_for_dma(). Exclusively accessed by
173 	 * write() which the hwmon core serializes.
174 	 *
175 	 * pwm_duty[channel] is committed only after a positive device ACK so a
176 	 * failed or timed-out write does not corrupt the cached state.
177 	 *
178 	 * Residual theoretical race: if write A times out (write_pending
179 	 * cleared), write B sets write_pending = true, and a late ACK from
180 	 * write A—delayed beyond ARCTIC_ACK_TIMEOUT_MS—arrives during write
181 	 * B's pending window, it would falsely satisfy write B's completion.
182 	 * This cannot be prevented in driver code without protocol support
183 	 * (for example, a correlation ID echoed in the device ACK report).
184 	 * In testing, observed ACK latency stayed below the 1 s timeout
185 	 * (maximum ~563 ms over 500 iterations).
186 	 *
187 	 * The wait is non-interruptible so that a signal cannot cause write()
188 	 * to return early while the OUT report is already in flight; an
189 	 * interruptible early return would create the same late-ACK window
190 	 * without even the timeout guard.
191 	 * Serialized by the hwmon core: only one arctic_fan_write() at a time.
192 	 * Use irqsave to match the IRQ context in which raw_event may run.
193 	 */
194 	spin_lock_irqsave(&priv->in_report_lock, flags);
195 	priv->buf[0] = ARCTIC_OUTPUT_REPORT_ID;
196 	for (i = 0; i < ARCTIC_NUM_FANS; i++) {
197 		u8 d = i == channel ? new_duty : priv->pwm_duty[i];
198 
199 		priv->buf[1 + i] = DIV_ROUND_CLOSEST((unsigned int)d * 100, 255);
200 	}
201 	priv->ack_status = -ETIMEDOUT;
202 	priv->write_pending = true;
203 	reinit_completion(&priv->in_report_received);
204 	spin_unlock_irqrestore(&priv->in_report_lock, flags);
205 
206 	ret = hid_hw_output_report(priv->hdev, priv->buf, ARCTIC_REPORT_LEN);
207 	if (ret < 0) {
208 		spin_lock_irqsave(&priv->in_report_lock, flags);
209 		priv->write_pending = false;
210 		spin_unlock_irqrestore(&priv->in_report_lock, flags);
211 		return ret;
212 	}
213 
214 	t = wait_for_completion_timeout(&priv->in_report_received,
215 					msecs_to_jiffies(ARCTIC_ACK_TIMEOUT_MS));
216 	spin_lock_irqsave(&priv->in_report_lock, flags);
217 	priv->write_pending = false;
218 	/* Commit inside the lock so reset_resume() cannot race with this write */
219 	if (t && priv->ack_status == 0)
220 		priv->pwm_duty[channel] = new_duty;
221 	spin_unlock_irqrestore(&priv->in_report_lock, flags);
222 
223 	if (!t)
224 		return -ETIMEDOUT;
225 	return priv->ack_status; /* 0=OK, -EIO=device error */
226 }
227 
228 static const struct hwmon_ops arctic_fan_ops = {
229 	.is_visible = arctic_fan_is_visible,
230 	.read = arctic_fan_read,
231 	.write = arctic_fan_write,
232 };
233 
234 static const struct hwmon_channel_info *arctic_fan_info[] = {
235 	HWMON_CHANNEL_INFO(fan,
236 			   HWMON_F_INPUT, HWMON_F_INPUT, HWMON_F_INPUT,
237 			   HWMON_F_INPUT, HWMON_F_INPUT, HWMON_F_INPUT,
238 			   HWMON_F_INPUT, HWMON_F_INPUT, HWMON_F_INPUT,
239 			   HWMON_F_INPUT),
240 	HWMON_CHANNEL_INFO(pwm,
241 			   HWMON_PWM_INPUT, HWMON_PWM_INPUT, HWMON_PWM_INPUT,
242 			   HWMON_PWM_INPUT, HWMON_PWM_INPUT, HWMON_PWM_INPUT,
243 			   HWMON_PWM_INPUT, HWMON_PWM_INPUT, HWMON_PWM_INPUT,
244 			   HWMON_PWM_INPUT),
245 	NULL
246 };
247 
248 static const struct hwmon_chip_info arctic_fan_chip_info = {
249 	.ops = &arctic_fan_ops,
250 	.info = arctic_fan_info,
251 };
252 
253 static int arctic_fan_reset_resume(struct hid_device *hdev)
254 {
255 	struct arctic_fan_data *priv = hid_get_drvdata(hdev);
256 	unsigned long flags;
257 
258 	/*
259 	 * The device resets its PWM channels to hardware defaults on power
260 	 * loss during suspend. Clear the cached duty values so they reflect
261 	 * the unknown hardware state, consistent with probe-time behaviour
262 	 * (the device has no GET_REPORT support). Hold in_report_lock so
263 	 * this does not race with a concurrent pwm read or write callback.
264 	 */
265 	spin_lock_irqsave(&priv->in_report_lock, flags);
266 	memset(priv->pwm_duty, 0, sizeof(priv->pwm_duty));
267 	spin_unlock_irqrestore(&priv->in_report_lock, flags);
268 	return 0;
269 }
270 
271 static int arctic_fan_probe(struct hid_device *hdev,
272 			    const struct hid_device_id *id)
273 {
274 	struct arctic_fan_data *priv;
275 	int ret;
276 
277 	if (!hid_is_usb(hdev))
278 		return -ENODEV;
279 
280 	ret = hid_parse(hdev);
281 	if (ret)
282 		return ret;
283 
284 	priv = devm_kzalloc(&hdev->dev, sizeof(*priv), GFP_KERNEL);
285 	if (!priv)
286 		return -ENOMEM;
287 
288 	priv->hdev = hdev;
289 	spin_lock_init(&priv->in_report_lock);
290 	init_completion(&priv->in_report_received);
291 	hid_set_drvdata(hdev, priv);
292 
293 	ret = hid_hw_start(hdev, HID_CONNECT_DRIVER);
294 	if (ret)
295 		return ret;
296 
297 	ret = hid_hw_open(hdev);
298 	if (ret)
299 		goto out_stop;
300 
301 	/*
302 	 * Start IO before registering with hwmon. If IO were started after
303 	 * hwmon registration, a sysfs write arriving in that narrow window
304 	 * would send an OUT report but the ACK could not be delivered (the HID
305 	 * core discards events until io_started), causing a spurious timeout.
306 	 */
307 	hid_device_io_start(hdev);
308 
309 	/*
310 	 * Use the non-devm variant and store the pointer so remove() can
311 	 * call hwmon_device_unregister() before tearing down the HID
312 	 * transport. devm_hwmon_device_register_with_info() would defer
313 	 * unregistration until after remove() returns, leaving a window
314 	 * where a concurrent sysfs write could call hid_hw_output_report()
315 	 * on an already-stopped device (use-after-free).
316 	 */
317 	priv->hwmon_dev = hwmon_device_register_with_info(&hdev->dev, "arctic_fan",
318 							  priv, &arctic_fan_chip_info,
319 							  NULL);
320 	if (IS_ERR(priv->hwmon_dev)) {
321 		ret = PTR_ERR(priv->hwmon_dev);
322 		goto out_close;
323 	}
324 
325 	return 0;
326 
327 out_close:
328 	hid_device_io_stop(hdev);
329 	hid_hw_close(hdev);
330 out_stop:
331 	hid_hw_stop(hdev);
332 	return ret;
333 }
334 
335 static void arctic_fan_remove(struct hid_device *hdev)
336 {
337 	struct arctic_fan_data *priv = hid_get_drvdata(hdev);
338 
339 	/*
340 	 * Unregister hwmon before stopping the HID transport. This removes
341 	 * the sysfs files and waits for any in-progress write() callback to
342 	 * return, so no hwmon op can call hid_hw_output_report() after
343 	 * hid_hw_stop() frees the underlying USB resources.
344 	 * Matches the pattern used by nzxt-smart2 and aquacomputer_d5next.
345 	 *
346 	 * The HID core clears hdev->io_started before invoking ->remove(),
347 	 * so hid_device_io_stop() is not called here; doing so would emit
348 	 * a spurious "io already stopped" warning.
349 	 */
350 	hwmon_device_unregister(priv->hwmon_dev);
351 	hid_hw_close(hdev);
352 	hid_hw_stop(hdev);
353 }
354 
355 static const struct hid_device_id arctic_fan_id_table[] = {
356 	{ HID_USB_DEVICE(ARCTIC_VID, ARCTIC_PID) },
357 	{ }
358 };
359 MODULE_DEVICE_TABLE(hid, arctic_fan_id_table);
360 
361 static struct hid_driver arctic_fan_driver = {
362 	.name = "arctic_fan",
363 	.id_table = arctic_fan_id_table,
364 	.probe = arctic_fan_probe,
365 	.remove = arctic_fan_remove,
366 	.raw_event = arctic_fan_raw_event,
367 	.reset_resume = arctic_fan_reset_resume,
368 };
369 
370 module_hid_driver(arctic_fan_driver);
371 
372 MODULE_AUTHOR("Aureo Serrano de Souza <aureo.serrano@arctic.de>");
373 MODULE_DESCRIPTION("HID hwmon driver for ARCTIC Fan Controller");
374 MODULE_LICENSE("GPL");
375