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