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