x86/xen: resume timer irqs early
[linux/fpc-iii.git] / drivers / staging / ced1401 / usb1401.c
blob97c55f9e5151e9277e8fc108d922f51a8ea0ebea
1 /***********************************************************************************
2 CED1401 usb driver. This basic loading is based on the usb-skeleton.c code that is:
3 Copyright (C) 2001-2004 Greg Kroah-Hartman (greg@kroah.com)
4 Copyright (C) 2012 Alois Schloegl <alois.schloegl@ist.ac.at>
5 There is not a great deal of the skeleton left.
7 All the remainder dealing specifically with the CED1401 is based on drivers written
8 by CED for other systems (mainly Windows) and is:
9 Copyright (C) 2010 Cambridge Electronic Design Ltd
10 Author Greg P Smith (greg@ced.co.uk)
12 This program is free software; you can redistribute it and/or
13 modify it under the terms of the GNU General Public License
14 as published by the Free Software Foundation; either version 2
15 of the License, or (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 Endpoints
27 *********
28 There are 4 endpoints plus the control endpoint in the standard interface
29 provided by most 1401s. The control endpoint is used for standard USB requests,
30 plus various CED-specific transactions such as start self test, debug and get
31 the 1401 status. The other endpoints are:
33 1 Characters to the 1401
34 2 Characters from the 1401
35 3 Block data to the 1401
36 4 Block data to the host.
38 inside the driver these are indexed as an array from 0 to 3, transactions
39 over the control endpoint are carried out using a separate mechanism. The
40 use of the endpoints is mostly straightforward, with the driver issuing
41 IO request packets (IRPs) as required to transfer data to and from the 1401.
42 The handling of endpoint 2 is different because it is used for characters
43 from the 1401, which can appear spontaneously and without any other driver
44 activity - for example to repeatedly request DMA transfers in Spike2. The
45 desired effect is achieved by using an interrupt endpoint which can be
46 polled to see if it has data available, and writing the driver so that it
47 always maintains a pending read IRP from that endpoint which will read the
48 character data and terminate as soon as the 1401 makes data available. This
49 works very well, some care is taken with when you kick off this character
50 read IRP to avoid it being active when it is not wanted but generally it
51 is running all the time.
53 In the 2270, there are only three endpoints plus the control endpoint. In
54 addition to the transactions mentioned above, the control endpoint is used
55 to transfer character data to the 1401. The other endpoints are used as:
57 1 Characters from the 1401
58 2 Block data to the 1401
59 3 Block data to the host.
61 The type of interface available is specified by the interface subclass field
62 in the interface descriptor provided by the 1401. See the USB_INT_ constants
63 for the values that this field can hold.
65 ****************************************************************************
66 Linux implementation
68 Although Linux Device Drivers (3rd Edition) was a major source of information,
69 it is very out of date. A lot of information was gleaned from the latest
70 usb_skeleton.c code (you need to download the kernel sources to get this).
72 To match the Windows version, everything is done using ioctl calls. All the
73 device state is held in the DEVICE_EXTENSION (named to match Windows use).
74 Block transfers are done by using get_user_pages() to pin down a list of
75 pages that we hold a pointer to in the device driver. We also allocate a
76 coherent transfer buffer of size STAGED_SZ (this must be a multiple of the
77 bulk endpoint size so that the 1401 does not realise that we break large
78 transfers down into smaller pieces). We use kmap_atomic() to get a kernel
79 va for each page, as it is required, for copying; see CopyUserSpace().
81 All character and data transfers are done using asynchronous IO. All Urbs are
82 tracked by anchoring them. Status and debug ioctls are implemented with the
83 synchronous non-Urb based transfers.
86 #include <linux/kernel.h>
87 #include <linux/errno.h>
88 #include <linux/usb.h>
89 #include <linux/mutex.h>
90 #include <linux/mm.h>
91 #include <linux/highmem.h>
92 #include <linux/init.h>
93 #include <linux/slab.h>
94 #include <linux/module.h>
95 #include <linux/kref.h>
96 #include <linux/uaccess.h>
98 #include "usb1401.h"
100 /* Define these values to match your devices */
101 #define USB_CED_VENDOR_ID 0x0525
102 #define USB_CED_PRODUCT_ID 0xa0f0
104 /* table of devices that work with this driver */
105 static const struct usb_device_id ced_table[] = {
106 {USB_DEVICE(USB_CED_VENDOR_ID, USB_CED_PRODUCT_ID)},
107 {} /* Terminating entry */
110 MODULE_DEVICE_TABLE(usb, ced_table);
112 /* Get a minor range for your devices from the usb maintainer */
113 #define USB_CED_MINOR_BASE 192
115 /* our private defines. if this grows any larger, use your own .h file */
116 #define MAX_TRANSFER (PAGE_SIZE - 512)
117 /* MAX_TRANSFER is chosen so that the VM is not stressed by
118 allocations > PAGE_SIZE and the number of packets in a page
119 is an integer 512 is the largest possible packet on EHCI */
120 #define WRITES_IN_FLIGHT 8
121 /* arbitrarily chosen */
123 static struct usb_driver ced_driver;
125 static void ced_delete(struct kref *kref)
127 DEVICE_EXTENSION *pdx = to_DEVICE_EXTENSION(kref);
129 /* Free up the output buffer, then free the output urb. Note that the interface member */
130 /* of pdx will probably be NULL, so cannot be used to get to dev. */
131 usb_free_coherent(pdx->udev, OUTBUF_SZ, pdx->pCoherCharOut,
132 pdx->pUrbCharOut->transfer_dma);
133 usb_free_urb(pdx->pUrbCharOut);
135 /* Do the same for chan input */
136 usb_free_coherent(pdx->udev, INBUF_SZ, pdx->pCoherCharIn,
137 pdx->pUrbCharIn->transfer_dma);
138 usb_free_urb(pdx->pUrbCharIn);
140 /* Do the same for the block transfers */
141 usb_free_coherent(pdx->udev, STAGED_SZ, pdx->pCoherStagedIO,
142 pdx->pStagedUrb->transfer_dma);
143 usb_free_urb(pdx->pStagedUrb);
145 usb_put_dev(pdx->udev);
146 kfree(pdx);
149 /* This is the driver end of the open() call from user space. */
150 static int ced_open(struct inode *inode, struct file *file)
152 DEVICE_EXTENSION *pdx;
153 int retval = 0;
154 int subminor = iminor(inode);
155 struct usb_interface *interface =
156 usb_find_interface(&ced_driver, subminor);
157 if (!interface) {
158 pr_err("%s - error, can't find device for minor %d", __func__,
159 subminor);
160 retval = -ENODEV;
161 goto exit;
164 pdx = usb_get_intfdata(interface);
165 if (!pdx) {
166 retval = -ENODEV;
167 goto exit;
170 dev_dbg(&interface->dev, "%s got pdx", __func__);
172 /* increment our usage count for the device */
173 kref_get(&pdx->kref);
175 /* lock the device to allow correctly handling errors
176 * in resumption */
177 mutex_lock(&pdx->io_mutex);
179 if (!pdx->open_count++) {
180 retval = usb_autopm_get_interface(interface);
181 if (retval) {
182 pdx->open_count--;
183 mutex_unlock(&pdx->io_mutex);
184 kref_put(&pdx->kref, ced_delete);
185 goto exit;
187 } else { /* uncomment this block if you want exclusive open */
188 dev_err(&interface->dev, "%s fail: already open", __func__);
189 retval = -EBUSY;
190 pdx->open_count--;
191 mutex_unlock(&pdx->io_mutex);
192 kref_put(&pdx->kref, ced_delete);
193 goto exit;
195 /* prevent the device from being autosuspended */
197 /* save our object in the file's private structure */
198 file->private_data = pdx;
199 mutex_unlock(&pdx->io_mutex);
201 exit:
202 return retval;
205 static int ced_release(struct inode *inode, struct file *file)
207 DEVICE_EXTENSION *pdx = file->private_data;
208 if (pdx == NULL)
209 return -ENODEV;
211 dev_dbg(&pdx->interface->dev, "%s called", __func__);
212 mutex_lock(&pdx->io_mutex);
213 if (!--pdx->open_count && pdx->interface) /* Allow autosuspend */
214 usb_autopm_put_interface(pdx->interface);
215 mutex_unlock(&pdx->io_mutex);
217 kref_put(&pdx->kref, ced_delete); /* decrement the count on our device */
218 return 0;
221 static int ced_flush(struct file *file, fl_owner_t id)
223 int res;
224 DEVICE_EXTENSION *pdx = file->private_data;
225 if (pdx == NULL)
226 return -ENODEV;
228 dev_dbg(&pdx->interface->dev, "%s char in pend=%d", __func__,
229 pdx->bReadCharsPending);
231 /* wait for io to stop */
232 mutex_lock(&pdx->io_mutex);
233 dev_dbg(&pdx->interface->dev, "%s got io_mutex", __func__);
234 ced_draw_down(pdx);
236 /* read out errors, leave subsequent opens a clean slate */
237 spin_lock_irq(&pdx->err_lock);
238 res = pdx->errors ? (pdx->errors == -EPIPE ? -EPIPE : -EIO) : 0;
239 pdx->errors = 0;
240 spin_unlock_irq(&pdx->err_lock);
242 mutex_unlock(&pdx->io_mutex);
243 dev_dbg(&pdx->interface->dev, "%s exit reached", __func__);
245 return res;
248 /***************************************************************************
249 ** CanAcceptIoRequests
250 ** If the device is removed, interface is set NULL. We also clear our pointer
251 ** from the interface, so we should make sure that pdx is not NULL. This will
252 ** not help with a device extension held by a file.
253 ** return true if can accept new io requests, else false
255 static bool CanAcceptIoRequests(DEVICE_EXTENSION *pdx)
257 return pdx && pdx->interface; /* Can we accept IO requests */
260 /****************************************************************************
261 ** Callback routine to complete writes. This may need to fire off another
262 ** urb to complete the transfer.
263 ****************************************************************************/
264 static void ced_writechar_callback(struct urb *pUrb)
266 DEVICE_EXTENSION *pdx = pUrb->context;
267 int nGot = pUrb->actual_length; /* what we transferred */
269 if (pUrb->status) { /* sync/async unlink faults aren't errors */
270 if (!
271 (pUrb->status == -ENOENT || pUrb->status == -ECONNRESET
272 || pUrb->status == -ESHUTDOWN)) {
273 dev_err(&pdx->interface->dev,
274 "%s - nonzero write bulk status received: %d",
275 __func__, pUrb->status);
278 spin_lock(&pdx->err_lock);
279 pdx->errors = pUrb->status;
280 spin_unlock(&pdx->err_lock);
281 nGot = 0; /* and tidy up again if so */
283 spin_lock(&pdx->charOutLock); /* already at irq level */
284 pdx->dwOutBuffGet = 0; /* Reset the output buffer */
285 pdx->dwOutBuffPut = 0;
286 pdx->dwNumOutput = 0; /* Clear the char count */
287 pdx->bPipeError[0] = 1; /* Flag an error for later */
288 pdx->bSendCharsPending = false; /* Allow other threads again */
289 spin_unlock(&pdx->charOutLock); /* already at irq level */
290 dev_dbg(&pdx->interface->dev,
291 "%s - char out done, 0 chars sent", __func__);
292 } else {
293 dev_dbg(&pdx->interface->dev,
294 "%s - char out done, %d chars sent", __func__, nGot);
295 spin_lock(&pdx->charOutLock); /* already at irq level */
296 pdx->dwNumOutput -= nGot; /* Now adjust the char send buffer */
297 pdx->dwOutBuffGet += nGot; /* to match what we did */
298 if (pdx->dwOutBuffGet >= OUTBUF_SZ) /* Can't do this any earlier as data could be overwritten */
299 pdx->dwOutBuffGet = 0;
301 if (pdx->dwNumOutput > 0) { /* if more to be done... */
302 int nPipe = 0; /* The pipe number to use */
303 int iReturn;
304 char *pDat = &pdx->outputBuffer[pdx->dwOutBuffGet];
305 unsigned int dwCount = pdx->dwNumOutput; /* maximum to send */
306 if ((pdx->dwOutBuffGet + dwCount) > OUTBUF_SZ) /* does it cross buffer end? */
307 dwCount = OUTBUF_SZ - pdx->dwOutBuffGet;
308 spin_unlock(&pdx->charOutLock); /* we are done with stuff that changes */
309 memcpy(pdx->pCoherCharOut, pDat, dwCount); /* copy output data to the buffer */
310 usb_fill_bulk_urb(pdx->pUrbCharOut, pdx->udev,
311 usb_sndbulkpipe(pdx->udev,
312 pdx->epAddr[0]),
313 pdx->pCoherCharOut, dwCount,
314 ced_writechar_callback, pdx);
315 pdx->pUrbCharOut->transfer_flags |=
316 URB_NO_TRANSFER_DMA_MAP;
317 usb_anchor_urb(pdx->pUrbCharOut, &pdx->submitted); /* in case we need to kill it */
318 iReturn = usb_submit_urb(pdx->pUrbCharOut, GFP_ATOMIC);
319 dev_dbg(&pdx->interface->dev, "%s n=%d>%s<", __func__,
320 dwCount, pDat);
321 spin_lock(&pdx->charOutLock); /* grab lock for errors */
322 if (iReturn) {
323 pdx->bPipeError[nPipe] = 1; /* Flag an error to be handled later */
324 pdx->bSendCharsPending = false; /* Allow other threads again */
325 usb_unanchor_urb(pdx->pUrbCharOut);
326 dev_err(&pdx->interface->dev,
327 "%s usb_submit_urb() returned %d",
328 __func__, iReturn);
330 } else
331 pdx->bSendCharsPending = false; /* Allow other threads again */
332 spin_unlock(&pdx->charOutLock); /* already at irq level */
336 /****************************************************************************
337 ** SendChars
338 ** Transmit the characters in the output buffer to the 1401. This may need
339 ** breaking down into multiple transfers.
340 ****************************************************************************/
341 int SendChars(DEVICE_EXTENSION *pdx)
343 int iReturn = U14ERR_NOERROR;
345 spin_lock_irq(&pdx->charOutLock); /* Protect ourselves */
347 if ((!pdx->bSendCharsPending) && /* Not currently sending */
348 (pdx->dwNumOutput > 0) && /* has characters to output */
349 (CanAcceptIoRequests(pdx))) { /* and current activity is OK */
350 unsigned int dwCount = pdx->dwNumOutput; /* Get a copy of the character count */
351 pdx->bSendCharsPending = true; /* Set flag to lock out other threads */
353 dev_dbg(&pdx->interface->dev,
354 "Send %d chars to 1401, EP0 flag %d\n", dwCount,
355 pdx->nPipes == 3);
356 /* If we have only 3 end points we must send the characters to the 1401 using EP0. */
357 if (pdx->nPipes == 3) {
358 /* For EP0 character transmissions to the 1401, we have to hang about until they */
359 /* are gone, as otherwise without more character IO activity they will never go. */
360 unsigned int count = dwCount; /* Local char counter */
361 unsigned int index = 0; /* The index into the char buffer */
363 spin_unlock_irq(&pdx->charOutLock); /* Free spinlock as we call USBD */
365 while ((count > 0) && (iReturn == U14ERR_NOERROR)) {
366 /* We have to break the transfer up into 64-byte chunks because of a 2270 problem */
367 int n = count > 64 ? 64 : count; /* Chars for this xfer, max of 64 */
368 int nSent = usb_control_msg(pdx->udev,
369 usb_sndctrlpipe(pdx->udev, 0), /* use end point 0 */
370 DB_CHARS, /* bRequest */
371 (H_TO_D | VENDOR | DEVREQ), /* to the device, vendor request to the device */
372 0, 0, /* value and index are both 0 */
373 &pdx->outputBuffer[index], /* where to send from */
374 n, /* how much to send */
375 1000); /* timeout in jiffies */
376 if (nSent <= 0) {
377 iReturn = nSent ? nSent : -ETIMEDOUT; /* if 0 chars says we timed out */
378 dev_err(&pdx->interface->dev,
379 "Send %d chars by EP0 failed: %d",
380 n, iReturn);
381 } else {
382 dev_dbg(&pdx->interface->dev,
383 "Sent %d chars by EP0", n);
384 count -= nSent;
385 index += nSent;
389 spin_lock_irq(&pdx->charOutLock); /* Protect pdx changes, released by general code */
390 pdx->dwOutBuffGet = 0; /* so reset the output buffer */
391 pdx->dwOutBuffPut = 0;
392 pdx->dwNumOutput = 0; /* and clear the buffer count */
393 pdx->bSendCharsPending = false; /* Allow other threads again */
394 } else { /* Here for sending chars normally - we hold the spin lock */
395 int nPipe = 0; /* The pipe number to use */
396 char *pDat = &pdx->outputBuffer[pdx->dwOutBuffGet];
398 if ((pdx->dwOutBuffGet + dwCount) > OUTBUF_SZ) /* does it cross buffer end? */
399 dwCount = OUTBUF_SZ - pdx->dwOutBuffGet;
400 spin_unlock_irq(&pdx->charOutLock); /* we are done with stuff that changes */
401 memcpy(pdx->pCoherCharOut, pDat, dwCount); /* copy output data to the buffer */
402 usb_fill_bulk_urb(pdx->pUrbCharOut, pdx->udev,
403 usb_sndbulkpipe(pdx->udev,
404 pdx->epAddr[0]),
405 pdx->pCoherCharOut, dwCount,
406 ced_writechar_callback, pdx);
407 pdx->pUrbCharOut->transfer_flags |=
408 URB_NO_TRANSFER_DMA_MAP;
409 usb_anchor_urb(pdx->pUrbCharOut, &pdx->submitted);
410 iReturn = usb_submit_urb(pdx->pUrbCharOut, GFP_KERNEL);
411 spin_lock_irq(&pdx->charOutLock); /* grab lock for errors */
412 if (iReturn) {
413 pdx->bPipeError[nPipe] = 1; /* Flag an error to be handled later */
414 pdx->bSendCharsPending = false; /* Allow other threads again */
415 usb_unanchor_urb(pdx->pUrbCharOut); /* remove from list of active urbs */
418 } else if (pdx->bSendCharsPending && (pdx->dwNumOutput > 0))
419 dev_dbg(&pdx->interface->dev,
420 "SendChars bSendCharsPending:true");
422 dev_dbg(&pdx->interface->dev, "SendChars exit code: %d", iReturn);
423 spin_unlock_irq(&pdx->charOutLock); /* Now let go of the spinlock */
424 return iReturn;
427 /***************************************************************************
428 ** CopyUserSpace
429 ** This moves memory between pinned down user space and the pCoherStagedIO
430 ** memory buffer we use for transfers. Copy n bytes in the directions that
431 ** is defined by pdx->StagedRead. The user space is determined by the area
432 ** in pdx->StagedId and the offset in pdx->StagedDone. The user
433 ** area may well not start on a page boundary, so allow for that.
435 ** We have a table of physical pages that describe the area, so we can use
436 ** this to get a virtual address that the kernel can use.
438 ** pdx Is our device extension which holds all we know about the transfer.
439 ** n The number of bytes to move one way or the other.
440 ***************************************************************************/
441 static void CopyUserSpace(DEVICE_EXTENSION *pdx, int n)
443 unsigned int nArea = pdx->StagedId;
444 if (nArea < MAX_TRANSAREAS) {
445 TRANSAREA *pArea = &pdx->rTransDef[nArea]; /* area to be used */
446 unsigned int dwOffset =
447 pdx->StagedDone + pdx->StagedOffset + pArea->dwBaseOffset;
448 char *pCoherBuf = pdx->pCoherStagedIO; /* coherent buffer */
449 if (!pArea->bUsed) {
450 dev_err(&pdx->interface->dev, "%s area %d unused",
451 __func__, nArea);
452 return;
455 while (n) {
456 int nPage = dwOffset >> PAGE_SHIFT; /* page number in table */
457 if (nPage < pArea->nPages) {
458 char *pvAddress =
459 (char *)kmap_atomic(pArea->pPages[nPage]);
460 if (pvAddress) {
461 unsigned int uiPageOff = dwOffset & (PAGE_SIZE - 1); /* offset into the page */
462 size_t uiXfer = PAGE_SIZE - uiPageOff; /* max to transfer on this page */
463 if (uiXfer > n) /* limit byte count if too much */
464 uiXfer = n; /* for the page */
465 if (pdx->StagedRead)
466 memcpy(pvAddress + uiPageOff,
467 pCoherBuf, uiXfer);
468 else
469 memcpy(pCoherBuf,
470 pvAddress + uiPageOff,
471 uiXfer);
472 kunmap_atomic(pvAddress);
473 dwOffset += uiXfer;
474 pCoherBuf += uiXfer;
475 n -= uiXfer;
476 } else {
477 dev_err(&pdx->interface->dev,
478 "%s did not map page %d",
479 __func__, nPage);
480 return;
483 } else {
484 dev_err(&pdx->interface->dev,
485 "%s exceeded pages %d", __func__,
486 nPage);
487 return;
490 } else
491 dev_err(&pdx->interface->dev, "%s bad area %d", __func__,
492 nArea);
495 /* Forward declarations for stuff used circularly */
496 static int StageChunk(DEVICE_EXTENSION *pdx);
497 /***************************************************************************
498 ** ReadWrite_Complete
500 ** Completion routine for our staged read/write Irps
502 static void staged_callback(struct urb *pUrb)
504 DEVICE_EXTENSION *pdx = pUrb->context;
505 unsigned int nGot = pUrb->actual_length; /* what we transferred */
506 bool bCancel = false;
507 bool bRestartCharInput; /* used at the end */
509 spin_lock(&pdx->stagedLock); /* stop ReadWriteMem() action while this routine is running */
510 pdx->bStagedUrbPending = false; /* clear the flag for staged IRP pending */
512 if (pUrb->status) { /* sync/async unlink faults aren't errors */
513 if (!
514 (pUrb->status == -ENOENT || pUrb->status == -ECONNRESET
515 || pUrb->status == -ESHUTDOWN)) {
516 dev_err(&pdx->interface->dev,
517 "%s - nonzero write bulk status received: %d",
518 __func__, pUrb->status);
519 } else
520 dev_info(&pdx->interface->dev,
521 "%s - staged xfer cancelled", __func__);
523 spin_lock(&pdx->err_lock);
524 pdx->errors = pUrb->status;
525 spin_unlock(&pdx->err_lock);
526 nGot = 0; /* and tidy up again if so */
527 bCancel = true;
528 } else {
529 dev_dbg(&pdx->interface->dev, "%s %d chars xferred", __func__,
530 nGot);
531 if (pdx->StagedRead) /* if reading, save to user space */
532 CopyUserSpace(pdx, nGot); /* copy from buffer to user */
533 if (nGot == 0)
534 dev_dbg(&pdx->interface->dev, "%s ZLP", __func__);
537 /* Update the transfer length based on the TransferBufferLength value in the URB */
538 pdx->StagedDone += nGot;
540 dev_dbg(&pdx->interface->dev, "%s, done %d bytes of %d", __func__,
541 pdx->StagedDone, pdx->StagedLength);
543 if ((pdx->StagedDone == pdx->StagedLength) || /* If no more to do */
544 (bCancel)) { /* or this IRP was cancelled */
545 TRANSAREA *pArea = &pdx->rTransDef[pdx->StagedId]; /* Transfer area info */
546 dev_dbg(&pdx->interface->dev,
547 "%s transfer done, bytes %d, cancel %d", __func__,
548 pdx->StagedDone, bCancel);
550 /* Here is where we sort out what to do with this transfer if using a circular buffer. We have */
551 /* a completed transfer that can be assumed to fit into the transfer area. We should be able to */
552 /* add this to the end of a growing block or to use it to start a new block unless the code */
553 /* that calculates the offset to use (in ReadWriteMem) is totally duff. */
554 if ((pArea->bCircular) && (pArea->bCircToHost) && (!bCancel) && /* Time to sort out circular buffer info? */
555 (pdx->StagedRead)) { /* Only for tohost transfers for now */
556 if (pArea->aBlocks[1].dwSize > 0) { /* If block 1 is in use we must append to it */
557 if (pdx->StagedOffset ==
558 (pArea->aBlocks[1].dwOffset +
559 pArea->aBlocks[1].dwSize)) {
560 pArea->aBlocks[1].dwSize +=
561 pdx->StagedLength;
562 dev_dbg(&pdx->interface->dev,
563 "RWM_Complete, circ block 1 now %d bytes at %d",
564 pArea->aBlocks[1].dwSize,
565 pArea->aBlocks[1].dwOffset);
566 } else {
567 /* Here things have gone very, very, wrong, but I cannot see how this can actually be achieved */
568 pArea->aBlocks[1].dwOffset =
569 pdx->StagedOffset;
570 pArea->aBlocks[1].dwSize =
571 pdx->StagedLength;
572 dev_err(&pdx->interface->dev,
573 "%s ERROR, circ block 1 re-started %d bytes at %d",
574 __func__,
575 pArea->aBlocks[1].dwSize,
576 pArea->aBlocks[1].dwOffset);
578 } else { /* If block 1 is not used, we try to add to block 0 */
579 if (pArea->aBlocks[0].dwSize > 0) { /* Got stored block 0 information? */
580 /* Must append onto the existing block 0 */
581 if (pdx->StagedOffset ==
582 (pArea->aBlocks[0].dwOffset +
583 pArea->aBlocks[0].dwSize)) {
584 pArea->aBlocks[0].dwSize += pdx->StagedLength; /* Just add this transfer in */
585 dev_dbg(&pdx->interface->dev,
586 "RWM_Complete, circ block 0 now %d bytes at %d",
587 pArea->aBlocks[0].
588 dwSize,
589 pArea->aBlocks[0].
590 dwOffset);
591 } else { /* If it doesn't append, put into new block 1 */
592 pArea->aBlocks[1].dwOffset =
593 pdx->StagedOffset;
594 pArea->aBlocks[1].dwSize =
595 pdx->StagedLength;
596 dev_dbg(&pdx->interface->dev,
597 "RWM_Complete, circ block 1 started %d bytes at %d",
598 pArea->aBlocks[1].
599 dwSize,
600 pArea->aBlocks[1].
601 dwOffset);
603 } else { /* No info stored yet, just save in block 0 */
604 pArea->aBlocks[0].dwOffset =
605 pdx->StagedOffset;
606 pArea->aBlocks[0].dwSize =
607 pdx->StagedLength;
608 dev_dbg(&pdx->interface->dev,
609 "RWM_Complete, circ block 0 started %d bytes at %d",
610 pArea->aBlocks[0].dwSize,
611 pArea->aBlocks[0].dwOffset);
616 if (!bCancel) { /* Don't generate an event if cancelled */
617 dev_dbg(&pdx->interface->dev,
618 "RWM_Complete, bCircular %d, bToHost %d, eStart %d, eSize %d",
619 pArea->bCircular, pArea->bEventToHost,
620 pArea->dwEventSt, pArea->dwEventSz);
621 if ((pArea->dwEventSz) && /* Set a user-mode event... */
622 (pdx->StagedRead == pArea->bEventToHost)) { /* ...on transfers in this direction? */
623 int iWakeUp = 0; /* assume */
624 /* If we have completed the right sort of DMA transfer then set the event to notify */
625 /* the user code to wake up anyone that is waiting. */
626 if ((pArea->bCircular) && /* Circular areas use a simpler test */
627 (pArea->bCircToHost)) { /* only in supported direction */
628 /* Is total data waiting up to size limit? */
629 unsigned int dwTotal =
630 pArea->aBlocks[0].dwSize +
631 pArea->aBlocks[1].dwSize;
632 iWakeUp = (dwTotal >= pArea->dwEventSz);
633 } else {
634 unsigned int transEnd =
635 pdx->StagedOffset +
636 pdx->StagedLength;
637 unsigned int eventEnd =
638 pArea->dwEventSt + pArea->dwEventSz;
639 iWakeUp = (pdx->StagedOffset < eventEnd)
640 && (transEnd > pArea->dwEventSt);
643 if (iWakeUp) {
644 dev_dbg(&pdx->interface->dev,
645 "About to set event to notify app");
646 wake_up_interruptible(&pArea->wqEvent); /* wake up waiting processes */
647 ++pArea->iWakeUp; /* increment wakeup count */
652 pdx->dwDMAFlag = MODE_CHAR; /* Switch back to char mode before ReadWriteMem call */
654 if (!bCancel) { /* Don't look for waiting transfer if cancelled */
655 /* If we have a transfer waiting, kick it off */
656 if (pdx->bXFerWaiting) { /* Got a block xfer waiting? */
657 int iReturn;
658 dev_info(&pdx->interface->dev,
659 "*** RWM_Complete *** pending transfer will now be set up!!!");
660 iReturn =
661 ReadWriteMem(pdx, !pdx->rDMAInfo.bOutWard,
662 pdx->rDMAInfo.wIdent,
663 pdx->rDMAInfo.dwOffset,
664 pdx->rDMAInfo.dwSize);
666 if (iReturn)
667 dev_err(&pdx->interface->dev,
668 "RWM_Complete rw setup failed %d",
669 iReturn);
673 } else /* Here for more to do */
674 StageChunk(pdx); /* fire off the next bit */
676 /* While we hold the stagedLock, see if we should reallow character input ints */
677 /* Don't allow if cancelled, or if a new block has started or if there is a waiting block. */
678 /* This feels wrong as we should ask which spin lock protects dwDMAFlag. */
679 bRestartCharInput = !bCancel && (pdx->dwDMAFlag == MODE_CHAR)
680 && !pdx->bXFerWaiting;
682 spin_unlock(&pdx->stagedLock); /* Finally release the lock again */
684 /* This is not correct as dwDMAFlag is protected by the staged lock, but it is treated */
685 /* in Allowi as if it were protected by the char lock. In any case, most systems will */
686 /* not be upset by char input during DMA... sigh. Needs sorting out. */
687 if (bRestartCharInput) /* may be out of date, but... */
688 Allowi(pdx); /* ...Allowi tests a lock too. */
689 dev_dbg(&pdx->interface->dev, "%s done", __func__);
692 /****************************************************************************
693 ** StageChunk
695 ** Generates the next chunk of data making up a staged transfer.
697 ** The calling code must have acquired the staging spinlock before calling
698 ** this function, and is responsible for releasing it. We are at callback level.
699 ****************************************************************************/
700 static int StageChunk(DEVICE_EXTENSION *pdx)
702 int iReturn = U14ERR_NOERROR;
703 unsigned int ChunkSize;
704 int nPipe = pdx->StagedRead ? 3 : 2; /* The pipe number to use for reads or writes */
705 if (pdx->nPipes == 3)
706 nPipe--; /* Adjust for the 3-pipe case */
707 if (nPipe < 0) /* and trap case that should never happen */
708 return U14ERR_FAIL;
710 if (!CanAcceptIoRequests(pdx)) { /* got sudden remove? */
711 dev_info(&pdx->interface->dev, "%s sudden remove, giving up",
712 __func__);
713 return U14ERR_FAIL; /* could do with a better error */
716 ChunkSize = (pdx->StagedLength - pdx->StagedDone); /* transfer length remaining */
717 if (ChunkSize > STAGED_SZ) /* make sure to keep legal */
718 ChunkSize = STAGED_SZ; /* limit to max allowed */
720 if (!pdx->StagedRead) /* if writing... */
721 CopyUserSpace(pdx, ChunkSize); /* ...copy data into the buffer */
723 usb_fill_bulk_urb(pdx->pStagedUrb, pdx->udev,
724 pdx->StagedRead ? usb_rcvbulkpipe(pdx->udev,
725 pdx->
726 epAddr[nPipe]) :
727 usb_sndbulkpipe(pdx->udev, pdx->epAddr[nPipe]),
728 pdx->pCoherStagedIO, ChunkSize, staged_callback, pdx);
729 pdx->pStagedUrb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
730 usb_anchor_urb(pdx->pStagedUrb, &pdx->submitted); /* in case we need to kill it */
731 iReturn = usb_submit_urb(pdx->pStagedUrb, GFP_ATOMIC);
732 if (iReturn) {
733 usb_unanchor_urb(pdx->pStagedUrb); /* kill it */
734 pdx->bPipeError[nPipe] = 1; /* Flag an error to be handled later */
735 dev_err(&pdx->interface->dev, "%s submit urb failed, code %d",
736 __func__, iReturn);
737 } else
738 pdx->bStagedUrbPending = true; /* Set the flag for staged URB pending */
739 dev_dbg(&pdx->interface->dev, "%s done so far:%d, this size:%d",
740 __func__, pdx->StagedDone, ChunkSize);
742 return iReturn;
745 /***************************************************************************
746 ** ReadWriteMem
748 ** This routine is used generally for block read and write operations.
749 ** Breaks up a read or write in to specified sized chunks, as specified by pipe
750 ** information on maximum transfer size.
752 ** Any code that calls this must be holding the stagedLock
754 ** Arguments:
755 ** DeviceObject - pointer to our FDO (Functional Device Object)
756 ** Read - TRUE for read, FALSE for write. This is from POV of the driver
757 ** wIdent - the transfer area number - defines memory area and more.
758 ** dwOffs - the start offset within the transfer area of the start of this
759 ** transfer.
760 ** dwLen - the number of bytes to transfer.
762 int ReadWriteMem(DEVICE_EXTENSION *pdx, bool Read, unsigned short wIdent,
763 unsigned int dwOffs, unsigned int dwLen)
765 TRANSAREA *pArea = &pdx->rTransDef[wIdent]; /* Transfer area info */
767 if (!CanAcceptIoRequests(pdx)) { /* Are we in a state to accept new requests? */
768 dev_err(&pdx->interface->dev, "%s can't accept requests",
769 __func__);
770 return U14ERR_FAIL;
773 dev_dbg(&pdx->interface->dev,
774 "%s xfer %d bytes to %s, offset %d, area %d", __func__, dwLen,
775 Read ? "host" : "1401", dwOffs, wIdent);
777 /* Amazingly, we can get an escape sequence back before the current staged Urb is done, so we */
778 /* have to check for this situation and, if so, wait until all is OK. */
779 if (pdx->bStagedUrbPending) {
780 pdx->bXFerWaiting = true; /* Flag we are waiting */
781 dev_info(&pdx->interface->dev,
782 "%s xfer is waiting, as previous staged pending",
783 __func__);
784 return U14ERR_NOERROR;
787 if (dwLen == 0) { /* allow 0-len read or write; just return success */
788 dev_dbg(&pdx->interface->dev,
789 "%s OK; zero-len read/write request", __func__);
790 return U14ERR_NOERROR;
793 if ((pArea->bCircular) && /* Circular transfer? */
794 (pArea->bCircToHost) && (Read)) { /* In a supported direction */
795 /* If so, we sort out offset ourself */
796 bool bWait = false; /* Flag for transfer having to wait */
798 dev_dbg(&pdx->interface->dev,
799 "Circular buffers are %d at %d and %d at %d",
800 pArea->aBlocks[0].dwSize, pArea->aBlocks[0].dwOffset,
801 pArea->aBlocks[1].dwSize, pArea->aBlocks[1].dwOffset);
802 if (pArea->aBlocks[1].dwSize > 0) { /* Using the second block already? */
803 dwOffs = pArea->aBlocks[1].dwOffset + pArea->aBlocks[1].dwSize; /* take offset from that */
804 bWait = (dwOffs + dwLen) > pArea->aBlocks[0].dwOffset; /* Wait if will overwrite block 0? */
805 bWait |= (dwOffs + dwLen) > pArea->dwLength; /* or if it overflows the buffer */
806 } else { /* Area 1 not in use, try to use area 0 */
807 if (pArea->aBlocks[0].dwSize == 0) /* Reset block 0 if not in use */
808 pArea->aBlocks[0].dwOffset = 0;
809 dwOffs =
810 pArea->aBlocks[0].dwOffset +
811 pArea->aBlocks[0].dwSize;
812 if ((dwOffs + dwLen) > pArea->dwLength) { /* Off the end of the buffer? */
813 pArea->aBlocks[1].dwOffset = 0; /* Set up to use second block */
814 dwOffs = 0;
815 bWait = (dwOffs + dwLen) > pArea->aBlocks[0].dwOffset; /* Wait if will overwrite block 0? */
816 bWait |= (dwOffs + dwLen) > pArea->dwLength; /* or if it overflows the buffer */
820 if (bWait) { /* This transfer will have to wait? */
821 pdx->bXFerWaiting = true; /* Flag we are waiting */
822 dev_dbg(&pdx->interface->dev,
823 "%s xfer waiting for circular buffer space",
824 __func__);
825 return U14ERR_NOERROR;
828 dev_dbg(&pdx->interface->dev,
829 "%s circular xfer, %d bytes starting at %d", __func__,
830 dwLen, dwOffs);
832 /* Save the parameters for the read\write transfer */
833 pdx->StagedRead = Read; /* Save the parameters for this read */
834 pdx->StagedId = wIdent; /* ID allows us to get transfer area info */
835 pdx->StagedOffset = dwOffs; /* The area within the transfer area */
836 pdx->StagedLength = dwLen;
837 pdx->StagedDone = 0; /* Initialise the byte count */
838 pdx->dwDMAFlag = MODE_LINEAR; /* Set DMA mode flag at this point */
839 pdx->bXFerWaiting = false; /* Clearly not a transfer waiting now */
841 /* KeClearEvent(&pdx->StagingDoneEvent); // Clear the transfer done event */
842 StageChunk(pdx); /* fire off the first chunk */
844 return U14ERR_NOERROR;
847 /****************************************************************************
849 ** ReadChar
851 ** Reads a character a buffer. If there is no more
852 ** data we return FALSE. Used as part of decoding a DMA request.
854 ****************************************************************************/
855 static bool ReadChar(unsigned char *pChar, char *pBuf, unsigned int *pdDone,
856 unsigned int dGot)
858 bool bRead = false;
859 unsigned int dDone = *pdDone;
861 if (dDone < dGot) { /* If there is more data */
862 *pChar = (unsigned char)pBuf[dDone]; /* Extract the next char */
863 dDone++; /* Increment the done count */
864 *pdDone = dDone;
865 bRead = true; /* and flag success */
868 return bRead;
871 #ifdef NOTUSED
872 /****************************************************************************
874 ** ReadWord
876 ** Reads a word from the 1401, just uses ReadChar twice; passes on any error
878 *****************************************************************************/
879 static bool ReadWord(unsigned short *pWord, char *pBuf, unsigned int *pdDone,
880 unsigned int dGot)
882 if (ReadChar((unsigned char *)pWord, pBuf, pdDone, dGot))
883 return ReadChar(((unsigned char *)pWord) + 1, pBuf, pdDone,
884 dGot);
885 else
886 return false;
888 #endif
890 /****************************************************************************
891 ** ReadHuff
893 ** Reads a coded number in and returns it, Code is:
894 ** If data is in range 0..127 we receive 1 byte. If data in range 128-16383
895 ** we receive two bytes, top bit of first indicates another on its way. If
896 ** data in range 16384-4194303 we get three bytes, top two bits of first set
897 ** to indicate three byte total.
899 *****************************************************************************/
900 static bool ReadHuff(volatile unsigned int *pDWord, char *pBuf,
901 unsigned int *pdDone, unsigned int dGot)
903 unsigned char ucData; /* for each read to ReadChar */
904 bool bReturn = true; /* assume we will succeed */
905 unsigned int dwData = 0; /* Accumulator for the data */
907 if (ReadChar(&ucData, pBuf, pdDone, dGot)) {
908 dwData = ucData; /* copy the data */
909 if ((dwData & 0x00000080) != 0) { /* Bit set for more data ? */
910 dwData &= 0x0000007F; /* Clear the relevant bit */
911 if (ReadChar(&ucData, pBuf, pdDone, dGot)) {
912 dwData = (dwData << 8) | ucData;
913 if ((dwData & 0x00004000) != 0) { /* three byte sequence ? */
914 dwData &= 0x00003FFF; /* Clear the relevant bit */
915 if (ReadChar
916 (&ucData, pBuf, pdDone, dGot))
917 dwData = (dwData << 8) | ucData;
918 else
919 bReturn = false;
921 } else
922 bReturn = false; /* couldn't read data */
924 } else
925 bReturn = false;
927 *pDWord = dwData; /* return the data */
928 return bReturn;
931 /***************************************************************************
933 ** ReadDMAInfo
935 ** Tries to read info about the dma request from the 1401 and decode it into
936 ** the dma descriptor block. We have at this point had the escape character
937 ** from the 1401 and now we must read in the rest of the information about
938 ** the transfer request. Returns FALSE if 1401 fails to respond or obselete
939 ** code from 1401 or bad parameters.
941 ** The pBuf char pointer does not include the initial escape character, so
942 ** we start handling the data at offset zero.
944 *****************************************************************************/
945 static bool ReadDMAInfo(volatile DMADESC *pDmaDesc, DEVICE_EXTENSION *pdx,
946 char *pBuf, unsigned int dwCount)
948 bool bResult = false; /* assume we won't succeed */
949 unsigned char ucData;
950 unsigned int dDone = 0; /* We haven't parsed anything so far */
952 dev_dbg(&pdx->interface->dev, "%s", __func__);
954 if (ReadChar(&ucData, pBuf, &dDone, dwCount)) {
955 unsigned char ucTransCode = (ucData & 0x0F); /* get code for transfer type */
956 unsigned short wIdent = ((ucData >> 4) & 0x07); /* and area identifier */
958 /* fill in the structure we were given */
959 pDmaDesc->wTransType = ucTransCode; /* type of transfer */
960 pDmaDesc->wIdent = wIdent; /* area to use */
961 pDmaDesc->dwSize = 0; /* initialise other bits */
962 pDmaDesc->dwOffset = 0;
964 dev_dbg(&pdx->interface->dev, "%s type: %d ident: %d", __func__,
965 pDmaDesc->wTransType, pDmaDesc->wIdent);
967 pDmaDesc->bOutWard = (ucTransCode != TM_EXTTOHOST); /* set transfer direction */
969 switch (ucTransCode) {
970 case TM_EXTTOHOST: /* Extended linear transfer modes (the only ones!) */
971 case TM_EXTTO1401:
973 bResult =
974 ReadHuff(&(pDmaDesc->dwOffset), pBuf,
975 &dDone, dwCount)
976 && ReadHuff(&(pDmaDesc->dwSize), pBuf,
977 &dDone, dwCount);
978 if (bResult) {
979 dev_dbg(&pdx->interface->dev,
980 "%s xfer offset & size %d %d",
981 __func__, pDmaDesc->dwOffset,
982 pDmaDesc->dwSize);
984 if ((wIdent >= MAX_TRANSAREAS) || /* Illegal area number, or... */
985 (!pdx->rTransDef[wIdent].bUsed) || /* area not set up, or... */
986 (pDmaDesc->dwOffset > pdx->rTransDef[wIdent].dwLength) || /* range/size */
987 ((pDmaDesc->dwOffset +
988 pDmaDesc->dwSize) >
989 (pdx->rTransDef[wIdent].
990 dwLength))) {
991 bResult = false; /* bad parameter(s) */
992 dev_dbg(&pdx->interface->dev,
993 "%s bad param - id %d, bUsed %d, offset %d, size %d, area length %d",
994 __func__, wIdent,
995 pdx->rTransDef[wIdent].
996 bUsed,
997 pDmaDesc->dwOffset,
998 pDmaDesc->dwSize,
999 pdx->rTransDef[wIdent].
1000 dwLength);
1003 break;
1005 default:
1006 break;
1008 } else
1009 bResult = false;
1011 if (!bResult) /* now check parameters for validity */
1012 dev_err(&pdx->interface->dev, "%s error reading Esc sequence",
1013 __func__);
1015 return bResult;
1018 /****************************************************************************
1020 ** Handle1401Esc
1022 ** Deals with an escape sequence coming from the 1401. This can either be
1023 ** a DMA transfer request of various types or a response to an escape sequence
1024 ** sent to the 1401. This is called from a callback.
1026 ** Parameters are
1028 ** dwCount - the number of characters in the device extension char in buffer,
1029 ** this is known to be at least 2 or we will not be called.
1031 ****************************************************************************/
1032 static int Handle1401Esc(DEVICE_EXTENSION *pdx, char *pCh,
1033 unsigned int dwCount)
1035 int iReturn = U14ERR_FAIL;
1037 /* I have no idea what this next test is about. '?' is 0x3f, which is area 3, code */
1038 /* 15. At the moment, this is not used, so it does no harm, but unless someone can */
1039 /* tell me what this is for, it should be removed from this and the Windows driver. */
1040 if (pCh[0] == '?') { /* Is this an information response */
1041 /* Parse and save the information */
1042 } else {
1043 spin_lock(&pdx->stagedLock); /* Lock others out */
1045 if (ReadDMAInfo(&pdx->rDMAInfo, pdx, pCh, dwCount)) { /* Get DMA parameters */
1046 unsigned short wTransType = pdx->rDMAInfo.wTransType; /* check transfer type */
1048 dev_dbg(&pdx->interface->dev,
1049 "%s xfer to %s, offset %d, length %d", __func__,
1050 pdx->rDMAInfo.bOutWard ? "1401" : "host",
1051 pdx->rDMAInfo.dwOffset, pdx->rDMAInfo.dwSize);
1053 if (pdx->bXFerWaiting) { /* Check here for badly out of kilter... */
1054 /* This can never happen, really */
1055 dev_err(&pdx->interface->dev,
1056 "ERROR: DMA setup while transfer still waiting");
1057 spin_unlock(&pdx->stagedLock);
1058 } else {
1059 if ((wTransType == TM_EXTTOHOST)
1060 || (wTransType == TM_EXTTO1401)) {
1061 iReturn =
1062 ReadWriteMem(pdx,
1063 !pdx->rDMAInfo.
1064 bOutWard,
1065 pdx->rDMAInfo.wIdent,
1066 pdx->rDMAInfo.dwOffset,
1067 pdx->rDMAInfo.dwSize);
1068 if (iReturn != U14ERR_NOERROR)
1069 dev_err(&pdx->interface->dev,
1070 "%s ReadWriteMem() failed %d",
1071 __func__, iReturn);
1072 } else /* This covers non-linear transfer setup */
1073 dev_err(&pdx->interface->dev,
1074 "%s Unknown block xfer type %d",
1075 __func__, wTransType);
1077 } else /* Failed to read parameters */
1078 dev_err(&pdx->interface->dev, "%s ReadDMAInfo() fail",
1079 __func__);
1081 spin_unlock(&pdx->stagedLock); /* OK here */
1084 dev_dbg(&pdx->interface->dev, "%s returns %d", __func__, iReturn);
1086 return iReturn;
1089 /****************************************************************************
1090 ** Callback for the character read complete or error
1091 ****************************************************************************/
1092 static void ced_readchar_callback(struct urb *pUrb)
1094 DEVICE_EXTENSION *pdx = pUrb->context;
1095 int nGot = pUrb->actual_length; /* what we transferred */
1097 if (pUrb->status) { /* Do we have a problem to handle? */
1098 int nPipe = pdx->nPipes == 4 ? 1 : 0; /* The pipe number to use for error */
1099 /* sync/async unlink faults aren't errors... just saying device removed or stopped */
1100 if (!
1101 (pUrb->status == -ENOENT || pUrb->status == -ECONNRESET
1102 || pUrb->status == -ESHUTDOWN)) {
1103 dev_err(&pdx->interface->dev,
1104 "%s - nonzero write bulk status received: %d",
1105 __func__, pUrb->status);
1106 } else
1107 dev_dbg(&pdx->interface->dev,
1108 "%s - 0 chars pUrb->status=%d (shutdown?)",
1109 __func__, pUrb->status);
1111 spin_lock(&pdx->err_lock);
1112 pdx->errors = pUrb->status;
1113 spin_unlock(&pdx->err_lock);
1114 nGot = 0; /* and tidy up again if so */
1116 spin_lock(&pdx->charInLock); /* already at irq level */
1117 pdx->bPipeError[nPipe] = 1; /* Flag an error for later */
1118 } else {
1119 if ((nGot > 1) && ((pdx->pCoherCharIn[0] & 0x7f) == 0x1b)) { /* Esc sequence? */
1120 Handle1401Esc(pdx, &pdx->pCoherCharIn[1], nGot - 1); /* handle it */
1121 spin_lock(&pdx->charInLock); /* already at irq level */
1122 } else {
1123 spin_lock(&pdx->charInLock); /* already at irq level */
1124 if (nGot > 0) {
1125 unsigned int i;
1126 if (nGot < INBUF_SZ) {
1127 pdx->pCoherCharIn[nGot] = 0; /* tidy the string */
1128 dev_dbg(&pdx->interface->dev,
1129 "%s got %d chars >%s<",
1130 __func__, nGot,
1131 pdx->pCoherCharIn);
1133 /* We know that whatever we read must fit in the input buffer */
1134 for (i = 0; i < nGot; i++) {
1135 pdx->inputBuffer[pdx->dwInBuffPut++] =
1136 pdx->pCoherCharIn[i] & 0x7F;
1137 if (pdx->dwInBuffPut >= INBUF_SZ)
1138 pdx->dwInBuffPut = 0;
1141 if ((pdx->dwNumInput + nGot) <= INBUF_SZ)
1142 pdx->dwNumInput += nGot; /* Adjust the buffer count accordingly */
1143 } else
1144 dev_dbg(&pdx->interface->dev, "%s read ZLP",
1145 __func__);
1149 pdx->bReadCharsPending = false; /* No longer have a pending read */
1150 spin_unlock(&pdx->charInLock); /* already at irq level */
1152 Allowi(pdx); /* see if we can do the next one */
1155 /****************************************************************************
1156 ** Allowi
1158 ** This is used to make sure that there is always a pending input transfer so
1159 ** we can pick up any inward transfers. This can be called in multiple contexts
1160 ** so we use the irqsave version of the spinlock.
1161 ****************************************************************************/
1162 int Allowi(DEVICE_EXTENSION *pdx)
1164 int iReturn = U14ERR_NOERROR;
1165 unsigned long flags;
1166 spin_lock_irqsave(&pdx->charInLock, flags); /* can be called in multiple contexts */
1168 /* We don't want char input running while DMA is in progress as we know that this */
1169 /* can cause sequencing problems for the 2270. So don't. It will also allow the */
1170 /* ERR response to get back to the host code too early on some PCs, even if there */
1171 /* is no actual driver failure, so we don't allow this at all. */
1172 if (!pdx->bInDrawDown && /* stop input if */
1173 !pdx->bReadCharsPending && /* If no read request outstanding */
1174 (pdx->dwNumInput < (INBUF_SZ / 2)) && /* and there is some space */
1175 (pdx->dwDMAFlag == MODE_CHAR) && /* not doing any DMA */
1176 (!pdx->bXFerWaiting) && /* no xfer waiting to start */
1177 (CanAcceptIoRequests(pdx))) { /* and activity is generally OK */
1178 /* then off we go */
1179 unsigned int nMax = INBUF_SZ - pdx->dwNumInput; /* max we could read */
1180 int nPipe = pdx->nPipes == 4 ? 1 : 0; /* The pipe number to use */
1182 dev_dbg(&pdx->interface->dev, "%s %d chars in input buffer",
1183 __func__, pdx->dwNumInput);
1185 usb_fill_int_urb(pdx->pUrbCharIn, pdx->udev,
1186 usb_rcvintpipe(pdx->udev, pdx->epAddr[nPipe]),
1187 pdx->pCoherCharIn, nMax, ced_readchar_callback,
1188 pdx, pdx->bInterval);
1189 pdx->pUrbCharIn->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* short xfers are OK by default */
1190 usb_anchor_urb(pdx->pUrbCharIn, &pdx->submitted); /* in case we need to kill it */
1191 iReturn = usb_submit_urb(pdx->pUrbCharIn, GFP_ATOMIC);
1192 if (iReturn) {
1193 usb_unanchor_urb(pdx->pUrbCharIn); /* remove from list of active Urbs */
1194 pdx->bPipeError[nPipe] = 1; /* Flag an error to be handled later */
1195 dev_err(&pdx->interface->dev,
1196 "%s submit urb failed: %d", __func__, iReturn);
1197 } else
1198 pdx->bReadCharsPending = true; /* Flag that we are active here */
1201 spin_unlock_irqrestore(&pdx->charInLock, flags);
1203 return iReturn;
1207 /*****************************************************************************
1208 ** The ioctl entry point to the driver that is used by us to talk to it.
1209 ** inode The device node (no longer in 3.0.0 kernels)
1210 ** file The file that is open, which holds our pdx pointer
1211 ** ulArg The argument passed in. Note that long is 64-bits in 64-bit system, i.e. it is big
1212 ** enough for a 64-bit pointer.
1213 *****************************************************************************/
1214 static long ced_ioctl(struct file *file, unsigned int cmd, unsigned long ulArg)
1216 int err = 0;
1217 DEVICE_EXTENSION *pdx = file->private_data;
1218 if (!CanAcceptIoRequests(pdx)) /* check we still exist */
1219 return -ENODEV;
1221 /* Check that access is allowed, where is is needed. Anything that would have an indeterminate */
1222 /* size will be checked by the specific command. */
1223 if (_IOC_DIR(cmd) & _IOC_READ) /* read from point of view of user... */
1224 err = !access_ok(VERIFY_WRITE, (void __user *)ulArg, _IOC_SIZE(cmd)); /* is kernel write */
1225 else if (_IOC_DIR(cmd) & _IOC_WRITE) /* and write from point of view of user... */
1226 err = !access_ok(VERIFY_READ, (void __user *)ulArg, _IOC_SIZE(cmd)); /* is kernel read */
1227 if (err)
1228 return -EFAULT;
1230 switch (_IOC_NR(cmd)) {
1231 case _IOC_NR(IOCTL_CED_SENDSTRING(0)):
1232 return SendString(pdx, (const char __user *)ulArg,
1233 _IOC_SIZE(cmd));
1235 case _IOC_NR(IOCTL_CED_RESET1401):
1236 return Reset1401(pdx);
1238 case _IOC_NR(IOCTL_CED_GETCHAR):
1239 return GetChar(pdx);
1241 case _IOC_NR(IOCTL_CED_SENDCHAR):
1242 return SendChar(pdx, (char)ulArg);
1244 case _IOC_NR(IOCTL_CED_STAT1401):
1245 return Stat1401(pdx);
1247 case _IOC_NR(IOCTL_CED_LINECOUNT):
1248 return LineCount(pdx);
1250 case _IOC_NR(IOCTL_CED_GETSTRING(0)):
1251 return GetString(pdx, (char __user *)ulArg, _IOC_SIZE(cmd));
1253 case _IOC_NR(IOCTL_CED_SETTRANSFER):
1254 return SetTransfer(pdx, (TRANSFERDESC __user *) ulArg);
1256 case _IOC_NR(IOCTL_CED_UNSETTRANSFER):
1257 return UnsetTransfer(pdx, (int)ulArg);
1259 case _IOC_NR(IOCTL_CED_SETEVENT):
1260 return SetEvent(pdx, (TRANSFEREVENT __user *) ulArg);
1262 case _IOC_NR(IOCTL_CED_GETOUTBUFSPACE):
1263 return GetOutBufSpace(pdx);
1265 case _IOC_NR(IOCTL_CED_GETBASEADDRESS):
1266 return -1;
1268 case _IOC_NR(IOCTL_CED_GETDRIVERREVISION):
1269 return (2 << 24) | (DRIVERMAJREV << 16) | DRIVERMINREV; /* USB | MAJOR | MINOR */
1271 case _IOC_NR(IOCTL_CED_GETTRANSFER):
1272 return GetTransfer(pdx, (TGET_TX_BLOCK __user *) ulArg);
1274 case _IOC_NR(IOCTL_CED_KILLIO1401):
1275 return KillIO1401(pdx);
1277 case _IOC_NR(IOCTL_CED_STATEOF1401):
1278 return StateOf1401(pdx);
1280 case _IOC_NR(IOCTL_CED_GRAB1401):
1281 case _IOC_NR(IOCTL_CED_FREE1401):
1282 return U14ERR_NOERROR;
1284 case _IOC_NR(IOCTL_CED_STARTSELFTEST):
1285 return StartSelfTest(pdx);
1287 case _IOC_NR(IOCTL_CED_CHECKSELFTEST):
1288 return CheckSelfTest(pdx, (TGET_SELFTEST __user *) ulArg);
1290 case _IOC_NR(IOCTL_CED_TYPEOF1401):
1291 return TypeOf1401(pdx);
1293 case _IOC_NR(IOCTL_CED_TRANSFERFLAGS):
1294 return TransferFlags(pdx);
1296 case _IOC_NR(IOCTL_CED_DBGPEEK):
1297 return DbgPeek(pdx, (TDBGBLOCK __user *) ulArg);
1299 case _IOC_NR(IOCTL_CED_DBGPOKE):
1300 return DbgPoke(pdx, (TDBGBLOCK __user *) ulArg);
1302 case _IOC_NR(IOCTL_CED_DBGRAMPDATA):
1303 return DbgRampData(pdx, (TDBGBLOCK __user *) ulArg);
1305 case _IOC_NR(IOCTL_CED_DBGRAMPADDR):
1306 return DbgRampAddr(pdx, (TDBGBLOCK __user *) ulArg);
1308 case _IOC_NR(IOCTL_CED_DBGGETDATA):
1309 return DbgGetData(pdx, (TDBGBLOCK __user *) ulArg);
1311 case _IOC_NR(IOCTL_CED_DBGSTOPLOOP):
1312 return DbgStopLoop(pdx);
1314 case _IOC_NR(IOCTL_CED_FULLRESET):
1315 pdx->bForceReset = true; /* Set a flag for a full reset */
1316 break;
1318 case _IOC_NR(IOCTL_CED_SETCIRCULAR):
1319 return SetCircular(pdx, (TRANSFERDESC __user *) ulArg);
1321 case _IOC_NR(IOCTL_CED_GETCIRCBLOCK):
1322 return GetCircBlock(pdx, (TCIRCBLOCK __user *) ulArg);
1324 case _IOC_NR(IOCTL_CED_FREECIRCBLOCK):
1325 return FreeCircBlock(pdx, (TCIRCBLOCK __user *) ulArg);
1327 case _IOC_NR(IOCTL_CED_WAITEVENT):
1328 return WaitEvent(pdx, (int)(ulArg & 0xff), (int)(ulArg >> 8));
1330 case _IOC_NR(IOCTL_CED_TESTEVENT):
1331 return TestEvent(pdx, (int)ulArg);
1333 default:
1334 return U14ERR_NO_SUCH_FN;
1336 return U14ERR_NOERROR;
1339 static const struct file_operations ced_fops = {
1340 .owner = THIS_MODULE,
1341 .open = ced_open,
1342 .release = ced_release,
1343 .flush = ced_flush,
1344 .llseek = noop_llseek,
1345 .unlocked_ioctl = ced_ioctl,
1349 * usb class driver info in order to get a minor number from the usb core,
1350 * and to have the device registered with the driver core
1352 static struct usb_class_driver ced_class = {
1353 .name = "cedusb%d",
1354 .fops = &ced_fops,
1355 .minor_base = USB_CED_MINOR_BASE,
1358 /* Check that the device that matches a 1401 vendor and product ID is OK to use and */
1359 /* initialise our DEVICE_EXTENSION. */
1360 static int ced_probe(struct usb_interface *interface,
1361 const struct usb_device_id *id)
1363 DEVICE_EXTENSION *pdx;
1364 struct usb_host_interface *iface_desc;
1365 struct usb_endpoint_descriptor *endpoint;
1366 int i, bcdDevice;
1367 int retval = -ENOMEM;
1369 /* allocate memory for our device extension and initialize it */
1370 pdx = kzalloc(sizeof(*pdx), GFP_KERNEL);
1371 if (!pdx)
1372 goto error;
1374 for (i = 0; i < MAX_TRANSAREAS; ++i) { /* Initialise the wait queues */
1375 init_waitqueue_head(&pdx->rTransDef[i].wqEvent);
1378 /* Put initialises for our stuff here. Note that all of *pdx is zero, so */
1379 /* no need to explicitly zero it. */
1380 spin_lock_init(&pdx->charOutLock);
1381 spin_lock_init(&pdx->charInLock);
1382 spin_lock_init(&pdx->stagedLock);
1384 /* Initialises from the skeleton stuff */
1385 kref_init(&pdx->kref);
1386 mutex_init(&pdx->io_mutex);
1387 spin_lock_init(&pdx->err_lock);
1388 init_usb_anchor(&pdx->submitted);
1390 pdx->udev = usb_get_dev(interface_to_usbdev(interface));
1391 pdx->interface = interface;
1393 /* Attempt to identify the device */
1394 bcdDevice = pdx->udev->descriptor.bcdDevice;
1395 i = (bcdDevice >> 8);
1396 if (i == 0)
1397 pdx->s1401Type = TYPEU1401;
1398 else if ((i >= 1) && (i <= 23))
1399 pdx->s1401Type = i + 2;
1400 else {
1401 dev_err(&interface->dev, "%s Unknown device. bcdDevice = %d",
1402 __func__, bcdDevice);
1403 goto error;
1405 /* set up the endpoint information. We only care about the number of EP as */
1406 /* we know that we are dealing with a 1401 device. */
1407 iface_desc = interface->cur_altsetting;
1408 pdx->nPipes = iface_desc->desc.bNumEndpoints;
1409 dev_info(&interface->dev, "1401Type=%d with %d End Points",
1410 pdx->s1401Type, pdx->nPipes);
1411 if ((pdx->nPipes < 3) || (pdx->nPipes > 4))
1412 goto error;
1414 /* Allocate the URBs we hold for performing transfers */
1415 pdx->pUrbCharOut = usb_alloc_urb(0, GFP_KERNEL); /* character output URB */
1416 pdx->pUrbCharIn = usb_alloc_urb(0, GFP_KERNEL); /* character input URB */
1417 pdx->pStagedUrb = usb_alloc_urb(0, GFP_KERNEL); /* block transfer URB */
1418 if (!pdx->pUrbCharOut || !pdx->pUrbCharIn || !pdx->pStagedUrb) {
1419 dev_err(&interface->dev, "%s URB alloc failed", __func__);
1420 goto error;
1423 pdx->pCoherStagedIO =
1424 usb_alloc_coherent(pdx->udev, STAGED_SZ, GFP_KERNEL,
1425 &pdx->pStagedUrb->transfer_dma);
1426 pdx->pCoherCharOut =
1427 usb_alloc_coherent(pdx->udev, OUTBUF_SZ, GFP_KERNEL,
1428 &pdx->pUrbCharOut->transfer_dma);
1429 pdx->pCoherCharIn =
1430 usb_alloc_coherent(pdx->udev, INBUF_SZ, GFP_KERNEL,
1431 &pdx->pUrbCharIn->transfer_dma);
1432 if (!pdx->pCoherCharOut || !pdx->pCoherCharIn || !pdx->pCoherStagedIO) {
1433 dev_err(&interface->dev, "%s Coherent buffer alloc failed",
1434 __func__);
1435 goto error;
1438 for (i = 0; i < pdx->nPipes; ++i) {
1439 endpoint = &iface_desc->endpoint[i].desc;
1440 pdx->epAddr[i] = endpoint->bEndpointAddress;
1441 dev_info(&interface->dev, "Pipe %d, ep address %02x", i,
1442 pdx->epAddr[i]);
1443 if (((pdx->nPipes == 3) && (i == 0)) || /* if char input end point */
1444 ((pdx->nPipes == 4) && (i == 1))) {
1445 pdx->bInterval = endpoint->bInterval; /* save the endpoint interrupt interval */
1446 dev_info(&interface->dev, "Pipe %d, bInterval = %d", i,
1447 pdx->bInterval);
1449 /* Detect USB2 by checking last ep size (64 if USB1) */
1450 if (i == pdx->nPipes - 1) { /* if this is the last ep (bulk) */
1451 pdx->bIsUSB2 =
1452 le16_to_cpu(endpoint->wMaxPacketSize) > 64;
1453 dev_info(&pdx->interface->dev, "USB%d",
1454 pdx->bIsUSB2 + 1);
1458 /* save our data pointer in this interface device */
1459 usb_set_intfdata(interface, pdx);
1461 /* we can register the device now, as it is ready */
1462 retval = usb_register_dev(interface, &ced_class);
1463 if (retval) {
1464 /* something prevented us from registering this driver */
1465 dev_err(&interface->dev,
1466 "Not able to get a minor for this device.\n");
1467 usb_set_intfdata(interface, NULL);
1468 goto error;
1471 /* let the user know what node this device is now attached to */
1472 dev_info(&interface->dev,
1473 "USB CEDUSB device now attached to cedusb #%d",
1474 interface->minor);
1475 return 0;
1477 error:
1478 if (pdx)
1479 kref_put(&pdx->kref, ced_delete); /* frees allocated memory */
1480 return retval;
1483 static void ced_disconnect(struct usb_interface *interface)
1485 DEVICE_EXTENSION *pdx = usb_get_intfdata(interface);
1486 int minor = interface->minor;
1487 int i;
1489 usb_set_intfdata(interface, NULL); /* remove the pdx from the interface */
1490 usb_deregister_dev(interface, &ced_class); /* give back our minor device number */
1492 mutex_lock(&pdx->io_mutex); /* stop more I/O starting while... */
1493 ced_draw_down(pdx); /* ...wait for then kill any io */
1494 for (i = 0; i < MAX_TRANSAREAS; ++i) {
1495 int iErr = ClearArea(pdx, i); /* ...release any used memory */
1496 if (iErr == U14ERR_UNLOCKFAIL)
1497 dev_err(&pdx->interface->dev, "%s Area %d was in used",
1498 __func__, i);
1500 pdx->interface = NULL; /* ...we kill off link to interface */
1501 mutex_unlock(&pdx->io_mutex);
1503 usb_kill_anchored_urbs(&pdx->submitted);
1505 kref_put(&pdx->kref, ced_delete); /* decrement our usage count */
1507 dev_info(&interface->dev, "USB cedusb #%d now disconnected", minor);
1510 /* Wait for all the urbs we know of to be done with, then kill off any that */
1511 /* are left. NBNB we will need to have a mechanism to stop circular xfers */
1512 /* from trying to fire off more urbs. We will wait up to 3 seconds for Urbs */
1513 /* to be done. */
1514 void ced_draw_down(DEVICE_EXTENSION *pdx)
1516 int time;
1517 dev_dbg(&pdx->interface->dev, "%s called", __func__);
1519 pdx->bInDrawDown = true;
1520 time = usb_wait_anchor_empty_timeout(&pdx->submitted, 3000);
1521 if (!time) { /* if we timed out we kill the urbs */
1522 usb_kill_anchored_urbs(&pdx->submitted);
1523 dev_err(&pdx->interface->dev, "%s timed out", __func__);
1525 pdx->bInDrawDown = false;
1528 static int ced_suspend(struct usb_interface *intf, pm_message_t message)
1530 DEVICE_EXTENSION *pdx = usb_get_intfdata(intf);
1531 if (!pdx)
1532 return 0;
1533 ced_draw_down(pdx);
1535 dev_dbg(&pdx->interface->dev, "%s called", __func__);
1536 return 0;
1539 static int ced_resume(struct usb_interface *intf)
1541 DEVICE_EXTENSION *pdx = usb_get_intfdata(intf);
1542 if (!pdx)
1543 return 0;
1544 dev_dbg(&pdx->interface->dev, "%s called", __func__);
1545 return 0;
1548 static int ced_pre_reset(struct usb_interface *intf)
1550 DEVICE_EXTENSION *pdx = usb_get_intfdata(intf);
1551 dev_dbg(&pdx->interface->dev, "%s", __func__);
1552 mutex_lock(&pdx->io_mutex);
1553 ced_draw_down(pdx);
1554 return 0;
1557 static int ced_post_reset(struct usb_interface *intf)
1559 DEVICE_EXTENSION *pdx = usb_get_intfdata(intf);
1560 dev_dbg(&pdx->interface->dev, "%s", __func__);
1562 /* we are sure no URBs are active - no locking needed */
1563 pdx->errors = -EPIPE;
1564 mutex_unlock(&pdx->io_mutex);
1566 return 0;
1569 static struct usb_driver ced_driver = {
1570 .name = "cedusb",
1571 .probe = ced_probe,
1572 .disconnect = ced_disconnect,
1573 .suspend = ced_suspend,
1574 .resume = ced_resume,
1575 .pre_reset = ced_pre_reset,
1576 .post_reset = ced_post_reset,
1577 .id_table = ced_table,
1578 .supports_autosuspend = 1,
1581 module_usb_driver(ced_driver);
1582 MODULE_LICENSE("GPL");