1 // SPDX-License-Identifier: GPL-2.0
2 
3 /***************************************************************************
4  *  This code has been developed at the Department of Physics (University  *
5  *  of Florence, Italy) to support in linux-gpib the open usb-gpib adapter *
6  *  implemented at the University of Ljubljana (lpvo.fe.uni-lj.si/gpib)	   *
7  *									   *
8  *  copyright		 : (C) 2011 Marcello Carla'			   *
9  ***************************************************************************/
10 
11 /* base module includes */
12 
13 #include <linux/module.h>
14 #include <linux/sched.h>
15 #include <linux/init.h>
16 #include <linux/kernel.h>
17 #include <linux/tty.h>
18 #include <linux/types.h>
19 #include <linux/slab.h>
20 #include <linux/mm.h>
21 #include <linux/vmalloc.h>
22 #include <linux/spinlock.h>
23 #include <linux/file.h>
24 #include <linux/timer.h>
25 #include <linux/delay.h>
26 #include <linux/sched/signal.h>
27 #include <linux/usb.h>
28 
29 #include "gpibP.h"
30 
31 MODULE_LICENSE("GPL");
32 MODULE_DESCRIPTION("GPIB driver for LPVO usb devices");
33 
34 #define NAME "lpvo_usb_gpib"
35 
36 /*
37  *  Table of devices that work with this driver.
38  *
39  *  Currently, only one device is known to be used in the
40  *  lpvo_usb_gpib adapter (FTDI 0403:6001).
41  *  If your adapter uses a different chip, insert a line
42  *  in the following table with proper <Vendor-id>, <Product-id>.
43  *
44  *  To have your chip automatically handled by the driver,
45  *  update files "/usr/local/etc/modprobe.d/lpvo_usb_gpib.conf"
46  *  and /usr/local/etc/udev/rules.d/99-lpvo_usb_gpib.rules.
47  *
48  */
49 
50 static const struct usb_device_id skel_table[] = {
51 	{ USB_DEVICE(0x0403, 0x6001) },
52 	{ }					   /* Terminating entry */
53 };
54 MODULE_DEVICE_TABLE(usb, skel_table);
55 
56 /*
57  *    ***  Diagnostics and Debug  ***
58  *
59  *  The module parameter "debug" controls the sending of debug messages to
60  *  syslog. By default it is set to 0 or 1 according to GPIB_CONFIG_KERNEL_DEBUG.
61  *    debug = 0: only register/deregister messages are generated
62  *	      1: every action is logged
63  *	      2: extended logging; each single exchanged byte is documented
64  *		 (about twice the log volume of [1])
65  *    To switch debug level:
66  *	      At module loading:  modprobe lpvo_usb_gpib debug={0,1,2}
67  *	      On the fly: echo {0,1,2} > /sys/modules/lpvo_usb_gpib/parameters/debug
68  */
69 
70 static int debug;
71 module_param(debug, int, 0644);
72 
73 #define DIA_LOG(level, format, ...)					\
74 	do { if (debug >= (level))					\
75 			pr_alert("%s:%s - " format, NAME, __func__, ## __VA_ARGS__); } \
76 	while (0)
77 
78 /* standard and extended command sets of the usb-gpib adapter */
79 
80 #define USB_GPIB_ON	 "\nIB\n"
81 #define USB_GPIB_OFF	 "\nIBO\n"
82 #define USB_GPIB_IBm0	 "\nIBm0\n"   /* do not assert REN with IFC */
83 #define USB_GPIB_IBm1	 "\nIBm1\n"   /* assert REN with IFC */
84 #define USB_GPIB_IBCL	 "\nIBZ\n"
85 #define USB_GPIB_STATUS	 "\nIBS\n"
86 #define USB_GPIB_READ	 "\nIB?\n"
87 #define USB_GPIB_READ_1	 "\nIBB\n"
88 #define USB_GPIB_EOI	 "\nIBe0\n"
89 #define USB_GPIB_FTMO	 "\nIBf0\n"    /* disable first byte timeout */
90 #define USB_GPIB_TTMOZ	 "\nIBt0\n"    /* disable byte timeout */
91 
92 /* incomplete commands */
93 
94 #define USB_GPIB_BTMO	 "\nIBt"      /* set byte timeout */
95 #define USB_GPIB_TTMO	 "\nIBT"      /* set total timeout */
96 
97 #define USB_GPIB_DEBUG_ON    "\nIBDE\xAA\n"
98 #define USB_GPIB_SET_LISTEN  "\nIBDT0\n"
99 #define USB_GPIB_SET_TALK    "\nIBDT1\n"
100 #define USB_GPIB_SET_LINES   "\nIBDC.\n"
101 #define USB_GPIB_SET_DATA    "\nIBDM.\n"
102 #define USB_GPIB_READ_LINES  "\nIBD?C\n"
103 #define USB_GPIB_READ_DATA   "\nIBD?M\n"
104 #define USB_GPIB_READ_BUS    "\nIBD??\n"
105 
106 /* command sequences */
107 
108 #define USB_GPIB_UNTALK "\nIBC_\n"
109 #define USB_GPIB_UNLISTEN "\nIBC?\n"
110 
111 /* special characters used by the adapter */
112 
113 #define DLE ('\020')
114 #define STX ('\02')
115 #define ETX ('\03')
116 #define ACK ('\06')
117 #define NODATA ('\03')
118 #define NODAV ('\011')
119 
120 #define IB_BUS_REN  0x01
121 #define IB_BUS_IFC  0x02
122 #define IB_BUS_NDAC 0x04
123 #define IB_BUS_NRFD 0x08
124 #define IB_BUS_DAV  0x10
125 #define IB_BUS_EOI  0x20
126 #define IB_BUS_ATN  0x40
127 #define IB_BUS_SRQ  0x80
128 
129 #define INBUF_SIZE 128
130 
131 struct char_buf {		/* used by one_char() routine */
132 	char *inbuf;
133 	int last;
134 	int nchar;
135 };
136 
137 struct usb_gpib_priv {		/* private data to the device */
138 	u8 eos;		        /* eos character */
139 	short eos_flags;	/* eos mode */
140 	int timeout;		/* current value for timeout */
141 	void *dev;		/* the usb device private data structure */
142 };
143 
144 #define GPIB_DEV (((struct usb_gpib_priv *)board->private_data)->dev)
145 
146 #define SHOW_STATUS(board) {						\
147 		DIA_LOG(2, "# - board %p\n", board);			\
148 		DIA_LOG(2, "# - buffer_length %d\n", board->buffer_length); \
149 		DIA_LOG(2, "# - status %lx\n", board->status);		\
150 		DIA_LOG(2, "# - use_count %d\n", board->use_count);	\
151 		DIA_LOG(2, "# - pad %x\n", board->pad);			\
152 		DIA_LOG(2, "# - sad %x\n", board->sad);			\
153 		DIA_LOG(2, "# - timeout %d\n", board->usec_timeout);	\
154 		DIA_LOG(2, "# - ppc %d\n", board->parallel_poll_configuration); \
155 		DIA_LOG(2, "# - t1delay %d\n", board->t1_nano_sec);	\
156 		DIA_LOG(2, "# - online %d\n", board->online);		\
157 		DIA_LOG(2, "# - autopoll %d\n", board->autospollers);	\
158 		DIA_LOG(2, "# - autopoll task %p\n", board->autospoll_task); \
159 		DIA_LOG(2, "# - minor %d\n", board->minor);		\
160 		DIA_LOG(2, "# - master %d\n", board->master);		\
161 		DIA_LOG(2, "# - list %d\n", board->ist);		\
162 	}
163 /*
164  * n = 0;
165  * list_for_each (l, &board->device_list) n++;
166  * TTY_LOG ("%s:%s - devices in list %d\n", a, b, n);
167  */
168 
169 /*
170  * TTY_LOG - write a message to the current work terminal (if any)
171  */
172 
173 #define TTY_LOG(format, ...) {						\
174 		char buf[128];						\
175 		struct tty_struct *tty = get_current_tty();		\
176 		if (tty) {						\
177 			snprintf(buf, 128, format, __VA_ARGS__);	\
178 			tty->driver->ops->write(tty, buf, strlen(buf)); \
179 			tty->driver->ops->write(tty, "\r", 1);		\
180 		}							\
181 	}
182 
183 /*
184  *  GLOBAL VARIABLES: required for
185  *  pairing among gpib minor and usb minor.
186  *  MAX_DEV is the max number of usb-gpib adapters; free
187  *  to change as you like, but no more than 32
188  */
189 
190 #define MAX_DEV 8
191 static struct usb_interface *lpvo_usb_interfaces[MAX_DEV];   /* registered interfaces */
192 static int usb_minors[MAX_DEV];			   /* usb minors */
193 static int assigned_usb_minors;		   /* mask of filled slots */
194 static struct mutex minors_lock;     /* operations on usb_minors are to be protected */
195 
196 /*
197  *  usb-skeleton prototypes
198  */
199 
200 struct usb_skel;
201 static ssize_t skel_do_write(struct usb_skel *, const char *, size_t);
202 static ssize_t skel_do_read(struct usb_skel *, char *, size_t);
203 static int skel_do_open(gpib_board_t *, int);
204 static int skel_do_release(gpib_board_t *);
205 
206 /*
207  *   usec_diff : take difference in MICROsec between two 'timespec'
208  *		 (unix time in sec and NANOsec)
209  */
210 
usec_diff(struct timespec64 * a,struct timespec64 * b)211 static inline int usec_diff(struct timespec64 *a, struct timespec64 *b)
212 {
213 	return ((a->tv_sec - b->tv_sec) * 1000000 +
214 		(a->tv_nsec - b->tv_nsec) / 1000);
215 }
216 
217 /*
218  *   ***  these routines are specific to the usb-gpib adapter  ***
219  */
220 
221 /**
222  * write_loop() - Send a byte sequence to the adapter
223  *
224  * @dev:      the private device structure
225  * @msg:      the byte sequence.
226  * @leng:     the byte sequence length.
227  *
228  */
229 
write_loop(void * dev,char * msg,int leng)230 static int write_loop(void *dev, char *msg, int leng)
231 {
232 //	  int nchar = 0, val;
233 
234 //	  do {
235 
236 	return skel_do_write(dev, msg, leng);
237 
238 //		  if (val < 1) {
239 //			  printk (KERN_ALERT "%s:%s - write error: %d %d/%d\n",
240 //				  NAME, __func__, val, nchar, leng);
241 //			  return -EIO;
242 //		  }
243 //		  nchar +=val;
244 //	  } while (nchar < leng);
245 //	  return leng;
246 }
247 
printable(char x)248 static char printable(char x)
249 {
250 	if (x < 32 || x > 126)
251 		return ' ';
252 	return x;
253 }
254 
255 /**
256  * send_command() - Send a byte sequence and return a single byte reply.
257  *
258  * @board:    the gpib_board_struct data area for this gpib interface
259  * @msg:      the byte sequence.
260  * @leng      the byte sequence length; can be given as zero and is
261  *	      computed automatically, but if 'msg' contains a zero byte,
262  *	      it has to be given explicitly.
263  */
264 
send_command(gpib_board_t * board,char * msg,int leng)265 static int send_command(gpib_board_t *board, char *msg, int leng)
266 {
267 	char buffer[64];
268 	int nchar, j;
269 	int retval;
270 	struct timespec64 before, after;
271 
272 	ktime_get_real_ts64 (&before);
273 
274 	if (!leng)
275 		leng = strlen(msg);
276 	retval = write_loop(GPIB_DEV, msg, leng);
277 	if (retval < 0)
278 		return retval;
279 
280 	nchar = skel_do_read(GPIB_DEV, buffer, 64);
281 
282 	if (nchar < 0) {
283 		DIA_LOG(0, " return from read: %d\n", nchar);
284 		return nchar;
285 	} else if (nchar != 1) {
286 		for (j = 0 ; j < leng ; j++) {
287 			DIA_LOG(0, " Irregular reply to command: %d  %x %c\n",
288 				j, msg[j], printable(msg[j]));
289 		}
290 		for (j = 0 ; j < nchar ; j++) {
291 			DIA_LOG(0, " Irregular command reply: %d %x %c\n",
292 				j, buffer[j] & 0xff, printable(buffer[j]));
293 		}
294 		return -EIO;
295 	}
296 	ktime_get_real_ts64 (&after);
297 
298 	DIA_LOG(1, "Sent %d - done %d us.\n", leng, usec_diff(&after, &before));
299 
300 	return buffer[0] & 0xff;
301 }
302 
303 /*
304  *
305  * set_control_line() - Set the value of a single gpib control line
306  *
307  * @board:    the gpib_board_struct data area for this gpib interface
308  * @line:     line mask
309  * @value:    line new value (0/1)
310  *
311  */
312 
set_control_line(gpib_board_t * board,int line,int value)313 static int set_control_line(gpib_board_t *board, int line, int value)
314 {
315 	char msg[] = USB_GPIB_SET_LINES;
316 	int retval;
317 	int leng = strlen(msg);
318 
319 	DIA_LOG(1, "setting line %x to %x\n", line, value);
320 
321 	retval = send_command(board, USB_GPIB_READ_LINES, 0);
322 
323 	DIA_LOG(1, "old line values: %x\n", retval);
324 
325 	if (retval == -EIO)
326 		return retval;
327 
328 	msg[leng - 2] = value ? (retval & ~line) : retval | line;
329 
330 	retval = send_command(board, msg, 0);
331 
332 	DIA_LOG(1, "operation result: %x\n", retval);
333 
334 	return retval;
335 }
336 
337 /*
338  * one_char() - read one single byte from input buffer
339  *
340  * @board:      the gpib_board_struct data area for this gpib interface
341  * @char_buf:   the routine private data structure
342  */
343 
one_char(gpib_board_t * board,struct char_buf * b)344 static int one_char(gpib_board_t *board, struct char_buf *b)
345 {
346 	struct timespec64 before, after;
347 
348 	if (b->nchar) {
349 		DIA_LOG(2, "-> %x\n", b->inbuf[b->last - b->nchar]);
350 		return b->inbuf[b->last - b->nchar--];
351 	}
352 	ktime_get_real_ts64 (&before);
353 	b->nchar = skel_do_read(GPIB_DEV, b->inbuf, INBUF_SIZE);
354 	b->last = b->nchar;
355 	ktime_get_real_ts64 (&after);
356 
357 	DIA_LOG(2, "read %d bytes in %d usec\n",
358 		b->nchar, usec_diff(&after, &before));
359 
360 	if (b->nchar > 0) {
361 		DIA_LOG(2, "--> %x\n", b->inbuf[b->last - b->nchar]);
362 		return b->inbuf[b->last - b->nchar--];
363 	} else if (b->nchar == 0) {
364 		dev_alert(board->gpib_dev, "%s:%s - read returned EOF\n", NAME, __func__);
365 		return -EIO;
366 	}
367 	dev_alert(board->gpib_dev, "%s:%s - read error %d\n", NAME, __func__, b->nchar);
368 	TTY_LOG("\n *** %s *** Read Error - %s\n", NAME,
369 		"Reset the adapter with 'gpib_config'\n");
370 	return -EIO;
371 }
372 
373 /**
374  * set_timeout() - set single byte / total timeouts on the adapter
375  *
376  * @board:    the gpib_board_struct data area for this gpib interface
377  *
378  *	   For sake of speed, the operation is performed only if it
379  *	   modifies the current (saved) value. Minimum allowed timeout
380  *	   is 30 ms (T30ms -> 8); timeout disable (TNONE -> 0) currently
381  *	   not supported.
382  */
383 
set_timeout(gpib_board_t * board)384 static void set_timeout(gpib_board_t *board)
385 {
386 	int n, val;
387 	char command[sizeof(USB_GPIB_TTMO) + 6];
388 	struct usb_gpib_priv *data = board->private_data;
389 
390 	if (data->timeout == board->usec_timeout)
391 		return;
392 
393 	n = (board->usec_timeout + 32767) / 32768;
394 	if (n < 2)
395 		n = 2;
396 
397 	DIA_LOG(1, "Set timeout to %d us -> %d\n", board->usec_timeout, n);
398 
399 	sprintf(command, "%s%d\n", USB_GPIB_BTMO, n > 255 ? 255 : n);
400 	val = send_command(board, command, 0);
401 
402 	if (val == ACK) {
403 		if (n > 65535)
404 			n = 65535;
405 		sprintf(command, "%s%d\n", USB_GPIB_TTMO, n);
406 		val = send_command(board, command, 0);
407 	}
408 
409 	if (val != ACK) {
410 		dev_alert(board->gpib_dev, "%s:%s - error in timeout set: <%s>\n",
411 			  NAME, __func__, command);
412 	} else {
413 		data->timeout = board->usec_timeout;
414 	}
415 }
416 
417 /*
418  *    now the standard interface functions - attach and detach
419  */
420 
421 /**
422  * usb_gpib_attach() - activate the usb-gpib converter board
423  *
424  * @board:    the gpib_board_struct data area for this gpib interface
425  * @config:   firmware data, if any (from gpib_config -I <file>)
426  *
427  * The channel name is ttyUSBn, with n=0 by default. Other values for n
428  * passed with gpib_config -b <n>.
429  *
430  * In this routine I trust that when an error code is returned
431  * detach() will be called. Always.
432  */
433 
usb_gpib_attach(gpib_board_t * board,const gpib_board_config_t * config)434 static int usb_gpib_attach(gpib_board_t *board, const gpib_board_config_t *config)
435 {
436 	int retval, j;
437 	u32 base = config->ibbase;
438 	char *device_path;
439 	int match;
440 	struct usb_device *udev;
441 
442 	DIA_LOG(0, "Board %p -t %s -m %d -a %p -u %d -l %d -b %d\n",
443 		board, board->interface->name, board->minor, config->device_path,
444 		config->pci_bus, config->pci_slot, base);
445 
446 	board->private_data = NULL;  /* to be sure - we can detach before setting */
447 
448 	/* identify device to be attached */
449 
450 	mutex_lock(&minors_lock);
451 
452 	if (config->device_path) {
453 		/* if config->device_path given, try that first */
454 		dev_alert(board->gpib_dev, "%s:%s - Looking for device_path: %s\n",
455 			  NAME, __func__, config->device_path);
456 		for (j = 0 ; j < MAX_DEV ; j++) {
457 			if ((assigned_usb_minors & 1 << j) == 0)
458 				continue;
459 			udev =	usb_get_dev(interface_to_usbdev(lpvo_usb_interfaces[j]));
460 			device_path = kobject_get_path(&udev->dev.kobj, GFP_KERNEL);
461 			match = gpib_match_device_path(&lpvo_usb_interfaces[j]->dev,
462 						       config->device_path);
463 			DIA_LOG(1, "dev. %d: minor %d  path: %s --> %d\n", j,
464 				lpvo_usb_interfaces[j]->minor, device_path, match);
465 			kfree(device_path);
466 			if (match)
467 				break;
468 		}
469 	} else if (config->pci_bus != -1 && config->pci_slot != -1) {
470 		/* second: look for bus and slot */
471 		for (j = 0 ; j < MAX_DEV ; j++) {
472 			if ((assigned_usb_minors & 1 << j) == 0)
473 				continue;
474 			udev =	usb_get_dev(interface_to_usbdev(lpvo_usb_interfaces[j]));
475 			DIA_LOG(1, "dev. %d: bus %d -> %d  dev: %d -> %d\n", j,
476 				udev->bus->busnum, config->pci_bus, udev->devnum, config->pci_slot);
477 			if (config->pci_bus == udev->bus->busnum &&
478 			    config->pci_slot == udev->devnum)
479 				break;
480 		}
481 	} else {		/* last chance: usb_minor, given as ibbase */
482 		for (j = 0 ; j < MAX_DEV ; j++) {
483 			if (usb_minors[j] == base && assigned_usb_minors & 1 << j)
484 				break;
485 		}
486 	}
487 	mutex_unlock(&minors_lock);
488 
489 	if (j == MAX_DEV) {
490 		dev_alert(board->gpib_dev, "%s:%s - Requested device is not registered.\n",
491 			  NAME, __func__);
492 		return -EIO;
493 	}
494 
495 	board->private_data = kzalloc(sizeof(struct usb_gpib_priv), GFP_KERNEL);
496 	if (!board->private_data)
497 		return -ENOMEM;
498 
499 	retval = skel_do_open(board, usb_minors[j]);
500 
501 	DIA_LOG(1, "Skel open: %d\n", retval);
502 
503 	if (retval) {
504 		TTY_LOG("%s:%s - skel open failed.\n", NAME, __func__);
505 		kfree(board->private_data);
506 		board->private_data = NULL;
507 		return -ENODEV;
508 	}
509 
510 	SHOW_STATUS(board);
511 
512 	retval = send_command(board, USB_GPIB_ON, 0);
513 	DIA_LOG(1, "USB_GPIB_ON returns %x\n", retval);
514 	if (retval != ACK)
515 		return -EIO;
516 
517 	/* We must setup debug mode because we need the extended instruction
518 	 * set to cope with the Core (gpib_common) point of view
519 	 */
520 
521 	retval = send_command(board, USB_GPIB_DEBUG_ON, 0);
522 	DIA_LOG(1, "USB_GPIB_DEBUG_ON returns %x\n", retval);
523 	if (retval != ACK)
524 		return -EIO;
525 
526 	/* We must keep REN off after an IFC because so it is
527 	 * assumed by the Core
528 	 */
529 
530 	retval = send_command(board, USB_GPIB_IBm0, 0);
531 	DIA_LOG(1, "USB_GPIB_IBm0 returns %x\n", retval);
532 	if (retval != ACK)
533 		return -EIO;
534 
535 	retval = set_control_line(board, IB_BUS_REN, 0);
536 	if (retval != ACK)
537 		return -EIO;
538 
539 	retval = send_command(board, USB_GPIB_FTMO, 0);
540 	DIA_LOG(1, "USB_GPIB_FTMO returns %x\n", retval);
541 	if (retval != ACK)
542 		return -EIO;
543 
544 	SHOW_STATUS(board);
545 	TTY_LOG("Module '%s' has been sucesfully configured\n", NAME);
546 	return 0;
547 }
548 
549 /**
550  * usb_gpib_detach() - deactivate the usb-gpib converter board
551  *
552  * @board:    the gpib_board data area for this gpib interface
553  *
554  */
555 
usb_gpib_detach(gpib_board_t * board)556 static void usb_gpib_detach(gpib_board_t *board)
557 {
558 	int retval;
559 
560 	SHOW_STATUS(board);
561 
562 	DIA_LOG(0, "detaching %p\n", board);
563 
564 	if (board->private_data) {
565 		if (GPIB_DEV) {
566 			write_loop(GPIB_DEV, USB_GPIB_OFF, strlen(USB_GPIB_OFF));
567 			msleep(100);
568 			DIA_LOG(1, "%s", "GPIB off\n");
569 			retval = skel_do_release(board);
570 			DIA_LOG(1, "skel release -> %d\n", retval);
571 		}
572 		kfree(board->private_data);
573 		board->private_data = NULL;
574 	}
575 
576 	DIA_LOG(0, "done %p\n", board);
577 	TTY_LOG("Module '%s' has been detached\n", NAME);
578 }
579 
580 /*
581  *   Other functions follow in alphabetical order
582  */
583 /* command */
usb_gpib_command(gpib_board_t * board,u8 * buffer,size_t length,size_t * bytes_written)584 static int usb_gpib_command(gpib_board_t *board,
585 			    u8 *buffer,
586 			    size_t length,
587 			    size_t *bytes_written)
588 {
589 	int i, retval;
590 	char command[6] = "IBc.\n";
591 
592 	DIA_LOG(1, "enter %p\n", board);
593 
594 	set_timeout(board);
595 
596 	*bytes_written = 0;
597 	for (i = 0 ; i < length ; i++) {
598 		command[3] = buffer[i];
599 		retval = send_command(board, command, 5);
600 		DIA_LOG(2, "%d ==> %x %x\n", i, buffer[i], retval);
601 		if (retval != 0x06)
602 			return retval;
603 		++(*bytes_written);
604 	}
605 	return 0;
606 }
607 
608 /**
609  * usb_gpib_disable_eos() - Disable END on eos byte (END on EOI only)
610  *
611  * @board:    the gpib_board data area for this gpib interface
612  *
613  *   With the lpvo adapter eos can only be handled via software.
614  *   Cannot do nothing here, but remember for future use.
615  */
616 
usb_gpib_disable_eos(gpib_board_t * board)617 static void usb_gpib_disable_eos(gpib_board_t *board)
618 {
619 	((struct usb_gpib_priv *)board->private_data)->eos_flags &= ~REOS;
620 	DIA_LOG(1, "done: %x\n",
621 		((struct usb_gpib_priv *)board->private_data)->eos_flags);
622 }
623 
624 /**
625  * usb_gpib_enable_eos() - Enable END for reads when eos byte is received.
626  *
627  * @board:    the gpib_board data area for this gpib interface
628  * @eos_byte: the 'eos' byte
629  * @compare_8_bits: if zero ignore eigthth bit when comparing
630  *
631  */
632 
usb_gpib_enable_eos(gpib_board_t * board,u8 eos_byte,int compare_8_bits)633 static int usb_gpib_enable_eos(gpib_board_t *board,
634 			       u8 eos_byte,
635 			       int compare_8_bits)
636 {
637 	struct usb_gpib_priv *pd = (struct usb_gpib_priv *)board->private_data;
638 
639 	DIA_LOG(1, "enter with %x\n", eos_byte);
640 	pd->eos = eos_byte;
641 	pd->eos_flags = REOS;
642 	if (compare_8_bits)
643 		pd->eos_flags |= BIN;
644 	return 0;
645 }
646 
647 /**
648  * usb_gpib_go_to_standby() - De-assert ATN
649  *
650  * @board:    the gpib_board data area for this gpib interface
651  */
652 
usb_gpib_go_to_standby(gpib_board_t * board)653 static int usb_gpib_go_to_standby(gpib_board_t *board)
654 {
655 	int retval = set_control_line(board, IB_BUS_ATN, 0);
656 
657 	DIA_LOG(1, "done with %x\n", retval);
658 
659 	if (retval == ACK)
660 		return 0;
661 	return -EIO;
662 }
663 
664 /**
665  * usb_gpib_interface_clear() - Assert or de-assert IFC
666  *
667  * @board:    the gpib_board data area for this gpib interface
668  * assert:    1: assert IFC;  0: de-assert IFC
669  *
670  *    Currently on the assert request we issue the lpvo IBZ
671  *    command that cycles IFC low for 100 usec, then we ignore
672  *    the de-assert request.
673  */
674 
usb_gpib_interface_clear(gpib_board_t * board,int assert)675 static void usb_gpib_interface_clear(gpib_board_t *board, int assert)
676 {
677 	int retval = 0;
678 
679 	DIA_LOG(1, "enter with %d\n", assert);
680 
681 	if (assert) {
682 		retval = send_command(board, USB_GPIB_IBCL, 0);
683 
684 		set_bit(CIC_NUM, &board->status);
685 	}
686 
687 	DIA_LOG(1, "done with %d %d\n", assert, retval);
688 }
689 
690 /**
691  * line_status() - Read the status of the bus lines.
692  *
693  *  @board:    the gpib_board data area for this gpib interface
694  *
695  *    We can read all lines.
696  */
697 
698 #define WQT wait_queue_entry_t
699 #define WQH head
700 #define WQE entry
701 
usb_gpib_line_status(const gpib_board_t * board)702 static int usb_gpib_line_status(const gpib_board_t *board)
703 {
704 	int buffer;
705 	int line_status = ValidALL;   /* all lines will be read */
706 	struct list_head *p, *q;
707 	WQT *item;
708 	unsigned long flags;
709 	int sleep = 0;
710 
711 	DIA_LOG(1, "%s\n", "request");
712 
713 	/* if we are on the wait queue (board->wait), do not hurry
714 	 * reading status line; instead, pause a little
715 	 */
716 
717 	spin_lock_irqsave((spinlock_t *)&board->wait.lock, flags);
718 	q = (struct list_head *)&board->wait.WQH;
719 	list_for_each(p, q) {
720 		item = container_of(p, WQT, WQE);
721 		if (item->private == current) {
722 			sleep = 20;
723 			break;
724 		}
725 		/* pid is: ((struct task_struct *) item->private)->pid); */
726 	}
727 	spin_unlock_irqrestore((spinlock_t *)&board->wait.lock, flags);
728 	if (sleep) {
729 		DIA_LOG(1, "we are on the wait queue - sleep %d ms\n", sleep);
730 		msleep(sleep);
731 	}
732 
733 	buffer = send_command((gpib_board_t *)board, USB_GPIB_STATUS, 0);
734 
735 	if (buffer < 0) {
736 		dev_alert(board->gpib_dev, "%s:%s - line status read failed with %d\n",
737 			  NAME, __func__, buffer);
738 		return -1;
739 	}
740 
741 	if ((buffer & 0x01) == 0)
742 		line_status |= BusREN;
743 	if ((buffer & 0x02) == 0)
744 		line_status |= BusIFC;
745 	if ((buffer & 0x04) == 0)
746 		line_status |= BusNDAC;
747 	if ((buffer & 0x08) == 0)
748 		line_status |= BusNRFD;
749 	if ((buffer & 0x10) == 0)
750 		line_status |= BusDAV;
751 	if ((buffer & 0x20) == 0)
752 		line_status |= BusEOI;
753 	if ((buffer & 0x40) == 0)
754 		line_status |= BusATN;
755 	if ((buffer & 0x80) == 0)
756 		line_status |= BusSRQ;
757 
758 	DIA_LOG(1, "done with %x %x\n", buffer, line_status);
759 
760 	return line_status;
761 }
762 
763 /* parallel_poll */
764 
usb_gpib_parallel_poll(gpib_board_t * board,uint8_t * result)765 static int usb_gpib_parallel_poll(gpib_board_t *board, uint8_t *result)
766 {
767 	/* request parallel poll asserting ATN | EOI;
768 	 * we suppose ATN already asserted
769 	 */
770 
771 	int retval;
772 
773 	DIA_LOG(1, "enter %p\n", board);
774 
775 	retval = set_control_line(board, IB_BUS_EOI, 1);
776 	if (retval != ACK) {
777 		dev_alert(board->gpib_dev, "%s:%s - assert EOI failed\n", NAME, __func__);
778 		return -EIO;
779 	}
780 
781 	*result = send_command(board, USB_GPIB_READ_DATA, 0);
782 
783 	DIA_LOG(1, "done with %x\n", *result);
784 
785 	retval = set_control_line(board, IB_BUS_EOI, 0);
786 	if (retval != 0x06) {
787 		dev_alert(board->gpib_dev, "%s:%s - unassert EOI failed\n", NAME, __func__);
788 		return -EIO;
789 	}
790 
791 	return 0;
792 }
793 
794 /* read */
795 
usb_gpib_read(gpib_board_t * board,u8 * buffer,size_t length,int * end,size_t * bytes_read)796 static int usb_gpib_read(gpib_board_t *board,
797 			 u8 *buffer,
798 			 size_t length,
799 			 int *end,
800 			 size_t *bytes_read)
801 {
802 #define MAX_READ_EXCESS 16384
803 
804 	struct char_buf b = {NULL, 0};
805 
806 	int retval;
807 	char c, nc;
808 	int ic;
809 	struct timespec64 before, after;
810 	int read_count = MAX_READ_EXCESS;
811 	struct usb_gpib_priv *pd = (struct usb_gpib_priv *)board->private_data;
812 
813 	DIA_LOG(1, "enter %p -> %zu\n", board, length);
814 
815 	*bytes_read = 0;      /* by default, things go wrong */
816 	*end = 0;
817 
818 	set_timeout(board);
819 
820 	/* single byte read has a special handling */
821 
822 	if (length == 1) {
823 		char inbuf[2] = {0, 0};
824 
825 		/* read a single character */
826 
827 		ktime_get_real_ts64 (&before);
828 
829 		retval = write_loop(GPIB_DEV, USB_GPIB_READ_1, strlen(USB_GPIB_READ_1));
830 		if (retval < 0)
831 			return retval;
832 
833 		retval = skel_do_read(GPIB_DEV, inbuf, 1);
834 		retval += skel_do_read(GPIB_DEV, inbuf + 1, 1);
835 
836 		ktime_get_real_ts64 (&after);
837 
838 		DIA_LOG(1, "single read: %x %x %x in %d\n", retval,
839 			inbuf[0], inbuf[1],
840 			usec_diff(&after, &before));
841 
842 		/* good char / last char? */
843 
844 		if (retval == 2 && inbuf[1] == ACK) {
845 			buffer[0] = inbuf[0];
846 			*bytes_read = 1;
847 			return 0;
848 		}
849 		if (retval < 2)
850 			return -EIO;
851 		else
852 			return -ETIME;
853 		return 0;
854 	}
855 
856 	/* allocate buffer for multibyte read */
857 
858 	b.inbuf = kmalloc(INBUF_SIZE, GFP_KERNEL);
859 	if (!b.inbuf)
860 		return -ENOMEM;
861 
862 	/* send read command and check <DLE><STX> sequence */
863 
864 	retval = write_loop(GPIB_DEV, USB_GPIB_READ, strlen(USB_GPIB_READ));
865 	if (retval < 0)
866 		goto read_return;
867 
868 	if (one_char(board, &b) != DLE || one_char(board, &b) != STX) {
869 		dev_alert(board->gpib_dev, "%s:%s - wrong <DLE><STX> sequence\n",
870 			  NAME, __func__);
871 		retval = -EIO;
872 		goto read_return;
873 	}
874 
875 	/* get data flow */
876 
877 	while (1) {
878 		ic = one_char(board, &b);
879 		if (ic == -EIO) {
880 			retval = -EIO;
881 			goto read_return;
882 		}
883 		c = ic;
884 
885 		if (c == DLE)
886 			nc = one_char(board, &b);
887 		if (c != DLE || nc == DLE) {
888 			/* data byte - store into buffer */
889 
890 			if (*bytes_read == length)
891 				break; /* data overflow */
892 			if (c == DLE)
893 				c = nc;
894 			buffer[(*bytes_read)++] = c;
895 			if (c == pd->eos) {
896 				*end = 1;
897 				break;
898 			}
899 
900 		} else {
901 			/* we are in the closing <DLE><ETX> sequence */
902 			c = nc;
903 			if (c == ETX) {
904 				c = one_char(board, &b);
905 				if (c == ACK) {
906 					*end = 1;
907 					retval = 0;
908 					goto read_return;
909 				} else {
910 					dev_alert(board->gpib_dev, "%s:%s - %s %x\n",
911 						  NAME, __func__,
912 						  "Wrong end of message", c);
913 					retval = -ETIME;
914 					goto read_return;
915 				}
916 			} else {
917 				dev_alert(board->gpib_dev, "%s:%s - %s\n", NAME, __func__,
918 					  "lone <DLE> in stream");
919 				retval = -EIO;
920 				goto read_return;
921 			}
922 		}
923 	}
924 
925 	/* we had a data overflow - flush excess data */
926 
927 	while (read_count--) {
928 		if (one_char(board, &b) != DLE)
929 			continue;
930 		c = one_char(board, &b);
931 		if (c == DLE)
932 			continue;
933 		if (c == ETX) {
934 			c = one_char(board, &b);
935 			if (c == ACK) {
936 				if (MAX_READ_EXCESS - read_count > 1)
937 					dev_alert(board->gpib_dev, "%s:%s - %s\n", NAME, __func__,
938 						  "small buffer - maybe some data lost");
939 				retval = 0;
940 				goto read_return;
941 			}
942 			break;
943 		}
944 	}
945 
946 	dev_alert(board->gpib_dev, "%s:%s - no input end - GPIB board in odd state\n",
947 		  NAME, __func__);
948 	retval = -EIO;
949 
950 read_return:
951 	kfree(b.inbuf);
952 
953 	DIA_LOG(1, "done with byte/status: %d %x %d\n",
954 		(int)*bytes_read, retval, *end);
955 
956 	if (retval == 0 || retval == -ETIME) {
957 		if (send_command(board, USB_GPIB_UNTALK, sizeof(USB_GPIB_UNTALK)) == 0x06)
958 			return retval;
959 		return	-EIO;
960 	}
961 
962 	return retval;
963 }
964 
965 /* remote_enable */
966 
usb_gpib_remote_enable(gpib_board_t * board,int enable)967 static void usb_gpib_remote_enable(gpib_board_t *board, int enable)
968 {
969 	int retval;
970 
971 	retval = set_control_line(board, IB_BUS_REN, enable ? 1 : 0);
972 	if (retval != ACK)
973 		dev_alert(board->gpib_dev, "%s:%s - could not set REN line: %x\n",
974 			  NAME, __func__, retval);
975 
976 	DIA_LOG(1, "done with %x\n", retval);
977 }
978 
979 /* request_system_control */
980 
usb_gpib_request_system_control(gpib_board_t * board,int request_control)981 static void usb_gpib_request_system_control(gpib_board_t *board,
982 					    int request_control)
983 {
984 	if (request_control)
985 		set_bit(CIC_NUM, &board->status);
986 	else
987 		clear_bit(CIC_NUM, &board->status);
988 
989 	DIA_LOG(1, "done with %d -> %lx\n", request_control, board->status);
990 }
991 
992 /* take_control */
993 /* beware: the sync flag is ignored; what is its real meaning? */
994 
usb_gpib_take_control(gpib_board_t * board,int sync)995 static int usb_gpib_take_control(gpib_board_t *board, int sync)
996 {
997 	int retval;
998 
999 	retval = set_control_line(board, IB_BUS_ATN, 1);
1000 
1001 	DIA_LOG(1, "done with %d %x\n", sync, retval);
1002 
1003 	if (retval == ACK)
1004 		return 0;
1005 	return -EIO;
1006 }
1007 
1008 /* update_status */
1009 
usb_gpib_update_status(gpib_board_t * board,unsigned int clear_mask)1010 static unsigned int usb_gpib_update_status(gpib_board_t *board,
1011 					   unsigned int clear_mask)
1012 {
1013 	/* There is nothing we can do here, I guess */
1014 
1015 	board->status &= ~clear_mask;
1016 
1017 	DIA_LOG(1, "done with %x %lx\n", clear_mask, board->status);
1018 
1019 	return board->status;
1020 }
1021 
1022 /* write */
1023 /* beware: DLE characters are not escaped - can only send ASCII data */
1024 
usb_gpib_write(gpib_board_t * board,u8 * buffer,size_t length,int send_eoi,size_t * bytes_written)1025 static int usb_gpib_write(gpib_board_t *board,
1026 			  u8 *buffer,
1027 			  size_t length,
1028 			  int send_eoi,
1029 			  size_t *bytes_written)
1030 {
1031 	int retval;
1032 	char *msg;
1033 
1034 	DIA_LOG(1, "enter %p -> %zu\n", board, length);
1035 
1036 	set_timeout(board);
1037 
1038 	msg = kmalloc(length + 8, GFP_KERNEL);
1039 	if (!msg)
1040 		return -ENOMEM;
1041 
1042 	memcpy(msg, "\nIB\020\002", 5);
1043 	memcpy(msg + 5, buffer, length);
1044 	memcpy(msg + 5 + length, "\020\003\n", 3);
1045 
1046 	retval = send_command(board, msg, length + 8);
1047 	kfree(msg);
1048 
1049 	DIA_LOG(1, "<%.*s> -> %x\n", (int)length, buffer, retval);
1050 
1051 	if (retval != ACK)
1052 		return -EPIPE;
1053 
1054 	*bytes_written = length;
1055 
1056 	if (send_command(board, USB_GPIB_UNLISTEN, sizeof(USB_GPIB_UNLISTEN))
1057 	    != 0x06)
1058 		return  -EPIPE;
1059 
1060 	return length;
1061 }
1062 
1063 /*
1064  *  ***	 following functions not implemented yet  ***
1065  */
1066 
1067 /* parallel_poll configure */
1068 
usb_gpib_parallel_poll_configure(gpib_board_t * board,uint8_t configuration)1069 static void usb_gpib_parallel_poll_configure(gpib_board_t *board,
1070 					     uint8_t configuration)
1071 {
1072 	dev_alert(board->gpib_dev, "%s:%s - currently a NOP\n", NAME, __func__);
1073 }
1074 
1075 /* parallel_poll_response */
1076 
usb_gpib_parallel_poll_response(gpib_board_t * board,int ist)1077 static void usb_gpib_parallel_poll_response(gpib_board_t *board, int ist)
1078 {
1079 	dev_alert(board->gpib_dev, "%s:%s - currently a NOP\n", NAME, __func__);
1080 }
1081 
1082 /* primary_address */
1083 
usb_gpib_primary_address(gpib_board_t * board,unsigned int address)1084 static int  usb_gpib_primary_address(gpib_board_t *board, unsigned int address)
1085 {
1086 	dev_alert(board->gpib_dev, "%s:%s - currently a NOP\n", NAME, __func__);
1087 	return 0;
1088 }
1089 
1090 /* return_to_local */
1091 
usb_gpib_return_to_local(gpib_board_t * board)1092 static	void usb_gpib_return_to_local(gpib_board_t *board)
1093 {
1094 	dev_alert(board->gpib_dev, "%s:%s - currently a NOP\n", NAME, __func__);
1095 }
1096 
1097 /* secondary_address */
1098 
usb_gpib_secondary_address(gpib_board_t * board,unsigned int address,int enable)1099 static int usb_gpib_secondary_address(gpib_board_t *board,
1100 				      unsigned int address,
1101 				      int enable)
1102 {
1103 	dev_alert(board->gpib_dev, "%s:%s - currently a NOP\n", NAME, __func__);
1104 	return 0;
1105 }
1106 
1107 /* serial_poll_response */
1108 
usb_gpib_serial_poll_response(gpib_board_t * board,uint8_t status)1109 static void usb_gpib_serial_poll_response(gpib_board_t *board, uint8_t status)
1110 {
1111 	dev_alert(board->gpib_dev, "%s:%s - currently a NOP\n", NAME, __func__);
1112 }
1113 
1114 /* serial_poll_status */
1115 
usb_gpib_serial_poll_status(gpib_board_t * board)1116 static uint8_t usb_gpib_serial_poll_status(gpib_board_t *board)
1117 {
1118 	dev_alert(board->gpib_dev, "%s:%s - currently a NOP\n", NAME, __func__);
1119 	return 0;
1120 }
1121 
1122 /* t1_delay */
1123 
usb_gpib_t1_delay(gpib_board_t * board,unsigned int nano_sec)1124 static unsigned int usb_gpib_t1_delay(gpib_board_t *board, unsigned int nano_sec)
1125 {
1126 	dev_alert(board->gpib_dev, "%s:%s - currently a NOP\n", NAME, __func__);
1127 	return 0;
1128 }
1129 
1130 /*
1131  *   ***  module dispatch table and init/exit functions	 ***
1132  */
1133 
1134 static gpib_interface_t usb_gpib_interface = {
1135 	.name = NAME,
1136 	.attach = usb_gpib_attach,
1137 	.detach = usb_gpib_detach,
1138 	.read = usb_gpib_read,
1139 	.write = usb_gpib_write,
1140 	.command = usb_gpib_command,
1141 	.take_control = usb_gpib_take_control,
1142 	.go_to_standby = usb_gpib_go_to_standby,
1143 	.request_system_control = usb_gpib_request_system_control,
1144 	.interface_clear = usb_gpib_interface_clear,
1145 	.remote_enable = usb_gpib_remote_enable,
1146 	.enable_eos = usb_gpib_enable_eos,
1147 	.disable_eos = usb_gpib_disable_eos,
1148 	.parallel_poll = usb_gpib_parallel_poll,
1149 	.parallel_poll_configure = usb_gpib_parallel_poll_configure,
1150 	.parallel_poll_response = usb_gpib_parallel_poll_response,
1151 	.local_parallel_poll_mode = NULL, // XXX
1152 	.line_status = usb_gpib_line_status,
1153 	.update_status = usb_gpib_update_status,
1154 	.primary_address = usb_gpib_primary_address,
1155 	.secondary_address = usb_gpib_secondary_address,
1156 	.serial_poll_response = usb_gpib_serial_poll_response,
1157 	.serial_poll_status = usb_gpib_serial_poll_status,
1158 	.t1_delay = usb_gpib_t1_delay,
1159 	.return_to_local = usb_gpib_return_to_local,
1160 	.skip_check_for_command_acceptors = 1
1161 };
1162 
1163 /*
1164  *   usb_gpib_init_module(), usb_gpib_exit_module()
1165  *
1166  *   This functions are called every time a new device is detected
1167  *   and registered or is removed and unregistered.
1168  *   We must take note of created and destroyed usb minors to be used
1169  *   when usb_gpib_attach() and usb_gpib_detach() will be called on
1170  *   request by gpib_config.
1171  */
1172 
usb_gpib_init_module(struct usb_interface * interface)1173 static int usb_gpib_init_module(struct usb_interface *interface)
1174 {
1175 	int j, mask, rv;
1176 
1177 	rv = mutex_lock_interruptible(&minors_lock);
1178 	if (rv < 0)
1179 		return rv;
1180 
1181 	if (!assigned_usb_minors) {
1182 		rv = gpib_register_driver(&usb_gpib_interface, THIS_MODULE);
1183 		if (rv) {
1184 			pr_err("lpvo_usb_gpib: gpib_register_driver failed: error = %d\n", rv);
1185 			goto exit;
1186 		}
1187 	} else {
1188 		/* check if minor is already registered - maybe useless, but if
1189 		 *  it happens the code is inconsistent somewhere
1190 		 */
1191 
1192 		for (j = 0 ; j < MAX_DEV ; j++) {
1193 			if (usb_minors[j] == interface->minor && assigned_usb_minors & 1 << j) {
1194 				pr_alert("%s:%s - CODE BUG: USB minor %d registered at %d.\n",
1195 					 NAME, __func__, interface->minor, j);
1196 				rv = -1;
1197 				goto exit;
1198 			}
1199 		}
1200 	}
1201 
1202 	/* find a free slot */
1203 
1204 	for (j = 0 ; j < MAX_DEV ; j++) {
1205 		mask = 1 << j;
1206 		if ((assigned_usb_minors & mask) == 0) {
1207 			usb_minors[j] = interface->minor;
1208 			lpvo_usb_interfaces[j] = interface;
1209 			assigned_usb_minors |= mask;
1210 			DIA_LOG(0, "usb minor %d registered at %d\n", interface->minor, j);
1211 			rv = 0;
1212 			goto exit;
1213 		}
1214 	}
1215 	pr_alert("%s:%s - No slot available for interface %p minor %d\n",
1216 		 NAME, __func__, interface, interface->minor);
1217 	rv = -1;
1218 
1219 exit:
1220 	mutex_unlock(&minors_lock);
1221 	return rv;
1222 }
1223 
usb_gpib_exit_module(int minor)1224 static void usb_gpib_exit_module(int minor)
1225 {
1226 	int j;
1227 
1228 	mutex_lock(&minors_lock);
1229 	for (j = 0 ; j < MAX_DEV ; j++) {
1230 		if (usb_minors[j] == minor && assigned_usb_minors & 1 << j) {
1231 			assigned_usb_minors &= ~(1 << j);
1232 			usb_minors[j] = -1;
1233 			if (assigned_usb_minors == 0)
1234 				gpib_unregister_driver(&usb_gpib_interface);
1235 			goto exit;
1236 		}
1237 	}
1238 	pr_alert("%s:%s - CODE BUG: USB minor %d not found.\n", NAME, __func__, minor);
1239 
1240 exit:
1241 	mutex_unlock(&minors_lock);
1242 }
1243 
1244 /*
1245  *     Default latency time (16 msec) is too long.
1246  *     We must use 1 msec (best); anyhow, no more than 5 msec.
1247  *
1248  *     Defines and function taken and modified from the kernel tree
1249  *     (see ftdi_sio.h and ftdi_sio.c).
1250  *
1251  */
1252 
1253 #define FTDI_SIO_SET_LATENCY_TIMER	9 /* Set the latency timer */
1254 #define FTDI_SIO_SET_LATENCY_TIMER_REQUEST FTDI_SIO_SET_LATENCY_TIMER
1255 #define FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE 0x40
1256 #define WDR_TIMEOUT 5000 /* default urb timeout */
1257 #define WDR_SHORT_TIMEOUT 1000	/* shorter urb timeout */
1258 
1259 #define LATENCY_TIMER 1		   /* use a small latency timer: 1 ... 5 msec */
1260 #define LATENCY_CHANNEL 0	   /* channel selection in multichannel devices */
write_latency_timer(struct usb_device * udev)1261 static int write_latency_timer(struct usb_device *udev)
1262 {
1263 	int rv = usb_control_msg(udev,
1264 				 usb_sndctrlpipe(udev, 0),
1265 				 FTDI_SIO_SET_LATENCY_TIMER_REQUEST,
1266 				 FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE,
1267 				 LATENCY_TIMER, LATENCY_CHANNEL,
1268 				 NULL, 0, WDR_TIMEOUT);
1269 	if (rv < 0)
1270 		pr_alert("Unable to write latency timer: %i\n", rv);
1271 	return rv;
1272 }
1273 
1274 /*****************************************************************************
1275  *									     *
1276  *  The following code is a modified version of the USB Skeleton driver	     *
1277  *  written by Greg Kroah-Hartman and available in the kernel tree.	     *
1278  *									     *
1279  *  Functions skel_open() and skel_release() have been rewritten and named   *
1280  *  skel_do_open() and skel_do_release() to process the attach and detach    *
1281  *  requests coming from gpib_config.					     *
1282  *									     *
1283  *  Functions skel_read() and skel_write() have been split into a	     *
1284  *  skel_do_read() and skel_do_write(), that cover the kernel stuff of read  *
1285  *  and write operations, and the original skel_read() and skel_write(),     *
1286  *  that handle communication with user space and call their _do_ companion. *
1287  *									     *
1288  *  Only the _do_ versions are used by the lpvo_usb_gpib driver; other ones  *
1289  *  can be (optionally) maintained in the compilation to have direct access  *
1290  *  to a gpib controller for debug and diagnostics.			     *
1291  *									     *
1292  *  To avoid collisions in names, devices in user space have been renamed    *
1293  *  lpvo_raw1, lpvo_raw2 ....  and the usb driver has been renamed with the  *
1294  *  gpib module name.							     *
1295  *									     *
1296  *****************************************************************************/
1297 
1298 /*
1299  * USB Skeleton driver - 2.2
1300  *
1301  * Copyright (C) 2001-2004 Greg Kroah-Hartman ([email protected])
1302  *
1303  * This driver is based on the 2.6.3 version of drivers/usb/usb-skeleton.c
1304  * but has been rewritten to be easier to read and use.
1305  */
1306 
1307 #include <linux/errno.h>
1308 #include <linux/kref.h>
1309 #include <linux/uaccess.h>
1310 #include <linux/mutex.h>
1311 
1312 /* Get a minor range for your devices from the usb maintainer */
1313 #define USB_SKEL_MINOR_BASE	   192
1314 
1315 /*   private defines   */
1316 
1317 #define MAX_TRANSFER		    (PAGE_SIZE - 512)
1318 /* MAX_TRANSFER is chosen so that the VM is not stressed by
1319  * allocations > PAGE_SIZE and the number of packets in a page
1320  * is an integer 512 is the largest possible packet on EHCI
1321  */
1322 
1323 #define WRITES_IN_FLIGHT	1     /* we do not want more than one pending write */
1324 #define USER_DEVICE 1		      /* compile for device(s) in user space */
1325 
1326 /* Structure to hold all of our device specific stuff */
1327 struct usb_skel {
1328 	struct usb_device     *udev;		     /* the usb device for this device */
1329 	struct usb_interface  *interface;	     /* the interface for this device */
1330 	struct semaphore      limit_sem;	     /* limiting the number of writes in progress */
1331 	struct usb_anchor     submitted;	     /* in case need to retract our submissions */
1332 	struct urb	      *bulk_in_urb;	     /* the urb to read data with */
1333 	unsigned char	      *bulk_in_buffer;	     /* the buffer to receive data */
1334 	size_t		      bulk_in_size;	     /* the size of the receive buffer */
1335 	size_t		      bulk_in_filled;	     /* number of bytes in the buffer */
1336 	size_t		      bulk_in_copied;	     /* already copied to user space */
1337 	__u8		      bulk_in_endpoint_addr;  /* the address of the bulk in endpoint */
1338 	__u8		      bulk_out_endpoint_addr; /* the address of the bulk out endpoint */
1339 	int		      errors;		     /* the last request tanked */
1340 	bool		      ongoing_read;	     /* a read is going on */
1341 	spinlock_t	      err_lock;		     /* lock for errors */
1342 	struct kref	      kref;
1343 	struct mutex	      io_mutex;		     /* synchronize I/O with disconnect */
1344 	wait_queue_head_t     bulk_in_wait;	     /* to wait for an ongoing read */
1345 };
1346 
1347 #define to_skel_dev(d) container_of(d, struct usb_skel, kref)
1348 
1349 static struct usb_driver skel_driver;
1350 static void skel_draw_down(struct usb_skel *dev);
1351 
skel_delete(struct kref * kref)1352 static void skel_delete(struct kref *kref)
1353 {
1354 	struct usb_skel *dev = to_skel_dev(kref);
1355 
1356 	usb_free_urb(dev->bulk_in_urb);
1357 	usb_put_dev(dev->udev);
1358 	kfree(dev->bulk_in_buffer);
1359 	kfree(dev);
1360 }
1361 
1362 /*
1363  *   skel_do_open() - to be called by usb_gpib_attach
1364  */
1365 
skel_do_open(gpib_board_t * board,int subminor)1366 static int skel_do_open(gpib_board_t *board, int subminor)
1367 {
1368 	struct usb_skel *dev;
1369 	struct usb_interface *interface;
1370 	int retval = 0;
1371 
1372 	DIA_LOG(0, "Required minor: %d\n", subminor);
1373 
1374 	interface = usb_find_interface(&skel_driver, subminor);
1375 	if (!interface) {
1376 		pr_err("%s - error, can't find device for minor %d\n",
1377 		       __func__, subminor);
1378 		retval = -ENODEV;
1379 		goto exit;
1380 	}
1381 
1382 	dev = usb_get_intfdata(interface);
1383 	if (!dev) {
1384 		retval = -ENODEV;
1385 		goto exit;
1386 	}
1387 
1388 	retval = usb_autopm_get_interface(interface);
1389 	if (retval)
1390 		goto exit;
1391 
1392 	/* increment our usage count for the device */
1393 	kref_get(&dev->kref);
1394 
1395 	/* save our object in the file's private structure */
1396 	GPIB_DEV = dev;
1397 
1398 exit:
1399 	return retval;
1400 }
1401 
1402 /*
1403  *   skel_do_release() - to be called by usb_gpib_detach
1404  */
1405 
skel_do_release(gpib_board_t * board)1406 static int skel_do_release(gpib_board_t *board)
1407 {
1408 	struct usb_skel *dev;
1409 
1410 	dev = GPIB_DEV;
1411 	if (!dev)
1412 		return -ENODEV;
1413 
1414 	/* allow the device to be autosuspended */
1415 	mutex_lock(&dev->io_mutex);
1416 	if (dev->interface)
1417 		usb_autopm_put_interface(dev->interface);
1418 	mutex_unlock(&dev->io_mutex);
1419 
1420 	/* decrement the count on our device */
1421 	kref_put(&dev->kref, skel_delete);
1422 	return 0;
1423 }
1424 
1425 /*
1426  *   read functions
1427  */
1428 
skel_read_bulk_callback(struct urb * urb)1429 static void skel_read_bulk_callback(struct urb *urb)
1430 {
1431 	struct usb_skel *dev;
1432 	unsigned long flags;
1433 
1434 	dev = urb->context;
1435 
1436 	spin_lock_irqsave(&dev->err_lock, flags);
1437 	/* sync/async unlink faults aren't errors */
1438 	if (urb->status) {
1439 		if (!(urb->status == -ENOENT ||
1440 		      urb->status == -ECONNRESET ||
1441 		      urb->status == -ESHUTDOWN))
1442 			dev_err(&dev->interface->dev,
1443 				"%s - nonzero read bulk status received: %d\n",
1444 				__func__, urb->status);
1445 
1446 		dev->errors = urb->status;
1447 	} else {
1448 		dev->bulk_in_filled = urb->actual_length;
1449 	}
1450 	dev->ongoing_read = 0;
1451 	spin_unlock_irqrestore(&dev->err_lock, flags);
1452 
1453 	wake_up_interruptible(&dev->bulk_in_wait);
1454 }
1455 
skel_do_read_io(struct usb_skel * dev,size_t count)1456 static int skel_do_read_io(struct usb_skel *dev, size_t count)
1457 {
1458 	int rv;
1459 
1460 	/* prepare a read */
1461 	usb_fill_bulk_urb(dev->bulk_in_urb,
1462 			  dev->udev,
1463 			  usb_rcvbulkpipe(dev->udev,
1464 					  dev->bulk_in_endpoint_addr),
1465 			  dev->bulk_in_buffer,
1466 			  min(dev->bulk_in_size, count),
1467 			  skel_read_bulk_callback,
1468 			  dev);
1469 	/* tell everybody to leave the URB alone */
1470 	spin_lock_irq(&dev->err_lock);
1471 	dev->ongoing_read = 1;
1472 	spin_unlock_irq(&dev->err_lock);
1473 
1474 	/* submit bulk in urb, which means no data to deliver */
1475 	dev->bulk_in_filled = 0;
1476 	dev->bulk_in_copied = 0;
1477 
1478 	/* do it */
1479 	rv = usb_submit_urb(dev->bulk_in_urb, GFP_KERNEL);
1480 	if (rv < 0) {
1481 		dev_err(&dev->interface->dev,
1482 			"%s - failed submitting read urb, error %d\n",
1483 			__func__, rv);
1484 		rv = (rv == -ENOMEM) ? rv : -EIO;
1485 		spin_lock_irq(&dev->err_lock);
1486 		dev->ongoing_read = 0;
1487 		spin_unlock_irq(&dev->err_lock);
1488 	}
1489 
1490 	return rv;
1491 }
1492 
1493 /*
1494  *   skel_do_read() - read operations from lpvo_usb_gpib
1495  */
1496 
skel_do_read(struct usb_skel * dev,char * buffer,size_t count)1497 static ssize_t skel_do_read(struct usb_skel *dev, char *buffer, size_t count)
1498 {
1499 	int rv;
1500 	bool ongoing_io;
1501 
1502 	/* if we cannot read at all, return EOF */
1503 
1504 	if (!dev->bulk_in_urb || !count)
1505 		return 0;
1506 
1507 	DIA_LOG(1, "enter for %zu.\n", count);
1508 
1509 restart:  /* added to comply with ftdi timeout technique */
1510 
1511 	/* no concurrent readers */
1512 
1513 	DIA_LOG(2, "restart with %zd %zd.\n", dev->bulk_in_filled, dev->bulk_in_copied);
1514 
1515 	rv = mutex_lock_interruptible(&dev->io_mutex);
1516 	if (rv < 0)
1517 		return rv;
1518 
1519 	if (!dev->interface) {		      /* disconnect() was called */
1520 		rv = -ENODEV;
1521 		goto exit;
1522 	}
1523 
1524 retry:
1525 	/* if IO is under way, we must not touch things */
1526 	spin_lock_irq(&dev->err_lock);
1527 	ongoing_io = dev->ongoing_read;
1528 	spin_unlock_irq(&dev->err_lock);
1529 
1530 	DIA_LOG(2, "retry with %d.\n", ongoing_io);
1531 
1532 	if (ongoing_io) {
1533 //		  /* nonblocking IO shall not wait */
1534 //		  /* no file, no O_NONBLOCK; maybe provide when from user space */
1535 //		  if (file->f_flags & O_NONBLOCK) {
1536 //			  rv = -EAGAIN;
1537 //			  goto exit;
1538 //		  }
1539 
1540 		/*
1541 		 * IO may take forever
1542 		 * hence wait in an interruptible state
1543 		 */
1544 		rv = wait_event_interruptible(dev->bulk_in_wait, (!dev->ongoing_read));
1545 		if (rv < 0)
1546 			goto exit;
1547 	}
1548 
1549 	/* errors must be reported */
1550 	rv = dev->errors;
1551 	if (rv < 0) {
1552 		/* any error is reported once */
1553 		dev->errors = 0;
1554 		/* to preserve notifications about reset */
1555 		rv = (rv == -EPIPE) ? rv : -EIO;
1556 		/* report it */
1557 		goto exit;
1558 	}
1559 
1560 	/*
1561 	 * if the buffer is filled we may satisfy the read
1562 	 * else we need to start IO
1563 	 */
1564 
1565 	if (dev->bulk_in_filled) {
1566 		/* we had read data */
1567 
1568 		size_t available = dev->bulk_in_filled - dev->bulk_in_copied;
1569 //		  size_t chunk = min(available, count);	 /* compute chunk later */
1570 		size_t chunk;
1571 
1572 		DIA_LOG(2, "we have data: %zu %zu.\n", dev->bulk_in_filled, dev->bulk_in_copied);
1573 
1574 		if (!available) {
1575 			/*
1576 			 * all data has been used
1577 			 * actual IO needs to be done
1578 			 */
1579 			/* it seems that requests for less than dev->bulk_in_size
1580 			 *  are not accepted
1581 			 */
1582 			rv = skel_do_read_io(dev, dev->bulk_in_size);
1583 			if (rv < 0)
1584 				goto exit;
1585 			else
1586 				goto retry;
1587 		}
1588 
1589 		/*
1590 		 * data is available - chunk tells us how much shall be copied
1591 		 */
1592 
1593 		/* Condition dev->bulk_in_copied > 0 maybe will never happen. In case,
1594 		 * signal the event and copy using the original procedure, i.e., copy
1595 		 * first two bytes also
1596 		 */
1597 
1598 		if (dev->bulk_in_copied) {
1599 			int j;
1600 
1601 			for (j = 0 ; j < dev->bulk_in_filled ; j++) {
1602 				pr_alert("copy -> %x %zu %x\n",
1603 					 j, dev->bulk_in_copied, dev->bulk_in_buffer[j]);
1604 			}
1605 			chunk = min(available, count);
1606 			memcpy(buffer, dev->bulk_in_buffer + dev->bulk_in_copied, chunk);
1607 			rv = chunk;
1608 			dev->bulk_in_copied += chunk;
1609 
1610 			/* copy discarding first two bytes that contain ftdi chip status */
1611 
1612 		} else {
1613 			/* account for two bytes to be discarded */
1614 			chunk = min(available, count + 2);
1615 			if (chunk < 2) {
1616 				pr_alert("BAD READ - chunk: %zu\n", chunk);
1617 				rv = -EIO;
1618 				goto exit;
1619 			}
1620 
1621 			memcpy(buffer, dev->bulk_in_buffer + 2, chunk - 2);
1622 			rv = chunk;
1623 			dev->bulk_in_copied += chunk;
1624 		}
1625 
1626 		/*
1627 		 * if we are asked for more than we have,
1628 		 * we start IO but don't wait
1629 		 *
1630 		 * No, no read ahead allowed; if the case, more data will be
1631 		 * asked for by the lpvo_usb_gpib layer.
1632 		 */
1633 //		  if (available < count)
1634 //			  skel_do_read_io(dev, dev->bulk_in_size);
1635 	} else {
1636 		DIA_LOG(1, "no data - start read - copied: %zd.\n", dev->bulk_in_copied);
1637 
1638 		/* no data in the buffer */
1639 		rv = skel_do_read_io(dev, dev->bulk_in_size);
1640 		if (rv < 0)
1641 			goto exit;
1642 		else
1643 			goto retry;
1644 	}
1645 exit:
1646 	mutex_unlock(&dev->io_mutex);
1647 	if (rv == 2)
1648 		goto restart;   /* ftdi chip returns two status bytes after a latency anyhow */
1649 	DIA_LOG(1, "exit with %d.\n", rv);
1650 	if (rv > 0)
1651 		return rv - 2;  /* account for 2 discarded bytes in a valid buffer */
1652 	return rv;
1653 }
1654 
1655 /*
1656  *   write functions
1657  */
1658 
skel_write_bulk_callback(struct urb * urb)1659 static void skel_write_bulk_callback(struct urb *urb)
1660 {
1661 	struct usb_skel *dev;
1662 	unsigned long flags;
1663 
1664 	dev = urb->context;
1665 
1666 	/* sync/async unlink faults aren't errors */
1667 	if (urb->status) {
1668 		if (!(urb->status == -ENOENT ||
1669 		      urb->status == -ECONNRESET ||
1670 		      urb->status == -ESHUTDOWN))
1671 			dev_err(&dev->interface->dev,
1672 				"%s - nonzero write bulk status received: %d\n",
1673 				__func__, urb->status);
1674 
1675 		spin_lock_irqsave(&dev->err_lock, flags);
1676 		dev->errors = urb->status;
1677 		spin_unlock_irqrestore(&dev->err_lock, flags);
1678 	}
1679 
1680 	/* free up our allocated buffer */
1681 	usb_free_coherent(urb->dev, urb->transfer_buffer_length,
1682 			  urb->transfer_buffer, urb->transfer_dma);
1683 	up(&dev->limit_sem);
1684 }
1685 
1686 /*
1687  *   skel_do_write() - write operations from lpvo_usb_gpib
1688  */
1689 
skel_do_write(struct usb_skel * dev,const char * buffer,size_t count)1690 static ssize_t skel_do_write(struct usb_skel *dev, const char *buffer, size_t count)
1691 {
1692 	int retval = 0;
1693 	struct urb *urb = NULL;
1694 	char *buf = NULL;
1695 	size_t writesize = min_t(size_t, count, (size_t)MAX_TRANSFER);
1696 
1697 	/* verify that we actually have some data to write */
1698 	if (count == 0)
1699 		goto exit;
1700 
1701 	/*
1702 	 * limit the number of URBs in flight to stop a user from using up all
1703 	 * RAM
1704 	 */
1705 	/* Only one URB is used, because we can't have a pending write() and go on */
1706 
1707 //	  if (!(file->f_flags & O_NONBLOCK)) {	/* no NONBLOCK provided */
1708 	if (down_interruptible(&dev->limit_sem)) {
1709 		retval = -ERESTARTSYS;
1710 		goto exit;
1711 	}
1712 //	  } else {
1713 //		  if (down_trylock(&dev->limit_sem)) {
1714 //			  retval = -EAGAIN;
1715 //			  goto exit;
1716 //		  }
1717 //	  }
1718 
1719 	spin_lock_irq(&dev->err_lock);
1720 	retval = dev->errors;
1721 	if (retval < 0) {
1722 		/* any error is reported once */
1723 		dev->errors = 0;
1724 		/* to preserve notifications about reset */
1725 		retval = (retval == -EPIPE) ? retval : -EIO;
1726 	}
1727 	spin_unlock_irq(&dev->err_lock);
1728 	if (retval < 0)
1729 		goto error;
1730 
1731 	/* create a urb, and a buffer for it, and copy the data to the urb */
1732 	urb = usb_alloc_urb(0, GFP_KERNEL);
1733 	if (!urb) {
1734 		retval = -ENOMEM;
1735 		goto error;
1736 	}
1737 
1738 	buf = usb_alloc_coherent(dev->udev, writesize, GFP_KERNEL,
1739 				 &urb->transfer_dma);
1740 	if (!buf) {
1741 		retval = -ENOMEM;
1742 		goto error;
1743 	}
1744 
1745 	memcpy(buf, buffer, count);
1746 
1747 	/* this lock makes sure we don't submit URBs to gone devices */
1748 	mutex_lock(&dev->io_mutex);
1749 	if (!dev->interface) {		      /* disconnect() was called */
1750 		mutex_unlock(&dev->io_mutex);
1751 		retval = -ENODEV;
1752 		goto error;
1753 	}
1754 
1755 	/* initialize the urb properly */
1756 	usb_fill_bulk_urb(urb, dev->udev,
1757 			  usb_sndbulkpipe(dev->udev, dev->bulk_out_endpoint_addr),
1758 			  buf, writesize, skel_write_bulk_callback, dev);
1759 	urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1760 	usb_anchor_urb(urb, &dev->submitted);
1761 
1762 	/* send the data out the bulk port */
1763 	retval = usb_submit_urb(urb, GFP_KERNEL);
1764 	mutex_unlock(&dev->io_mutex);
1765 	if (retval) {
1766 		dev_err(&dev->interface->dev,
1767 			"%s - failed submitting write urb, error %d\n",
1768 			__func__, retval);
1769 		goto error_unanchor;
1770 	}
1771 
1772 	/*
1773 	 * release our reference to this urb, the USB core will eventually free
1774 	 * it entirely
1775 	 */
1776 	usb_free_urb(urb);
1777 
1778 	return writesize;
1779 
1780 error_unanchor:
1781 	usb_unanchor_urb(urb);
1782 error:
1783 	if (urb) {
1784 		usb_free_coherent(dev->udev, writesize, buf, urb->transfer_dma);
1785 		usb_free_urb(urb);
1786 	}
1787 	up(&dev->limit_sem);
1788 
1789 exit:
1790 	return retval;
1791 }
1792 
1793 /*
1794  *   services for the user space devices
1795  */
1796 
1797 #if USER_DEVICE	 /* conditional compilation of user space device */
1798 
skel_flush(struct file * file,fl_owner_t id)1799 static int skel_flush(struct file *file, fl_owner_t id)
1800 {
1801 	struct usb_skel *dev;
1802 	int res;
1803 
1804 	dev = file->private_data;
1805 	if (!dev)
1806 		return -ENODEV;
1807 
1808 	/* wait for io to stop */
1809 	mutex_lock(&dev->io_mutex);
1810 	skel_draw_down(dev);
1811 
1812 	/* read out errors, leave subsequent opens a clean slate */
1813 	spin_lock_irq(&dev->err_lock);
1814 	res = dev->errors ? (dev->errors == -EPIPE ? -EPIPE : -EIO) : 0;
1815 	dev->errors = 0;
1816 	spin_unlock_irq(&dev->err_lock);
1817 
1818 	mutex_unlock(&dev->io_mutex);
1819 
1820 	return res;
1821 }
1822 
skel_open(struct inode * inode,struct file * file)1823 static int skel_open(struct inode *inode, struct file *file)
1824 {
1825 	struct usb_skel *dev;
1826 	struct usb_interface *interface;
1827 	int subminor;
1828 	int retval = 0;
1829 
1830 	subminor = iminor(inode);
1831 
1832 	interface = usb_find_interface(&skel_driver, subminor);
1833 	if (!interface) {
1834 		pr_err("%s - error, can't find device for minor %d\n",
1835 		       __func__, subminor);
1836 		retval = -ENODEV;
1837 		goto exit;
1838 	}
1839 
1840 	dev = usb_get_intfdata(interface);
1841 	if (!dev) {
1842 		retval = -ENODEV;
1843 		goto exit;
1844 	}
1845 
1846 	retval = usb_autopm_get_interface(interface);
1847 	if (retval)
1848 		goto exit;
1849 
1850 	/* increment our usage count for the device */
1851 	kref_get(&dev->kref);
1852 
1853 	/* save our object in the file's private structure */
1854 	file->private_data = dev;
1855 
1856 exit:
1857 	return retval;
1858 }
1859 
skel_release(struct inode * inode,struct file * file)1860 static int skel_release(struct inode *inode, struct file *file)
1861 {
1862 	struct usb_skel *dev;
1863 
1864 	dev = file->private_data;
1865 	if (!dev)
1866 		return -ENODEV;
1867 
1868 	/* allow the device to be autosuspended */
1869 	mutex_lock(&dev->io_mutex);
1870 	if (dev->interface)
1871 		usb_autopm_put_interface(dev->interface);
1872 	mutex_unlock(&dev->io_mutex);
1873 
1874 	/* decrement the count on our device */
1875 	kref_put(&dev->kref, skel_delete);
1876 	return 0;
1877 }
1878 
1879 /*
1880  *  user space access to read function
1881  */
1882 
skel_read(struct file * file,char __user * buffer,size_t count,loff_t * ppos)1883 static ssize_t skel_read(struct file *file, char __user *buffer, size_t count,
1884 			 loff_t *ppos)
1885 {
1886 	struct usb_skel *dev;
1887 	char *buf;
1888 	ssize_t rv;
1889 
1890 	dev = file->private_data;
1891 
1892 	buf = kmalloc(count, GFP_KERNEL);
1893 	if (!buf)
1894 		return -ENOMEM;
1895 
1896 	rv = skel_do_read(dev, buf, count);
1897 
1898 	pr_alert("%s - return with %zu\n", __func__, rv);
1899 
1900 	if (rv > 0) {
1901 		if (copy_to_user(buffer, buf, rv)) {
1902 			kfree(buf);
1903 			return -EFAULT;
1904 		}
1905 	}
1906 	kfree(buf);
1907 	return rv;
1908 }
1909 
1910 /*
1911  *  user space access to write function
1912  */
1913 
skel_write(struct file * file,const char __user * user_buffer,size_t count,loff_t * ppos)1914 static ssize_t skel_write(struct file *file, const char __user *user_buffer,
1915 			  size_t count, loff_t *ppos)
1916 {
1917 	struct usb_skel *dev;
1918 	char *buf;
1919 	ssize_t rv;
1920 
1921 	dev = file->private_data;
1922 
1923 	buf = kmalloc(count, GFP_KERNEL);
1924 	if (!buf)
1925 		return -ENOMEM;
1926 
1927 	if (copy_from_user(buf, user_buffer, count)) {
1928 		kfree(buf);
1929 		return -EFAULT;
1930 	}
1931 
1932 	rv = skel_do_write(dev, buf, count);
1933 	kfree(buf);
1934 	return rv;
1935 }
1936 #endif
1937 
1938 static const struct file_operations skel_fops = {
1939 	.owner =	THIS_MODULE,
1940 #if USER_DEVICE
1941 	.read =	   skel_read,
1942 	.write =   skel_write,
1943 	.open =	   skel_open,
1944 	.release = skel_release,
1945 	.flush =   skel_flush,
1946 	.llseek =  noop_llseek,
1947 #endif
1948 };
1949 
1950 /*
1951  * usb class driver info in order to get a minor number from the usb core,
1952  * and to have the device registered with the driver core
1953  */
1954 #if USER_DEVICE
1955 static struct usb_class_driver skel_class = {
1956 	.name =		       "lpvo_raw%d",
1957 	.fops =		       &skel_fops,
1958 	.minor_base =	     USB_SKEL_MINOR_BASE,
1959 };
1960 #endif
1961 
skel_probe(struct usb_interface * interface,const struct usb_device_id * id)1962 static int skel_probe(struct usb_interface *interface,
1963 		      const struct usb_device_id *id)
1964 {
1965 	struct usb_skel *dev;
1966 	struct usb_endpoint_descriptor *bulk_in, *bulk_out;
1967 	int retval;
1968 	char *device_path;
1969 
1970 	mutex_init(&minors_lock);   /* required for handling minor numbers table */
1971 
1972 	/* allocate memory for our device state and initialize it */
1973 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1974 	if (!dev)
1975 		return -ENOMEM;
1976 
1977 	kref_init(&dev->kref);
1978 	sema_init(&dev->limit_sem, WRITES_IN_FLIGHT);
1979 	mutex_init(&dev->io_mutex);
1980 	spin_lock_init(&dev->err_lock);
1981 	init_usb_anchor(&dev->submitted);
1982 	init_waitqueue_head(&dev->bulk_in_wait);
1983 
1984 	dev->udev = usb_get_dev(interface_to_usbdev(interface));
1985 	dev->interface = interface;
1986 
1987 	/* set up the endpoint information */
1988 	/* use only the first bulk-in and bulk-out endpoints */
1989 	retval = usb_find_common_endpoints(interface->cur_altsetting,
1990 					   &bulk_in, &bulk_out, NULL, NULL);
1991 	if (retval) {
1992 		dev_err(&interface->dev,
1993 			"Could not find both bulk-in and bulk-out endpoints\n");
1994 		goto error;
1995 	}
1996 
1997 	dev->bulk_in_size = usb_endpoint_maxp(bulk_in);
1998 	dev->bulk_in_endpoint_addr = bulk_in->bEndpointAddress;
1999 	dev->bulk_in_buffer = kmalloc(dev->bulk_in_size, GFP_KERNEL);
2000 	if (!dev->bulk_in_buffer) {
2001 		retval = -ENOMEM;
2002 		goto error;
2003 	}
2004 	dev->bulk_in_urb = usb_alloc_urb(0, GFP_KERNEL);
2005 	if (!dev->bulk_in_urb) {
2006 		retval = -ENOMEM;
2007 		goto error;
2008 	}
2009 
2010 	dev->bulk_out_endpoint_addr = bulk_out->bEndpointAddress;
2011 
2012 	/* save our data pointer in this interface device */
2013 	usb_set_intfdata(interface, dev);
2014 
2015 	/* let the world know */
2016 
2017 	device_path = kobject_get_path(&dev->udev->dev.kobj, GFP_KERNEL);
2018 	pr_alert("%s:%s - New lpvo_usb_device -> bus: %d  dev: %d  path: %s\n", NAME, __func__,
2019 		 dev->udev->bus->busnum, dev->udev->devnum, device_path);
2020 	kfree(device_path);
2021 
2022 #if USER_DEVICE
2023 	/* we can register the device now, as it is ready */
2024 	retval = usb_register_dev(interface, &skel_class);
2025 	if (retval) {
2026 		/* something prevented us from registering this driver */
2027 		dev_err(&interface->dev,
2028 			"Not able to get a minor for this device.\n");
2029 		usb_set_intfdata(interface, NULL);
2030 		goto error;
2031 	}
2032 
2033 	/* let the user know what node this device is now attached to */
2034 	dev_info(&interface->dev,
2035 		 "lpvo_usb_gpib device now attached to lpvo_raw%d",
2036 		 interface->minor);
2037 #endif
2038 
2039 	write_latency_timer(dev->udev);     /* adjust the latency timer */
2040 
2041 	usb_gpib_init_module(interface);    /* last, init the lpvo for this minor */
2042 
2043 	return 0;
2044 
2045 error:
2046 	/* this frees allocated memory */
2047 	kref_put(&dev->kref, skel_delete);
2048 
2049 	return retval;
2050 }
2051 
skel_disconnect(struct usb_interface * interface)2052 static void skel_disconnect(struct usb_interface *interface)
2053 {
2054 	struct usb_skel *dev;
2055 	int minor = interface->minor;
2056 
2057 	usb_gpib_exit_module(minor);	  /* first, disactivate the lpvo */
2058 
2059 	dev = usb_get_intfdata(interface);
2060 	usb_set_intfdata(interface, NULL);
2061 
2062 #if USER_DEVICE
2063 	/* give back our minor */
2064 	usb_deregister_dev(interface, &skel_class);
2065 #endif
2066 
2067 	/* prevent more I/O from starting */
2068 	mutex_lock(&dev->io_mutex);
2069 	dev->interface = NULL;
2070 	mutex_unlock(&dev->io_mutex);
2071 
2072 	usb_kill_anchored_urbs(&dev->submitted);
2073 
2074 	/* decrement our usage count */
2075 	kref_put(&dev->kref, skel_delete);
2076 
2077 	dev_info(&interface->dev, "USB lpvo_raw #%d now disconnected", minor);
2078 }
2079 
skel_draw_down(struct usb_skel * dev)2080 static void skel_draw_down(struct usb_skel *dev)
2081 {
2082 	int time;
2083 
2084 	time = usb_wait_anchor_empty_timeout(&dev->submitted, 1000);
2085 	if (!time)
2086 		usb_kill_anchored_urbs(&dev->submitted);
2087 	usb_kill_urb(dev->bulk_in_urb);
2088 }
2089 
skel_suspend(struct usb_interface * intf,pm_message_t message)2090 static int skel_suspend(struct usb_interface *intf, pm_message_t message)
2091 {
2092 	struct usb_skel *dev = usb_get_intfdata(intf);
2093 
2094 	if (!dev)
2095 		return 0;
2096 	skel_draw_down(dev);
2097 	return 0;
2098 }
2099 
skel_resume(struct usb_interface * intf)2100 static int skel_resume(struct usb_interface *intf)
2101 {
2102 	return 0;
2103 }
2104 
skel_pre_reset(struct usb_interface * intf)2105 static int skel_pre_reset(struct usb_interface *intf)
2106 {
2107 	struct usb_skel *dev = usb_get_intfdata(intf);
2108 
2109 	mutex_lock(&dev->io_mutex);
2110 	skel_draw_down(dev);
2111 
2112 	return 0;
2113 }
2114 
skel_post_reset(struct usb_interface * intf)2115 static int skel_post_reset(struct usb_interface *intf)
2116 {
2117 	struct usb_skel *dev = usb_get_intfdata(intf);
2118 
2119 	/* we are sure no URBs are active - no locking needed */
2120 	dev->errors = -EPIPE;
2121 	mutex_unlock(&dev->io_mutex);
2122 
2123 	return 0;
2124 }
2125 
2126 static struct usb_driver skel_driver = {
2127 	.name =			NAME,
2128 	.probe =		skel_probe,
2129 	.disconnect =		skel_disconnect,
2130 	.suspend =		skel_suspend,
2131 	.resume =		skel_resume,
2132 	.pre_reset =		skel_pre_reset,
2133 	.post_reset =		skel_post_reset,
2134 	.id_table =		skel_table,
2135 	.supports_autosuspend = 1,
2136 };
2137 
2138 module_usb_driver(skel_driver);
2139