xref: /openbmc/linux/drivers/usb/class/usbtmc.c (revision 9a29f5fc)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * drivers/usb/class/usbtmc.c - USB Test & Measurement class driver
4  *
5  * Copyright (C) 2007 Stefan Kopp, Gechingen, Germany
6  * Copyright (C) 2008 Novell, Inc.
7  * Copyright (C) 2008 Greg Kroah-Hartman <gregkh@suse.de>
8  * Copyright (C) 2018 IVI Foundation, Inc.
9  */
10 
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 
13 #include <linux/module.h>
14 #include <linux/kernel.h>
15 #include <linux/fs.h>
16 #include <linux/uaccess.h>
17 #include <linux/kref.h>
18 #include <linux/slab.h>
19 #include <linux/poll.h>
20 #include <linux/mutex.h>
21 #include <linux/usb.h>
22 #include <linux/compat.h>
23 #include <linux/usb/tmc.h>
24 
25 /* Increment API VERSION when changing tmc.h with new flags or ioctls
26  * or when changing a significant behavior of the driver.
27  */
28 #define USBTMC_API_VERSION (3)
29 
30 #define USBTMC_HEADER_SIZE	12
31 #define USBTMC_MINOR_BASE	176
32 
33 /* Minimum USB timeout (in milliseconds) */
34 #define USBTMC_MIN_TIMEOUT	100
35 /* Default USB timeout (in milliseconds) */
36 #define USBTMC_TIMEOUT		5000
37 
38 /* Max number of urbs used in write transfers */
39 #define MAX_URBS_IN_FLIGHT	16
40 /* I/O buffer size used in generic read/write functions */
41 #define USBTMC_BUFSIZE		(4096)
42 
43 /*
44  * Maximum number of read cycles to empty bulk in endpoint during CLEAR and
45  * ABORT_BULK_IN requests. Ends the loop if (for whatever reason) a short
46  * packet is never read.
47  */
48 #define USBTMC_MAX_READS_TO_CLEAR_BULK_IN	100
49 
50 static const struct usb_device_id usbtmc_devices[] = {
51 	{ USB_INTERFACE_INFO(USB_CLASS_APP_SPEC, 3, 0), },
52 	{ USB_INTERFACE_INFO(USB_CLASS_APP_SPEC, 3, 1), },
53 	{ 0, } /* terminating entry */
54 };
55 MODULE_DEVICE_TABLE(usb, usbtmc_devices);
56 
57 /*
58  * This structure is the capabilities for the device
59  * See section 4.2.1.8 of the USBTMC specification,
60  * and section 4.2.2 of the USBTMC usb488 subclass
61  * specification for details.
62  */
63 struct usbtmc_dev_capabilities {
64 	__u8 interface_capabilities;
65 	__u8 device_capabilities;
66 	__u8 usb488_interface_capabilities;
67 	__u8 usb488_device_capabilities;
68 };
69 
70 /* This structure holds private data for each USBTMC device. One copy is
71  * allocated for each USBTMC device in the driver's probe function.
72  */
73 struct usbtmc_device_data {
74 	const struct usb_device_id *id;
75 	struct usb_device *usb_dev;
76 	struct usb_interface *intf;
77 	struct list_head file_list;
78 
79 	unsigned int bulk_in;
80 	unsigned int bulk_out;
81 
82 	u8 bTag;
83 	u8 bTag_last_write;	/* needed for abort */
84 	u8 bTag_last_read;	/* needed for abort */
85 
86 	/* packet size of IN bulk */
87 	u16            wMaxPacketSize;
88 
89 	/* data for interrupt in endpoint handling */
90 	u8             bNotify1;
91 	u8             bNotify2;
92 	u16            ifnum;
93 	u8             iin_bTag;
94 	u8            *iin_buffer;
95 	atomic_t       iin_data_valid;
96 	unsigned int   iin_ep;
97 	int            iin_ep_present;
98 	int            iin_interval;
99 	struct urb    *iin_urb;
100 	u16            iin_wMaxPacketSize;
101 
102 	/* coalesced usb488_caps from usbtmc_dev_capabilities */
103 	__u8 usb488_caps;
104 
105 	bool zombie; /* fd of disconnected device */
106 
107 	struct usbtmc_dev_capabilities	capabilities;
108 	struct kref kref;
109 	struct mutex io_mutex;	/* only one i/o function running at a time */
110 	wait_queue_head_t waitq;
111 	struct fasync_struct *fasync;
112 	spinlock_t dev_lock; /* lock for file_list */
113 };
114 #define to_usbtmc_data(d) container_of(d, struct usbtmc_device_data, kref)
115 
116 /*
117  * This structure holds private data for each USBTMC file handle.
118  */
119 struct usbtmc_file_data {
120 	struct usbtmc_device_data *data;
121 	struct list_head file_elem;
122 
123 	u32            timeout;
124 	u8             srq_byte;
125 	atomic_t       srq_asserted;
126 	atomic_t       closing;
127 	u8             bmTransferAttributes; /* member of DEV_DEP_MSG_IN */
128 
129 	u8             eom_val;
130 	u8             term_char;
131 	bool           term_char_enabled;
132 	bool           auto_abort;
133 
134 	spinlock_t     err_lock; /* lock for errors */
135 
136 	struct usb_anchor submitted;
137 
138 	/* data for generic_write */
139 	struct semaphore limit_write_sem;
140 	u32 out_transfer_size;
141 	int out_status;
142 
143 	/* data for generic_read */
144 	u32 in_transfer_size;
145 	int in_status;
146 	int in_urbs_used;
147 	struct usb_anchor in_anchor;
148 	wait_queue_head_t wait_bulk_in;
149 };
150 
151 /* Forward declarations */
152 static struct usb_driver usbtmc_driver;
153 static void usbtmc_draw_down(struct usbtmc_file_data *file_data);
154 
155 static void usbtmc_delete(struct kref *kref)
156 {
157 	struct usbtmc_device_data *data = to_usbtmc_data(kref);
158 
159 	usb_put_dev(data->usb_dev);
160 	kfree(data);
161 }
162 
163 static int usbtmc_open(struct inode *inode, struct file *filp)
164 {
165 	struct usb_interface *intf;
166 	struct usbtmc_device_data *data;
167 	struct usbtmc_file_data *file_data;
168 
169 	intf = usb_find_interface(&usbtmc_driver, iminor(inode));
170 	if (!intf) {
171 		pr_err("can not find device for minor %d", iminor(inode));
172 		return -ENODEV;
173 	}
174 
175 	file_data = kzalloc(sizeof(*file_data), GFP_KERNEL);
176 	if (!file_data)
177 		return -ENOMEM;
178 
179 	spin_lock_init(&file_data->err_lock);
180 	sema_init(&file_data->limit_write_sem, MAX_URBS_IN_FLIGHT);
181 	init_usb_anchor(&file_data->submitted);
182 	init_usb_anchor(&file_data->in_anchor);
183 	init_waitqueue_head(&file_data->wait_bulk_in);
184 
185 	data = usb_get_intfdata(intf);
186 	/* Protect reference to data from file structure until release */
187 	kref_get(&data->kref);
188 
189 	mutex_lock(&data->io_mutex);
190 	file_data->data = data;
191 
192 	atomic_set(&file_data->closing, 0);
193 
194 	file_data->timeout = USBTMC_TIMEOUT;
195 	file_data->term_char = '\n';
196 	file_data->term_char_enabled = 0;
197 	file_data->auto_abort = 0;
198 	file_data->eom_val = 1;
199 
200 	INIT_LIST_HEAD(&file_data->file_elem);
201 	spin_lock_irq(&data->dev_lock);
202 	list_add_tail(&file_data->file_elem, &data->file_list);
203 	spin_unlock_irq(&data->dev_lock);
204 	mutex_unlock(&data->io_mutex);
205 
206 	/* Store pointer in file structure's private data field */
207 	filp->private_data = file_data;
208 
209 	return 0;
210 }
211 
212 /*
213  * usbtmc_flush - called before file handle is closed
214  */
215 static int usbtmc_flush(struct file *file, fl_owner_t id)
216 {
217 	struct usbtmc_file_data *file_data;
218 	struct usbtmc_device_data *data;
219 
220 	file_data = file->private_data;
221 	if (file_data == NULL)
222 		return -ENODEV;
223 
224 	atomic_set(&file_data->closing, 1);
225 	data = file_data->data;
226 
227 	/* wait for io to stop */
228 	mutex_lock(&data->io_mutex);
229 
230 	usbtmc_draw_down(file_data);
231 
232 	spin_lock_irq(&file_data->err_lock);
233 	file_data->in_status = 0;
234 	file_data->in_transfer_size = 0;
235 	file_data->in_urbs_used = 0;
236 	file_data->out_status = 0;
237 	file_data->out_transfer_size = 0;
238 	spin_unlock_irq(&file_data->err_lock);
239 
240 	wake_up_interruptible_all(&data->waitq);
241 	mutex_unlock(&data->io_mutex);
242 
243 	return 0;
244 }
245 
246 static int usbtmc_release(struct inode *inode, struct file *file)
247 {
248 	struct usbtmc_file_data *file_data = file->private_data;
249 
250 	/* prevent IO _AND_ usbtmc_interrupt */
251 	mutex_lock(&file_data->data->io_mutex);
252 	spin_lock_irq(&file_data->data->dev_lock);
253 
254 	list_del(&file_data->file_elem);
255 
256 	spin_unlock_irq(&file_data->data->dev_lock);
257 	mutex_unlock(&file_data->data->io_mutex);
258 
259 	kref_put(&file_data->data->kref, usbtmc_delete);
260 	file_data->data = NULL;
261 	kfree(file_data);
262 	return 0;
263 }
264 
265 static int usbtmc_ioctl_abort_bulk_in_tag(struct usbtmc_device_data *data,
266 					  u8 tag)
267 {
268 	u8 *buffer;
269 	struct device *dev;
270 	int rv;
271 	int n;
272 	int actual;
273 
274 	dev = &data->intf->dev;
275 	buffer = kmalloc(USBTMC_BUFSIZE, GFP_KERNEL);
276 	if (!buffer)
277 		return -ENOMEM;
278 
279 	rv = usb_control_msg(data->usb_dev,
280 			     usb_rcvctrlpipe(data->usb_dev, 0),
281 			     USBTMC_REQUEST_INITIATE_ABORT_BULK_IN,
282 			     USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT,
283 			     tag, data->bulk_in,
284 			     buffer, 2, USB_CTRL_GET_TIMEOUT);
285 
286 	if (rv < 0) {
287 		dev_err(dev, "usb_control_msg returned %d\n", rv);
288 		goto exit;
289 	}
290 
291 	dev_dbg(dev, "INITIATE_ABORT_BULK_IN returned %x with tag %02x\n",
292 		buffer[0], buffer[1]);
293 
294 	if (buffer[0] == USBTMC_STATUS_FAILED) {
295 		/* No transfer in progress and the Bulk-OUT FIFO is empty. */
296 		rv = 0;
297 		goto exit;
298 	}
299 
300 	if (buffer[0] == USBTMC_STATUS_TRANSFER_NOT_IN_PROGRESS) {
301 		/* The device returns this status if either:
302 		 * - There is a transfer in progress, but the specified bTag
303 		 *   does not match.
304 		 * - There is no transfer in progress, but the Bulk-OUT FIFO
305 		 *   is not empty.
306 		 */
307 		rv = -ENOMSG;
308 		goto exit;
309 	}
310 
311 	if (buffer[0] != USBTMC_STATUS_SUCCESS) {
312 		dev_err(dev, "INITIATE_ABORT_BULK_IN returned %x\n",
313 			buffer[0]);
314 		rv = -EPERM;
315 		goto exit;
316 	}
317 
318 	n = 0;
319 
320 usbtmc_abort_bulk_in_status:
321 	dev_dbg(dev, "Reading from bulk in EP\n");
322 
323 	/* Data must be present. So use low timeout 300 ms */
324 	actual = 0;
325 	rv = usb_bulk_msg(data->usb_dev,
326 			  usb_rcvbulkpipe(data->usb_dev,
327 					  data->bulk_in),
328 			  buffer, USBTMC_BUFSIZE,
329 			  &actual, 300);
330 
331 	print_hex_dump_debug("usbtmc ", DUMP_PREFIX_NONE, 16, 1,
332 			     buffer, actual, true);
333 
334 	n++;
335 
336 	if (rv < 0) {
337 		dev_err(dev, "usb_bulk_msg returned %d\n", rv);
338 		if (rv != -ETIMEDOUT)
339 			goto exit;
340 	}
341 
342 	if (actual == USBTMC_BUFSIZE)
343 		goto usbtmc_abort_bulk_in_status;
344 
345 	if (n >= USBTMC_MAX_READS_TO_CLEAR_BULK_IN) {
346 		dev_err(dev, "Couldn't clear device buffer within %d cycles\n",
347 			USBTMC_MAX_READS_TO_CLEAR_BULK_IN);
348 		rv = -EPERM;
349 		goto exit;
350 	}
351 
352 	rv = usb_control_msg(data->usb_dev,
353 			     usb_rcvctrlpipe(data->usb_dev, 0),
354 			     USBTMC_REQUEST_CHECK_ABORT_BULK_IN_STATUS,
355 			     USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT,
356 			     0, data->bulk_in, buffer, 0x08,
357 			     USB_CTRL_GET_TIMEOUT);
358 
359 	if (rv < 0) {
360 		dev_err(dev, "usb_control_msg returned %d\n", rv);
361 		goto exit;
362 	}
363 
364 	dev_dbg(dev, "CHECK_ABORT_BULK_IN returned %x\n", buffer[0]);
365 
366 	if (buffer[0] == USBTMC_STATUS_SUCCESS) {
367 		rv = 0;
368 		goto exit;
369 	}
370 
371 	if (buffer[0] != USBTMC_STATUS_PENDING) {
372 		dev_err(dev, "CHECK_ABORT_BULK_IN returned %x\n", buffer[0]);
373 		rv = -EPERM;
374 		goto exit;
375 	}
376 
377 	if ((buffer[1] & 1) > 0) {
378 		/* The device has 1 or more queued packets the Host can read */
379 		goto usbtmc_abort_bulk_in_status;
380 	}
381 
382 	/* The Host must send CHECK_ABORT_BULK_IN_STATUS at a later time. */
383 	rv = -EAGAIN;
384 exit:
385 	kfree(buffer);
386 	return rv;
387 }
388 
389 static int usbtmc_ioctl_abort_bulk_in(struct usbtmc_device_data *data)
390 {
391 	return usbtmc_ioctl_abort_bulk_in_tag(data, data->bTag_last_read);
392 }
393 
394 static int usbtmc_ioctl_abort_bulk_out_tag(struct usbtmc_device_data *data,
395 					   u8 tag)
396 {
397 	struct device *dev;
398 	u8 *buffer;
399 	int rv;
400 	int n;
401 
402 	dev = &data->intf->dev;
403 
404 	buffer = kmalloc(8, GFP_KERNEL);
405 	if (!buffer)
406 		return -ENOMEM;
407 
408 	rv = usb_control_msg(data->usb_dev,
409 			     usb_rcvctrlpipe(data->usb_dev, 0),
410 			     USBTMC_REQUEST_INITIATE_ABORT_BULK_OUT,
411 			     USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT,
412 			     tag, data->bulk_out,
413 			     buffer, 2, USB_CTRL_GET_TIMEOUT);
414 
415 	if (rv < 0) {
416 		dev_err(dev, "usb_control_msg returned %d\n", rv);
417 		goto exit;
418 	}
419 
420 	dev_dbg(dev, "INITIATE_ABORT_BULK_OUT returned %x\n", buffer[0]);
421 
422 	if (buffer[0] != USBTMC_STATUS_SUCCESS) {
423 		dev_err(dev, "INITIATE_ABORT_BULK_OUT returned %x\n",
424 			buffer[0]);
425 		rv = -EPERM;
426 		goto exit;
427 	}
428 
429 	n = 0;
430 
431 usbtmc_abort_bulk_out_check_status:
432 	/* do not stress device with subsequent requests */
433 	msleep(50);
434 	rv = usb_control_msg(data->usb_dev,
435 			     usb_rcvctrlpipe(data->usb_dev, 0),
436 			     USBTMC_REQUEST_CHECK_ABORT_BULK_OUT_STATUS,
437 			     USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT,
438 			     0, data->bulk_out, buffer, 0x08,
439 			     USB_CTRL_GET_TIMEOUT);
440 	n++;
441 	if (rv < 0) {
442 		dev_err(dev, "usb_control_msg returned %d\n", rv);
443 		goto exit;
444 	}
445 
446 	dev_dbg(dev, "CHECK_ABORT_BULK_OUT returned %x\n", buffer[0]);
447 
448 	if (buffer[0] == USBTMC_STATUS_SUCCESS)
449 		goto usbtmc_abort_bulk_out_clear_halt;
450 
451 	if ((buffer[0] == USBTMC_STATUS_PENDING) &&
452 	    (n < USBTMC_MAX_READS_TO_CLEAR_BULK_IN))
453 		goto usbtmc_abort_bulk_out_check_status;
454 
455 	rv = -EPERM;
456 	goto exit;
457 
458 usbtmc_abort_bulk_out_clear_halt:
459 	rv = usb_clear_halt(data->usb_dev,
460 			    usb_sndbulkpipe(data->usb_dev, data->bulk_out));
461 
462 	if (rv < 0) {
463 		dev_err(dev, "usb_control_msg returned %d\n", rv);
464 		goto exit;
465 	}
466 	rv = 0;
467 
468 exit:
469 	kfree(buffer);
470 	return rv;
471 }
472 
473 static int usbtmc_ioctl_abort_bulk_out(struct usbtmc_device_data *data)
474 {
475 	return usbtmc_ioctl_abort_bulk_out_tag(data, data->bTag_last_write);
476 }
477 
478 static int usbtmc_get_stb(struct usbtmc_file_data *file_data, __u8 *stb)
479 {
480 	struct usbtmc_device_data *data = file_data->data;
481 	struct device *dev = &data->intf->dev;
482 	u8 *buffer;
483 	u8 tag;
484 	int rv;
485 
486 	dev_dbg(dev, "Enter ioctl_read_stb iin_ep_present: %d\n",
487 		data->iin_ep_present);
488 
489 	buffer = kmalloc(8, GFP_KERNEL);
490 	if (!buffer)
491 		return -ENOMEM;
492 
493 	atomic_set(&data->iin_data_valid, 0);
494 
495 	rv = usb_control_msg(data->usb_dev,
496 			usb_rcvctrlpipe(data->usb_dev, 0),
497 			USBTMC488_REQUEST_READ_STATUS_BYTE,
498 			USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
499 			data->iin_bTag,
500 			data->ifnum,
501 			buffer, 0x03, USB_CTRL_GET_TIMEOUT);
502 	if (rv < 0) {
503 		dev_err(dev, "stb usb_control_msg returned %d\n", rv);
504 		goto exit;
505 	}
506 
507 	if (buffer[0] != USBTMC_STATUS_SUCCESS) {
508 		dev_err(dev, "control status returned %x\n", buffer[0]);
509 		rv = -EIO;
510 		goto exit;
511 	}
512 
513 	if (data->iin_ep_present) {
514 		rv = wait_event_interruptible_timeout(
515 			data->waitq,
516 			atomic_read(&data->iin_data_valid) != 0,
517 			file_data->timeout);
518 		if (rv < 0) {
519 			dev_dbg(dev, "wait interrupted %d\n", rv);
520 			goto exit;
521 		}
522 
523 		if (rv == 0) {
524 			dev_dbg(dev, "wait timed out\n");
525 			rv = -ETIMEDOUT;
526 			goto exit;
527 		}
528 
529 		tag = data->bNotify1 & 0x7f;
530 		if (tag != data->iin_bTag) {
531 			dev_err(dev, "expected bTag %x got %x\n",
532 				data->iin_bTag, tag);
533 		}
534 
535 		*stb = data->bNotify2;
536 	} else {
537 		*stb = buffer[2];
538 	}
539 
540 	dev_dbg(dev, "stb:0x%02x received %d\n", (unsigned int)*stb, rv);
541 
542  exit:
543 	/* bump interrupt bTag */
544 	data->iin_bTag += 1;
545 	if (data->iin_bTag > 127)
546 		/* 1 is for SRQ see USBTMC-USB488 subclass spec section 4.3.1 */
547 		data->iin_bTag = 2;
548 
549 	kfree(buffer);
550 	return rv;
551 }
552 
553 static int usbtmc488_ioctl_read_stb(struct usbtmc_file_data *file_data,
554 				void __user *arg)
555 {
556 	int srq_asserted = 0;
557 	__u8 stb;
558 	int rv;
559 
560 	rv = usbtmc_get_stb(file_data, &stb);
561 
562 	if (rv > 0) {
563 		srq_asserted = atomic_xchg(&file_data->srq_asserted,
564 					srq_asserted);
565 		if (srq_asserted)
566 			stb |= 0x40; /* Set RQS bit */
567 
568 		rv = put_user(stb, (__u8 __user *)arg);
569 	}
570 	return rv;
571 
572 }
573 
574 static int usbtmc_ioctl_get_srq_stb(struct usbtmc_file_data *file_data,
575 				void __user *arg)
576 {
577 	struct usbtmc_device_data *data = file_data->data;
578 	struct device *dev = &data->intf->dev;
579 	int srq_asserted = 0;
580 	__u8 stb = 0;
581 	int rv;
582 
583 	spin_lock_irq(&data->dev_lock);
584 	srq_asserted  = atomic_xchg(&file_data->srq_asserted, srq_asserted);
585 
586 	if (srq_asserted) {
587 		stb = file_data->srq_byte;
588 		spin_unlock_irq(&data->dev_lock);
589 		rv = put_user(stb, (__u8 __user *)arg);
590 	} else {
591 		spin_unlock_irq(&data->dev_lock);
592 		rv = -ENOMSG;
593 	}
594 
595 	dev_dbg(dev, "stb:0x%02x with srq received %d\n", (unsigned int)stb, rv);
596 
597 	return rv;
598 }
599 
600 static int usbtmc488_ioctl_wait_srq(struct usbtmc_file_data *file_data,
601 				    __u32 __user *arg)
602 {
603 	struct usbtmc_device_data *data = file_data->data;
604 	struct device *dev = &data->intf->dev;
605 	int rv;
606 	u32 timeout;
607 	unsigned long expire;
608 
609 	if (!data->iin_ep_present) {
610 		dev_dbg(dev, "no interrupt endpoint present\n");
611 		return -EFAULT;
612 	}
613 
614 	if (get_user(timeout, arg))
615 		return -EFAULT;
616 
617 	expire = msecs_to_jiffies(timeout);
618 
619 	mutex_unlock(&data->io_mutex);
620 
621 	rv = wait_event_interruptible_timeout(
622 			data->waitq,
623 			atomic_read(&file_data->srq_asserted) != 0 ||
624 			atomic_read(&file_data->closing),
625 			expire);
626 
627 	mutex_lock(&data->io_mutex);
628 
629 	/* Note! disconnect or close could be called in the meantime */
630 	if (atomic_read(&file_data->closing) || data->zombie)
631 		rv = -ENODEV;
632 
633 	if (rv < 0) {
634 		/* dev can be invalid now! */
635 		pr_debug("%s - wait interrupted %d\n", __func__, rv);
636 		return rv;
637 	}
638 
639 	if (rv == 0) {
640 		dev_dbg(dev, "%s - wait timed out\n", __func__);
641 		return -ETIMEDOUT;
642 	}
643 
644 	dev_dbg(dev, "%s - srq asserted\n", __func__);
645 	return 0;
646 }
647 
648 static int usbtmc488_ioctl_simple(struct usbtmc_device_data *data,
649 				void __user *arg, unsigned int cmd)
650 {
651 	struct device *dev = &data->intf->dev;
652 	__u8 val;
653 	u8 *buffer;
654 	u16 wValue;
655 	int rv;
656 
657 	if (!(data->usb488_caps & USBTMC488_CAPABILITY_SIMPLE))
658 		return -EINVAL;
659 
660 	buffer = kmalloc(8, GFP_KERNEL);
661 	if (!buffer)
662 		return -ENOMEM;
663 
664 	if (cmd == USBTMC488_REQUEST_REN_CONTROL) {
665 		rv = copy_from_user(&val, arg, sizeof(val));
666 		if (rv) {
667 			rv = -EFAULT;
668 			goto exit;
669 		}
670 		wValue = val ? 1 : 0;
671 	} else {
672 		wValue = 0;
673 	}
674 
675 	rv = usb_control_msg(data->usb_dev,
676 			usb_rcvctrlpipe(data->usb_dev, 0),
677 			cmd,
678 			USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
679 			wValue,
680 			data->ifnum,
681 			buffer, 0x01, USB_CTRL_GET_TIMEOUT);
682 	if (rv < 0) {
683 		dev_err(dev, "simple usb_control_msg failed %d\n", rv);
684 		goto exit;
685 	} else if (rv != 1) {
686 		dev_warn(dev, "simple usb_control_msg returned %d\n", rv);
687 		rv = -EIO;
688 		goto exit;
689 	}
690 
691 	if (buffer[0] != USBTMC_STATUS_SUCCESS) {
692 		dev_err(dev, "simple control status returned %x\n", buffer[0]);
693 		rv = -EIO;
694 		goto exit;
695 	}
696 	rv = 0;
697 
698  exit:
699 	kfree(buffer);
700 	return rv;
701 }
702 
703 /*
704  * Sends a TRIGGER Bulk-OUT command message
705  * See the USBTMC-USB488 specification, Table 2.
706  *
707  * Also updates bTag_last_write.
708  */
709 static int usbtmc488_ioctl_trigger(struct usbtmc_file_data *file_data)
710 {
711 	struct usbtmc_device_data *data = file_data->data;
712 	int retval;
713 	u8 *buffer;
714 	int actual;
715 
716 	buffer = kzalloc(USBTMC_HEADER_SIZE, GFP_KERNEL);
717 	if (!buffer)
718 		return -ENOMEM;
719 
720 	buffer[0] = 128;
721 	buffer[1] = data->bTag;
722 	buffer[2] = ~data->bTag;
723 
724 	retval = usb_bulk_msg(data->usb_dev,
725 			      usb_sndbulkpipe(data->usb_dev,
726 					      data->bulk_out),
727 			      buffer, USBTMC_HEADER_SIZE,
728 			      &actual, file_data->timeout);
729 
730 	/* Store bTag (in case we need to abort) */
731 	data->bTag_last_write = data->bTag;
732 
733 	/* Increment bTag -- and increment again if zero */
734 	data->bTag++;
735 	if (!data->bTag)
736 		data->bTag++;
737 
738 	kfree(buffer);
739 	if (retval < 0) {
740 		dev_err(&data->intf->dev, "%s returned %d\n",
741 			__func__, retval);
742 		return retval;
743 	}
744 
745 	return 0;
746 }
747 
748 static struct urb *usbtmc_create_urb(void)
749 {
750 	const size_t bufsize = USBTMC_BUFSIZE;
751 	u8 *dmabuf = NULL;
752 	struct urb *urb = usb_alloc_urb(0, GFP_KERNEL);
753 
754 	if (!urb)
755 		return NULL;
756 
757 	dmabuf = kmalloc(bufsize, GFP_KERNEL);
758 	if (!dmabuf) {
759 		usb_free_urb(urb);
760 		return NULL;
761 	}
762 
763 	urb->transfer_buffer = dmabuf;
764 	urb->transfer_buffer_length = bufsize;
765 	urb->transfer_flags |= URB_FREE_BUFFER;
766 	return urb;
767 }
768 
769 static void usbtmc_read_bulk_cb(struct urb *urb)
770 {
771 	struct usbtmc_file_data *file_data = urb->context;
772 	int status = urb->status;
773 	unsigned long flags;
774 
775 	/* sync/async unlink faults aren't errors */
776 	if (status) {
777 		if (!(/* status == -ENOENT || */
778 			status == -ECONNRESET ||
779 			status == -EREMOTEIO || /* Short packet */
780 			status == -ESHUTDOWN))
781 			dev_err(&file_data->data->intf->dev,
782 			"%s - nonzero read bulk status received: %d\n",
783 			__func__, status);
784 
785 		spin_lock_irqsave(&file_data->err_lock, flags);
786 		if (!file_data->in_status)
787 			file_data->in_status = status;
788 		spin_unlock_irqrestore(&file_data->err_lock, flags);
789 	}
790 
791 	spin_lock_irqsave(&file_data->err_lock, flags);
792 	file_data->in_transfer_size += urb->actual_length;
793 	dev_dbg(&file_data->data->intf->dev,
794 		"%s - total size: %u current: %d status: %d\n",
795 		__func__, file_data->in_transfer_size,
796 		urb->actual_length, status);
797 	spin_unlock_irqrestore(&file_data->err_lock, flags);
798 	usb_anchor_urb(urb, &file_data->in_anchor);
799 
800 	wake_up_interruptible(&file_data->wait_bulk_in);
801 	wake_up_interruptible(&file_data->data->waitq);
802 }
803 
804 static inline bool usbtmc_do_transfer(struct usbtmc_file_data *file_data)
805 {
806 	bool data_or_error;
807 
808 	spin_lock_irq(&file_data->err_lock);
809 	data_or_error = !usb_anchor_empty(&file_data->in_anchor)
810 			|| file_data->in_status;
811 	spin_unlock_irq(&file_data->err_lock);
812 	dev_dbg(&file_data->data->intf->dev, "%s: returns %d\n", __func__,
813 		data_or_error);
814 	return data_or_error;
815 }
816 
817 static ssize_t usbtmc_generic_read(struct usbtmc_file_data *file_data,
818 				   void __user *user_buffer,
819 				   u32 transfer_size,
820 				   u32 *transferred,
821 				   u32 flags)
822 {
823 	struct usbtmc_device_data *data = file_data->data;
824 	struct device *dev = &data->intf->dev;
825 	u32 done = 0;
826 	u32 remaining;
827 	const u32 bufsize = USBTMC_BUFSIZE;
828 	int retval = 0;
829 	u32 max_transfer_size;
830 	unsigned long expire;
831 	int bufcount = 1;
832 	int again = 0;
833 
834 	/* mutex already locked */
835 
836 	*transferred = done;
837 
838 	max_transfer_size = transfer_size;
839 
840 	if (flags & USBTMC_FLAG_IGNORE_TRAILER) {
841 		/* The device may send extra alignment bytes (up to
842 		 * wMaxPacketSize – 1) to avoid sending a zero-length
843 		 * packet
844 		 */
845 		remaining = transfer_size;
846 		if ((max_transfer_size % data->wMaxPacketSize) == 0)
847 			max_transfer_size += (data->wMaxPacketSize - 1);
848 	} else {
849 		/* round down to bufsize to avoid truncated data left */
850 		if (max_transfer_size > bufsize) {
851 			max_transfer_size =
852 				roundup(max_transfer_size + 1 - bufsize,
853 					bufsize);
854 		}
855 		remaining = max_transfer_size;
856 	}
857 
858 	spin_lock_irq(&file_data->err_lock);
859 
860 	if (file_data->in_status) {
861 		/* return the very first error */
862 		retval = file_data->in_status;
863 		spin_unlock_irq(&file_data->err_lock);
864 		goto error;
865 	}
866 
867 	if (flags & USBTMC_FLAG_ASYNC) {
868 		if (usb_anchor_empty(&file_data->in_anchor))
869 			again = 1;
870 
871 		if (file_data->in_urbs_used == 0) {
872 			file_data->in_transfer_size = 0;
873 			file_data->in_status = 0;
874 		}
875 	} else {
876 		file_data->in_transfer_size = 0;
877 		file_data->in_status = 0;
878 	}
879 
880 	if (max_transfer_size == 0) {
881 		bufcount = 0;
882 	} else {
883 		bufcount = roundup(max_transfer_size, bufsize) / bufsize;
884 		if (bufcount > file_data->in_urbs_used)
885 			bufcount -= file_data->in_urbs_used;
886 		else
887 			bufcount = 0;
888 
889 		if (bufcount + file_data->in_urbs_used > MAX_URBS_IN_FLIGHT) {
890 			bufcount = MAX_URBS_IN_FLIGHT -
891 					file_data->in_urbs_used;
892 		}
893 	}
894 	spin_unlock_irq(&file_data->err_lock);
895 
896 	dev_dbg(dev, "%s: requested=%u flags=0x%X size=%u bufs=%d used=%d\n",
897 		__func__, transfer_size, flags,
898 		max_transfer_size, bufcount, file_data->in_urbs_used);
899 
900 	while (bufcount > 0) {
901 		u8 *dmabuf = NULL;
902 		struct urb *urb = usbtmc_create_urb();
903 
904 		if (!urb) {
905 			retval = -ENOMEM;
906 			goto error;
907 		}
908 
909 		dmabuf = urb->transfer_buffer;
910 
911 		usb_fill_bulk_urb(urb, data->usb_dev,
912 			usb_rcvbulkpipe(data->usb_dev, data->bulk_in),
913 			dmabuf, bufsize,
914 			usbtmc_read_bulk_cb, file_data);
915 
916 		usb_anchor_urb(urb, &file_data->submitted);
917 		retval = usb_submit_urb(urb, GFP_KERNEL);
918 		/* urb is anchored. We can release our reference. */
919 		usb_free_urb(urb);
920 		if (unlikely(retval)) {
921 			usb_unanchor_urb(urb);
922 			goto error;
923 		}
924 		file_data->in_urbs_used++;
925 		bufcount--;
926 	}
927 
928 	if (again) {
929 		dev_dbg(dev, "%s: ret=again\n", __func__);
930 		return -EAGAIN;
931 	}
932 
933 	if (user_buffer == NULL)
934 		return -EINVAL;
935 
936 	expire = msecs_to_jiffies(file_data->timeout);
937 
938 	while (max_transfer_size > 0) {
939 		u32 this_part;
940 		struct urb *urb = NULL;
941 
942 		if (!(flags & USBTMC_FLAG_ASYNC)) {
943 			dev_dbg(dev, "%s: before wait time %lu\n",
944 				__func__, expire);
945 			retval = wait_event_interruptible_timeout(
946 				file_data->wait_bulk_in,
947 				usbtmc_do_transfer(file_data),
948 				expire);
949 
950 			dev_dbg(dev, "%s: wait returned %d\n",
951 				__func__, retval);
952 
953 			if (retval <= 0) {
954 				if (retval == 0)
955 					retval = -ETIMEDOUT;
956 				goto error;
957 			}
958 		}
959 
960 		urb = usb_get_from_anchor(&file_data->in_anchor);
961 		if (!urb) {
962 			if (!(flags & USBTMC_FLAG_ASYNC)) {
963 				/* synchronous case: must not happen */
964 				retval = -EFAULT;
965 				goto error;
966 			}
967 
968 			/* asynchronous case: ready, do not block or wait */
969 			*transferred = done;
970 			dev_dbg(dev, "%s: (async) done=%u ret=0\n",
971 				__func__, done);
972 			return 0;
973 		}
974 
975 		file_data->in_urbs_used--;
976 
977 		if (max_transfer_size > urb->actual_length)
978 			max_transfer_size -= urb->actual_length;
979 		else
980 			max_transfer_size = 0;
981 
982 		if (remaining > urb->actual_length)
983 			this_part = urb->actual_length;
984 		else
985 			this_part = remaining;
986 
987 		print_hex_dump_debug("usbtmc ", DUMP_PREFIX_NONE, 16, 1,
988 			urb->transfer_buffer, urb->actual_length, true);
989 
990 		if (copy_to_user(user_buffer + done,
991 				 urb->transfer_buffer, this_part)) {
992 			usb_free_urb(urb);
993 			retval = -EFAULT;
994 			goto error;
995 		}
996 
997 		remaining -= this_part;
998 		done += this_part;
999 
1000 		spin_lock_irq(&file_data->err_lock);
1001 		if (urb->status) {
1002 			/* return the very first error */
1003 			retval = file_data->in_status;
1004 			spin_unlock_irq(&file_data->err_lock);
1005 			usb_free_urb(urb);
1006 			goto error;
1007 		}
1008 		spin_unlock_irq(&file_data->err_lock);
1009 
1010 		if (urb->actual_length < bufsize) {
1011 			/* short packet or ZLP received => ready */
1012 			usb_free_urb(urb);
1013 			retval = 1;
1014 			break;
1015 		}
1016 
1017 		if (!(flags & USBTMC_FLAG_ASYNC) &&
1018 		    max_transfer_size > (bufsize * file_data->in_urbs_used)) {
1019 			/* resubmit, since other buffers still not enough */
1020 			usb_anchor_urb(urb, &file_data->submitted);
1021 			retval = usb_submit_urb(urb, GFP_KERNEL);
1022 			if (unlikely(retval)) {
1023 				usb_unanchor_urb(urb);
1024 				usb_free_urb(urb);
1025 				goto error;
1026 			}
1027 			file_data->in_urbs_used++;
1028 		}
1029 		usb_free_urb(urb);
1030 		retval = 0;
1031 	}
1032 
1033 error:
1034 	*transferred = done;
1035 
1036 	dev_dbg(dev, "%s: before kill\n", __func__);
1037 	/* Attention: killing urbs can take long time (2 ms) */
1038 	usb_kill_anchored_urbs(&file_data->submitted);
1039 	dev_dbg(dev, "%s: after kill\n", __func__);
1040 	usb_scuttle_anchored_urbs(&file_data->in_anchor);
1041 	file_data->in_urbs_used = 0;
1042 	file_data->in_status = 0; /* no spinlock needed here */
1043 	dev_dbg(dev, "%s: done=%u ret=%d\n", __func__, done, retval);
1044 
1045 	return retval;
1046 }
1047 
1048 static ssize_t usbtmc_ioctl_generic_read(struct usbtmc_file_data *file_data,
1049 					 void __user *arg)
1050 {
1051 	struct usbtmc_message msg;
1052 	ssize_t retval = 0;
1053 
1054 	/* mutex already locked */
1055 
1056 	if (copy_from_user(&msg, arg, sizeof(struct usbtmc_message)))
1057 		return -EFAULT;
1058 
1059 	retval = usbtmc_generic_read(file_data, msg.message,
1060 				     msg.transfer_size, &msg.transferred,
1061 				     msg.flags);
1062 
1063 	if (put_user(msg.transferred,
1064 		     &((struct usbtmc_message __user *)arg)->transferred))
1065 		return -EFAULT;
1066 
1067 	return retval;
1068 }
1069 
1070 static void usbtmc_write_bulk_cb(struct urb *urb)
1071 {
1072 	struct usbtmc_file_data *file_data = urb->context;
1073 	int wakeup = 0;
1074 	unsigned long flags;
1075 
1076 	spin_lock_irqsave(&file_data->err_lock, flags);
1077 	file_data->out_transfer_size += urb->actual_length;
1078 
1079 	/* sync/async unlink faults aren't errors */
1080 	if (urb->status) {
1081 		if (!(urb->status == -ENOENT ||
1082 			urb->status == -ECONNRESET ||
1083 			urb->status == -ESHUTDOWN))
1084 			dev_err(&file_data->data->intf->dev,
1085 				"%s - nonzero write bulk status received: %d\n",
1086 				__func__, urb->status);
1087 
1088 		if (!file_data->out_status) {
1089 			file_data->out_status = urb->status;
1090 			wakeup = 1;
1091 		}
1092 	}
1093 	spin_unlock_irqrestore(&file_data->err_lock, flags);
1094 
1095 	dev_dbg(&file_data->data->intf->dev,
1096 		"%s - write bulk total size: %u\n",
1097 		__func__, file_data->out_transfer_size);
1098 
1099 	up(&file_data->limit_write_sem);
1100 	if (usb_anchor_empty(&file_data->submitted) || wakeup)
1101 		wake_up_interruptible(&file_data->data->waitq);
1102 }
1103 
1104 static ssize_t usbtmc_generic_write(struct usbtmc_file_data *file_data,
1105 				    const void __user *user_buffer,
1106 				    u32 transfer_size,
1107 				    u32 *transferred,
1108 				    u32 flags)
1109 {
1110 	struct usbtmc_device_data *data = file_data->data;
1111 	struct device *dev;
1112 	u32 done = 0;
1113 	u32 remaining;
1114 	unsigned long expire;
1115 	const u32 bufsize = USBTMC_BUFSIZE;
1116 	struct urb *urb = NULL;
1117 	int retval = 0;
1118 	u32 timeout;
1119 
1120 	*transferred = 0;
1121 
1122 	/* Get pointer to private data structure */
1123 	dev = &data->intf->dev;
1124 
1125 	dev_dbg(dev, "%s: size=%u flags=0x%X sema=%u\n",
1126 		__func__, transfer_size, flags,
1127 		file_data->limit_write_sem.count);
1128 
1129 	if (flags & USBTMC_FLAG_APPEND) {
1130 		spin_lock_irq(&file_data->err_lock);
1131 		retval = file_data->out_status;
1132 		spin_unlock_irq(&file_data->err_lock);
1133 		if (retval < 0)
1134 			return retval;
1135 	} else {
1136 		spin_lock_irq(&file_data->err_lock);
1137 		file_data->out_transfer_size = 0;
1138 		file_data->out_status = 0;
1139 		spin_unlock_irq(&file_data->err_lock);
1140 	}
1141 
1142 	remaining = transfer_size;
1143 	if (remaining > INT_MAX)
1144 		remaining = INT_MAX;
1145 
1146 	timeout = file_data->timeout;
1147 	expire = msecs_to_jiffies(timeout);
1148 
1149 	while (remaining > 0) {
1150 		u32 this_part, aligned;
1151 		u8 *buffer = NULL;
1152 
1153 		if (flags & USBTMC_FLAG_ASYNC) {
1154 			if (down_trylock(&file_data->limit_write_sem)) {
1155 				retval = (done)?(0):(-EAGAIN);
1156 				goto exit;
1157 			}
1158 		} else {
1159 			retval = down_timeout(&file_data->limit_write_sem,
1160 					      expire);
1161 			if (retval < 0) {
1162 				retval = -ETIMEDOUT;
1163 				goto error;
1164 			}
1165 		}
1166 
1167 		spin_lock_irq(&file_data->err_lock);
1168 		retval = file_data->out_status;
1169 		spin_unlock_irq(&file_data->err_lock);
1170 		if (retval < 0) {
1171 			up(&file_data->limit_write_sem);
1172 			goto error;
1173 		}
1174 
1175 		/* prepare next urb to send */
1176 		urb = usbtmc_create_urb();
1177 		if (!urb) {
1178 			retval = -ENOMEM;
1179 			up(&file_data->limit_write_sem);
1180 			goto error;
1181 		}
1182 		buffer = urb->transfer_buffer;
1183 
1184 		if (remaining > bufsize)
1185 			this_part = bufsize;
1186 		else
1187 			this_part = remaining;
1188 
1189 		if (copy_from_user(buffer, user_buffer + done, this_part)) {
1190 			retval = -EFAULT;
1191 			up(&file_data->limit_write_sem);
1192 			goto error;
1193 		}
1194 
1195 		print_hex_dump_debug("usbtmc ", DUMP_PREFIX_NONE,
1196 			16, 1, buffer, this_part, true);
1197 
1198 		/* fill bulk with 32 bit alignment to meet USBTMC specification
1199 		 * (size + 3 & ~3) rounds up and simplifies user code
1200 		 */
1201 		aligned = (this_part + 3) & ~3;
1202 		dev_dbg(dev, "write(size:%u align:%u done:%u)\n",
1203 			(unsigned int)this_part,
1204 			(unsigned int)aligned,
1205 			(unsigned int)done);
1206 
1207 		usb_fill_bulk_urb(urb, data->usb_dev,
1208 			usb_sndbulkpipe(data->usb_dev, data->bulk_out),
1209 			urb->transfer_buffer, aligned,
1210 			usbtmc_write_bulk_cb, file_data);
1211 
1212 		usb_anchor_urb(urb, &file_data->submitted);
1213 		retval = usb_submit_urb(urb, GFP_KERNEL);
1214 		if (unlikely(retval)) {
1215 			usb_unanchor_urb(urb);
1216 			up(&file_data->limit_write_sem);
1217 			goto error;
1218 		}
1219 
1220 		usb_free_urb(urb);
1221 		urb = NULL; /* urb will be finally released by usb driver */
1222 
1223 		remaining -= this_part;
1224 		done += this_part;
1225 	}
1226 
1227 	/* All urbs are on the fly */
1228 	if (!(flags & USBTMC_FLAG_ASYNC)) {
1229 		if (!usb_wait_anchor_empty_timeout(&file_data->submitted,
1230 						   timeout)) {
1231 			retval = -ETIMEDOUT;
1232 			goto error;
1233 		}
1234 	}
1235 
1236 	retval = 0;
1237 	goto exit;
1238 
1239 error:
1240 	usb_kill_anchored_urbs(&file_data->submitted);
1241 exit:
1242 	usb_free_urb(urb);
1243 
1244 	spin_lock_irq(&file_data->err_lock);
1245 	if (!(flags & USBTMC_FLAG_ASYNC))
1246 		done = file_data->out_transfer_size;
1247 	if (!retval && file_data->out_status)
1248 		retval = file_data->out_status;
1249 	spin_unlock_irq(&file_data->err_lock);
1250 
1251 	*transferred = done;
1252 
1253 	dev_dbg(dev, "%s: done=%u, retval=%d, urbstat=%d\n",
1254 		__func__, done, retval, file_data->out_status);
1255 
1256 	return retval;
1257 }
1258 
1259 static ssize_t usbtmc_ioctl_generic_write(struct usbtmc_file_data *file_data,
1260 					  void __user *arg)
1261 {
1262 	struct usbtmc_message msg;
1263 	ssize_t retval = 0;
1264 
1265 	/* mutex already locked */
1266 
1267 	if (copy_from_user(&msg, arg, sizeof(struct usbtmc_message)))
1268 		return -EFAULT;
1269 
1270 	retval = usbtmc_generic_write(file_data, msg.message,
1271 				      msg.transfer_size, &msg.transferred,
1272 				      msg.flags);
1273 
1274 	if (put_user(msg.transferred,
1275 		     &((struct usbtmc_message __user *)arg)->transferred))
1276 		return -EFAULT;
1277 
1278 	return retval;
1279 }
1280 
1281 /*
1282  * Get the generic write result
1283  */
1284 static ssize_t usbtmc_ioctl_write_result(struct usbtmc_file_data *file_data,
1285 				void __user *arg)
1286 {
1287 	u32 transferred;
1288 	int retval;
1289 
1290 	spin_lock_irq(&file_data->err_lock);
1291 	transferred = file_data->out_transfer_size;
1292 	retval = file_data->out_status;
1293 	spin_unlock_irq(&file_data->err_lock);
1294 
1295 	if (put_user(transferred, (__u32 __user *)arg))
1296 		return -EFAULT;
1297 
1298 	return retval;
1299 }
1300 
1301 /*
1302  * Sends a REQUEST_DEV_DEP_MSG_IN message on the Bulk-OUT endpoint.
1303  * @transfer_size: number of bytes to request from the device.
1304  *
1305  * See the USBTMC specification, Table 4.
1306  *
1307  * Also updates bTag_last_write.
1308  */
1309 static int send_request_dev_dep_msg_in(struct usbtmc_file_data *file_data,
1310 				       u32 transfer_size)
1311 {
1312 	struct usbtmc_device_data *data = file_data->data;
1313 	int retval;
1314 	u8 *buffer;
1315 	int actual;
1316 
1317 	buffer = kmalloc(USBTMC_HEADER_SIZE, GFP_KERNEL);
1318 	if (!buffer)
1319 		return -ENOMEM;
1320 	/* Setup IO buffer for REQUEST_DEV_DEP_MSG_IN message
1321 	 * Refer to class specs for details
1322 	 */
1323 	buffer[0] = 2;
1324 	buffer[1] = data->bTag;
1325 	buffer[2] = ~data->bTag;
1326 	buffer[3] = 0; /* Reserved */
1327 	buffer[4] = transfer_size >> 0;
1328 	buffer[5] = transfer_size >> 8;
1329 	buffer[6] = transfer_size >> 16;
1330 	buffer[7] = transfer_size >> 24;
1331 	buffer[8] = file_data->term_char_enabled * 2;
1332 	/* Use term character? */
1333 	buffer[9] = file_data->term_char;
1334 	buffer[10] = 0; /* Reserved */
1335 	buffer[11] = 0; /* Reserved */
1336 
1337 	/* Send bulk URB */
1338 	retval = usb_bulk_msg(data->usb_dev,
1339 			      usb_sndbulkpipe(data->usb_dev,
1340 					      data->bulk_out),
1341 			      buffer, USBTMC_HEADER_SIZE,
1342 			      &actual, file_data->timeout);
1343 
1344 	/* Store bTag (in case we need to abort) */
1345 	data->bTag_last_write = data->bTag;
1346 
1347 	/* Increment bTag -- and increment again if zero */
1348 	data->bTag++;
1349 	if (!data->bTag)
1350 		data->bTag++;
1351 
1352 	kfree(buffer);
1353 	if (retval < 0)
1354 		dev_err(&data->intf->dev, "%s returned %d\n",
1355 			__func__, retval);
1356 
1357 	return retval;
1358 }
1359 
1360 static ssize_t usbtmc_read(struct file *filp, char __user *buf,
1361 			   size_t count, loff_t *f_pos)
1362 {
1363 	struct usbtmc_file_data *file_data;
1364 	struct usbtmc_device_data *data;
1365 	struct device *dev;
1366 	const u32 bufsize = USBTMC_BUFSIZE;
1367 	u32 n_characters;
1368 	u8 *buffer;
1369 	int actual;
1370 	u32 done = 0;
1371 	u32 remaining;
1372 	int retval;
1373 
1374 	/* Get pointer to private data structure */
1375 	file_data = filp->private_data;
1376 	data = file_data->data;
1377 	dev = &data->intf->dev;
1378 
1379 	buffer = kmalloc(bufsize, GFP_KERNEL);
1380 	if (!buffer)
1381 		return -ENOMEM;
1382 
1383 	mutex_lock(&data->io_mutex);
1384 	if (data->zombie) {
1385 		retval = -ENODEV;
1386 		goto exit;
1387 	}
1388 
1389 	if (count > INT_MAX)
1390 		count = INT_MAX;
1391 
1392 	dev_dbg(dev, "%s(count:%zu)\n", __func__, count);
1393 
1394 	retval = send_request_dev_dep_msg_in(file_data, count);
1395 
1396 	if (retval < 0) {
1397 		if (file_data->auto_abort)
1398 			usbtmc_ioctl_abort_bulk_out(data);
1399 		goto exit;
1400 	}
1401 
1402 	/* Loop until we have fetched everything we requested */
1403 	remaining = count;
1404 	actual = 0;
1405 
1406 	/* Send bulk URB */
1407 	retval = usb_bulk_msg(data->usb_dev,
1408 			      usb_rcvbulkpipe(data->usb_dev,
1409 					      data->bulk_in),
1410 			      buffer, bufsize, &actual,
1411 			      file_data->timeout);
1412 
1413 	dev_dbg(dev, "%s: bulk_msg retval(%u), actual(%d)\n",
1414 		__func__, retval, actual);
1415 
1416 	/* Store bTag (in case we need to abort) */
1417 	data->bTag_last_read = data->bTag;
1418 
1419 	if (retval < 0) {
1420 		if (file_data->auto_abort)
1421 			usbtmc_ioctl_abort_bulk_in(data);
1422 		goto exit;
1423 	}
1424 
1425 	/* Sanity checks for the header */
1426 	if (actual < USBTMC_HEADER_SIZE) {
1427 		dev_err(dev, "Device sent too small first packet: %u < %u\n",
1428 			actual, USBTMC_HEADER_SIZE);
1429 		if (file_data->auto_abort)
1430 			usbtmc_ioctl_abort_bulk_in(data);
1431 		goto exit;
1432 	}
1433 
1434 	if (buffer[0] != 2) {
1435 		dev_err(dev, "Device sent reply with wrong MsgID: %u != 2\n",
1436 			buffer[0]);
1437 		if (file_data->auto_abort)
1438 			usbtmc_ioctl_abort_bulk_in(data);
1439 		goto exit;
1440 	}
1441 
1442 	if (buffer[1] != data->bTag_last_write) {
1443 		dev_err(dev, "Device sent reply with wrong bTag: %u != %u\n",
1444 		buffer[1], data->bTag_last_write);
1445 		if (file_data->auto_abort)
1446 			usbtmc_ioctl_abort_bulk_in(data);
1447 		goto exit;
1448 	}
1449 
1450 	/* How many characters did the instrument send? */
1451 	n_characters = buffer[4] +
1452 		       (buffer[5] << 8) +
1453 		       (buffer[6] << 16) +
1454 		       (buffer[7] << 24);
1455 
1456 	file_data->bmTransferAttributes = buffer[8];
1457 
1458 	dev_dbg(dev, "Bulk-IN header: N_characters(%u), bTransAttr(%u)\n",
1459 		n_characters, buffer[8]);
1460 
1461 	if (n_characters > remaining) {
1462 		dev_err(dev, "Device wants to return more data than requested: %u > %zu\n",
1463 			n_characters, count);
1464 		if (file_data->auto_abort)
1465 			usbtmc_ioctl_abort_bulk_in(data);
1466 		goto exit;
1467 	}
1468 
1469 	print_hex_dump_debug("usbtmc ", DUMP_PREFIX_NONE,
1470 			     16, 1, buffer, actual, true);
1471 
1472 	remaining = n_characters;
1473 
1474 	/* Remove the USBTMC header */
1475 	actual -= USBTMC_HEADER_SIZE;
1476 
1477 	/* Remove padding if it exists */
1478 	if (actual > remaining)
1479 		actual = remaining;
1480 
1481 	remaining -= actual;
1482 
1483 	/* Copy buffer to user space */
1484 	if (copy_to_user(buf, &buffer[USBTMC_HEADER_SIZE], actual)) {
1485 		/* There must have been an addressing problem */
1486 		retval = -EFAULT;
1487 		goto exit;
1488 	}
1489 
1490 	if ((actual + USBTMC_HEADER_SIZE) == bufsize) {
1491 		retval = usbtmc_generic_read(file_data, buf + actual,
1492 					     remaining,
1493 					     &done,
1494 					     USBTMC_FLAG_IGNORE_TRAILER);
1495 		if (retval < 0)
1496 			goto exit;
1497 	}
1498 	done += actual;
1499 
1500 	/* Update file position value */
1501 	*f_pos = *f_pos + done;
1502 	retval = done;
1503 
1504 exit:
1505 	mutex_unlock(&data->io_mutex);
1506 	kfree(buffer);
1507 	return retval;
1508 }
1509 
1510 static ssize_t usbtmc_write(struct file *filp, const char __user *buf,
1511 			    size_t count, loff_t *f_pos)
1512 {
1513 	struct usbtmc_file_data *file_data;
1514 	struct usbtmc_device_data *data;
1515 	struct urb *urb = NULL;
1516 	ssize_t retval = 0;
1517 	u8 *buffer;
1518 	u32 remaining, done;
1519 	u32 transfersize, aligned, buflen;
1520 
1521 	file_data = filp->private_data;
1522 	data = file_data->data;
1523 
1524 	mutex_lock(&data->io_mutex);
1525 
1526 	if (data->zombie) {
1527 		retval = -ENODEV;
1528 		goto exit;
1529 	}
1530 
1531 	done = 0;
1532 
1533 	spin_lock_irq(&file_data->err_lock);
1534 	file_data->out_transfer_size = 0;
1535 	file_data->out_status = 0;
1536 	spin_unlock_irq(&file_data->err_lock);
1537 
1538 	if (!count)
1539 		goto exit;
1540 
1541 	if (down_trylock(&file_data->limit_write_sem)) {
1542 		/* previous calls were async */
1543 		retval = -EBUSY;
1544 		goto exit;
1545 	}
1546 
1547 	urb = usbtmc_create_urb();
1548 	if (!urb) {
1549 		retval = -ENOMEM;
1550 		up(&file_data->limit_write_sem);
1551 		goto exit;
1552 	}
1553 
1554 	buffer = urb->transfer_buffer;
1555 	buflen = urb->transfer_buffer_length;
1556 
1557 	if (count > INT_MAX) {
1558 		transfersize = INT_MAX;
1559 		buffer[8] = 0;
1560 	} else {
1561 		transfersize = count;
1562 		buffer[8] = file_data->eom_val;
1563 	}
1564 
1565 	/* Setup IO buffer for DEV_DEP_MSG_OUT message */
1566 	buffer[0] = 1;
1567 	buffer[1] = data->bTag;
1568 	buffer[2] = ~data->bTag;
1569 	buffer[3] = 0; /* Reserved */
1570 	buffer[4] = transfersize >> 0;
1571 	buffer[5] = transfersize >> 8;
1572 	buffer[6] = transfersize >> 16;
1573 	buffer[7] = transfersize >> 24;
1574 	/* buffer[8] is set above... */
1575 	buffer[9] = 0; /* Reserved */
1576 	buffer[10] = 0; /* Reserved */
1577 	buffer[11] = 0; /* Reserved */
1578 
1579 	remaining = transfersize;
1580 
1581 	if (transfersize + USBTMC_HEADER_SIZE > buflen) {
1582 		transfersize = buflen - USBTMC_HEADER_SIZE;
1583 		aligned = buflen;
1584 	} else {
1585 		aligned = (transfersize + (USBTMC_HEADER_SIZE + 3)) & ~3;
1586 	}
1587 
1588 	if (copy_from_user(&buffer[USBTMC_HEADER_SIZE], buf, transfersize)) {
1589 		retval = -EFAULT;
1590 		up(&file_data->limit_write_sem);
1591 		goto exit;
1592 	}
1593 
1594 	dev_dbg(&data->intf->dev, "%s(size:%u align:%u)\n", __func__,
1595 		(unsigned int)transfersize, (unsigned int)aligned);
1596 
1597 	print_hex_dump_debug("usbtmc ", DUMP_PREFIX_NONE,
1598 			     16, 1, buffer, aligned, true);
1599 
1600 	usb_fill_bulk_urb(urb, data->usb_dev,
1601 		usb_sndbulkpipe(data->usb_dev, data->bulk_out),
1602 		urb->transfer_buffer, aligned,
1603 		usbtmc_write_bulk_cb, file_data);
1604 
1605 	usb_anchor_urb(urb, &file_data->submitted);
1606 	retval = usb_submit_urb(urb, GFP_KERNEL);
1607 	if (unlikely(retval)) {
1608 		usb_unanchor_urb(urb);
1609 		up(&file_data->limit_write_sem);
1610 		goto exit;
1611 	}
1612 
1613 	remaining -= transfersize;
1614 
1615 	data->bTag_last_write = data->bTag;
1616 	data->bTag++;
1617 
1618 	if (!data->bTag)
1619 		data->bTag++;
1620 
1621 	/* call generic_write even when remaining = 0 */
1622 	retval = usbtmc_generic_write(file_data, buf + transfersize, remaining,
1623 				      &done, USBTMC_FLAG_APPEND);
1624 	/* truncate alignment bytes */
1625 	if (done > remaining)
1626 		done = remaining;
1627 
1628 	/*add size of first urb*/
1629 	done += transfersize;
1630 
1631 	if (retval < 0) {
1632 		usb_kill_anchored_urbs(&file_data->submitted);
1633 
1634 		dev_err(&data->intf->dev,
1635 			"Unable to send data, error %d\n", (int)retval);
1636 		if (file_data->auto_abort)
1637 			usbtmc_ioctl_abort_bulk_out(data);
1638 		goto exit;
1639 	}
1640 
1641 	retval = done;
1642 exit:
1643 	usb_free_urb(urb);
1644 	mutex_unlock(&data->io_mutex);
1645 	return retval;
1646 }
1647 
1648 static int usbtmc_ioctl_clear(struct usbtmc_device_data *data)
1649 {
1650 	struct device *dev;
1651 	u8 *buffer;
1652 	int rv;
1653 	int n;
1654 	int actual = 0;
1655 
1656 	dev = &data->intf->dev;
1657 
1658 	dev_dbg(dev, "Sending INITIATE_CLEAR request\n");
1659 
1660 	buffer = kmalloc(USBTMC_BUFSIZE, GFP_KERNEL);
1661 	if (!buffer)
1662 		return -ENOMEM;
1663 
1664 	rv = usb_control_msg(data->usb_dev,
1665 			     usb_rcvctrlpipe(data->usb_dev, 0),
1666 			     USBTMC_REQUEST_INITIATE_CLEAR,
1667 			     USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1668 			     0, 0, buffer, 1, USB_CTRL_GET_TIMEOUT);
1669 	if (rv < 0) {
1670 		dev_err(dev, "usb_control_msg returned %d\n", rv);
1671 		goto exit;
1672 	}
1673 
1674 	dev_dbg(dev, "INITIATE_CLEAR returned %x\n", buffer[0]);
1675 
1676 	if (buffer[0] != USBTMC_STATUS_SUCCESS) {
1677 		dev_err(dev, "INITIATE_CLEAR returned %x\n", buffer[0]);
1678 		rv = -EPERM;
1679 		goto exit;
1680 	}
1681 
1682 	n = 0;
1683 
1684 usbtmc_clear_check_status:
1685 
1686 	dev_dbg(dev, "Sending CHECK_CLEAR_STATUS request\n");
1687 
1688 	rv = usb_control_msg(data->usb_dev,
1689 			     usb_rcvctrlpipe(data->usb_dev, 0),
1690 			     USBTMC_REQUEST_CHECK_CLEAR_STATUS,
1691 			     USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1692 			     0, 0, buffer, 2, USB_CTRL_GET_TIMEOUT);
1693 	if (rv < 0) {
1694 		dev_err(dev, "usb_control_msg returned %d\n", rv);
1695 		goto exit;
1696 	}
1697 
1698 	dev_dbg(dev, "CHECK_CLEAR_STATUS returned %x\n", buffer[0]);
1699 
1700 	if (buffer[0] == USBTMC_STATUS_SUCCESS)
1701 		goto usbtmc_clear_bulk_out_halt;
1702 
1703 	if (buffer[0] != USBTMC_STATUS_PENDING) {
1704 		dev_err(dev, "CHECK_CLEAR_STATUS returned %x\n", buffer[0]);
1705 		rv = -EPERM;
1706 		goto exit;
1707 	}
1708 
1709 	if ((buffer[1] & 1) != 0) {
1710 		do {
1711 			dev_dbg(dev, "Reading from bulk in EP\n");
1712 
1713 			actual = 0;
1714 			rv = usb_bulk_msg(data->usb_dev,
1715 					  usb_rcvbulkpipe(data->usb_dev,
1716 							  data->bulk_in),
1717 					  buffer, USBTMC_BUFSIZE,
1718 					  &actual, USB_CTRL_GET_TIMEOUT);
1719 
1720 			print_hex_dump_debug("usbtmc ", DUMP_PREFIX_NONE,
1721 					     16, 1, buffer, actual, true);
1722 
1723 			n++;
1724 
1725 			if (rv < 0) {
1726 				dev_err(dev, "usb_control_msg returned %d\n",
1727 					rv);
1728 				goto exit;
1729 			}
1730 		} while ((actual == USBTMC_BUFSIZE) &&
1731 			  (n < USBTMC_MAX_READS_TO_CLEAR_BULK_IN));
1732 	} else {
1733 		/* do not stress device with subsequent requests */
1734 		msleep(50);
1735 		n++;
1736 	}
1737 
1738 	if (n >= USBTMC_MAX_READS_TO_CLEAR_BULK_IN) {
1739 		dev_err(dev, "Couldn't clear device buffer within %d cycles\n",
1740 			USBTMC_MAX_READS_TO_CLEAR_BULK_IN);
1741 		rv = -EPERM;
1742 		goto exit;
1743 	}
1744 
1745 	goto usbtmc_clear_check_status;
1746 
1747 usbtmc_clear_bulk_out_halt:
1748 
1749 	rv = usb_clear_halt(data->usb_dev,
1750 			    usb_sndbulkpipe(data->usb_dev, data->bulk_out));
1751 	if (rv < 0) {
1752 		dev_err(dev, "usb_clear_halt returned %d\n", rv);
1753 		goto exit;
1754 	}
1755 	rv = 0;
1756 
1757 exit:
1758 	kfree(buffer);
1759 	return rv;
1760 }
1761 
1762 static int usbtmc_ioctl_clear_out_halt(struct usbtmc_device_data *data)
1763 {
1764 	int rv;
1765 
1766 	rv = usb_clear_halt(data->usb_dev,
1767 			    usb_sndbulkpipe(data->usb_dev, data->bulk_out));
1768 
1769 	if (rv < 0)
1770 		dev_err(&data->usb_dev->dev, "%s returned %d\n", __func__, rv);
1771 	return rv;
1772 }
1773 
1774 static int usbtmc_ioctl_clear_in_halt(struct usbtmc_device_data *data)
1775 {
1776 	int rv;
1777 
1778 	rv = usb_clear_halt(data->usb_dev,
1779 			    usb_rcvbulkpipe(data->usb_dev, data->bulk_in));
1780 
1781 	if (rv < 0)
1782 		dev_err(&data->usb_dev->dev, "%s returned %d\n", __func__, rv);
1783 	return rv;
1784 }
1785 
1786 static int usbtmc_ioctl_cancel_io(struct usbtmc_file_data *file_data)
1787 {
1788 	spin_lock_irq(&file_data->err_lock);
1789 	file_data->in_status = -ECANCELED;
1790 	file_data->out_status = -ECANCELED;
1791 	spin_unlock_irq(&file_data->err_lock);
1792 	usb_kill_anchored_urbs(&file_data->submitted);
1793 	return 0;
1794 }
1795 
1796 static int usbtmc_ioctl_cleanup_io(struct usbtmc_file_data *file_data)
1797 {
1798 	usb_kill_anchored_urbs(&file_data->submitted);
1799 	usb_scuttle_anchored_urbs(&file_data->in_anchor);
1800 	spin_lock_irq(&file_data->err_lock);
1801 	file_data->in_status = 0;
1802 	file_data->in_transfer_size = 0;
1803 	file_data->out_status = 0;
1804 	file_data->out_transfer_size = 0;
1805 	spin_unlock_irq(&file_data->err_lock);
1806 
1807 	file_data->in_urbs_used = 0;
1808 	return 0;
1809 }
1810 
1811 static int get_capabilities(struct usbtmc_device_data *data)
1812 {
1813 	struct device *dev = &data->usb_dev->dev;
1814 	char *buffer;
1815 	int rv = 0;
1816 
1817 	buffer = kmalloc(0x18, GFP_KERNEL);
1818 	if (!buffer)
1819 		return -ENOMEM;
1820 
1821 	rv = usb_control_msg(data->usb_dev, usb_rcvctrlpipe(data->usb_dev, 0),
1822 			     USBTMC_REQUEST_GET_CAPABILITIES,
1823 			     USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1824 			     0, 0, buffer, 0x18, USB_CTRL_GET_TIMEOUT);
1825 	if (rv < 0) {
1826 		dev_err(dev, "usb_control_msg returned %d\n", rv);
1827 		goto err_out;
1828 	}
1829 
1830 	dev_dbg(dev, "GET_CAPABILITIES returned %x\n", buffer[0]);
1831 	if (buffer[0] != USBTMC_STATUS_SUCCESS) {
1832 		dev_err(dev, "GET_CAPABILITIES returned %x\n", buffer[0]);
1833 		rv = -EPERM;
1834 		goto err_out;
1835 	}
1836 	dev_dbg(dev, "Interface capabilities are %x\n", buffer[4]);
1837 	dev_dbg(dev, "Device capabilities are %x\n", buffer[5]);
1838 	dev_dbg(dev, "USB488 interface capabilities are %x\n", buffer[14]);
1839 	dev_dbg(dev, "USB488 device capabilities are %x\n", buffer[15]);
1840 
1841 	data->capabilities.interface_capabilities = buffer[4];
1842 	data->capabilities.device_capabilities = buffer[5];
1843 	data->capabilities.usb488_interface_capabilities = buffer[14];
1844 	data->capabilities.usb488_device_capabilities = buffer[15];
1845 	data->usb488_caps = (buffer[14] & 0x07) | ((buffer[15] & 0x0f) << 4);
1846 	rv = 0;
1847 
1848 err_out:
1849 	kfree(buffer);
1850 	return rv;
1851 }
1852 
1853 #define capability_attribute(name)					\
1854 static ssize_t name##_show(struct device *dev,				\
1855 			   struct device_attribute *attr, char *buf)	\
1856 {									\
1857 	struct usb_interface *intf = to_usb_interface(dev);		\
1858 	struct usbtmc_device_data *data = usb_get_intfdata(intf);	\
1859 									\
1860 	return sprintf(buf, "%d\n", data->capabilities.name);		\
1861 }									\
1862 static DEVICE_ATTR_RO(name)
1863 
1864 capability_attribute(interface_capabilities);
1865 capability_attribute(device_capabilities);
1866 capability_attribute(usb488_interface_capabilities);
1867 capability_attribute(usb488_device_capabilities);
1868 
1869 static struct attribute *usbtmc_attrs[] = {
1870 	&dev_attr_interface_capabilities.attr,
1871 	&dev_attr_device_capabilities.attr,
1872 	&dev_attr_usb488_interface_capabilities.attr,
1873 	&dev_attr_usb488_device_capabilities.attr,
1874 	NULL,
1875 };
1876 ATTRIBUTE_GROUPS(usbtmc);
1877 
1878 static int usbtmc_ioctl_indicator_pulse(struct usbtmc_device_data *data)
1879 {
1880 	struct device *dev;
1881 	u8 *buffer;
1882 	int rv;
1883 
1884 	dev = &data->intf->dev;
1885 
1886 	buffer = kmalloc(2, GFP_KERNEL);
1887 	if (!buffer)
1888 		return -ENOMEM;
1889 
1890 	rv = usb_control_msg(data->usb_dev,
1891 			     usb_rcvctrlpipe(data->usb_dev, 0),
1892 			     USBTMC_REQUEST_INDICATOR_PULSE,
1893 			     USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1894 			     0, 0, buffer, 0x01, USB_CTRL_GET_TIMEOUT);
1895 
1896 	if (rv < 0) {
1897 		dev_err(dev, "usb_control_msg returned %d\n", rv);
1898 		goto exit;
1899 	}
1900 
1901 	dev_dbg(dev, "INDICATOR_PULSE returned %x\n", buffer[0]);
1902 
1903 	if (buffer[0] != USBTMC_STATUS_SUCCESS) {
1904 		dev_err(dev, "INDICATOR_PULSE returned %x\n", buffer[0]);
1905 		rv = -EPERM;
1906 		goto exit;
1907 	}
1908 	rv = 0;
1909 
1910 exit:
1911 	kfree(buffer);
1912 	return rv;
1913 }
1914 
1915 static int usbtmc_ioctl_request(struct usbtmc_device_data *data,
1916 				void __user *arg)
1917 {
1918 	struct device *dev = &data->intf->dev;
1919 	struct usbtmc_ctrlrequest request;
1920 	u8 *buffer = NULL;
1921 	int rv;
1922 	unsigned int is_in, pipe;
1923 	unsigned long res;
1924 
1925 	res = copy_from_user(&request, arg, sizeof(struct usbtmc_ctrlrequest));
1926 	if (res)
1927 		return -EFAULT;
1928 
1929 	if (request.req.wLength > USBTMC_BUFSIZE)
1930 		return -EMSGSIZE;
1931 
1932 	is_in = request.req.bRequestType & USB_DIR_IN;
1933 
1934 	if (request.req.wLength) {
1935 		buffer = kmalloc(request.req.wLength, GFP_KERNEL);
1936 		if (!buffer)
1937 			return -ENOMEM;
1938 
1939 		if (!is_in) {
1940 			/* Send control data to device */
1941 			res = copy_from_user(buffer, request.data,
1942 					     request.req.wLength);
1943 			if (res) {
1944 				rv = -EFAULT;
1945 				goto exit;
1946 			}
1947 		}
1948 	}
1949 
1950 	if (is_in)
1951 		pipe = usb_rcvctrlpipe(data->usb_dev, 0);
1952 	else
1953 		pipe = usb_sndctrlpipe(data->usb_dev, 0);
1954 	rv = usb_control_msg(data->usb_dev,
1955 			pipe,
1956 			request.req.bRequest,
1957 			request.req.bRequestType,
1958 			request.req.wValue,
1959 			request.req.wIndex,
1960 			buffer, request.req.wLength, USB_CTRL_GET_TIMEOUT);
1961 
1962 	if (rv < 0) {
1963 		dev_err(dev, "%s failed %d\n", __func__, rv);
1964 		goto exit;
1965 	}
1966 
1967 	if (rv && is_in) {
1968 		/* Read control data from device */
1969 		res = copy_to_user(request.data, buffer, rv);
1970 		if (res)
1971 			rv = -EFAULT;
1972 	}
1973 
1974  exit:
1975 	kfree(buffer);
1976 	return rv;
1977 }
1978 
1979 /*
1980  * Get the usb timeout value
1981  */
1982 static int usbtmc_ioctl_get_timeout(struct usbtmc_file_data *file_data,
1983 				void __user *arg)
1984 {
1985 	u32 timeout;
1986 
1987 	timeout = file_data->timeout;
1988 
1989 	return put_user(timeout, (__u32 __user *)arg);
1990 }
1991 
1992 /*
1993  * Set the usb timeout value
1994  */
1995 static int usbtmc_ioctl_set_timeout(struct usbtmc_file_data *file_data,
1996 				void __user *arg)
1997 {
1998 	u32 timeout;
1999 
2000 	if (get_user(timeout, (__u32 __user *)arg))
2001 		return -EFAULT;
2002 
2003 	/* Note that timeout = 0 means
2004 	 * MAX_SCHEDULE_TIMEOUT in usb_control_msg
2005 	 */
2006 	if (timeout < USBTMC_MIN_TIMEOUT)
2007 		return -EINVAL;
2008 
2009 	file_data->timeout = timeout;
2010 
2011 	return 0;
2012 }
2013 
2014 /*
2015  * enables/disables sending EOM on write
2016  */
2017 static int usbtmc_ioctl_eom_enable(struct usbtmc_file_data *file_data,
2018 				void __user *arg)
2019 {
2020 	u8 eom_enable;
2021 
2022 	if (copy_from_user(&eom_enable, arg, sizeof(eom_enable)))
2023 		return -EFAULT;
2024 
2025 	if (eom_enable > 1)
2026 		return -EINVAL;
2027 
2028 	file_data->eom_val = eom_enable;
2029 
2030 	return 0;
2031 }
2032 
2033 /*
2034  * Configure termination character for read()
2035  */
2036 static int usbtmc_ioctl_config_termc(struct usbtmc_file_data *file_data,
2037 				void __user *arg)
2038 {
2039 	struct usbtmc_termchar termc;
2040 
2041 	if (copy_from_user(&termc, arg, sizeof(termc)))
2042 		return -EFAULT;
2043 
2044 	if ((termc.term_char_enabled > 1) ||
2045 		(termc.term_char_enabled &&
2046 		!(file_data->data->capabilities.device_capabilities & 1)))
2047 		return -EINVAL;
2048 
2049 	file_data->term_char = termc.term_char;
2050 	file_data->term_char_enabled = termc.term_char_enabled;
2051 
2052 	return 0;
2053 }
2054 
2055 static long usbtmc_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2056 {
2057 	struct usbtmc_file_data *file_data;
2058 	struct usbtmc_device_data *data;
2059 	int retval = -EBADRQC;
2060 	__u8 tmp_byte;
2061 
2062 	file_data = file->private_data;
2063 	data = file_data->data;
2064 
2065 	mutex_lock(&data->io_mutex);
2066 	if (data->zombie) {
2067 		retval = -ENODEV;
2068 		goto skip_io_on_zombie;
2069 	}
2070 
2071 	switch (cmd) {
2072 	case USBTMC_IOCTL_CLEAR_OUT_HALT:
2073 		retval = usbtmc_ioctl_clear_out_halt(data);
2074 		break;
2075 
2076 	case USBTMC_IOCTL_CLEAR_IN_HALT:
2077 		retval = usbtmc_ioctl_clear_in_halt(data);
2078 		break;
2079 
2080 	case USBTMC_IOCTL_INDICATOR_PULSE:
2081 		retval = usbtmc_ioctl_indicator_pulse(data);
2082 		break;
2083 
2084 	case USBTMC_IOCTL_CLEAR:
2085 		retval = usbtmc_ioctl_clear(data);
2086 		break;
2087 
2088 	case USBTMC_IOCTL_ABORT_BULK_OUT:
2089 		retval = usbtmc_ioctl_abort_bulk_out(data);
2090 		break;
2091 
2092 	case USBTMC_IOCTL_ABORT_BULK_IN:
2093 		retval = usbtmc_ioctl_abort_bulk_in(data);
2094 		break;
2095 
2096 	case USBTMC_IOCTL_CTRL_REQUEST:
2097 		retval = usbtmc_ioctl_request(data, (void __user *)arg);
2098 		break;
2099 
2100 	case USBTMC_IOCTL_GET_TIMEOUT:
2101 		retval = usbtmc_ioctl_get_timeout(file_data,
2102 						  (void __user *)arg);
2103 		break;
2104 
2105 	case USBTMC_IOCTL_SET_TIMEOUT:
2106 		retval = usbtmc_ioctl_set_timeout(file_data,
2107 						  (void __user *)arg);
2108 		break;
2109 
2110 	case USBTMC_IOCTL_EOM_ENABLE:
2111 		retval = usbtmc_ioctl_eom_enable(file_data,
2112 						 (void __user *)arg);
2113 		break;
2114 
2115 	case USBTMC_IOCTL_CONFIG_TERMCHAR:
2116 		retval = usbtmc_ioctl_config_termc(file_data,
2117 						   (void __user *)arg);
2118 		break;
2119 
2120 	case USBTMC_IOCTL_WRITE:
2121 		retval = usbtmc_ioctl_generic_write(file_data,
2122 						    (void __user *)arg);
2123 		break;
2124 
2125 	case USBTMC_IOCTL_READ:
2126 		retval = usbtmc_ioctl_generic_read(file_data,
2127 						   (void __user *)arg);
2128 		break;
2129 
2130 	case USBTMC_IOCTL_WRITE_RESULT:
2131 		retval = usbtmc_ioctl_write_result(file_data,
2132 						   (void __user *)arg);
2133 		break;
2134 
2135 	case USBTMC_IOCTL_API_VERSION:
2136 		retval = put_user(USBTMC_API_VERSION,
2137 				  (__u32 __user *)arg);
2138 		break;
2139 
2140 	case USBTMC488_IOCTL_GET_CAPS:
2141 		retval = put_user(data->usb488_caps,
2142 				  (unsigned char __user *)arg);
2143 		break;
2144 
2145 	case USBTMC488_IOCTL_READ_STB:
2146 		retval = usbtmc488_ioctl_read_stb(file_data,
2147 						  (void __user *)arg);
2148 		break;
2149 
2150 	case USBTMC488_IOCTL_REN_CONTROL:
2151 		retval = usbtmc488_ioctl_simple(data, (void __user *)arg,
2152 						USBTMC488_REQUEST_REN_CONTROL);
2153 		break;
2154 
2155 	case USBTMC488_IOCTL_GOTO_LOCAL:
2156 		retval = usbtmc488_ioctl_simple(data, (void __user *)arg,
2157 						USBTMC488_REQUEST_GOTO_LOCAL);
2158 		break;
2159 
2160 	case USBTMC488_IOCTL_LOCAL_LOCKOUT:
2161 		retval = usbtmc488_ioctl_simple(data, (void __user *)arg,
2162 						USBTMC488_REQUEST_LOCAL_LOCKOUT);
2163 		break;
2164 
2165 	case USBTMC488_IOCTL_TRIGGER:
2166 		retval = usbtmc488_ioctl_trigger(file_data);
2167 		break;
2168 
2169 	case USBTMC488_IOCTL_WAIT_SRQ:
2170 		retval = usbtmc488_ioctl_wait_srq(file_data,
2171 						  (__u32 __user *)arg);
2172 		break;
2173 
2174 	case USBTMC_IOCTL_MSG_IN_ATTR:
2175 		retval = put_user(file_data->bmTransferAttributes,
2176 				  (__u8 __user *)arg);
2177 		break;
2178 
2179 	case USBTMC_IOCTL_AUTO_ABORT:
2180 		retval = get_user(tmp_byte, (unsigned char __user *)arg);
2181 		if (retval == 0)
2182 			file_data->auto_abort = !!tmp_byte;
2183 		break;
2184 
2185 	case USBTMC_IOCTL_GET_STB:
2186 		retval = usbtmc_get_stb(file_data, &tmp_byte);
2187 		if (retval > 0)
2188 			retval = put_user(tmp_byte, (__u8 __user *)arg);
2189 		break;
2190 
2191 	case USBTMC_IOCTL_GET_SRQ_STB:
2192 		retval = usbtmc_ioctl_get_srq_stb(file_data,
2193 						  (void __user *)arg);
2194 		break;
2195 
2196 	case USBTMC_IOCTL_CANCEL_IO:
2197 		retval = usbtmc_ioctl_cancel_io(file_data);
2198 		break;
2199 
2200 	case USBTMC_IOCTL_CLEANUP_IO:
2201 		retval = usbtmc_ioctl_cleanup_io(file_data);
2202 		break;
2203 	}
2204 
2205 skip_io_on_zombie:
2206 	mutex_unlock(&data->io_mutex);
2207 	return retval;
2208 }
2209 
2210 static int usbtmc_fasync(int fd, struct file *file, int on)
2211 {
2212 	struct usbtmc_file_data *file_data = file->private_data;
2213 
2214 	return fasync_helper(fd, file, on, &file_data->data->fasync);
2215 }
2216 
2217 static __poll_t usbtmc_poll(struct file *file, poll_table *wait)
2218 {
2219 	struct usbtmc_file_data *file_data = file->private_data;
2220 	struct usbtmc_device_data *data = file_data->data;
2221 	__poll_t mask;
2222 
2223 	mutex_lock(&data->io_mutex);
2224 
2225 	if (data->zombie) {
2226 		mask = EPOLLHUP | EPOLLERR;
2227 		goto no_poll;
2228 	}
2229 
2230 	poll_wait(file, &data->waitq, wait);
2231 
2232 	/* Note that EPOLLPRI is now assigned to SRQ, and
2233 	 * EPOLLIN|EPOLLRDNORM to normal read data.
2234 	 */
2235 	mask = 0;
2236 	if (atomic_read(&file_data->srq_asserted))
2237 		mask |= EPOLLPRI;
2238 
2239 	/* Note that the anchor submitted includes all urbs for BULK IN
2240 	 * and OUT. So EPOLLOUT is signaled when BULK OUT is empty and
2241 	 * all BULK IN urbs are completed and moved to in_anchor.
2242 	 */
2243 	if (usb_anchor_empty(&file_data->submitted))
2244 		mask |= (EPOLLOUT | EPOLLWRNORM);
2245 	if (!usb_anchor_empty(&file_data->in_anchor))
2246 		mask |= (EPOLLIN | EPOLLRDNORM);
2247 
2248 	spin_lock_irq(&file_data->err_lock);
2249 	if (file_data->in_status || file_data->out_status)
2250 		mask |= EPOLLERR;
2251 	spin_unlock_irq(&file_data->err_lock);
2252 
2253 	dev_dbg(&data->intf->dev, "poll mask = %x\n", mask);
2254 
2255 no_poll:
2256 	mutex_unlock(&data->io_mutex);
2257 	return mask;
2258 }
2259 
2260 static const struct file_operations fops = {
2261 	.owner		= THIS_MODULE,
2262 	.read		= usbtmc_read,
2263 	.write		= usbtmc_write,
2264 	.open		= usbtmc_open,
2265 	.release	= usbtmc_release,
2266 	.flush		= usbtmc_flush,
2267 	.unlocked_ioctl	= usbtmc_ioctl,
2268 	.compat_ioctl	= compat_ptr_ioctl,
2269 	.fasync         = usbtmc_fasync,
2270 	.poll           = usbtmc_poll,
2271 	.llseek		= default_llseek,
2272 };
2273 
2274 static struct usb_class_driver usbtmc_class = {
2275 	.name =		"usbtmc%d",
2276 	.fops =		&fops,
2277 	.minor_base =	USBTMC_MINOR_BASE,
2278 };
2279 
2280 static void usbtmc_interrupt(struct urb *urb)
2281 {
2282 	struct usbtmc_device_data *data = urb->context;
2283 	struct device *dev = &data->intf->dev;
2284 	int status = urb->status;
2285 	int rv;
2286 
2287 	dev_dbg(&data->intf->dev, "int status: %d len %d\n",
2288 		status, urb->actual_length);
2289 
2290 	switch (status) {
2291 	case 0: /* SUCCESS */
2292 		/* check for valid STB notification */
2293 		if (data->iin_buffer[0] > 0x81) {
2294 			data->bNotify1 = data->iin_buffer[0];
2295 			data->bNotify2 = data->iin_buffer[1];
2296 			atomic_set(&data->iin_data_valid, 1);
2297 			wake_up_interruptible(&data->waitq);
2298 			goto exit;
2299 		}
2300 		/* check for SRQ notification */
2301 		if (data->iin_buffer[0] == 0x81) {
2302 			unsigned long flags;
2303 			struct list_head *elem;
2304 
2305 			if (data->fasync)
2306 				kill_fasync(&data->fasync,
2307 					SIGIO, POLL_PRI);
2308 
2309 			spin_lock_irqsave(&data->dev_lock, flags);
2310 			list_for_each(elem, &data->file_list) {
2311 				struct usbtmc_file_data *file_data;
2312 
2313 				file_data = list_entry(elem,
2314 						       struct usbtmc_file_data,
2315 						       file_elem);
2316 				file_data->srq_byte = data->iin_buffer[1];
2317 				atomic_set(&file_data->srq_asserted, 1);
2318 			}
2319 			spin_unlock_irqrestore(&data->dev_lock, flags);
2320 
2321 			dev_dbg(dev, "srq received bTag %x stb %x\n",
2322 				(unsigned int)data->iin_buffer[0],
2323 				(unsigned int)data->iin_buffer[1]);
2324 			wake_up_interruptible_all(&data->waitq);
2325 			goto exit;
2326 		}
2327 		dev_warn(dev, "invalid notification: %x\n",
2328 			 data->iin_buffer[0]);
2329 		break;
2330 	case -EOVERFLOW:
2331 		dev_err(dev, "overflow with length %d, actual length is %d\n",
2332 			data->iin_wMaxPacketSize, urb->actual_length);
2333 		fallthrough;
2334 	default:
2335 		/* urb terminated, clean up */
2336 		dev_dbg(dev, "urb terminated, status: %d\n", status);
2337 		return;
2338 	}
2339 exit:
2340 	rv = usb_submit_urb(urb, GFP_ATOMIC);
2341 	if (rv)
2342 		dev_err(dev, "usb_submit_urb failed: %d\n", rv);
2343 }
2344 
2345 static void usbtmc_free_int(struct usbtmc_device_data *data)
2346 {
2347 	if (!data->iin_ep_present || !data->iin_urb)
2348 		return;
2349 	usb_kill_urb(data->iin_urb);
2350 	kfree(data->iin_buffer);
2351 	data->iin_buffer = NULL;
2352 	usb_free_urb(data->iin_urb);
2353 	data->iin_urb = NULL;
2354 	kref_put(&data->kref, usbtmc_delete);
2355 }
2356 
2357 static int usbtmc_probe(struct usb_interface *intf,
2358 			const struct usb_device_id *id)
2359 {
2360 	struct usbtmc_device_data *data;
2361 	struct usb_host_interface *iface_desc;
2362 	struct usb_endpoint_descriptor *bulk_in, *bulk_out, *int_in;
2363 	int retcode;
2364 
2365 	dev_dbg(&intf->dev, "%s called\n", __func__);
2366 
2367 	data = kzalloc(sizeof(*data), GFP_KERNEL);
2368 	if (!data)
2369 		return -ENOMEM;
2370 
2371 	data->intf = intf;
2372 	data->id = id;
2373 	data->usb_dev = usb_get_dev(interface_to_usbdev(intf));
2374 	usb_set_intfdata(intf, data);
2375 	kref_init(&data->kref);
2376 	mutex_init(&data->io_mutex);
2377 	init_waitqueue_head(&data->waitq);
2378 	atomic_set(&data->iin_data_valid, 0);
2379 	INIT_LIST_HEAD(&data->file_list);
2380 	spin_lock_init(&data->dev_lock);
2381 
2382 	data->zombie = 0;
2383 
2384 	/* Initialize USBTMC bTag and other fields */
2385 	data->bTag	= 1;
2386 	/*  2 <= bTag <= 127   USBTMC-USB488 subclass specification 4.3.1 */
2387 	data->iin_bTag = 2;
2388 
2389 	/* USBTMC devices have only one setting, so use that */
2390 	iface_desc = data->intf->cur_altsetting;
2391 	data->ifnum = iface_desc->desc.bInterfaceNumber;
2392 
2393 	/* Find bulk endpoints */
2394 	retcode = usb_find_common_endpoints(iface_desc,
2395 			&bulk_in, &bulk_out, NULL, NULL);
2396 	if (retcode) {
2397 		dev_err(&intf->dev, "bulk endpoints not found\n");
2398 		goto err_put;
2399 	}
2400 
2401 	retcode = -EINVAL;
2402 	data->bulk_in = bulk_in->bEndpointAddress;
2403 	data->wMaxPacketSize = usb_endpoint_maxp(bulk_in);
2404 	if (!data->wMaxPacketSize)
2405 		goto err_put;
2406 	dev_dbg(&intf->dev, "Found bulk in endpoint at %u\n", data->bulk_in);
2407 
2408 	data->bulk_out = bulk_out->bEndpointAddress;
2409 	dev_dbg(&intf->dev, "Found Bulk out endpoint at %u\n", data->bulk_out);
2410 
2411 	/* Find int endpoint */
2412 	retcode = usb_find_int_in_endpoint(iface_desc, &int_in);
2413 	if (!retcode) {
2414 		data->iin_ep_present = 1;
2415 		data->iin_ep = int_in->bEndpointAddress;
2416 		data->iin_wMaxPacketSize = usb_endpoint_maxp(int_in);
2417 		data->iin_interval = int_in->bInterval;
2418 		dev_dbg(&intf->dev, "Found Int in endpoint at %u\n",
2419 				data->iin_ep);
2420 	}
2421 
2422 	retcode = get_capabilities(data);
2423 	if (retcode)
2424 		dev_err(&intf->dev, "can't read capabilities\n");
2425 
2426 	if (data->iin_ep_present) {
2427 		/* allocate int urb */
2428 		data->iin_urb = usb_alloc_urb(0, GFP_KERNEL);
2429 		if (!data->iin_urb) {
2430 			retcode = -ENOMEM;
2431 			goto error_register;
2432 		}
2433 
2434 		/* Protect interrupt in endpoint data until iin_urb is freed */
2435 		kref_get(&data->kref);
2436 
2437 		/* allocate buffer for interrupt in */
2438 		data->iin_buffer = kmalloc(data->iin_wMaxPacketSize,
2439 					GFP_KERNEL);
2440 		if (!data->iin_buffer) {
2441 			retcode = -ENOMEM;
2442 			goto error_register;
2443 		}
2444 
2445 		/* fill interrupt urb */
2446 		usb_fill_int_urb(data->iin_urb, data->usb_dev,
2447 				usb_rcvintpipe(data->usb_dev, data->iin_ep),
2448 				data->iin_buffer, data->iin_wMaxPacketSize,
2449 				usbtmc_interrupt,
2450 				data, data->iin_interval);
2451 
2452 		retcode = usb_submit_urb(data->iin_urb, GFP_KERNEL);
2453 		if (retcode) {
2454 			dev_err(&intf->dev, "Failed to submit iin_urb\n");
2455 			goto error_register;
2456 		}
2457 	}
2458 
2459 	retcode = usb_register_dev(intf, &usbtmc_class);
2460 	if (retcode) {
2461 		dev_err(&intf->dev, "Not able to get a minor (base %u, slice default): %d\n",
2462 			USBTMC_MINOR_BASE,
2463 			retcode);
2464 		goto error_register;
2465 	}
2466 	dev_dbg(&intf->dev, "Using minor number %d\n", intf->minor);
2467 
2468 	return 0;
2469 
2470 error_register:
2471 	usbtmc_free_int(data);
2472 err_put:
2473 	kref_put(&data->kref, usbtmc_delete);
2474 	return retcode;
2475 }
2476 
2477 static void usbtmc_disconnect(struct usb_interface *intf)
2478 {
2479 	struct usbtmc_device_data *data  = usb_get_intfdata(intf);
2480 	struct list_head *elem;
2481 
2482 	usb_deregister_dev(intf, &usbtmc_class);
2483 	mutex_lock(&data->io_mutex);
2484 	data->zombie = 1;
2485 	wake_up_interruptible_all(&data->waitq);
2486 	list_for_each(elem, &data->file_list) {
2487 		struct usbtmc_file_data *file_data;
2488 
2489 		file_data = list_entry(elem,
2490 				       struct usbtmc_file_data,
2491 				       file_elem);
2492 		usb_kill_anchored_urbs(&file_data->submitted);
2493 		usb_scuttle_anchored_urbs(&file_data->in_anchor);
2494 	}
2495 	mutex_unlock(&data->io_mutex);
2496 	usbtmc_free_int(data);
2497 	kref_put(&data->kref, usbtmc_delete);
2498 }
2499 
2500 static void usbtmc_draw_down(struct usbtmc_file_data *file_data)
2501 {
2502 	int time;
2503 
2504 	time = usb_wait_anchor_empty_timeout(&file_data->submitted, 1000);
2505 	if (!time)
2506 		usb_kill_anchored_urbs(&file_data->submitted);
2507 	usb_scuttle_anchored_urbs(&file_data->in_anchor);
2508 }
2509 
2510 static int usbtmc_suspend(struct usb_interface *intf, pm_message_t message)
2511 {
2512 	struct usbtmc_device_data *data = usb_get_intfdata(intf);
2513 	struct list_head *elem;
2514 
2515 	if (!data)
2516 		return 0;
2517 
2518 	mutex_lock(&data->io_mutex);
2519 	list_for_each(elem, &data->file_list) {
2520 		struct usbtmc_file_data *file_data;
2521 
2522 		file_data = list_entry(elem,
2523 				       struct usbtmc_file_data,
2524 				       file_elem);
2525 		usbtmc_draw_down(file_data);
2526 	}
2527 
2528 	if (data->iin_ep_present && data->iin_urb)
2529 		usb_kill_urb(data->iin_urb);
2530 
2531 	mutex_unlock(&data->io_mutex);
2532 	return 0;
2533 }
2534 
2535 static int usbtmc_resume(struct usb_interface *intf)
2536 {
2537 	struct usbtmc_device_data *data = usb_get_intfdata(intf);
2538 	int retcode = 0;
2539 
2540 	if (data->iin_ep_present && data->iin_urb)
2541 		retcode = usb_submit_urb(data->iin_urb, GFP_KERNEL);
2542 	if (retcode)
2543 		dev_err(&intf->dev, "Failed to submit iin_urb\n");
2544 
2545 	return retcode;
2546 }
2547 
2548 static int usbtmc_pre_reset(struct usb_interface *intf)
2549 {
2550 	struct usbtmc_device_data *data  = usb_get_intfdata(intf);
2551 	struct list_head *elem;
2552 
2553 	if (!data)
2554 		return 0;
2555 
2556 	mutex_lock(&data->io_mutex);
2557 
2558 	list_for_each(elem, &data->file_list) {
2559 		struct usbtmc_file_data *file_data;
2560 
2561 		file_data = list_entry(elem,
2562 				       struct usbtmc_file_data,
2563 				       file_elem);
2564 		usbtmc_ioctl_cancel_io(file_data);
2565 	}
2566 
2567 	return 0;
2568 }
2569 
2570 static int usbtmc_post_reset(struct usb_interface *intf)
2571 {
2572 	struct usbtmc_device_data *data  = usb_get_intfdata(intf);
2573 
2574 	mutex_unlock(&data->io_mutex);
2575 
2576 	return 0;
2577 }
2578 
2579 static struct usb_driver usbtmc_driver = {
2580 	.name		= "usbtmc",
2581 	.id_table	= usbtmc_devices,
2582 	.probe		= usbtmc_probe,
2583 	.disconnect	= usbtmc_disconnect,
2584 	.suspend	= usbtmc_suspend,
2585 	.resume		= usbtmc_resume,
2586 	.pre_reset	= usbtmc_pre_reset,
2587 	.post_reset	= usbtmc_post_reset,
2588 	.dev_groups	= usbtmc_groups,
2589 };
2590 
2591 module_usb_driver(usbtmc_driver);
2592 
2593 MODULE_LICENSE("GPL");
2594