Path: blob/master/drivers/gpib/lpvo_usb_gpib/lpvo_usb_gpib.c
38186 views
// SPDX-License-Identifier: GPL-2.012/***************************************************************************3* This code has been developed at the Department of Physics (University *4* of Florence, Italy) to support in linux-gpib the open usb-gpib adapter *5* implemented at the University of Ljubljana (lpvo.fe.uni-lj.si/gpib) *6* *7* copyright : (C) 2011 Marcello Carla' *8***************************************************************************/910#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt11#define dev_fmt pr_fmt12#define NAME KBUILD_MODNAME1314/* base module includes */1516#include <linux/module.h>17#include <linux/sched.h>18#include <linux/init.h>19#include <linux/kernel.h>20#include <linux/tty.h>21#include <linux/types.h>22#include <linux/slab.h>23#include <linux/mm.h>24#include <linux/vmalloc.h>25#include <linux/spinlock.h>26#include <linux/file.h>27#include <linux/timer.h>28#include <linux/delay.h>29#include <linux/sched/signal.h>30#include <linux/usb.h>3132#include "gpibP.h"3334MODULE_LICENSE("GPL");35MODULE_DESCRIPTION("GPIB driver for LPVO usb devices");3637/*38* Table of devices that work with this driver.39*40* Currently, only one device is known to be used in the41* lpvo_usb_gpib adapter (FTDI 0403:6001).42* If your adapter uses a different chip, insert a line43* in the following table with proper <Vendor-id>, <Product-id>.44*45* To have your chip automatically handled by the driver,46* update files "/usr/local/etc/modprobe.d/lpvo_usb_gpib.conf"47* and /usr/local/etc/udev/rules.d/99-lpvo_usb_gpib.rules.48*49*/5051static const struct usb_device_id skel_table[] = {52{ USB_DEVICE(0x0403, 0x6001) },53{ } /* Terminating entry */54};55MODULE_DEVICE_TABLE(usb, skel_table);5657/*58* *** Diagnostics and Debug ***59* To enable the diagnostic and debug messages either compile with DEBUG set60* or control via the dynamic debug mechanisms.61* The module parameter "debug" controls the sending of debug messages to62* syslog. By default it is set to 063* debug = 0: only attach/detach messages are sent64* 1: every action is logged65* 2: extended logging; each single exchanged byte is documented66* (about twice the log volume of [1])67* To switch debug level:68* At module loading: modprobe lpvo_usb_gpib debug={0,1,2}69* On the fly: echo {0,1,2} > /sys/modules/lpvo_usb_gpib/parameters/debug70*/7172static int debug;73module_param(debug, int, 0644);7475#define DIA_LOG(level, format, ...) \76do { if (debug >= (level)) \77dev_dbg(board->gpib_dev, format, ## __VA_ARGS__); } \78while (0)7980#define WQT wait_queue_entry_t81#define WQH head82#define WQE entry8384/* standard and extended command sets of the usb-gpib adapter */8586#define USB_GPIB_ON "\nIB\n"87#define USB_GPIB_OFF "\nIBO\n"88#define USB_GPIB_IBm0 "\nIBm0\n" /* do not assert REN with IFC */89#define USB_GPIB_IBm1 "\nIBm1\n" /* assert REN with IFC */90#define USB_GPIB_IBCL "\nIBZ\n"91#define USB_GPIB_STATUS "\nIBS\n"92#define USB_GPIB_READ "\nIB?\n"93#define USB_GPIB_READ_1 "\nIBB\n"94#define USB_GPIB_EOI "\nIBe0\n"95#define USB_GPIB_FTMO "\nIBf0\n" /* disable first byte timeout */96#define USB_GPIB_TTMOZ "\nIBt0\n" /* disable byte timeout */9798/* incomplete commands */99100#define USB_GPIB_BTMO "\nIBt" /* set byte timeout */101#define USB_GPIB_TTMO "\nIBT" /* set total timeout */102103#define USB_GPIB_DEBUG_ON "\nIBDE\xAA\n"104#define USB_GPIB_SET_LISTEN "\nIBDT0\n"105#define USB_GPIB_SET_TALK "\nIBDT1\n"106#define USB_GPIB_SET_LINES "\nIBDC.\n"107#define USB_GPIB_SET_DATA "\nIBDM.\n"108#define USB_GPIB_READ_LINES "\nIBD?C\n"109#define USB_GPIB_READ_DATA "\nIBD?M\n"110#define USB_GPIB_READ_BUS "\nIBD??\n"111112/* command sequences */113114#define USB_GPIB_UNTALK "\nIBC_\n"115#define USB_GPIB_UNLISTEN "\nIBC?\n"116117/* special characters used by the adapter */118119#define DLE ('\020')120#define STX ('\02')121#define ETX ('\03')122#define ACK ('\06')123#define NODATA ('\03')124#define NODAV ('\011')125126#define IB_BUS_REN 0x01127#define IB_BUS_IFC 0x02128#define IB_BUS_NDAC 0x04129#define IB_BUS_NRFD 0x08130#define IB_BUS_DAV 0x10131#define IB_BUS_EOI 0x20132#define IB_BUS_ATN 0x40133#define IB_BUS_SRQ 0x80134135#define INBUF_SIZE 128136137struct char_buf { /* used by one_char() routine */138char *inbuf;139int last;140int nchar;141};142143struct usb_gpib_priv { /* private data to the device */144u8 eos; /* eos character */145short eos_flags; /* eos mode */146int timeout; /* current value for timeout */147void *dev; /* the usb device private data structure */148};149150#define GPIB_DEV (((struct usb_gpib_priv *)board->private_data)->dev)151152static void show_status(struct gpib_board *board)153{154DIA_LOG(2, "# - buffer_length %d\n", board->buffer_length);155DIA_LOG(2, "# - status %lx\n", board->status);156DIA_LOG(2, "# - use_count %d\n", board->use_count);157DIA_LOG(2, "# - pad %x\n", board->pad);158DIA_LOG(2, "# - sad %x\n", board->sad);159DIA_LOG(2, "# - timeout %d\n", board->usec_timeout);160DIA_LOG(2, "# - ppc %d\n", board->parallel_poll_configuration);161DIA_LOG(2, "# - t1delay %d\n", board->t1_nano_sec);162DIA_LOG(2, "# - online %d\n", board->online);163DIA_LOG(2, "# - autopoll %d\n", board->autospollers);164DIA_LOG(2, "# - autopoll task %p\n", board->autospoll_task);165DIA_LOG(2, "# - minor %d\n", board->minor);166DIA_LOG(2, "# - master %d\n", board->master);167DIA_LOG(2, "# - list %d\n", board->ist);168}169170/*171* GLOBAL VARIABLES: required for172* pairing among gpib minor and usb minor.173* MAX_DEV is the max number of usb-gpib adapters; free174* to change as you like, but no more than 32175*/176177#define MAX_DEV 8178static struct usb_interface *lpvo_usb_interfaces[MAX_DEV]; /* registered interfaces */179static int usb_minors[MAX_DEV]; /* usb minors */180static int assigned_usb_minors; /* mask of filled slots */181static struct mutex minors_lock; /* operations on usb_minors are to be protected */182183/*184* usb-skeleton prototypes185*/186187struct usb_skel;188static ssize_t skel_do_write(struct usb_skel *, const char *, size_t);189static ssize_t skel_do_read(struct usb_skel *, char *, size_t);190static int skel_do_open(struct gpib_board *, int);191static int skel_do_release(struct gpib_board *);192193/*194* usec_diff : take difference in MICROsec between two 'timespec'195* (unix time in sec and NANOsec)196*/197198static inline int usec_diff(struct timespec64 *a, struct timespec64 *b)199{200return ((a->tv_sec - b->tv_sec) * 1000000 +201(a->tv_nsec - b->tv_nsec) / 1000);202}203204/*205* *** these routines are specific to the usb-gpib adapter ***206*/207208/**209* write_loop() - Send a byte sequence to the adapter210*211* @dev: the private device structure212* @msg: the byte sequence.213* @leng: the byte sequence length.214*215*/216217static int write_loop(void *dev, char *msg, int leng)218{219return skel_do_write(dev, msg, leng);220}221222/**223* send_command() - Send a byte sequence and return a single byte reply.224*225* @board: the gpib_board_struct data area for this gpib interface226* @msg: the byte sequence.227* @leng: the byte sequence length; can be given as zero and is228* computed automatically, but if 'msg' contains a zero byte,229* it has to be given explicitly.230*/231232static int send_command(struct gpib_board *board, char *msg, int leng)233{234char buffer[64];235int nchar;236int retval;237struct timespec64 before, after;238239ktime_get_real_ts64 (&before);240241if (!leng)242leng = strlen(msg);243retval = write_loop(GPIB_DEV, msg, leng);244if (retval < 0)245return retval;246247nchar = skel_do_read(GPIB_DEV, buffer, 64);248249if (nchar < 0) {250dev_err(board->gpib_dev, " return from read: %d\n", nchar);251return nchar;252} else if (nchar != 1) {253dev_err(board->gpib_dev, " Irregular reply to command: %s\n", msg);254return -EIO;255}256ktime_get_real_ts64 (&after);257258DIA_LOG(1, "Sent %d - done %d us.\n", leng, usec_diff(&after, &before));259260return buffer[0] & 0xff;261}262263/*264* set_control_line() - Set the value of a single gpib control line265*266* @board: the gpib_board_struct data area for this gpib interface267* @line: line mask268* @value: line new value (0/1)269*/270271static int set_control_line(struct gpib_board *board, int line, int value)272{273char msg[] = USB_GPIB_SET_LINES;274int retval;275int leng = strlen(msg);276277DIA_LOG(1, "setting line %x to %x\n", line, value);278279retval = send_command(board, USB_GPIB_READ_LINES, 0);280281DIA_LOG(1, "old line values: %x\n", retval);282283if (retval == -EIO)284return retval;285286msg[leng - 2] = value ? (retval & ~line) : retval | line;287288retval = send_command(board, msg, 0);289290DIA_LOG(1, "operation result: %x\n", retval);291292return retval;293}294295/*296* one_char() - read one single byte from input buffer297*298* @board: the gpib_board_struct data area for this gpib interface299* @char_buf: the routine private data structure300*/301302static int one_char(struct gpib_board *board, struct char_buf *b)303{304struct timespec64 before, after;305306if (b->nchar) {307DIA_LOG(2, "-> %x\n", b->inbuf[b->last - b->nchar]);308return b->inbuf[b->last - b->nchar--];309}310ktime_get_real_ts64 (&before);311b->nchar = skel_do_read(GPIB_DEV, b->inbuf, INBUF_SIZE);312b->last = b->nchar;313ktime_get_real_ts64 (&after);314315DIA_LOG(2, "read %d bytes in %d usec\n",316b->nchar, usec_diff(&after, &before));317318if (b->nchar > 0) {319DIA_LOG(2, "--> %x\n", b->inbuf[b->last - b->nchar]);320return b->inbuf[b->last - b->nchar--];321}322return -EIO;323}324325/**326* set_timeout() - set single byte / total timeouts on the adapter327*328* @board: the gpib_board_struct data area for this gpib interface329*330* For sake of speed, the operation is performed only if it331* modifies the current (saved) value. Minimum allowed timeout332* is 30 ms (T30ms -> 8); timeout disable (TNONE -> 0) currently333* not supported.334*/335336static void set_timeout(struct gpib_board *board)337{338int n, val;339char command[sizeof(USB_GPIB_TTMO) + 6];340struct usb_gpib_priv *data = board->private_data;341342if (data->timeout == board->usec_timeout)343return;344345n = (board->usec_timeout + 32767) / 32768;346if (n < 2)347n = 2;348349DIA_LOG(1, "Set timeout to %d us -> %d\n", board->usec_timeout, n);350351sprintf(command, "%s%d\n", USB_GPIB_BTMO, n > 255 ? 255 : n);352val = send_command(board, command, 0);353354if (val == ACK) {355if (n > 65535)356n = 65535;357sprintf(command, "%s%d\n", USB_GPIB_TTMO, n);358val = send_command(board, command, 0);359}360361if (val != ACK)362dev_err(board->gpib_dev, "error in timeout set: <%s>\n", command);363else364data->timeout = board->usec_timeout;365}366367/*368* now the standard interface functions - attach and detach369*/370371/**372* usb_gpib_attach() - activate the usb-gpib converter board373*374* @board: the gpib_board_struct data area for this gpib interface375* @config: firmware data, if any (from gpib_config -I <file>)376*377* The channel name is ttyUSBn, with n=0 by default. Other values for n378* passed with gpib_config -b <n>.379*380* In this routine I trust that when an error code is returned381* detach() will be called. Always.382*/383384static int usb_gpib_attach(struct gpib_board *board, const struct gpib_board_config *config)385{386int retval, j;387u32 base = config->ibbase;388char *device_path;389int match;390struct usb_device *udev;391392DIA_LOG(0, "Board %p -t %s -m %d -a %p -u %d -l %d -b %d\n",393board, board->interface->name, board->minor, config->device_path,394config->pci_bus, config->pci_slot, base);395396board->private_data = NULL; /* to be sure - we can detach before setting */397398/* identify device to be attached */399400mutex_lock(&minors_lock);401402if (config->device_path) {403/* if config->device_path given, try that first */404for (j = 0 ; j < MAX_DEV ; j++) {405if ((assigned_usb_minors & 1 << j) == 0)406continue;407udev = usb_get_dev(interface_to_usbdev(lpvo_usb_interfaces[j]));408device_path = kobject_get_path(&udev->dev.kobj, GFP_KERNEL);409match = gpib_match_device_path(&lpvo_usb_interfaces[j]->dev,410config->device_path);411DIA_LOG(1, "dev. %d: minor %d path: %s --> %d\n", j,412lpvo_usb_interfaces[j]->minor, device_path, match);413kfree(device_path);414if (match)415break;416}417} else if (config->pci_bus != -1 && config->pci_slot != -1) {418/* second: look for bus and slot */419for (j = 0 ; j < MAX_DEV ; j++) {420if ((assigned_usb_minors & 1 << j) == 0)421continue;422udev = usb_get_dev(interface_to_usbdev(lpvo_usb_interfaces[j]));423DIA_LOG(1, "dev. %d: bus %d -> %d dev: %d -> %d\n", j,424udev->bus->busnum, config->pci_bus, udev->devnum, config->pci_slot);425if (config->pci_bus == udev->bus->busnum &&426config->pci_slot == udev->devnum)427break;428}429} else { /* last chance: usb_minor, given as ibbase */430for (j = 0 ; j < MAX_DEV ; j++) {431if (usb_minors[j] == base && assigned_usb_minors & 1 << j)432break;433}434}435mutex_unlock(&minors_lock);436437if (j == MAX_DEV) {438dev_err(board->gpib_dev, "Requested device is not registered.\n");439return -EIO;440}441442board->private_data = kzalloc(sizeof(struct usb_gpib_priv), GFP_KERNEL);443if (!board->private_data)444return -ENOMEM;445446retval = skel_do_open(board, usb_minors[j]);447448DIA_LOG(1, "Skel open: %d\n", retval);449450if (retval) {451dev_err(board->gpib_dev, "skel open failed.\n");452kfree(board->private_data);453board->private_data = NULL;454return -ENODEV;455}456457show_status(board);458459retval = send_command(board, USB_GPIB_ON, 0);460DIA_LOG(1, "USB_GPIB_ON returns %x\n", retval);461if (retval != ACK)462return -EIO;463464/*465* We must setup debug mode because we need the extended instruction466* set to cope with the Core (gpib_common) point of view467*/468469retval = send_command(board, USB_GPIB_DEBUG_ON, 0);470DIA_LOG(1, "USB_GPIB_DEBUG_ON returns %x\n", retval);471if (retval != ACK)472return -EIO;473474/*475* We must keep REN off after an IFC because so it is476* assumed by the Core477*/478479retval = send_command(board, USB_GPIB_IBm0, 0);480DIA_LOG(1, "USB_GPIB_IBm0 returns %x\n", retval);481if (retval != ACK)482return -EIO;483484retval = set_control_line(board, IB_BUS_REN, 0);485if (retval != ACK)486return -EIO;487488retval = send_command(board, USB_GPIB_FTMO, 0);489DIA_LOG(1, "USB_GPIB_FTMO returns %x\n", retval);490if (retval != ACK)491return -EIO;492493show_status(board);494DIA_LOG(0, "attached\n");495return 0;496}497498/**499* usb_gpib_detach() - deactivate the usb-gpib converter board500*501* @board: the gpib_board data area for this gpib interface502*503*/504505static void usb_gpib_detach(struct gpib_board *board)506{507int retval;508509show_status(board);510511DIA_LOG(0, "detaching\n");512513if (board->private_data) {514if (GPIB_DEV) {515write_loop(GPIB_DEV, USB_GPIB_OFF, strlen(USB_GPIB_OFF));516msleep(100);517DIA_LOG(1, "%s", "GPIB off\n");518retval = skel_do_release(board);519DIA_LOG(1, "skel release -> %d\n", retval);520}521kfree(board->private_data);522board->private_data = NULL;523}524525DIA_LOG(0, "detached\n");526}527528/*529* Other functions follow in alphabetical order530*/531/* command */532static int usb_gpib_command(struct gpib_board *board,533u8 *buffer,534size_t length,535size_t *bytes_written)536{537int i, retval;538char command[6] = "IBc.\n";539540DIA_LOG(1, "enter %p\n", board);541542set_timeout(board);543544*bytes_written = 0;545for (i = 0 ; i < length ; i++) {546command[3] = buffer[i];547retval = send_command(board, command, 5);548DIA_LOG(2, "%d ==> %x %x\n", i, buffer[i], retval);549if (retval != 0x06)550return retval;551++(*bytes_written);552}553return 0;554}555556/**557* usb_gpib_disable_eos() - Disable END on eos byte (END on EOI only)558*559* @board: the gpib_board data area for this gpib interface560*561* With the lpvo adapter eos can only be handled via software.562* Cannot do nothing here, but remember for future use.563*/564565static void usb_gpib_disable_eos(struct gpib_board *board)566{567((struct usb_gpib_priv *)board->private_data)->eos_flags &= ~REOS;568DIA_LOG(1, "done: %x\n",569((struct usb_gpib_priv *)board->private_data)->eos_flags);570}571572/**573* usb_gpib_enable_eos() - Enable END for reads when eos byte is received.574*575* @board: the gpib_board data area for this gpib interface576* @eos_byte: the 'eos' byte577* @compare_8_bits: if zero ignore eigthth bit when comparing578*579*/580581static int usb_gpib_enable_eos(struct gpib_board *board,582u8 eos_byte,583int compare_8_bits)584{585struct usb_gpib_priv *pd = (struct usb_gpib_priv *)board->private_data;586587DIA_LOG(1, "enter with %x\n", eos_byte);588pd->eos = eos_byte;589pd->eos_flags = REOS;590if (compare_8_bits)591pd->eos_flags |= BIN;592return 0;593}594595/**596* usb_gpib_go_to_standby() - De-assert ATN597*598* @board: the gpib_board data area for this gpib interface599*/600601static int usb_gpib_go_to_standby(struct gpib_board *board)602{603int retval = set_control_line(board, IB_BUS_ATN, 0);604605DIA_LOG(1, "done with %x\n", retval);606607if (retval == ACK)608return 0;609return -EIO;610}611612/**613* usb_gpib_interface_clear() - Assert or de-assert IFC614*615* @board: the gpib_board data area for this gpib interface616* @assert: 1: assert IFC; 0: de-assert IFC617*618* Currently on the assert request we issue the lpvo IBZ619* command that cycles IFC low for 100 usec, then we ignore620* the de-assert request.621*/622623static void usb_gpib_interface_clear(struct gpib_board *board, int assert)624{625int retval = 0;626627DIA_LOG(1, "enter with %d\n", assert);628629if (assert) {630retval = send_command(board, USB_GPIB_IBCL, 0);631632set_bit(CIC_NUM, &board->status);633}634635DIA_LOG(1, "done with %d %d\n", assert, retval);636}637638/**639* usb_gpib_line_status() - Read the status of the bus lines.640*641* @board: the gpib_board data area for this gpib interface642*643* We can read all lines.644*/645static int usb_gpib_line_status(const struct gpib_board *board)646{647int buffer;648int line_status = VALID_ALL; /* all lines will be read */649struct list_head *p, *q;650WQT *item;651unsigned long flags;652int sleep = 0;653654DIA_LOG(1, "%s\n", "request");655656/*657* if we are on the wait queue (board->wait), do not hurry658* reading status line; instead, pause a little659*/660661spin_lock_irqsave((spinlock_t *)&board->wait.lock, flags);662q = (struct list_head *)&board->wait.WQH;663list_for_each(p, q) {664item = container_of(p, WQT, WQE);665if (item->private == current) {666sleep = 20;667break;668}669/* pid is: ((struct task_struct *) item->private)->pid); */670}671spin_unlock_irqrestore((spinlock_t *)&board->wait.lock, flags);672if (sleep) {673DIA_LOG(1, "we are on the wait queue - sleep %d ms\n", sleep);674msleep(sleep);675}676677buffer = send_command((struct gpib_board *)board, USB_GPIB_STATUS, 0);678679if (buffer < 0) {680dev_err(board->gpib_dev, "line status read failed with %d\n", buffer);681return -1;682}683684if ((buffer & 0x01) == 0)685line_status |= BUS_REN;686if ((buffer & 0x02) == 0)687line_status |= BUS_IFC;688if ((buffer & 0x04) == 0)689line_status |= BUS_NDAC;690if ((buffer & 0x08) == 0)691line_status |= BUS_NRFD;692if ((buffer & 0x10) == 0)693line_status |= BUS_DAV;694if ((buffer & 0x20) == 0)695line_status |= BUS_EOI;696if ((buffer & 0x40) == 0)697line_status |= BUS_ATN;698if ((buffer & 0x80) == 0)699line_status |= BUS_SRQ;700701DIA_LOG(1, "done with %x %x\n", buffer, line_status);702703return line_status;704}705706/* parallel_poll */707708static int usb_gpib_parallel_poll(struct gpib_board *board, u8 *result)709{710/*711* request parallel poll asserting ATN | EOI;712* we suppose ATN already asserted713*/714715int retval;716717DIA_LOG(1, "enter %p\n", board);718719retval = set_control_line(board, IB_BUS_EOI, 1);720if (retval != ACK)721return -EIO;722723*result = send_command(board, USB_GPIB_READ_DATA, 0);724725DIA_LOG(1, "done with %x\n", *result);726727retval = set_control_line(board, IB_BUS_EOI, 0);728if (retval != 0x06)729return -EIO;730731return 0;732}733734/* read */735736static int usb_gpib_read(struct gpib_board *board,737u8 *buffer,738size_t length,739int *end,740size_t *bytes_read)741{742#define MAX_READ_EXCESS 16384743744struct char_buf b = {NULL, 0};745746int retval;747char c, nc;748int ic;749struct timespec64 before, after;750int read_count = MAX_READ_EXCESS;751struct usb_gpib_priv *pd = (struct usb_gpib_priv *)board->private_data;752753DIA_LOG(1, "enter %p -> %zu\n", board, length);754755*bytes_read = 0; /* by default, things go wrong */756*end = 0;757758set_timeout(board);759760/* single byte read has a special handling */761762if (length == 1) {763char inbuf[2] = {0, 0};764765/* read a single character */766767ktime_get_real_ts64 (&before);768769retval = write_loop(GPIB_DEV, USB_GPIB_READ_1, strlen(USB_GPIB_READ_1));770if (retval < 0)771return retval;772773retval = skel_do_read(GPIB_DEV, inbuf, 1);774retval += skel_do_read(GPIB_DEV, inbuf + 1, 1);775776ktime_get_real_ts64 (&after);777778DIA_LOG(1, "single read: %x %x %x in %d\n", retval,779inbuf[0], inbuf[1],780usec_diff(&after, &before));781782/* good char / last char? */783784if (retval == 2 && inbuf[1] == ACK) {785buffer[0] = inbuf[0];786*bytes_read = 1;787return 0;788}789if (retval < 2)790return -EIO;791else792return -ETIME;793}794795/* allocate buffer for multibyte read */796797b.inbuf = kmalloc(INBUF_SIZE, GFP_KERNEL);798if (!b.inbuf)799return -ENOMEM;800801/* send read command and check <DLE><STX> sequence */802803retval = write_loop(GPIB_DEV, USB_GPIB_READ, strlen(USB_GPIB_READ));804if (retval < 0)805goto read_return;806807if (one_char(board, &b) != DLE || one_char(board, &b) != STX) {808dev_err(board->gpib_dev, "wrong <DLE><STX> sequence\n");809retval = -EIO;810goto read_return;811}812813/* get data flow */814815while (1) {816ic = one_char(board, &b);817if (ic == -EIO) {818retval = -EIO;819goto read_return;820}821c = ic;822823if (c == DLE)824nc = one_char(board, &b);825if (c != DLE || nc == DLE) {826/* data byte - store into buffer */827828if (*bytes_read == length)829break; /* data overflow */830if (c == DLE)831c = nc;832buffer[(*bytes_read)++] = c;833if (c == pd->eos) {834*end = 1;835break;836}837838} else {839/* we are in the closing <DLE><ETX> sequence */840c = nc;841if (c == ETX) {842c = one_char(board, &b);843if (c == ACK) {844*end = 1;845retval = 0;846goto read_return;847} else {848dev_err(board->gpib_dev, "wrong end of message %x", c);849retval = -ETIME;850goto read_return;851}852} else {853dev_err(board->gpib_dev, "lone <DLE> in stream");854retval = -EIO;855goto read_return;856}857}858}859860/* we had a data overflow - flush excess data */861862while (read_count--) {863if (one_char(board, &b) != DLE)864continue;865c = one_char(board, &b);866if (c == DLE)867continue;868if (c == ETX) {869c = one_char(board, &b);870if (c == ACK) {871if (MAX_READ_EXCESS - read_count > 1)872dev_dbg(board->gpib_dev, "small buffer - maybe some data lost");873retval = 0;874goto read_return;875}876break;877}878}879880dev_err(board->gpib_dev, "no input end - board in odd state\n");881retval = -EIO;882883read_return:884kfree(b.inbuf);885886DIA_LOG(1, "done with byte/status: %d %x %d\n", (int)*bytes_read, retval, *end);887888if (retval == 0 || retval == -ETIME) {889if (send_command(board, USB_GPIB_UNTALK, sizeof(USB_GPIB_UNTALK)) == 0x06)890return retval;891return -EIO;892}893894return retval;895}896897/* remote_enable */898899static void usb_gpib_remote_enable(struct gpib_board *board, int enable)900{901int retval;902903retval = set_control_line(board, IB_BUS_REN, enable ? 1 : 0);904if (retval != ACK)905dev_err(board->gpib_dev, "could not set REN line: %x\n", retval);906907DIA_LOG(1, "done with %x\n", retval);908}909910/* request_system_control */911912static int usb_gpib_request_system_control(struct gpib_board *board, int request_control)913{914if (!request_control)915return -EINVAL;916917DIA_LOG(1, "done with %d -> %lx\n", request_control, board->status);918return 0;919}920921/* take_control */922/* beware: the sync flag is ignored; what is its real meaning? */923924static int usb_gpib_take_control(struct gpib_board *board, int sync)925{926int retval;927928retval = set_control_line(board, IB_BUS_ATN, 1);929930DIA_LOG(1, "done with %d %x\n", sync, retval);931932if (retval == ACK)933return 0;934return -EIO;935}936937/* update_status */938939static unsigned int usb_gpib_update_status(struct gpib_board *board,940unsigned int clear_mask)941{942/* There is nothing we can do here, I guess */943944board->status &= ~clear_mask;945946DIA_LOG(1, "done with %x %lx\n", clear_mask, board->status);947948return board->status;949}950951/* write */952/* beware: DLE characters are not escaped - can only send ASCII data */953954static int usb_gpib_write(struct gpib_board *board,955u8 *buffer,956size_t length,957int send_eoi,958size_t *bytes_written)959{960int retval;961char *msg;962963DIA_LOG(1, "enter %p -> %zu\n", board, length);964965set_timeout(board);966967msg = kmalloc(length + 8, GFP_KERNEL);968if (!msg)969return -ENOMEM;970971memcpy(msg, "\nIB\020\002", 5);972memcpy(msg + 5, buffer, length);973memcpy(msg + 5 + length, "\020\003\n", 3);974975retval = send_command(board, msg, length + 8);976kfree(msg);977978DIA_LOG(1, "<%.*s> -> %x\n", (int)length, buffer, retval);979980if (retval != ACK)981return -EPIPE;982983*bytes_written = length;984985if (send_command(board, USB_GPIB_UNLISTEN, sizeof(USB_GPIB_UNLISTEN)) != 0x06)986return -EPIPE;987988return length;989}990991/*992* *** following functions not implemented yet ***993*/994995/* parallel_poll configure */996997static void usb_gpib_parallel_poll_configure(struct gpib_board *board,998u8 configuration)999{1000}10011002/* parallel_poll_response */10031004static void usb_gpib_parallel_poll_response(struct gpib_board *board, int ist)1005{1006}10071008/* primary_address */10091010static int usb_gpib_primary_address(struct gpib_board *board, unsigned int address)1011{1012return 0;1013}10141015/* return_to_local */10161017static void usb_gpib_return_to_local(struct gpib_board *board)1018{1019}10201021/* secondary_address */10221023static int usb_gpib_secondary_address(struct gpib_board *board,1024unsigned int address,1025int enable)1026{1027return 0;1028}10291030/* serial_poll_response */10311032static void usb_gpib_serial_poll_response(struct gpib_board *board, u8 status)1033{1034}10351036/* serial_poll_status */10371038static u8 usb_gpib_serial_poll_status(struct gpib_board *board)1039{1040return 0;1041}10421043/* t1_delay */10441045static int usb_gpib_t1_delay(struct gpib_board *board, unsigned int nano_sec)1046{1047return 0;1048}10491050/*1051* *** module dispatch table and init/exit functions ***1052*/10531054static struct gpib_interface usb_gpib_interface = {1055.name = NAME,1056.attach = usb_gpib_attach,1057.detach = usb_gpib_detach,1058.read = usb_gpib_read,1059.write = usb_gpib_write,1060.command = usb_gpib_command,1061.take_control = usb_gpib_take_control,1062.go_to_standby = usb_gpib_go_to_standby,1063.request_system_control = usb_gpib_request_system_control,1064.interface_clear = usb_gpib_interface_clear,1065.remote_enable = usb_gpib_remote_enable,1066.enable_eos = usb_gpib_enable_eos,1067.disable_eos = usb_gpib_disable_eos,1068.parallel_poll = usb_gpib_parallel_poll,1069.parallel_poll_configure = usb_gpib_parallel_poll_configure,1070.parallel_poll_response = usb_gpib_parallel_poll_response,1071.local_parallel_poll_mode = NULL, // XXX1072.line_status = usb_gpib_line_status,1073.update_status = usb_gpib_update_status,1074.primary_address = usb_gpib_primary_address,1075.secondary_address = usb_gpib_secondary_address,1076.serial_poll_response = usb_gpib_serial_poll_response,1077.serial_poll_status = usb_gpib_serial_poll_status,1078.t1_delay = usb_gpib_t1_delay,1079.return_to_local = usb_gpib_return_to_local,1080.skip_check_for_command_acceptors = 11081};10821083/*1084* usb_gpib_init_module(), usb_gpib_exit_module()1085*1086* This functions are called every time a new device is detected1087* and registered or is removed and unregistered.1088* We must take note of created and destroyed usb minors to be used1089* when usb_gpib_attach() and usb_gpib_detach() will be called on1090* request by gpib_config.1091*/10921093static int usb_gpib_init_module(struct usb_interface *interface)1094{1095int j, mask, rv;10961097rv = mutex_lock_interruptible(&minors_lock);1098if (rv < 0)1099return rv;11001101if (!assigned_usb_minors) {1102rv = gpib_register_driver(&usb_gpib_interface, THIS_MODULE);1103if (rv) {1104pr_err("gpib_register_driver failed: error = %d\n", rv);1105goto exit;1106}1107} else {1108/*1109* check if minor is already registered - maybe useless, but if1110* it happens the code is inconsistent somewhere1111*/11121113for (j = 0 ; j < MAX_DEV ; j++) {1114if (usb_minors[j] == interface->minor && assigned_usb_minors & 1 << j) {1115pr_err("CODE BUG: USB minor %d registered at %d.\n",1116interface->minor, j);1117rv = -1;1118goto exit;1119}1120}1121}11221123/* find a free slot */11241125for (j = 0 ; j < MAX_DEV ; j++) {1126mask = 1 << j;1127if ((assigned_usb_minors & mask) == 0) {1128usb_minors[j] = interface->minor;1129lpvo_usb_interfaces[j] = interface;1130assigned_usb_minors |= mask;1131rv = 0;1132goto exit;1133}1134}1135pr_err("No slot available for interface %p minor %d\n", interface, interface->minor);1136rv = -1;11371138exit:1139mutex_unlock(&minors_lock);1140return rv;1141}11421143static void usb_gpib_exit_module(int minor)1144{1145int j;11461147mutex_lock(&minors_lock);1148for (j = 0 ; j < MAX_DEV ; j++) {1149if (usb_minors[j] == minor && assigned_usb_minors & 1 << j) {1150assigned_usb_minors &= ~(1 << j);1151usb_minors[j] = -1;1152if (assigned_usb_minors == 0)1153gpib_unregister_driver(&usb_gpib_interface);1154goto exit;1155}1156}1157pr_err("CODE BUG: USB minor %d not found.\n", minor);11581159exit:1160mutex_unlock(&minors_lock);1161}11621163/*1164* Default latency time (16 msec) is too long.1165* We must use 1 msec (best); anyhow, no more than 5 msec.1166*1167* Defines and function taken and modified from the kernel tree1168* (see ftdi_sio.h and ftdi_sio.c).1169*/11701171#define FTDI_SIO_SET_LATENCY_TIMER 9 /* Set the latency timer */1172#define FTDI_SIO_SET_LATENCY_TIMER_REQUEST FTDI_SIO_SET_LATENCY_TIMER1173#define FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE 0x401174#define WDR_TIMEOUT 5000 /* default urb timeout */1175#define WDR_SHORT_TIMEOUT 1000 /* shorter urb timeout */11761177#define LATENCY_TIMER 1 /* use a small latency timer: 1 ... 5 msec */1178#define LATENCY_CHANNEL 0 /* channel selection in multichannel devices */1179static int write_latency_timer(struct usb_device *udev)1180{1181int rv = usb_control_msg(udev,1182usb_sndctrlpipe(udev, 0),1183FTDI_SIO_SET_LATENCY_TIMER_REQUEST,1184FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE,1185LATENCY_TIMER, LATENCY_CHANNEL,1186NULL, 0, WDR_TIMEOUT);1187if (rv < 0)1188dev_err(&udev->dev, "Unable to write latency timer: %i\n", rv);1189return rv;1190}11911192/*****************************************************************************1193* *1194* The following code is a modified version of the USB Skeleton driver *1195* written by Greg Kroah-Hartman and available in the kernel tree. *1196* *1197* Functions skel_open() and skel_release() have been rewritten and named *1198* skel_do_open() and skel_do_release() to process the attach and detach *1199* requests coming from gpib_config. *1200* *1201* Functions skel_read() and skel_write() have been split into a *1202* skel_do_read() and skel_do_write(), that cover the kernel stuff of read *1203* and write operations, and the original skel_read() and skel_write(), *1204* that handle communication with user space and call their _do_ companion. *1205* *1206* Only the _do_ versions are used by the lpvo_usb_gpib driver; other ones *1207* can be (optionally) maintained in the compilation to have direct access *1208* to a gpib controller for debug and diagnostics. *1209* *1210* To avoid collisions in names, devices in user space have been renamed *1211* lpvo_raw1, lpvo_raw2 .... and the usb driver has been renamed with the *1212* gpib module name. *1213* *1214*****************************************************************************/12151216/*1217* USB Skeleton driver - 2.21218*1219* Copyright (C) 2001-2004 Greg Kroah-Hartman ([email protected])1220*1221* This driver is based on the 2.6.3 version of drivers/usb/usb-skeleton.c1222* but has been rewritten to be easier to read and use.1223*/12241225#include <linux/errno.h>1226#include <linux/kref.h>1227#include <linux/uaccess.h>1228#include <linux/mutex.h>12291230/* Get a minor range for your devices from the usb maintainer */1231#define USB_SKEL_MINOR_BASE 19212321233/* private defines */12341235#define MAX_TRANSFER (PAGE_SIZE - 512)1236/*1237* MAX_TRANSFER is chosen so that the VM is not stressed by1238* allocations > PAGE_SIZE and the number of packets in a page1239* is an integer 512 is the largest possible packet on EHCI1240*/12411242#define WRITES_IN_FLIGHT 1 /* we do not want more than one pending write */1243#define USER_DEVICE 1 /* compile for device(s) in user space */12441245/* Structure to hold all of our device specific stuff */1246struct usb_skel {1247struct usb_device *udev; /* the usb device for this device */1248struct usb_interface *interface; /* the interface for this device */1249struct semaphore limit_sem; /* limiting the number of writes in progress */1250struct usb_anchor submitted; /* in case need to retract our submissions */1251struct urb *bulk_in_urb; /* the urb to read data with */1252unsigned char *bulk_in_buffer; /* the buffer to receive data */1253size_t bulk_in_size; /* the size of the receive buffer */1254size_t bulk_in_filled; /* number of bytes in the buffer */1255size_t bulk_in_copied; /* already copied to user space */1256__u8 bulk_in_endpoint_addr; /* the address of the bulk in endpoint */1257__u8 bulk_out_endpoint_addr; /* the address of the bulk out endpoint */1258int errors; /* the last request tanked */1259bool ongoing_read; /* a read is going on */1260spinlock_t err_lock; /* lock for errors */1261struct kref kref;1262struct mutex io_mutex; /* synchronize I/O with disconnect */1263wait_queue_head_t bulk_in_wait; /* to wait for an ongoing read */1264};12651266#define to_skel_dev(d) container_of(d, struct usb_skel, kref)12671268static struct usb_driver skel_driver;1269static void skel_draw_down(struct usb_skel *dev);12701271static void skel_delete(struct kref *kref)1272{1273struct usb_skel *dev = to_skel_dev(kref);12741275usb_free_urb(dev->bulk_in_urb);1276usb_put_dev(dev->udev);1277kfree(dev->bulk_in_buffer);1278kfree(dev);1279}12801281/*1282* skel_do_open() - to be called by usb_gpib_attach1283*/12841285static int skel_do_open(struct gpib_board *board, int subminor)1286{1287struct usb_skel *dev;1288struct usb_interface *interface;1289int retval = 0;12901291interface = usb_find_interface(&skel_driver, subminor);1292if (!interface) {1293dev_err(board->gpib_dev, "can't find device for minor %d\n", subminor);1294retval = -ENODEV;1295goto exit;1296}12971298dev = usb_get_intfdata(interface);1299if (!dev) {1300retval = -ENODEV;1301goto exit;1302}13031304retval = usb_autopm_get_interface(interface);1305if (retval)1306goto exit;13071308/* increment our usage count for the device */1309kref_get(&dev->kref);13101311/* save our object in the file's private structure */1312GPIB_DEV = dev;13131314exit:1315return retval;1316}13171318/*1319* skel_do_release() - to be called by usb_gpib_detach1320*/13211322static int skel_do_release(struct gpib_board *board)1323{1324struct usb_skel *dev;13251326dev = GPIB_DEV;1327if (!dev)1328return -ENODEV;13291330/* allow the device to be autosuspended */1331mutex_lock(&dev->io_mutex);1332if (dev->interface)1333usb_autopm_put_interface(dev->interface);1334mutex_unlock(&dev->io_mutex);13351336/* decrement the count on our device */1337kref_put(&dev->kref, skel_delete);1338return 0;1339}13401341/*1342* read functions1343*/13441345static void skel_read_bulk_callback(struct urb *urb)1346{1347struct usb_skel *dev;1348unsigned long flags;13491350dev = urb->context;13511352spin_lock_irqsave(&dev->err_lock, flags);1353/* sync/async unlink faults aren't errors */1354if (urb->status) {1355if (!(urb->status == -ENOENT ||1356urb->status == -ECONNRESET ||1357urb->status == -ESHUTDOWN))1358dev_err(&dev->interface->dev, "nonzero read bulk status received: %d\n",1359urb->status);13601361dev->errors = urb->status;1362} else {1363dev->bulk_in_filled = urb->actual_length;1364}1365dev->ongoing_read = 0;1366spin_unlock_irqrestore(&dev->err_lock, flags);13671368wake_up_interruptible(&dev->bulk_in_wait);1369}13701371static int skel_do_read_io(struct usb_skel *dev, size_t count)1372{1373int rv;13741375/* prepare a read */1376usb_fill_bulk_urb(dev->bulk_in_urb,1377dev->udev,1378usb_rcvbulkpipe(dev->udev,1379dev->bulk_in_endpoint_addr),1380dev->bulk_in_buffer,1381min(dev->bulk_in_size, count),1382skel_read_bulk_callback,1383dev);1384/* tell everybody to leave the URB alone */1385spin_lock_irq(&dev->err_lock);1386dev->ongoing_read = 1;1387spin_unlock_irq(&dev->err_lock);13881389/* submit bulk in urb, which means no data to deliver */1390dev->bulk_in_filled = 0;1391dev->bulk_in_copied = 0;13921393/* do it */1394rv = usb_submit_urb(dev->bulk_in_urb, GFP_KERNEL);1395if (rv < 0) {1396dev_err(&dev->interface->dev, "failed submitting read urb, error %d\n", rv);1397rv = (rv == -ENOMEM) ? rv : -EIO;1398spin_lock_irq(&dev->err_lock);1399dev->ongoing_read = 0;1400spin_unlock_irq(&dev->err_lock);1401}14021403return rv;1404}14051406/*1407* skel_do_read() - read operations from lpvo_usb_gpib1408*/14091410static ssize_t skel_do_read(struct usb_skel *dev, char *buffer, size_t count)1411{1412int rv;1413bool ongoing_io;14141415/* if we cannot read at all, return EOF */14161417if (!dev->bulk_in_urb || !count)1418return 0;14191420restart: /* added to comply with ftdi timeout technique */14211422/* no concurrent readers */14231424rv = mutex_lock_interruptible(&dev->io_mutex);1425if (rv < 0)1426return rv;14271428if (!dev->interface) { /* disconnect() was called */1429rv = -ENODEV;1430goto exit;1431}14321433retry:1434/* if IO is under way, we must not touch things */1435spin_lock_irq(&dev->err_lock);1436ongoing_io = dev->ongoing_read;1437spin_unlock_irq(&dev->err_lock);14381439if (ongoing_io) {1440// /* nonblocking IO shall not wait */1441// /* no file, no O_NONBLOCK; maybe provide when from user space */1442// if (file->f_flags & O_NONBLOCK) {1443// rv = -EAGAIN;1444// goto exit;1445// }14461447/*1448* IO may take forever1449* hence wait in an interruptible state1450*/1451rv = wait_event_interruptible(dev->bulk_in_wait, (!dev->ongoing_read));1452if (rv < 0)1453goto exit;1454}14551456/* errors must be reported */1457rv = dev->errors;1458if (rv < 0) {1459/* any error is reported once */1460dev->errors = 0;1461/* to preserve notifications about reset */1462rv = (rv == -EPIPE) ? rv : -EIO;1463/* report it */1464goto exit;1465}14661467/*1468* if the buffer is filled we may satisfy the read1469* else we need to start IO1470*/14711472if (dev->bulk_in_filled) {1473/* we had read data */14741475size_t available = dev->bulk_in_filled - dev->bulk_in_copied;1476// size_t chunk = min(available, count); /* compute chunk later */1477size_t chunk;14781479if (!available) {1480/*1481* all data has been used1482* actual IO needs to be done1483*/1484/*1485* it seems that requests for less than dev->bulk_in_size1486* are not accepted1487*/1488rv = skel_do_read_io(dev, dev->bulk_in_size);1489if (rv < 0)1490goto exit;1491else1492goto retry;1493}14941495/*1496* data is available - chunk tells us how much shall be copied1497*/14981499/*1500* Condition dev->bulk_in_copied > 0 maybe will never happen. In case,1501* signal the event and copy using the original procedure, i.e., copy1502* first two bytes also1503*/15041505if (dev->bulk_in_copied) {1506chunk = min(available, count);1507memcpy(buffer, dev->bulk_in_buffer + dev->bulk_in_copied, chunk);1508rv = chunk;1509dev->bulk_in_copied += chunk;15101511/* copy discarding first two bytes that contain ftdi chip status */15121513} else {1514/* account for two bytes to be discarded */1515chunk = min(available, count + 2);1516if (chunk < 2) {1517dev_err(&dev->udev->dev, "BAD READ - chunk: %zu\n", chunk);1518rv = -EIO;1519goto exit;1520}15211522memcpy(buffer, dev->bulk_in_buffer + 2, chunk - 2);1523rv = chunk;1524dev->bulk_in_copied += chunk;1525}15261527/*1528* if we are asked for more than we have,1529* we start IO but don't wait1530*1531* No, no read ahead allowed; if the case, more data will be1532* asked for by the lpvo_usb_gpib layer.1533*/1534// if (available < count)1535// skel_do_read_io(dev, dev->bulk_in_size);1536} else {1537/* no data in the buffer */1538rv = skel_do_read_io(dev, dev->bulk_in_size);1539if (rv < 0)1540goto exit;1541else1542goto retry;1543}1544exit:1545mutex_unlock(&dev->io_mutex);1546if (rv == 2)1547goto restart; /* ftdi chip returns two status bytes after a latency anyhow */15481549if (rv > 0)1550return rv - 2; /* account for 2 discarded bytes in a valid buffer */1551return rv;1552}15531554/*1555* write functions1556*/15571558static void skel_write_bulk_callback(struct urb *urb)1559{1560struct usb_skel *dev;1561unsigned long flags;15621563dev = urb->context;15641565/* sync/async unlink faults aren't errors */1566if (urb->status) {1567if (!(urb->status == -ENOENT ||1568urb->status == -ECONNRESET ||1569urb->status == -ESHUTDOWN))1570dev_err(&dev->interface->dev,1571"nonzero write bulk status received: %d\n", urb->status);15721573spin_lock_irqsave(&dev->err_lock, flags);1574dev->errors = urb->status;1575spin_unlock_irqrestore(&dev->err_lock, flags);1576}15771578/* free up our allocated buffer */1579usb_free_coherent(urb->dev, urb->transfer_buffer_length,1580urb->transfer_buffer, urb->transfer_dma);1581up(&dev->limit_sem);1582}15831584/*1585* skel_do_write() - write operations from lpvo_usb_gpib1586*/15871588static ssize_t skel_do_write(struct usb_skel *dev, const char *buffer, size_t count)1589{1590int retval = 0;1591struct urb *urb = NULL;1592char *buf = NULL;1593size_t writesize = min_t(size_t, count, (size_t)MAX_TRANSFER);15941595/* verify that we actually have some data to write */1596if (count == 0)1597goto exit;15981599/*1600* limit the number of URBs in flight to stop a user from using up all1601* RAM1602*/1603/* Only one URB is used, because we can't have a pending write() and go on */16041605// if (!(file->f_flags & O_NONBLOCK)) { /* no NONBLOCK provided */1606if (down_interruptible(&dev->limit_sem)) {1607retval = -ERESTARTSYS;1608goto exit;1609}1610// } else {1611// if (down_trylock(&dev->limit_sem)) {1612// retval = -EAGAIN;1613// goto exit;1614// }1615// }16161617spin_lock_irq(&dev->err_lock);1618retval = dev->errors;1619if (retval < 0) {1620/* any error is reported once */1621dev->errors = 0;1622/* to preserve notifications about reset */1623retval = (retval == -EPIPE) ? retval : -EIO;1624}1625spin_unlock_irq(&dev->err_lock);1626if (retval < 0)1627goto error;16281629/* create a urb, and a buffer for it, and copy the data to the urb */1630urb = usb_alloc_urb(0, GFP_KERNEL);1631if (!urb) {1632retval = -ENOMEM;1633goto error;1634}16351636buf = usb_alloc_coherent(dev->udev, writesize, GFP_KERNEL,1637&urb->transfer_dma);1638if (!buf) {1639retval = -ENOMEM;1640goto error;1641}16421643memcpy(buf, buffer, count);16441645/* this lock makes sure we don't submit URBs to gone devices */1646mutex_lock(&dev->io_mutex);1647if (!dev->interface) { /* disconnect() was called */1648mutex_unlock(&dev->io_mutex);1649retval = -ENODEV;1650goto error;1651}16521653/* initialize the urb properly */1654usb_fill_bulk_urb(urb, dev->udev,1655usb_sndbulkpipe(dev->udev, dev->bulk_out_endpoint_addr),1656buf, writesize, skel_write_bulk_callback, dev);1657urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;1658usb_anchor_urb(urb, &dev->submitted);16591660/* send the data out the bulk port */1661retval = usb_submit_urb(urb, GFP_KERNEL);1662mutex_unlock(&dev->io_mutex);1663if (retval) {1664dev_err(&dev->interface->dev, "failed submitting write urb, error %d\n", retval);1665goto error_unanchor;1666}16671668/*1669* release our reference to this urb, the USB core will eventually free1670* it entirely1671*/1672usb_free_urb(urb);16731674return writesize;16751676error_unanchor:1677usb_unanchor_urb(urb);1678error:1679if (urb) {1680usb_free_coherent(dev->udev, writesize, buf, urb->transfer_dma);1681usb_free_urb(urb);1682}1683up(&dev->limit_sem);16841685exit:1686return retval;1687}16881689/*1690* services for the user space devices1691*/16921693#if USER_DEVICE /* conditional compilation of user space device */16941695static int skel_flush(struct file *file, fl_owner_t id)1696{1697struct usb_skel *dev;1698int res;16991700dev = file->private_data;1701if (!dev)1702return -ENODEV;17031704/* wait for io to stop */1705mutex_lock(&dev->io_mutex);1706skel_draw_down(dev);17071708/* read out errors, leave subsequent opens a clean slate */1709spin_lock_irq(&dev->err_lock);1710res = dev->errors ? (dev->errors == -EPIPE ? -EPIPE : -EIO) : 0;1711dev->errors = 0;1712spin_unlock_irq(&dev->err_lock);17131714mutex_unlock(&dev->io_mutex);17151716return res;1717}17181719static int skel_open(struct inode *inode, struct file *file)1720{1721struct usb_skel *dev;1722struct usb_interface *interface;1723int subminor;1724int retval = 0;17251726subminor = iminor(inode);17271728interface = usb_find_interface(&skel_driver, subminor);1729if (!interface) {1730pr_err("can't find device for minor %d\n", subminor);1731retval = -ENODEV;1732goto exit;1733}17341735dev = usb_get_intfdata(interface);1736if (!dev) {1737retval = -ENODEV;1738goto exit;1739}17401741retval = usb_autopm_get_interface(interface);1742if (retval)1743goto exit;17441745/* increment our usage count for the device */1746kref_get(&dev->kref);17471748/* save our object in the file's private structure */1749file->private_data = dev;17501751exit:1752return retval;1753}17541755static int skel_release(struct inode *inode, struct file *file)1756{1757struct usb_skel *dev;17581759dev = file->private_data;1760if (!dev)1761return -ENODEV;17621763/* allow the device to be autosuspended */1764mutex_lock(&dev->io_mutex);1765if (dev->interface)1766usb_autopm_put_interface(dev->interface);1767mutex_unlock(&dev->io_mutex);17681769/* decrement the count on our device */1770kref_put(&dev->kref, skel_delete);1771return 0;1772}17731774/*1775* user space access to read function1776*/17771778static ssize_t skel_read(struct file *file, char __user *buffer, size_t count,1779loff_t *ppos)1780{1781struct usb_skel *dev;1782char *buf;1783ssize_t rv;17841785dev = file->private_data;17861787buf = kmalloc(count, GFP_KERNEL);1788if (!buf)1789return -ENOMEM;17901791rv = skel_do_read(dev, buf, count);17921793if (rv > 0) {1794if (copy_to_user(buffer, buf, rv)) {1795kfree(buf);1796return -EFAULT;1797}1798}1799kfree(buf);1800return rv;1801}18021803/*1804* user space access to write function1805*/18061807static ssize_t skel_write(struct file *file, const char __user *user_buffer,1808size_t count, loff_t *ppos)1809{1810struct usb_skel *dev;1811char *buf;1812ssize_t rv;18131814dev = file->private_data;18151816buf = kmalloc(count, GFP_KERNEL);1817if (!buf)1818return -ENOMEM;18191820if (copy_from_user(buf, user_buffer, count)) {1821kfree(buf);1822return -EFAULT;1823}18241825rv = skel_do_write(dev, buf, count);1826kfree(buf);1827return rv;1828}1829#endif18301831static const struct file_operations skel_fops = {1832.owner = THIS_MODULE,1833#if USER_DEVICE1834.read = skel_read,1835.write = skel_write,1836.open = skel_open,1837.release = skel_release,1838.flush = skel_flush,1839.llseek = noop_llseek,1840#endif1841};18421843/*1844* usb class driver info in order to get a minor number from the usb core,1845* and to have the device registered with the driver core1846*/1847#if USER_DEVICE1848static struct usb_class_driver skel_class = {1849.name = "lpvo_raw%d",1850.fops = &skel_fops,1851.minor_base = USB_SKEL_MINOR_BASE,1852};1853#endif18541855static int skel_probe(struct usb_interface *interface,1856const struct usb_device_id *id)1857{1858struct usb_skel *dev;1859struct usb_endpoint_descriptor *bulk_in, *bulk_out;1860int retval;1861char *device_path;18621863mutex_init(&minors_lock); /* required for handling minor numbers table */18641865/* allocate memory for our device state and initialize it */1866dev = kzalloc(sizeof(*dev), GFP_KERNEL);1867if (!dev)1868return -ENOMEM;18691870kref_init(&dev->kref);1871sema_init(&dev->limit_sem, WRITES_IN_FLIGHT);1872mutex_init(&dev->io_mutex);1873spin_lock_init(&dev->err_lock);1874init_usb_anchor(&dev->submitted);1875init_waitqueue_head(&dev->bulk_in_wait);18761877dev->udev = usb_get_dev(interface_to_usbdev(interface));1878dev->interface = interface;18791880/* set up the endpoint information */1881/* use only the first bulk-in and bulk-out endpoints */1882retval = usb_find_common_endpoints(interface->cur_altsetting,1883&bulk_in, &bulk_out, NULL, NULL);1884if (retval) {1885dev_err(&interface->dev,1886"Could not find both bulk-in and bulk-out endpoints\n");1887goto error;1888}18891890dev->bulk_in_size = usb_endpoint_maxp(bulk_in);1891dev->bulk_in_endpoint_addr = bulk_in->bEndpointAddress;1892dev->bulk_in_buffer = kmalloc(dev->bulk_in_size, GFP_KERNEL);1893if (!dev->bulk_in_buffer) {1894retval = -ENOMEM;1895goto error;1896}1897dev->bulk_in_urb = usb_alloc_urb(0, GFP_KERNEL);1898if (!dev->bulk_in_urb) {1899retval = -ENOMEM;1900goto error;1901}19021903dev->bulk_out_endpoint_addr = bulk_out->bEndpointAddress;19041905/* save our data pointer in this interface device */1906usb_set_intfdata(interface, dev);19071908/* let the world know */19091910device_path = kobject_get_path(&dev->udev->dev.kobj, GFP_KERNEL);1911dev_dbg(&interface->dev, "New lpvo_usb_device -> bus: %d dev: %d path: %s\n",1912dev->udev->bus->busnum, dev->udev->devnum, device_path);1913kfree(device_path);19141915#if USER_DEVICE1916/* we can register the device now, as it is ready */1917retval = usb_register_dev(interface, &skel_class);1918if (retval) {1919/* something prevented us from registering this driver */1920dev_err(&interface->dev,1921"Not able to get a minor for this device.\n");1922usb_set_intfdata(interface, NULL);1923goto error;1924}1925#endif19261927write_latency_timer(dev->udev); /* adjust the latency timer */19281929usb_gpib_init_module(interface); /* last, init the lpvo for this minor */19301931return 0;19321933error:1934/* this frees allocated memory */1935kref_put(&dev->kref, skel_delete);19361937return retval;1938}19391940static void skel_disconnect(struct usb_interface *interface)1941{1942struct usb_skel *dev;1943int minor = interface->minor;19441945usb_gpib_exit_module(minor); /* first, disactivate the lpvo */19461947dev = usb_get_intfdata(interface);1948usb_set_intfdata(interface, NULL);19491950#if USER_DEVICE1951/* give back our minor */1952usb_deregister_dev(interface, &skel_class);1953#endif19541955/* prevent more I/O from starting */1956mutex_lock(&dev->io_mutex);1957dev->interface = NULL;1958mutex_unlock(&dev->io_mutex);19591960usb_kill_anchored_urbs(&dev->submitted);19611962/* decrement our usage count */1963kref_put(&dev->kref, skel_delete);1964}19651966static void skel_draw_down(struct usb_skel *dev)1967{1968int time;19691970time = usb_wait_anchor_empty_timeout(&dev->submitted, 1000);1971if (!time)1972usb_kill_anchored_urbs(&dev->submitted);1973usb_kill_urb(dev->bulk_in_urb);1974}19751976static int skel_suspend(struct usb_interface *intf, pm_message_t message)1977{1978struct usb_skel *dev = usb_get_intfdata(intf);19791980if (!dev)1981return 0;1982skel_draw_down(dev);1983return 0;1984}19851986static int skel_resume(struct usb_interface *intf)1987{1988return 0;1989}19901991static int skel_pre_reset(struct usb_interface *intf)1992{1993struct usb_skel *dev = usb_get_intfdata(intf);19941995mutex_lock(&dev->io_mutex);1996skel_draw_down(dev);19971998return 0;1999}20002001static int skel_post_reset(struct usb_interface *intf)2002{2003struct usb_skel *dev = usb_get_intfdata(intf);20042005/* we are sure no URBs are active - no locking needed */2006dev->errors = -EPIPE;2007mutex_unlock(&dev->io_mutex);20082009return 0;2010}20112012static struct usb_driver skel_driver = {2013.name = NAME,2014.probe = skel_probe,2015.disconnect = skel_disconnect,2016.suspend = skel_suspend,2017.resume = skel_resume,2018.pre_reset = skel_pre_reset,2019.post_reset = skel_post_reset,2020.id_table = skel_table,2021.supports_autosuspend = 1,2022};20232024module_usb_driver(skel_driver);202520262027