]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/staging/ced1401/ced_ioc.c
7b6ea79839b6351bbe38c62d763a75eb48fbb436
[karo-tx-linux.git] / drivers / staging / ced1401 / ced_ioc.c
1 /* ced_ioc.c
2  ioctl part of the 1401 usb device driver for linux.
3  Copyright (C) 2010 Cambridge Electronic Design Ltd
4  Author Greg P Smith (greg@ced.co.uk)
5
6  This program is free software; you can redistribute it and/or
7  modify it under the terms of the GNU General Public License
8  as published by the Free Software Foundation; either version 2
9  of the License, or (at your option) any later version.
10
11  This program is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  GNU General Public License for more details.
15
16  You should have received a copy of the GNU General Public License
17  along with this program; if not, write to the Free Software
18  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19 */
20 #include <linux/kernel.h>
21 #include <linux/errno.h>
22 #include <linux/slab.h>
23 #include <linux/module.h>
24 #include <linux/kref.h>
25 #include <linux/uaccess.h>
26 #include <linux/usb.h>
27 #include <linux/mutex.h>
28 #include <linux/page-flags.h>
29 #include <linux/pagemap.h>
30 #include <linux/jiffies.h>
31
32 #include "usb1401.h"
33
34 /****************************************************************************
35 ** ced_flush_out_buff
36 **
37 ** Empties the Output buffer and sets int lines. Used from user level only
38 ****************************************************************************/
39 static void ced_flush_out_buff(DEVICE_EXTENSION *pdx)
40 {
41         dev_dbg(&pdx->interface->dev, "%s: currentState=%d\n",
42                 __func__, pdx->sCurrentState);
43         if (pdx->sCurrentState == U14ERR_TIME)  /* Do nothing if hardware in trouble */
44                 return;
45         /* Kill off any pending I/O */
46         /* CharSend_Cancel(pdx);  */
47         spin_lock_irq(&pdx->charOutLock);
48         pdx->dwNumOutput = 0;
49         pdx->dwOutBuffGet = 0;
50         pdx->dwOutBuffPut = 0;
51         spin_unlock_irq(&pdx->charOutLock);
52 }
53
54 /****************************************************************************
55 **
56 ** ced_flush_in_buff
57 **
58 ** Empties the input buffer and sets int lines
59 ****************************************************************************/
60 static void ced_flush_in_buff(DEVICE_EXTENSION *pdx)
61 {
62         dev_dbg(&pdx->interface->dev, "%s: currentState=%d\n",
63                 __func__, pdx->sCurrentState);
64         if (pdx->sCurrentState == U14ERR_TIME)  /* Do nothing if hardware in trouble */
65                 return;
66         /* Kill off any pending I/O */
67         /*     CharRead_Cancel(pDevObject);  */
68         spin_lock_irq(&pdx->charInLock);
69         pdx->dwNumInput = 0;
70         pdx->dwInBuffGet = 0;
71         pdx->dwInBuffPut = 0;
72         spin_unlock_irq(&pdx->charInLock);
73 }
74
75 /****************************************************************************
76 ** ced_put_chars
77 **
78 ** Utility routine to copy chars into the output buffer and fire them off.
79 ** called from user mode, holds charOutLock.
80 ****************************************************************************/
81 static int ced_put_chars(DEVICE_EXTENSION *pdx, const char *pCh,
82                     unsigned int uCount)
83 {
84         int iReturn;
85         spin_lock_irq(&pdx->charOutLock);       /*  get the output spin lock */
86         if ((OUTBUF_SZ - pdx->dwNumOutput) >= uCount) {
87                 unsigned int u;
88                 for (u = 0; u < uCount; u++) {
89                         pdx->outputBuffer[pdx->dwOutBuffPut++] = pCh[u];
90                         if (pdx->dwOutBuffPut >= OUTBUF_SZ)
91                                 pdx->dwOutBuffPut = 0;
92                 }
93                 pdx->dwNumOutput += uCount;
94                 spin_unlock_irq(&pdx->charOutLock);
95                 iReturn = ced_send_chars(pdx);  /*  ...give a chance to transmit data */
96         } else {
97                 iReturn = U14ERR_NOOUT; /*  no room at the out (ha-ha) */
98                 spin_unlock_irq(&pdx->charOutLock);
99         }
100         return iReturn;
101 }
102
103 /*****************************************************************************
104 ** Add the data in pData (local pointer) of length n to the output buffer, and
105 ** trigger an output transfer if this is appropriate. User mode.
106 ** Holds the io_mutex
107 *****************************************************************************/
108 int ced_send_string(DEVICE_EXTENSION *pdx, const char __user *pData,
109                unsigned int n)
110 {
111         int iReturn = U14ERR_NOERROR;   /*  assume all will be well */
112         char buffer[OUTBUF_SZ + 1];     /*  space in our address space for characters */
113         if (n > OUTBUF_SZ)      /*  check space in local buffer... */
114                 return U14ERR_NOOUT;    /*  ...too many characters */
115         if (copy_from_user(buffer, pData, n))
116                 return -EFAULT;
117         buffer[n] = 0;          /*  terminate for debug purposes */
118
119         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
120         if (n > 0) {            /*  do nothing if nowt to do! */
121                 dev_dbg(&pdx->interface->dev, "%s: n=%d>%s<\n",
122                         __func__, n, buffer);
123                 iReturn = ced_put_chars(pdx, buffer, n);
124         }
125
126         ced_allowi(pdx);                /*  make sure we have input int */
127         mutex_unlock(&pdx->io_mutex);
128
129         return iReturn;
130 }
131
132 /****************************************************************************
133 ** ced_send_char
134 **
135 ** Sends a single character to the 1401. User mode, holds io_mutex.
136 ****************************************************************************/
137 int ced_send_char(DEVICE_EXTENSION *pdx, char c)
138 {
139         int iReturn;
140         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
141         iReturn = ced_put_chars(pdx, &c, 1);
142         dev_dbg(&pdx->interface->dev, "ced_send_char >%c< (0x%02x)\n", c, c);
143         ced_allowi(pdx);        /*  Make sure char reads are running */
144         mutex_unlock(&pdx->io_mutex);
145         return iReturn;
146 }
147
148 /***************************************************************************
149 **
150 ** ced_get_state
151 **
152 **  Retrieves state information from the 1401, adjusts the 1401 state held
153 **  in the device extension to indicate the current 1401 type.
154 **
155 **  *state is updated with information about the 1401 state as returned by the
156 **         1401. The low byte is a code for what 1401 is doing:
157 **
158 **  0       normal 1401 operation
159 **  1       sending chars to host
160 **  2       sending block data to host
161 **  3       reading block data from host
162 **  4       sending an escape sequence to the host
163 **  0x80    1401 is executing self-test, in which case the upper word
164 **          is the last error code seen (or zero for no new error).
165 **
166 ** *error is updated with error information if a self-test error code
167 **          is returned in the upper word of state.
168 **
169 **  both state and error are set to -1 if there are comms problems, and
170 **  to zero if there is a simple failure.
171 **
172 ** return error code (U14ERR_NOERROR for OK)
173 */
174 int ced_get_state(DEVICE_EXTENSION *pdx, __u32 *state, __u32 *error)
175 {
176         int nGot;
177         dev_dbg(&pdx->interface->dev, "%s: entry\n", __func__);
178
179         *state = 0xFFFFFFFF;    /*  Start off with invalid state */
180         nGot = usb_control_msg(pdx->udev, usb_rcvctrlpipe(pdx->udev, 0),
181                                GET_STATUS, (D_TO_H | VENDOR | DEVREQ), 0, 0,
182                                pdx->statBuf, sizeof(pdx->statBuf), HZ);
183         if (nGot != sizeof(pdx->statBuf)) {
184                 dev_err(&pdx->interface->dev,
185                         "%s: FAILED, return code %d\n", __func__, nGot);
186                 pdx->sCurrentState = U14ERR_TIME;       /*  Indicate that things are very wrong indeed */
187                 *state = 0;     /*  Force status values to a known state */
188                 *error = 0;
189         } else {
190                 int nDevice;
191                 dev_dbg(&pdx->interface->dev,
192                         "%s: Success, state: 0x%x, 0x%x\n",
193                         __func__, pdx->statBuf[0], pdx->statBuf[1]);
194
195                 *state = pdx->statBuf[0];       /*  Return the state values to the calling code */
196                 *error = pdx->statBuf[1];
197
198                 nDevice = pdx->udev->descriptor.bcdDevice >> 8; /*  1401 type code value */
199                 switch (nDevice) {      /*  so we can clean up current state */
200                 case 0:
201                         pdx->sCurrentState = U14ERR_U1401;
202                         break;
203
204                 default:        /*  allow lots of device codes for future 1401s */
205                         if ((nDevice >= 1) && (nDevice <= 23))
206                                 pdx->sCurrentState = (short)(nDevice + 6);
207                         else
208                                 pdx->sCurrentState = U14ERR_ILL;
209                         break;
210                 }
211         }
212
213         return pdx->sCurrentState >= 0 ? U14ERR_NOERROR : pdx->sCurrentState;
214 }
215
216 /****************************************************************************
217 ** ced_read_write_cancel
218 **
219 ** Kills off staged read\write request from the USB if one is pending.
220 ****************************************************************************/
221 int ced_read_write_cancel(DEVICE_EXTENSION *pdx)
222 {
223         dev_dbg(&pdx->interface->dev, "%s: entry %d\n",
224                 __func__, pdx->bStagedUrbPending);
225 #ifdef NOT_WRITTEN_YET
226         int ntStatus = STATUS_SUCCESS;
227         bool bResult = false;
228         unsigned int i;
229         /*  We can fill this in when we know how we will implement the staged transfer stuff */
230         spin_lock_irq(&pdx->stagedLock);
231
232         if (pdx->bStagedUrbPending) {   /*  anything to be cancelled? May need more... */
233                 dev_info(&pdx->interface - dev,
234                          "ced_read_write_cancel about to cancel Urb\n");
235                 /* Clear the staging done flag */
236                 /* KeClearEvent(&pdx->StagingDoneEvent); */
237                 USB_ASSERT(pdx->pStagedIrp != NULL);
238
239                 /*  Release the spinlock first otherwise the completion routine may hang */
240                 /*   on the spinlock while this function hands waiting for the event. */
241                 spin_unlock_irq(&pdx->stagedLock);
242                 bResult = IoCancelIrp(pdx->pStagedIrp); /*  Actually do the cancel */
243                 if (bResult) {
244                         LARGE_INTEGER timeout;
245                         timeout.QuadPart = -10000000;   /*  Use a timeout of 1 second */
246                         dev_info(&pdx->interface - dev,
247                                  "%s: about to wait till done\n", __func__);
248                         ntStatus =
249                             KeWaitForSingleObject(&pdx->StagingDoneEvent,
250                                                   Executive, KernelMode, FALSE,
251                                                   &timeout);
252                 } else {
253                         dev_info(&pdx->interface - dev,
254                                  "%s: cancellation failed\n", __func__);
255                         ntStatus = U14ERR_FAIL;
256                 }
257                 USB_KdPrint(DBGLVL_DEFAULT,
258                             ("ced_read_write_cancel ntStatus = 0x%x decimal %d\n",
259                              ntStatus, ntStatus));
260         } else
261                 spin_unlock_irq(&pdx->stagedLock);
262
263         dev_info(&pdx->interface - dev, "%s: done\n", __func__);
264         return ntStatus;
265 #else
266         return U14ERR_NOERROR;
267 #endif
268
269 }
270
271 /***************************************************************************
272 ** ced_in_self_test - utility to check in self test. Return 1 for ST, 0 for not or
273 ** a -ve error code if we failed for some reason.
274 ***************************************************************************/
275 static int ced_in_self_test(DEVICE_EXTENSION *pdx, unsigned int *pState)
276 {
277         unsigned int state, error;
278         int iReturn = ced_get_state(pdx, &state, &error);       /*  see if in self-test */
279         if (iReturn == U14ERR_NOERROR)  /*  if all still OK */
280                 iReturn = (state == (unsigned int)-1) ||        /*  TX problem or... */
281                     ((state & 0xff) == 0x80);   /*  ...self test */
282         *pState = state;        /*  return actual state */
283         return iReturn;
284 }
285
286 /***************************************************************************
287 ** ced_is_1401 - ALWAYS CALLED HOLDING THE io_mutex
288 **
289 ** Tests for the current state of the 1401. Sets sCurrentState:
290 **
291 **  U14ERR_NOIF  1401  i/f card not installed (not done here)
292 **  U14ERR_OFF   1401  apparently not switched on
293 **  U14ERR_NC    1401  appears to be not connected
294 **  U14ERR_ILL   1401  if it is there its not very well at all
295 **  U14ERR_TIME  1401  appears OK, but doesn't communicate - very bad
296 **  U14ERR_STD   1401  OK and ready for use
297 **  U14ERR_PLUS  1401+ OK and ready for use
298 **  U14ERR_U1401 Micro1401 OK and ready for use
299 **  U14ERR_POWER Power1401 OK and ready for use
300 **  U14ERR_U14012 Micro1401 mkII OK and ready for use
301 **
302 **  Returns TRUE if a 1401 detected and OK, else FALSE
303 ****************************************************************************/
304 static bool ced_is_1401(DEVICE_EXTENSION *pdx)
305 {
306         int iReturn;
307         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
308
309         ced_draw_down(pdx);     /*  wait for, then kill outstanding Urbs */
310         ced_flush_in_buff(pdx); /*  Clear out input buffer & pipe */
311         ced_flush_out_buff(pdx);        /*  Clear output buffer & pipe */
312
313         /*  The next call returns 0 if OK, but has returned 1 in the past, meaning that */
314         /*  usb_unlock_device() is needed... now it always is */
315         iReturn = usb_lock_device_for_reset(pdx->udev, pdx->interface);
316
317         /*  release the io_mutex because if we don't, we will deadlock due to system */
318         /*  calls back into the driver. */
319         mutex_unlock(&pdx->io_mutex);   /*  locked, so we will not get system calls */
320         if (iReturn >= 0) {     /*  if we failed */
321                 iReturn = usb_reset_device(pdx->udev);  /*  try to do the reset */
322                 usb_unlock_device(pdx->udev);   /*  undo the lock */
323         }
324
325         mutex_lock(&pdx->io_mutex);     /*  hold stuff off while we wait */
326         pdx->dwDMAFlag = MODE_CHAR;     /*  Clear DMA mode flag regardless! */
327         if (iReturn == 0) {     /*  if all is OK still */
328                 unsigned int state;
329                 iReturn = ced_in_self_test(pdx, &state);        /*  see if likely in self test */
330                 if (iReturn > 0) {      /*  do we need to wait for self-test? */
331                         unsigned long ulTimeOut = jiffies + 30 * HZ;    /*  when to give up */
332                         while ((iReturn > 0) && time_before(jiffies, ulTimeOut)) {
333                                 schedule();     /*  let other stuff run */
334                                 iReturn = ced_in_self_test(pdx, &state);        /*  see if done yet */
335                         }
336                 }
337
338                 if (iReturn == 0)       /*  if all is OK... */
339                         iReturn = state == 0;   /*  then success is that the state is 0 */
340         } else
341                 iReturn = 0;    /*  we failed */
342         pdx->bForceReset = false;       /*  Clear forced reset flag now */
343
344         return iReturn > 0;
345 }
346
347 /****************************************************************************
348 ** ced_quick_check  - ALWAYS CALLED HOLDING THE io_mutex
349 ** This is used to test for a 1401. It will try to do a quick check if all is
350 **  OK, that is the 1401 was OK the last time it was asked, and there is no DMA
351 **  in progress, and if the bTestBuff flag is set, the character buffers must be
352 **  empty too. If the quick check shows that the state is still the same, then
353 **  all is OK.
354 **
355 ** If any of the above conditions are not met, or if the state or type of the
356 **  1401 has changed since the previous test, the full ced_is_1401 test is done, but
357 **  only if bCanReset is also TRUE.
358 **
359 ** The return value is TRUE if a useable 1401 is found, FALSE if not
360 */
361 static bool ced_quick_check(DEVICE_EXTENSION *pdx, bool bTestBuff, bool bCanReset)
362 {
363         bool bRet = false;      /*  assume it will fail and we will reset */
364         bool bShortTest;
365
366         bShortTest = ((pdx->dwDMAFlag == MODE_CHAR) &&  /*  no DMA running */
367                       (!pdx->bForceReset) &&    /*  Not had a real reset forced */
368                       (pdx->sCurrentState >= U14ERR_STD));      /*  No 1401 errors stored */
369
370         dev_dbg(&pdx->interface->dev,
371                 "%s: DMAFlag:%d, state:%d, force:%d, testBuff:%d, short:%d\n",
372                 __func__, pdx->dwDMAFlag, pdx->sCurrentState, pdx->bForceReset,
373                 bTestBuff, bShortTest);
374
375         if ((bTestBuff) &&      /*  Buffer check requested, and... */
376             (pdx->dwNumInput || pdx->dwNumOutput)) {    /*  ...characters were in the buffer? */
377                 bShortTest = false;     /*  Then do the full test */
378                 dev_dbg(&pdx->interface->dev,
379                         "%s: will reset as buffers not empty\n", __func__);
380         }
381
382         if (bShortTest || !bCanReset) { /*  Still OK to try the short test? */
383                                 /*  Always test if no reset - we want state update */
384                 unsigned int state, error;
385                 dev_dbg(&pdx->interface->dev, "%s: ced_get_state\n", __func__);
386                 if (ced_get_state(pdx, &state, &error) == U14ERR_NOERROR) {     /*  Check on the 1401 state */
387                         if ((state & 0xFF) == 0)        /*  If call worked, check the status value */
388                                 bRet = true;    /*  If that was zero, all is OK, no reset needed */
389                 }
390         }
391
392         if (!bRet && bCanReset) { /*  If all not OK, then */
393                 dev_info(&pdx->interface->dev, "%s: ced_is_1401 %d %d %d %d\n",
394                          __func__, bShortTest, pdx->sCurrentState, bTestBuff,
395                          pdx->bForceReset);
396                 bRet = ced_is_1401(pdx);        /*   do full test */
397         }
398
399         return bRet;
400 }
401
402 /****************************************************************************
403 ** ced_reset
404 **
405 ** Resets the 1401 and empties the i/o buffers
406 *****************************************************************************/
407 int ced_reset(DEVICE_EXTENSION *pdx)
408 {
409         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
410         dev_dbg(&pdx->interface->dev, "%s: About to call ced_quick_check\n",
411                 __func__);
412         ced_quick_check(pdx, true, true);       /*  Check 1401, reset if not OK */
413         mutex_unlock(&pdx->io_mutex);
414         return U14ERR_NOERROR;
415 }
416
417 /****************************************************************************
418 ** ced_get_char
419 **
420 ** Gets a single character from the 1401
421 ****************************************************************************/
422 int ced_get_char(DEVICE_EXTENSION *pdx)
423 {
424         int iReturn = U14ERR_NOIN;      /*  assume we will get  nothing */
425         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
426
427         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
428
429         ced_allowi(pdx);        /*  Make sure char reads are running */
430         ced_send_chars(pdx);    /*  and send any buffered chars */
431
432         spin_lock_irq(&pdx->charInLock);
433         if (pdx->dwNumInput > 0) {      /*  worth looking */
434                 iReturn = pdx->inputBuffer[pdx->dwInBuffGet++];
435                 if (pdx->dwInBuffGet >= INBUF_SZ)
436                         pdx->dwInBuffGet = 0;
437                 pdx->dwNumInput--;
438         } else
439                 iReturn = U14ERR_NOIN;  /*  no input data to read */
440         spin_unlock_irq(&pdx->charInLock);
441
442         ced_allowi(pdx);        /*  Make sure char reads are running */
443
444         mutex_unlock(&pdx->io_mutex);   /*  Protect disconnect from new i/o */
445         return iReturn;
446 }
447
448 /****************************************************************************
449 ** ced_get_string
450 **
451 ** Gets a string from the 1401. Returns chars up to the next CR or when
452 ** there are no more to read or nowhere to put them. CR is translated to
453 ** 0 and counted as a character. If the string does not end in a 0, we will
454 ** add one, if there is room, but it is not counted as a character.
455 **
456 ** returns the count of characters (including the terminator, or 0 if none
457 ** or a negative error code.
458 ****************************************************************************/
459 int ced_get_string(DEVICE_EXTENSION *pdx, char __user *pUser, int n)
460 {
461         int nAvailable;         /*  character in the buffer */
462         int iReturn = U14ERR_NOIN;
463         if (n <= 0)
464                 return -ENOMEM;
465
466         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
467         ced_allowi(pdx);        /*  Make sure char reads are running */
468         ced_send_chars(pdx);            /*  and send any buffered chars */
469
470         spin_lock_irq(&pdx->charInLock);
471         nAvailable = pdx->dwNumInput;   /*  characters available now */
472         if (nAvailable > n)     /*  read max of space in pUser... */
473                 nAvailable = n; /*  ...or input characters */
474
475         if (nAvailable > 0) {   /*  worth looking? */
476                 char buffer[INBUF_SZ + 1];      /*  space for a linear copy of data */
477                 int nGot = 0;
478                 int nCopyToUser;        /*  number to copy to user */
479                 char cData;
480                 do {
481                         cData = pdx->inputBuffer[pdx->dwInBuffGet++];
482                         if (cData == CR_CHAR)   /*  replace CR with zero */
483                                 cData = (char)0;
484
485                         if (pdx->dwInBuffGet >= INBUF_SZ)
486                                 pdx->dwInBuffGet = 0;   /*  wrap buffer pointer */
487
488                         buffer[nGot++] = cData; /*  save the output */
489                 } while ((nGot < nAvailable) && cData);
490
491                 nCopyToUser = nGot;     /*  what to copy... */
492                 if (cData) {    /*  do we need null */
493                         buffer[nGot] = (char)0; /*  make it tidy */
494                         if (nGot < n)   /*  if space in user buffer... */
495                                 ++nCopyToUser;  /*  ...copy the 0 as well. */
496                 }
497
498                 pdx->dwNumInput -= nGot;
499                 spin_unlock_irq(&pdx->charInLock);
500
501                 dev_dbg(&pdx->interface->dev, "%s: read %d characters >%s<\n",
502                         __func__, nGot, buffer);
503                 if (copy_to_user(pUser, buffer, nCopyToUser))
504                         iReturn = -EFAULT;
505                 else
506                         iReturn = nGot;         /*  report characters read */
507         } else
508                 spin_unlock_irq(&pdx->charInLock);
509
510         ced_allowi(pdx);        /*  Make sure char reads are running */
511         mutex_unlock(&pdx->io_mutex);   /*  Protect disconnect from new i/o */
512
513         return iReturn;
514 }
515
516 /*******************************************************************************
517 ** Get count of characters in the inout buffer.
518 *******************************************************************************/
519 int ced_stat_1401(DEVICE_EXTENSION *pdx)
520 {
521         int iReturn;
522         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
523         ced_allowi(pdx);                /*  make sure we allow pending chars */
524         ced_send_chars(pdx);            /*  in both directions */
525         iReturn = pdx->dwNumInput;      /*  no lock as single read */
526         mutex_unlock(&pdx->io_mutex);   /*  Protect disconnect from new i/o */
527         return iReturn;
528 }
529
530 /****************************************************************************
531 ** ced_line_count
532 **
533 ** Returns the number of newline chars in the buffer. There is no need for
534 ** any fancy interlocks as we only read the interrupt routine data, and the
535 ** system is arranged so nothing can be destroyed.
536 ****************************************************************************/
537 int ced_line_count(DEVICE_EXTENSION *pdx)
538 {
539         int iReturn = 0;        /*  will be count of line ends */
540
541         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
542         ced_allowi(pdx);                /*  Make sure char reads are running */
543         ced_send_chars(pdx);            /*  and send any buffered chars */
544         spin_lock_irq(&pdx->charInLock);        /*  Get protection */
545
546         if (pdx->dwNumInput > 0) {      /*  worth looking? */
547                 unsigned int dwIndex = pdx->dwInBuffGet;        /*  start at first available */
548                 unsigned int dwEnd = pdx->dwInBuffPut;  /*  Position for search end */
549                 do {
550                         if (pdx->inputBuffer[dwIndex++] == CR_CHAR)
551                                 ++iReturn;      /*  inc count if CR */
552
553                         if (dwIndex >= INBUF_SZ)        /*  see if we fall off buff */
554                                 dwIndex = 0;
555                 } while (dwIndex != dwEnd);     /*  go to last available */
556         }
557
558         spin_unlock_irq(&pdx->charInLock);
559         dev_dbg(&pdx->interface->dev, "%s: returned %d\n", __func__, iReturn);
560         mutex_unlock(&pdx->io_mutex);   /*  Protect disconnect from new i/o */
561         return iReturn;
562 }
563
564 /****************************************************************************
565 ** ced_get_out_buf_space
566 **
567 ** Gets the space in the output buffer. Called from user code.
568 *****************************************************************************/
569 int ced_get_out_buf_space(DEVICE_EXTENSION *pdx)
570 {
571         int iReturn;
572         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
573         ced_send_chars(pdx);            /*  send any buffered chars */
574         iReturn = (int)(OUTBUF_SZ - pdx->dwNumOutput);  /*  no lock needed for single read */
575         dev_dbg(&pdx->interface->dev, "%s: %d\n", __func__, iReturn);
576         mutex_unlock(&pdx->io_mutex);   /*  Protect disconnect from new i/o */
577         return iReturn;
578 }
579
580 /****************************************************************************
581 **
582 ** ced_clear_area
583 **
584 ** Clears up a transfer area. This is always called in the context of a user
585 ** request, never from a call-back.
586 ****************************************************************************/
587 int ced_clear_area(DEVICE_EXTENSION *pdx, int nArea)
588 {
589         int iReturn = U14ERR_NOERROR;
590
591         if ((nArea < 0) || (nArea >= MAX_TRANSAREAS)) {
592                 iReturn = U14ERR_BADAREA;
593                 dev_err(&pdx->interface->dev, "%s: Attempt to clear area %d\n",
594                         __func__, nArea);
595         } else {
596                 TRANSAREA *pTA = &pdx->rTransDef[nArea];        /*  to save typing */
597                 if (!pTA->bUsed)        /*  if not used... */
598                         iReturn = U14ERR_NOTSET;        /*  ...nothing to be done */
599                 else {
600                         /*  We must save the memory we return as we shouldn't mess with memory while */
601                         /*  holding a spin lock. */
602                         struct page **pPages = NULL; /*save page address list*/
603                         int nPages = 0; /*  and number of pages */
604                         int np;
605
606                         dev_dbg(&pdx->interface->dev, "%s: area %d\n",
607                                 __func__, nArea);
608                         spin_lock_irq(&pdx->stagedLock);
609                         if ((pdx->StagedId == nArea)
610                             && (pdx->dwDMAFlag > MODE_CHAR)) {
611                                 iReturn = U14ERR_UNLOCKFAIL;    /*  cannot delete as in use */
612                                 dev_err(&pdx->interface->dev,
613                                         "%s: call on area %d while active\n",
614                                         __func__, nArea);
615                         } else {
616                                 pPages = pTA->pPages;   /*  save page address list */
617                                 nPages = pTA->nPages;   /*  and page count */
618                                 if (pTA->dwEventSz)     /*  if events flagging in use */
619                                         wake_up_interruptible(&pTA->wqEvent);   /*  release anything that was waiting */
620
621                                 if (pdx->bXFerWaiting
622                                     && (pdx->rDMAInfo.wIdent == nArea))
623                                         pdx->bXFerWaiting = false;      /*  Cannot have pending xfer if area cleared */
624
625                                 /*  Clean out the TRANSAREA except for the wait queue, which is at the end */
626                                 /*  This sets bUsed to false and dwEventSz to 0 to say area not used and no events. */
627                                 memset(pTA, 0,
628                                        sizeof(TRANSAREA) -
629                                        sizeof(wait_queue_head_t));
630                         }
631                         spin_unlock_irq(&pdx->stagedLock);
632
633                         if (pPages) {   /*  if we decided to release the memory */
634                                 /*  Now we must undo the pinning down of the pages. We will assume the worst and mark */
635                                 /*  all the pages as dirty. Don't be tempted to move this up above as you must not be */
636                                 /*  holding a spin lock to do this stuff as it is not atomic. */
637                                 dev_dbg(&pdx->interface->dev, "%s: nPages=%d\n",
638                                         __func__, nPages);
639
640                                 for (np = 0; np < nPages; ++np) {
641                                         if (pPages[np]) {
642                                                 SetPageDirty(pPages[np]);
643                                                 page_cache_release(pPages[np]);
644                                         }
645                                 }
646
647                                 kfree(pPages);
648                                 dev_dbg(&pdx->interface->dev,
649                                         "%s: kfree(pPages) done\n", __func__);
650                         }
651                 }
652         }
653
654         return iReturn;
655 }
656
657 /****************************************************************************
658 ** ced_set_area
659 **
660 ** Sets up a transfer area - the functional part. Called by both
661 ** ced_set_transfer and ced_set_circular.
662 ****************************************************************************/
663 static int ced_set_area(DEVICE_EXTENSION *pdx, int nArea, char __user *puBuf,
664                    unsigned int dwLength, bool bCircular, bool bCircToHost)
665 {
666         /*  Start by working out the page aligned start of the area and the size */
667         /*  of the area in pages, allowing for the start not being aligned and the */
668         /*  end needing to be rounded up to a page boundary. */
669         unsigned long ulStart = ((unsigned long)puBuf) & PAGE_MASK;
670         unsigned int ulOffset = ((unsigned long)puBuf) & (PAGE_SIZE - 1);
671         int len = (dwLength + ulOffset + PAGE_SIZE - 1) >> PAGE_SHIFT;
672
673         TRANSAREA *pTA = &pdx->rTransDef[nArea];        /*  to save typing */
674         struct page **pPages = NULL;    /*  space for page tables */
675         int nPages = 0;         /*  and number of pages */
676
677         int iReturn = ced_clear_area(pdx, nArea);       /*  see if OK to use this area */
678         if ((iReturn != U14ERR_NOTSET) &&       /*  if not area unused and... */
679             (iReturn != U14ERR_NOERROR))        /*  ...not all OK, then... */
680                 return iReturn; /*  ...we cannot use this area */
681
682         if (!access_ok(VERIFY_WRITE, puBuf, dwLength))  /*  if we cannot access the memory... */
683                 return -EFAULT; /*  ...then we are done */
684
685         /*  Now allocate space to hold the page pointer and virtual address pointer tables */
686         pPages = kmalloc(len * sizeof(struct page *), GFP_KERNEL);
687         if (!pPages) {
688                 iReturn = U14ERR_NOMEMORY;
689                 goto error;
690         }
691         dev_dbg(&pdx->interface->dev, "%s: %p, length=%06x, circular %d\n",
692                 __func__, puBuf, dwLength, bCircular);
693
694         /*  To pin down user pages we must first acquire the mapping semaphore. */
695         nPages = get_user_pages_fast(ulStart, len, 1, pPages);
696         dev_dbg(&pdx->interface->dev, "%s: nPages = %d\n", __func__, nPages);
697
698         if (nPages > 0) {               /*  if we succeeded */
699                 /*  If you are tempted to use page_address (form LDD3), forget it. You MUST use */
700                 /*  kmap() or kmap_atomic() to get a virtual address. page_address will give you */
701                 /*  (null) or at least it does in this context with an x86 machine. */
702                 spin_lock_irq(&pdx->stagedLock);
703                 pTA->lpvBuff = puBuf;   /*  keep start of region (user address) */
704                 pTA->dwBaseOffset = ulOffset;   /*  save offset in first page to start of xfer */
705                 pTA->dwLength = dwLength;       /*  Size if the region in bytes */
706                 pTA->pPages = pPages;   /*  list of pages that are used by buffer */
707                 pTA->nPages = nPages;   /*  number of pages */
708
709                 pTA->bCircular = bCircular;
710                 pTA->bCircToHost = bCircToHost;
711
712                 pTA->aBlocks[0].dwOffset = 0;
713                 pTA->aBlocks[0].dwSize = 0;
714                 pTA->aBlocks[1].dwOffset = 0;
715                 pTA->aBlocks[1].dwSize = 0;
716                 pTA->bUsed = true;      /*  This is now a used block */
717
718                 spin_unlock_irq(&pdx->stagedLock);
719                 iReturn = U14ERR_NOERROR;       /*  say all was well */
720         } else {
721                 iReturn = U14ERR_LOCKFAIL;
722                 goto error;
723         }
724
725         return iReturn;
726
727 error:
728         kfree(pPages);
729         return iReturn;
730 }
731
732 /****************************************************************************
733 ** ced_set_transfer
734 **
735 ** Sets up a transfer area record. If the area is already set, we attempt to
736 ** unset it. Unsetting will fail if the area is booked, and a transfer to that
737 ** area is in progress. Otherwise, we will release the area and re-assign it.
738 ****************************************************************************/
739 int ced_set_transfer(DEVICE_EXTENSION *pdx, struct transfer_area_desc __user *pTD)
740 {
741         int iReturn;
742         struct transfer_area_desc td;
743
744         if (copy_from_user(&td, pTD, sizeof(td)))
745                 return -EFAULT;
746
747         mutex_lock(&pdx->io_mutex);
748         dev_dbg(&pdx->interface->dev, "%s: area:%d, size:%08x\n",
749                 __func__, td.wAreaNum, td.dwLength);
750         /*  The strange cast is done so that we don't get warnings in 32-bit linux about the size of the */
751         /*  pointer. The pointer is always passed as a 64-bit object so that we don't have problems using */
752         /*  a 32-bit program on a 64-bit system. unsigned long is 64-bits on a 64-bit system. */
753         iReturn =
754             ced_set_area(pdx, td.wAreaNum,
755                     (char __user *)((unsigned long)td.lpvBuff), td.dwLength,
756                     false, false);
757         mutex_unlock(&pdx->io_mutex);
758         return iReturn;
759 }
760
761 /****************************************************************************
762 ** UnSetTransfer
763 ** Erases a transfer area record
764 ****************************************************************************/
765 int ced_unset_transfer(DEVICE_EXTENSION *pdx, int nArea)
766 {
767         int iReturn;
768         mutex_lock(&pdx->io_mutex);
769         iReturn = ced_clear_area(pdx, nArea);
770         mutex_unlock(&pdx->io_mutex);
771         return iReturn;
772 }
773
774 /****************************************************************************
775 ** ced_set_event
776 ** Creates an event that we can test for based on a transfer to/from an area.
777 ** The area must be setup for a transfer. We attempt to simulate the Windows
778 ** driver behavior for events (as we don't actually use them), which is to
779 ** pretend that whatever the user asked for was achieved, so we return 1 if
780 ** try to create one, and 0 if they ask to remove (assuming all else was OK).
781 ****************************************************************************/
782 int ced_set_event(DEVICE_EXTENSION *pdx, struct transfer_event __user *pTE)
783 {
784         int iReturn = U14ERR_NOERROR;
785         struct transfer_event te;
786
787         /*  get a local copy of the data */
788         if (copy_from_user(&te, pTE, sizeof(te)))
789                 return -EFAULT;
790
791         if (te.wAreaNum >= MAX_TRANSAREAS)      /*  the area must exist */
792                 return U14ERR_BADAREA;
793         else {
794                 TRANSAREA *pTA = &pdx->rTransDef[te.wAreaNum];
795                 mutex_lock(&pdx->io_mutex);     /*  make sure we have no competitor */
796                 spin_lock_irq(&pdx->stagedLock);
797                 if (pTA->bUsed) {       /*  area must be in use */
798                         pTA->dwEventSt = te.dwStart;    /*  set area regions */
799                         pTA->dwEventSz = te.dwLength;   /*  set size (0 cancels it) */
800                         pTA->bEventToHost = te.wFlags & 1;      /*  set the direction */
801                         pTA->iWakeUp = 0;       /*  zero the wake up count */
802                 } else
803                         iReturn = U14ERR_NOTSET;
804                 spin_unlock_irq(&pdx->stagedLock);
805                 mutex_unlock(&pdx->io_mutex);
806         }
807         return iReturn ==
808             U14ERR_NOERROR ? (te.iSetEvent ? 1 : U14ERR_NOERROR) : iReturn;
809 }
810
811 /****************************************************************************
812 ** ced_wait_event
813 ** Sleep the process with a timeout waiting for an event. Returns the number
814 ** of times that a block met the event condition since we last cleared it or
815 ** 0 if timed out, or -ve error (bad area or not set, or signal).
816 ****************************************************************************/
817 int ced_wait_event(DEVICE_EXTENSION *pdx, int nArea, int msTimeOut)
818 {
819         int iReturn;
820         if ((unsigned)nArea >= MAX_TRANSAREAS)
821                 return U14ERR_BADAREA;
822         else {
823                 int iWait;
824                 TRANSAREA *pTA = &pdx->rTransDef[nArea];
825                 msTimeOut = (msTimeOut * HZ + 999) / 1000;      /*  convert timeout to jiffies */
826
827                 /*  We cannot wait holding the mutex, but we check the flags while holding */
828                 /*  it. This may well be pointless as another thread could get in between */
829                 /*  releasing it and the wait call. However, this would have to clear the */
830                 /*  iWakeUp flag. However, the !pTA-bUsed may help us in this case. */
831                 mutex_lock(&pdx->io_mutex);     /*  make sure we have no competitor */
832                 if (!pTA->bUsed || !pTA->dwEventSz)     /*  check something to wait for... */
833                         return U14ERR_NOTSET;   /*  ...else we do nothing */
834                 mutex_unlock(&pdx->io_mutex);
835
836                 if (msTimeOut)
837                         iWait =
838                             wait_event_interruptible_timeout(pTA->wqEvent,
839                                                              pTA->iWakeUp
840                                                              || !pTA->bUsed,
841                                                              msTimeOut);
842                 else
843                         iWait =
844                             wait_event_interruptible(pTA->wqEvent, pTA->iWakeUp
845                                                      || !pTA->bUsed);
846                 if (iWait)
847                         iReturn = -ERESTARTSYS; /*  oops - we have had a SIGNAL */
848                 else
849                         iReturn = pTA->iWakeUp; /*  else the wakeup count */
850
851                 spin_lock_irq(&pdx->stagedLock);
852                 pTA->iWakeUp = 0;       /*  clear the flag */
853                 spin_unlock_irq(&pdx->stagedLock);
854         }
855         return iReturn;
856 }
857
858 /****************************************************************************
859 ** ced_test_event
860 ** Test the event to see if a ced_wait_event would return immediately. Returns the
861 ** number of times a block completed since the last call, or 0 if none or a
862 ** negative error.
863 ****************************************************************************/
864 int ced_test_event(DEVICE_EXTENSION *pdx, int nArea)
865 {
866         int iReturn;
867         if ((unsigned)nArea >= MAX_TRANSAREAS)
868                 iReturn = U14ERR_BADAREA;
869         else {
870                 TRANSAREA *pTA = &pdx->rTransDef[nArea];
871                 mutex_lock(&pdx->io_mutex);     /*  make sure we have no competitor */
872                 spin_lock_irq(&pdx->stagedLock);
873                 iReturn = pTA->iWakeUp; /*  get wakeup count since last call */
874                 pTA->iWakeUp = 0;       /*  clear the count */
875                 spin_unlock_irq(&pdx->stagedLock);
876                 mutex_unlock(&pdx->io_mutex);
877         }
878         return iReturn;
879 }
880
881 /****************************************************************************
882 ** ced_get_transferInfo
883 ** Puts the current state of the 1401 in a TGET_TX_BLOCK.
884 *****************************************************************************/
885 int ced_get_transfer(DEVICE_EXTENSION *pdx, TGET_TX_BLOCK __user *pTX)
886 {
887         int iReturn = U14ERR_NOERROR;
888         unsigned int dwIdent;
889
890         mutex_lock(&pdx->io_mutex);
891         dwIdent = pdx->StagedId;        /*  area ident for last xfer */
892         if (dwIdent >= MAX_TRANSAREAS)
893                 iReturn = U14ERR_BADAREA;
894         else {
895                 /*  Return the best information we have - we don't have physical addresses */
896                 TGET_TX_BLOCK *tx;
897
898                 tx = kzalloc(sizeof(*tx), GFP_KERNEL);
899                 if (!tx) {
900                         mutex_unlock(&pdx->io_mutex);
901                         return -ENOMEM;
902                 }
903                 tx->size = pdx->rTransDef[dwIdent].dwLength;
904                 tx->linear = (long long)((long)pdx->rTransDef[dwIdent].lpvBuff);
905                 tx->avail = GET_TX_MAXENTRIES;  /*  how many blocks we could return */
906                 tx->used = 1;   /*  number we actually return */
907                 tx->entries[0].physical =
908                     (long long)(tx->linear + pdx->StagedOffset);
909                 tx->entries[0].size = tx->size;
910
911                 if (copy_to_user(pTX, tx, sizeof(*tx)))
912                         iReturn = -EFAULT;
913                 kfree(tx);
914         }
915         mutex_unlock(&pdx->io_mutex);
916         return iReturn;
917 }
918
919 /****************************************************************************
920 ** ced_kill_io
921 **
922 ** Empties the host i/o buffers
923 ****************************************************************************/
924 int ced_kill_io(DEVICE_EXTENSION *pdx)
925 {
926         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
927         mutex_lock(&pdx->io_mutex);
928         ced_flush_out_buff(pdx);
929         ced_flush_in_buff(pdx);
930         mutex_unlock(&pdx->io_mutex);
931         return U14ERR_NOERROR;
932 }
933
934 /****************************************************************************
935 ** ced_state_of_1401
936 **
937 ** Puts the current state of the 1401 in the Irp return buffer.
938 *****************************************************************************/
939 int ced_state_of_1401(DEVICE_EXTENSION *pdx)
940 {
941         int iReturn;
942         mutex_lock(&pdx->io_mutex);
943
944         ced_quick_check(pdx, false, false);     /*  get state up to date, no reset */
945         iReturn = pdx->sCurrentState;
946
947         mutex_unlock(&pdx->io_mutex);
948         dev_dbg(&pdx->interface->dev, "%s: %d\n", __func__, iReturn);
949
950         return iReturn;
951 }
952
953 /****************************************************************************
954 ** ced_start_self_test
955 **
956 ** Initiates a self-test cycle. The assumption is that we have no interrupts
957 ** active, so we should make sure that this is the case.
958 *****************************************************************************/
959 int ced_start_self_test(DEVICE_EXTENSION *pdx)
960 {
961         int nGot;
962         mutex_lock(&pdx->io_mutex);
963         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
964
965         ced_draw_down(pdx);     /*  wait for, then kill outstanding Urbs */
966         ced_flush_in_buff(pdx); /*  Clear out input buffer & pipe */
967         ced_flush_out_buff(pdx);        /*  Clear output buffer & pipe */
968         /* so things stay tidy */
969         /* ced_read_write_cancel(pDeviceObject); */
970         pdx->dwDMAFlag = MODE_CHAR;     /* Clear DMA mode flags here */
971
972         nGot = usb_control_msg(pdx->udev, usb_rcvctrlpipe(pdx->udev, 0),
973                                DB_SELFTEST, (H_TO_D | VENDOR | DEVREQ),
974                                0, 0, NULL, 0, HZ); /* allow 1 second timeout */
975         pdx->ulSelfTestTime = jiffies + HZ * 30;        /*  30 seconds into the future */
976
977         mutex_unlock(&pdx->io_mutex);
978         if (nGot < 0)
979                 dev_err(&pdx->interface->dev, "%s: err=%d\n", __func__, nGot);
980         return nGot < 0 ? U14ERR_FAIL : U14ERR_NOERROR;
981 }
982
983 /****************************************************************************
984 ** ced_check_self_test
985 **
986 ** Check progress of a self-test cycle
987 ****************************************************************************/
988 int ced_check_self_test(DEVICE_EXTENSION *pdx, TGET_SELFTEST __user *pGST)
989 {
990         unsigned int state, error;
991         int iReturn;
992         TGET_SELFTEST gst;      /*  local work space */
993         memset(&gst, 0, sizeof(gst));   /*  clear out the space (sets code 0) */
994
995         mutex_lock(&pdx->io_mutex);
996
997         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
998         iReturn = ced_get_state(pdx, &state, &error);
999         if (iReturn == U14ERR_NOERROR)  /*  Only accept zero if it happens twice */
1000                 iReturn = ced_get_state(pdx, &state, &error);
1001
1002         if (iReturn != U14ERR_NOERROR) {        /*  Self-test can cause comms errors */
1003                                 /*  so we assume still testing */
1004                 dev_err(&pdx->interface->dev,
1005                         "%s: ced_get_state=%d, assuming still testing\n",
1006                         __func__, iReturn);
1007                 state = 0x80;   /*  Force still-testing, no error */
1008                 error = 0;
1009                 iReturn = U14ERR_NOERROR;
1010         }
1011
1012         if ((state == -1) && (error == -1)) {   /*  If ced_get_state had problems */
1013                 dev_err(&pdx->interface->dev,
1014                         "%s: ced_get_state failed, assuming still testing\n",
1015                         __func__);
1016                 state = 0x80;   /*  Force still-testing, no error */
1017                 error = 0;
1018         }
1019
1020         if ((state & 0xFF) == 0x80) {   /*  If we are still in self-test */
1021                 if (state & 0x00FF0000) { /*  Have we got an error? */
1022                         gst.code = (state & 0x00FF0000) >> 16;  /*  read the error code */
1023                         gst.x = error & 0x0000FFFF;     /*  Error data X */
1024                         gst.y = (error & 0xFFFF0000) >> 16;     /*  and data Y */
1025                         dev_dbg(&pdx->interface->dev,
1026                                 "Self-test error code %d\n", gst.code);
1027                 } else {                /*  No error, check for timeout */
1028                         unsigned long ulNow = jiffies;  /*  get current time */
1029                         if (time_after(ulNow, pdx->ulSelfTestTime)) {
1030                                 gst.code = -2;  /*  Flag the timeout */
1031                                 dev_dbg(&pdx->interface->dev,
1032                                         "Self-test timed-out\n");
1033                         } else
1034                                 dev_dbg(&pdx->interface->dev,
1035                                         "Self-test on-going\n");
1036                 }
1037         } else {
1038                 gst.code = -1;  /*  Flag the test is done */
1039                 dev_dbg(&pdx->interface->dev, "Self-test done\n");
1040         }
1041
1042         if (gst.code < 0) {     /*  If we have a problem or finished */
1043                                 /*  If using the 2890 we should reset properly */
1044                 if ((pdx->nPipes == 4) && (pdx->s1401Type <= TYPEPOWER))
1045                         ced_is_1401(pdx);       /*  Get 1401 reset and OK */
1046                 else
1047                         ced_quick_check(pdx, true, true);       /*  Otherwise check without reset unless problems */
1048         }
1049         mutex_unlock(&pdx->io_mutex);
1050
1051         if (copy_to_user(pGST, &gst, sizeof(gst)))
1052                 return -EFAULT;
1053
1054         return iReturn;
1055 }
1056
1057 /****************************************************************************
1058 ** ced_type_of_1401
1059 **
1060 ** Returns code for standard, plus, micro1401, power1401 or none
1061 ****************************************************************************/
1062 int ced_type_of_1401(DEVICE_EXTENSION *pdx)
1063 {
1064         int iReturn = TYPEUNKNOWN;
1065         mutex_lock(&pdx->io_mutex);
1066         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
1067
1068         switch (pdx->s1401Type) {
1069         case TYPE1401:
1070                 iReturn = U14ERR_STD;
1071                 break;          /*  Handle these types directly */
1072         case TYPEPLUS:
1073                 iReturn = U14ERR_PLUS;
1074                 break;
1075         case TYPEU1401:
1076                 iReturn = U14ERR_U1401;
1077                 break;
1078         default:
1079                 if ((pdx->s1401Type >= TYPEPOWER) && (pdx->s1401Type <= 25))
1080                         iReturn = pdx->s1401Type + 4;   /*  We can calculate types */
1081                 else            /*   for up-coming 1401 designs */
1082                         iReturn = TYPEUNKNOWN;  /*  Don't know or not there */
1083         }
1084         dev_dbg(&pdx->interface->dev, "%s %d\n", __func__, iReturn);
1085         mutex_unlock(&pdx->io_mutex);
1086
1087         return iReturn;
1088 }
1089
1090 /****************************************************************************
1091 ** ced_transfer_flags
1092 **
1093 ** Returns flags on block transfer abilities
1094 ****************************************************************************/
1095 int ced_transfer_flags(DEVICE_EXTENSION *pdx)
1096 {
1097         int iReturn = U14TF_MULTIA | U14TF_DIAG |       /*  we always have multiple DMA area */
1098             U14TF_NOTIFY | U14TF_CIRCTH;        /*  diagnostics, notify and circular */
1099         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
1100         mutex_lock(&pdx->io_mutex);
1101         if (pdx->bIsUSB2)       /*  Set flag for USB2 if appropriate */
1102                 iReturn |= U14TF_USB2;
1103         mutex_unlock(&pdx->io_mutex);
1104
1105         return iReturn;
1106 }
1107
1108 /***************************************************************************
1109 ** ced_dbg_cmd
1110 ** Issues a debug\diagnostic command to the 1401 along with a 32-bit datum
1111 ** This is a utility command used for dbg operations.
1112 */
1113 static int ced_dbg_cmd(DEVICE_EXTENSION *pdx, unsigned char cmd,
1114                       unsigned int data)
1115 {
1116         int iReturn;
1117         dev_dbg(&pdx->interface->dev, "%s: entry\n", __func__);
1118         iReturn = usb_control_msg(pdx->udev, usb_sndctrlpipe(pdx->udev, 0), cmd,
1119                                   (H_TO_D | VENDOR | DEVREQ),
1120                                   (unsigned short)data,
1121                                   (unsigned short)(data >> 16), NULL, 0, HZ);
1122                                                 /* allow 1 second timeout */
1123         if (iReturn < 0)
1124                 dev_err(&pdx->interface->dev, "%s: fail code=%d\n",
1125                         __func__, iReturn);
1126
1127         return iReturn;
1128 }
1129
1130 /****************************************************************************
1131 ** ced_dbg_peek
1132 **
1133 ** Execute the diagnostic peek operation. Uses address, width and repeats.
1134 ****************************************************************************/
1135 int ced_dbg_peek(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB)
1136 {
1137         int iReturn;
1138         TDBGBLOCK db;
1139
1140         if (copy_from_user(&db, pDB, sizeof(db)))
1141                 return -EFAULT;
1142
1143         mutex_lock(&pdx->io_mutex);
1144         dev_dbg(&pdx->interface->dev, "%s: @ %08x\n", __func__, db.iAddr);
1145
1146         iReturn = ced_dbg_cmd(pdx, DB_SETADD, db.iAddr);
1147         if (iReturn == U14ERR_NOERROR)
1148                 iReturn = ced_dbg_cmd(pdx, DB_WIDTH, db.iWidth);
1149         if (iReturn == U14ERR_NOERROR)
1150                 iReturn = ced_dbg_cmd(pdx, DB_REPEATS, db.iRepeats);
1151         if (iReturn == U14ERR_NOERROR)
1152                 iReturn = ced_dbg_cmd(pdx, DB_PEEK, 0);
1153         mutex_unlock(&pdx->io_mutex);
1154
1155         return iReturn;
1156 }
1157
1158 /****************************************************************************
1159 ** ced_dbg_poke
1160 **
1161 ** Execute the diagnostic poke operation. Parameters are in the CSBLOCK struct
1162 ** in order address, size, repeats and value to poke.
1163 ****************************************************************************/
1164 int ced_dbg_poke(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB)
1165 {
1166         int iReturn;
1167         TDBGBLOCK db;
1168
1169         if (copy_from_user(&db, pDB, sizeof(db)))
1170                 return -EFAULT;
1171
1172         mutex_lock(&pdx->io_mutex);
1173         dev_dbg(&pdx->interface->dev, "%s: @ %08x\n", __func__, db.iAddr);
1174
1175         iReturn = ced_dbg_cmd(pdx, DB_SETADD, db.iAddr);
1176         if (iReturn == U14ERR_NOERROR)
1177                 iReturn = ced_dbg_cmd(pdx, DB_WIDTH, db.iWidth);
1178         if (iReturn == U14ERR_NOERROR)
1179                 iReturn = ced_dbg_cmd(pdx, DB_REPEATS, db.iRepeats);
1180         if (iReturn == U14ERR_NOERROR)
1181                 iReturn = ced_dbg_cmd(pdx, DB_POKE, db.iData);
1182         mutex_unlock(&pdx->io_mutex);
1183
1184         return iReturn;
1185 }
1186
1187 /****************************************************************************
1188 ** ced_dbg_ramp_data
1189 **
1190 ** Execute the diagnostic ramp data operation. Parameters are in the CSBLOCK struct
1191 ** in order address, default, enable mask, size and repeats.
1192 ****************************************************************************/
1193 int ced_dbg_ramp_data(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB)
1194 {
1195         int iReturn;
1196         TDBGBLOCK db;
1197
1198         if (copy_from_user(&db, pDB, sizeof(db)))
1199                 return -EFAULT;
1200
1201         mutex_lock(&pdx->io_mutex);
1202         dev_dbg(&pdx->interface->dev, "%s: @ %08x\n", __func__, db.iAddr);
1203
1204         iReturn = ced_dbg_cmd(pdx, DB_SETADD, db.iAddr);
1205         if (iReturn == U14ERR_NOERROR)
1206                 iReturn = ced_dbg_cmd(pdx, DB_SETDEF, db.iDefault);
1207         if (iReturn == U14ERR_NOERROR)
1208                 iReturn = ced_dbg_cmd(pdx, DB_SETMASK, db.iMask);
1209         if (iReturn == U14ERR_NOERROR)
1210                 iReturn = ced_dbg_cmd(pdx, DB_WIDTH, db.iWidth);
1211         if (iReturn == U14ERR_NOERROR)
1212                 iReturn = ced_dbg_cmd(pdx, DB_REPEATS, db.iRepeats);
1213         if (iReturn == U14ERR_NOERROR)
1214                 iReturn = ced_dbg_cmd(pdx, DB_RAMPD, 0);
1215         mutex_unlock(&pdx->io_mutex);
1216
1217         return iReturn;
1218 }
1219
1220 /****************************************************************************
1221 ** ced_dbg_ramp_addr
1222 **
1223 ** Execute the diagnostic ramp address operation
1224 ****************************************************************************/
1225 int ced_dbg_ramp_addr(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB)
1226 {
1227         int iReturn;
1228         TDBGBLOCK db;
1229
1230         if (copy_from_user(&db, pDB, sizeof(db)))
1231                 return -EFAULT;
1232
1233         mutex_lock(&pdx->io_mutex);
1234         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
1235
1236         iReturn = ced_dbg_cmd(pdx, DB_SETDEF, db.iDefault);
1237         if (iReturn == U14ERR_NOERROR)
1238                 iReturn = ced_dbg_cmd(pdx, DB_SETMASK, db.iMask);
1239         if (iReturn == U14ERR_NOERROR)
1240                 iReturn = ced_dbg_cmd(pdx, DB_WIDTH, db.iWidth);
1241         if (iReturn == U14ERR_NOERROR)
1242                 iReturn = ced_dbg_cmd(pdx, DB_REPEATS, db.iRepeats);
1243         if (iReturn == U14ERR_NOERROR)
1244                 iReturn = ced_dbg_cmd(pdx, DB_RAMPA, 0);
1245         mutex_unlock(&pdx->io_mutex);
1246
1247         return iReturn;
1248 }
1249
1250 /****************************************************************************
1251 ** ced_dbg_get_data
1252 **
1253 ** Retrieve the data resulting from the last debug Peek operation
1254 ****************************************************************************/
1255 int ced_dbg_get_data(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB)
1256 {
1257         int iReturn;
1258         TDBGBLOCK db;
1259         memset(&db, 0, sizeof(db));     /*  fill returned block with 0s */
1260
1261         mutex_lock(&pdx->io_mutex);
1262         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
1263
1264         /*  Read back the last peeked value from the 1401. */
1265         iReturn = usb_control_msg(pdx->udev, usb_rcvctrlpipe(pdx->udev, 0),
1266                                   DB_DATA, (D_TO_H | VENDOR | DEVREQ), 0, 0,
1267                                   &db.iData, sizeof(db.iData), HZ);
1268         if (iReturn == sizeof(db.iData)) {
1269                 if (copy_to_user(pDB, &db, sizeof(db)))
1270                         iReturn = -EFAULT;
1271                 else
1272                         iReturn = U14ERR_NOERROR;
1273         } else
1274                 dev_err(&pdx->interface->dev, "%s: failed, code %d\n",
1275                         __func__, iReturn);
1276
1277         mutex_unlock(&pdx->io_mutex);
1278
1279         return iReturn;
1280 }
1281
1282 /****************************************************************************
1283 ** ced_dbg_stop_loop
1284 **
1285 ** Stop any never-ending debug loop, we just call ced_get_state for USB
1286 **
1287 ****************************************************************************/
1288 int ced_dbg_stop_loop(DEVICE_EXTENSION *pdx)
1289 {
1290         int iReturn;
1291         unsigned int uState, uErr;
1292
1293         mutex_lock(&pdx->io_mutex);
1294         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
1295         iReturn = ced_get_state(pdx, &uState, &uErr);
1296         mutex_unlock(&pdx->io_mutex);
1297
1298         return iReturn;
1299 }
1300
1301 /****************************************************************************
1302 ** ced_set_circular
1303 **
1304 ** Sets up a transfer area record for circular transfers. If the area is
1305 ** already set, we attempt to unset it. Unsetting will fail if the area is
1306 ** booked and a transfer to that area is in progress. Otherwise, we will
1307 ** release the area and re-assign it.
1308 ****************************************************************************/
1309 int ced_set_circular(DEVICE_EXTENSION *pdx, struct transfer_area_desc __user *pTD)
1310 {
1311         int iReturn;
1312         bool bToHost;
1313         struct transfer_area_desc td;
1314
1315         if (copy_from_user(&td, pTD, sizeof(td)))
1316                 return -EFAULT;
1317
1318         mutex_lock(&pdx->io_mutex);
1319         dev_dbg(&pdx->interface->dev, "%s: area:%d, size:%08x\n",
1320                 __func__, td.wAreaNum, td.dwLength);
1321         bToHost = td.eSize != 0;        /*  this is used as the tohost flag */
1322
1323         /*  The strange cast is done so that we don't get warnings in 32-bit linux about the size of the */
1324         /*  pointer. The pointer is always passed as a 64-bit object so that we don't have problems using */
1325         /*  a 32-bit program on a 64-bit system. unsigned long is 64-bits on a 64-bit system. */
1326         iReturn =
1327             ced_set_area(pdx, td.wAreaNum,
1328                     (char __user *)((unsigned long)td.lpvBuff), td.dwLength,
1329                     true, bToHost);
1330         mutex_unlock(&pdx->io_mutex);
1331         return iReturn;
1332 }
1333
1334 /****************************************************************************
1335 ** GetCircBlock
1336 **
1337 ** Return the next available block of circularly-transferred data.
1338 ****************************************************************************/
1339 int GetCircBlock(DEVICE_EXTENSION *pdx, TCIRCBLOCK __user *pCB)
1340 {
1341         int iReturn = U14ERR_NOERROR;
1342         unsigned int nArea;
1343         TCIRCBLOCK cb;
1344
1345         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
1346
1347         if (copy_from_user(&cb, pCB, sizeof(cb)))
1348                 return -EFAULT;
1349
1350         mutex_lock(&pdx->io_mutex);
1351
1352         nArea = cb.nArea;       /*  Retrieve parameters first */
1353         cb.dwOffset = 0;        /*  set default result (nothing) */
1354         cb.dwSize = 0;
1355
1356         if (nArea < MAX_TRANSAREAS) {   /*  The area number must be OK */
1357                 TRANSAREA *pArea = &pdx->rTransDef[nArea];      /*  Pointer to relevant info */
1358                 spin_lock_irq(&pdx->stagedLock);        /*  Lock others out */
1359
1360                 if ((pArea->bUsed) && (pArea->bCircular) &&     /*  Must be circular area */
1361                     (pArea->bCircToHost)) {     /*  For now at least must be to host */
1362                         if (pArea->aBlocks[0].dwSize > 0) {     /*  Got anything? */
1363                                 cb.dwOffset = pArea->aBlocks[0].dwOffset;
1364                                 cb.dwSize = pArea->aBlocks[0].dwSize;
1365                                 dev_dbg(&pdx->interface->dev,
1366                                         "%s: return block 0: %d bytes at %d\n",
1367                                         __func__, cb.dwSize, cb.dwOffset);
1368                         }
1369                 } else
1370                         iReturn = U14ERR_NOTSET;
1371
1372                 spin_unlock_irq(&pdx->stagedLock);
1373         } else
1374                 iReturn = U14ERR_BADAREA;
1375
1376         if (copy_to_user(pCB, &cb, sizeof(cb)))
1377                 iReturn = -EFAULT;
1378
1379         mutex_unlock(&pdx->io_mutex);
1380         return iReturn;
1381 }
1382
1383 /****************************************************************************
1384 ** FreeCircBlock
1385 **
1386 ** Frees a block of circularly-transferred data and returns the next one.
1387 ****************************************************************************/
1388 int FreeCircBlock(DEVICE_EXTENSION *pdx, TCIRCBLOCK __user *pCB)
1389 {
1390         int iReturn = U14ERR_NOERROR;
1391         unsigned int nArea, uStart, uSize;
1392         TCIRCBLOCK cb;
1393
1394         dev_dbg(&pdx->interface->dev, "%s\n", __func__);
1395
1396         if (copy_from_user(&cb, pCB, sizeof(cb)))
1397                 return -EFAULT;
1398
1399         mutex_lock(&pdx->io_mutex);
1400
1401         nArea = cb.nArea;       /*  Retrieve parameters first */
1402         uStart = cb.dwOffset;
1403         uSize = cb.dwSize;
1404         cb.dwOffset = 0;        /*  then set default result (nothing) */
1405         cb.dwSize = 0;
1406
1407         if (nArea < MAX_TRANSAREAS) {   /*  The area number must be OK */
1408                 TRANSAREA *pArea = &pdx->rTransDef[nArea];      /*  Pointer to relevant info */
1409                 spin_lock_irq(&pdx->stagedLock);        /*  Lock others out */
1410
1411                 if ((pArea->bUsed) && (pArea->bCircular) &&     /*  Must be circular area */
1412                     (pArea->bCircToHost)) {     /*  For now at least must be to host */
1413                         bool bWaiting = false;
1414
1415                         if ((pArea->aBlocks[0].dwSize >= uSize) &&      /*  Got anything? */
1416                             (pArea->aBlocks[0].dwOffset == uStart)) {   /*  Must be legal data */
1417                                 pArea->aBlocks[0].dwSize -= uSize;
1418                                 pArea->aBlocks[0].dwOffset += uSize;
1419                                 if (pArea->aBlocks[0].dwSize == 0) {    /*  Have we emptied this block? */
1420                                         if (pArea->aBlocks[1].dwSize) { /*  Is there a second block? */
1421                                                 pArea->aBlocks[0] = pArea->aBlocks[1];  /*  Copy down block 2 data */
1422                                                 pArea->aBlocks[1].dwSize = 0;   /*  and mark the second block as unused */
1423                                                 pArea->aBlocks[1].dwOffset = 0;
1424                                         } else
1425                                                 pArea->aBlocks[0].dwOffset = 0;
1426                                 }
1427
1428                                 dev_dbg(&pdx->interface->dev,
1429                                         "%s: free %d bytes at %d, return %d bytes at %d, wait=%d\n",
1430                                         __func__, uSize, uStart,
1431                                         pArea->aBlocks[0].dwSize,
1432                                         pArea->aBlocks[0].dwOffset,
1433                                         pdx->bXFerWaiting);
1434
1435                                 /*  Return the next available block of memory as well */
1436                                 if (pArea->aBlocks[0].dwSize > 0) {     /*  Got anything? */
1437                                         cb.dwOffset =
1438                                             pArea->aBlocks[0].dwOffset;
1439                                         cb.dwSize = pArea->aBlocks[0].dwSize;
1440                                 }
1441
1442                                 bWaiting = pdx->bXFerWaiting;
1443                                 if (bWaiting && pdx->bStagedUrbPending) {
1444                                         dev_err(&pdx->interface->dev,
1445                                                 "%s: ERROR: waiting xfer and staged Urb pending!\n",
1446                                                 __func__);
1447                                         bWaiting = false;
1448                                 }
1449                         } else {
1450                                 dev_err(&pdx->interface->dev,
1451                                         "%s: ERROR: freeing %d bytes at %d, block 0 is %d bytes at %d\n",
1452                                         __func__, uSize, uStart,
1453                                         pArea->aBlocks[0].dwSize,
1454                                         pArea->aBlocks[0].dwOffset);
1455                                 iReturn = U14ERR_NOMEMORY;
1456                         }
1457
1458                         /*  If we have one, kick off pending transfer */
1459                         if (bWaiting) { /*  Got a block xfer waiting? */
1460                                 int RWMStat =
1461                                     ced_read_write_mem(pdx, !pdx->rDMAInfo.bOutWard,
1462                                                  pdx->rDMAInfo.wIdent,
1463                                                  pdx->rDMAInfo.dwOffset,
1464                                                  pdx->rDMAInfo.dwSize);
1465                                 if (RWMStat != U14ERR_NOERROR)
1466                                         dev_err(&pdx->interface->dev,
1467                                                 "%s: rw setup failed %d\n",
1468                                                 __func__, RWMStat);
1469                         }
1470                 } else
1471                         iReturn = U14ERR_NOTSET;
1472
1473                 spin_unlock_irq(&pdx->stagedLock);
1474         } else
1475                 iReturn = U14ERR_BADAREA;
1476
1477         if (copy_to_user(pCB, &cb, sizeof(cb)))
1478                 iReturn = -EFAULT;
1479
1480         mutex_unlock(&pdx->io_mutex);
1481         return iReturn;
1482 }