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