]> Git Repo - linux.git/blob - drivers/staging/ced1401/ced_ioc.c
ARM: Kirkwood: Add support for many Synology NAS devices
[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 ([email protected])
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 ** FlushOutBuff
36 **
37 ** Empties the Output buffer and sets int lines. Used from user level only
38 ****************************************************************************/
39 static void FlushOutBuff(DEVICE_EXTENSION *pdx)
40 {
41         dev_dbg(&pdx->interface->dev, "%s currentState=%d", __func__,
42                 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 ** FlushInBuff
57 **
58 ** Empties the input buffer and sets int lines
59 ****************************************************************************/
60 static void FlushInBuff(DEVICE_EXTENSION *pdx)
61 {
62         dev_dbg(&pdx->interface->dev, "%s currentState=%d", __func__,
63                 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 ** PutChars
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 PutChars(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 = SendChars(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 SendString(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<", __func__, n,
122                         buffer);
123                 iReturn = PutChars(pdx, buffer, n);
124         }
125
126         Allowi(pdx);            /*  make sure we have input int */
127         mutex_unlock(&pdx->io_mutex);
128
129         return iReturn;
130 }
131
132 /****************************************************************************
133 ** SendChar
134 **
135 ** Sends a single character to the 1401. User mode, holds io_mutex.
136 ****************************************************************************/
137 int SendChar(DEVICE_EXTENSION *pdx, char c)
138 {
139         int iReturn;
140         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
141         iReturn = PutChars(pdx, &c, 1);
142         dev_dbg(&pdx->interface->dev, "SendChar >%c< (0x%02x)", c, c);
143         Allowi(pdx);    /*  Make sure char reads are running */
144         mutex_unlock(&pdx->io_mutex);
145         return iReturn;
146 }
147
148 /***************************************************************************
149 **
150 ** Get1401State
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 Get1401State(DEVICE_EXTENSION *pdx, __u32 *state, __u32 *error)
175 {
176         int nGot;
177         dev_dbg(&pdx->interface->dev, "Get1401State() entry");
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                         "Get1401State() FAILED, return code %d", 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                         "Get1401State() Success, state: 0x%x, 0x%x",
193                         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 ** ReadWrite_Cancel
218 **
219 ** Kills off staged read\write request from the USB if one is pending.
220 ****************************************************************************/
221 int ReadWrite_Cancel(DEVICE_EXTENSION *pdx)
222 {
223         dev_dbg(&pdx->interface->dev, "ReadWrite_Cancel entry %d",
224                 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                          "ReadWrite_Cancel about to cancel Urb");
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                                  "ReadWrite_Cancel about to wait till done");
248                         ntStatus =
249                             KeWaitForSingleObject(&pdx->StagingDoneEvent,
250                                                   Executive, KernelMode, FALSE,
251                                                   &timeout);
252                 } else {
253                         dev_info(&pdx->interface - dev,
254                                  "ReadWrite_Cancel, cancellation failed");
255                         ntStatus = U14ERR_FAIL;
256                 }
257                 USB_KdPrint(DBGLVL_DEFAULT,
258                             ("ReadWrite_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, "ReadWrite_Cancel  done");
264         return ntStatus;
265 #else
266         return U14ERR_NOERROR;
267 #endif
268
269 }
270
271 /***************************************************************************
272 ** InSelfTest - 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 InSelfTest(DEVICE_EXTENSION *pdx, unsigned int *pState)
276 {
277         unsigned int state, error;
278         int iReturn = Get1401State(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 ** Is1401 - 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 bool Is1401(DEVICE_EXTENSION *pdx)
305 {
306         int iReturn;
307         dev_dbg(&pdx->interface->dev, "%s", __func__);
308
309         ced_draw_down(pdx);     /*  wait for, then kill outstanding Urbs */
310         FlushInBuff(pdx);       /*  Clear out input buffer & pipe */
311         FlushOutBuff(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 = InSelfTest(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 = InSelfTest(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 ** QuickCheck  - 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 Is1401 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 bool QuickCheck(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",
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", __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->Get1401State", __func__);
386                 if (Get1401State(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->Is1401 %d %d %d %d",
394                          __func__, bShortTest, pdx->sCurrentState, bTestBuff,
395                          pdx->bForceReset);
396                 bRet = Is1401(pdx);     /*   do full test */
397         }
398
399         return bRet;
400 }
401
402 /****************************************************************************
403 ** Reset1401
404 **
405 ** Resets the 1401 and empties the i/o buffers
406 *****************************************************************************/
407 int Reset1401(DEVICE_EXTENSION *pdx)
408 {
409         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
410         dev_dbg(&pdx->interface->dev, "ABout to call QuickCheck");
411         QuickCheck(pdx, true, true);    /*  Check 1401, reset if not OK */
412         mutex_unlock(&pdx->io_mutex);
413         return U14ERR_NOERROR;
414 }
415
416 /****************************************************************************
417 ** GetChar
418 **
419 ** Gets a single character from the 1401
420 ****************************************************************************/
421 int GetChar(DEVICE_EXTENSION *pdx)
422 {
423         int iReturn = U14ERR_NOIN;      /*  assume we will get  nothing */
424         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
425
426         dev_dbg(&pdx->interface->dev, "GetChar");
427
428         Allowi(pdx);    /*  Make sure char reads are running */
429         SendChars(pdx); /*  and send any buffered chars */
430
431         spin_lock_irq(&pdx->charInLock);
432         if (pdx->dwNumInput > 0) {      /*  worth looking */
433                 iReturn = pdx->inputBuffer[pdx->dwInBuffGet++];
434                 if (pdx->dwInBuffGet >= INBUF_SZ)
435                         pdx->dwInBuffGet = 0;
436                 pdx->dwNumInput--;
437         } else
438                 iReturn = U14ERR_NOIN;  /*  no input data to read */
439         spin_unlock_irq(&pdx->charInLock);
440
441         Allowi(pdx);    /*  Make sure char reads are running */
442
443         mutex_unlock(&pdx->io_mutex);   /*  Protect disconnect from new i/o */
444         return iReturn;
445 }
446
447 /****************************************************************************
448 ** GetString
449 **
450 ** Gets a string from the 1401. Returns chars up to the next CR or when
451 ** there are no more to read or nowhere to put them. CR is translated to
452 ** 0 and counted as a character. If the string does not end in a 0, we will
453 ** add one, if there is room, but it is not counted as a character.
454 **
455 ** returns the count of characters (including the terminator, or 0 if none
456 ** or a negative error code.
457 ****************************************************************************/
458 int GetString(DEVICE_EXTENSION *pdx, char __user *pUser, int n)
459 {
460         int nAvailable;         /*  character in the buffer */
461         int iReturn = U14ERR_NOIN;
462         if (n <= 0)
463                 return -ENOMEM;
464
465         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
466         Allowi(pdx);    /*  Make sure char reads are running */
467         SendChars(pdx);         /*  and send any buffered chars */
468
469         spin_lock_irq(&pdx->charInLock);
470         nAvailable = pdx->dwNumInput;   /*  characters available now */
471         if (nAvailable > n)     /*  read max of space in pUser... */
472                 nAvailable = n; /*  ...or input characters */
473
474         if (nAvailable > 0) {   /*  worth looking? */
475                 char buffer[INBUF_SZ + 1];      /*  space for a linear copy of data */
476                 int nGot = 0;
477                 int nCopyToUser;        /*  number to copy to user */
478                 char cData;
479                 do {
480                         cData = pdx->inputBuffer[pdx->dwInBuffGet++];
481                         if (cData == CR_CHAR)   /*  replace CR with zero */
482                                 cData = (char)0;
483
484                         if (pdx->dwInBuffGet >= INBUF_SZ)
485                                 pdx->dwInBuffGet = 0;   /*  wrap buffer pointer */
486
487                         buffer[nGot++] = cData; /*  save the output */
488                 } while ((nGot < nAvailable) && cData);
489
490                 nCopyToUser = nGot;     /*  what to copy... */
491                 if (cData) {    /*  do we need null */
492                         buffer[nGot] = (char)0; /*  make it tidy */
493                         if (nGot < n)   /*  if space in user buffer... */
494                                 ++nCopyToUser;  /*  ...copy the 0 as well. */
495                 }
496
497                 pdx->dwNumInput -= nGot;
498                 spin_unlock_irq(&pdx->charInLock);
499
500                 dev_dbg(&pdx->interface->dev,
501                         "GetString read %d characters >%s<", nGot, buffer);
502                 if (copy_to_user(pUser, buffer, nCopyToUser))
503                         iReturn = -EFAULT;
504                 else
505                         iReturn = nGot;         /*  report characters read */
506         } else
507                 spin_unlock_irq(&pdx->charInLock);
508
509         Allowi(pdx);    /*  Make sure char reads are running */
510         mutex_unlock(&pdx->io_mutex);   /*  Protect disconnect from new i/o */
511
512         return iReturn;
513 }
514
515 /*******************************************************************************
516 ** Get count of characters in the inout buffer.
517 *******************************************************************************/
518 int Stat1401(DEVICE_EXTENSION *pdx)
519 {
520         int iReturn;
521         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
522         Allowi(pdx);            /*  make sure we allow pending chars */
523         SendChars(pdx);         /*  in both directions */
524         iReturn = pdx->dwNumInput;      /*  no lock as single read */
525         mutex_unlock(&pdx->io_mutex);   /*  Protect disconnect from new i/o */
526         return iReturn;
527 }
528
529 /****************************************************************************
530 ** LineCount
531 **
532 ** Returns the number of newline chars in the buffer. There is no need for
533 ** any fancy interlocks as we only read the interrupt routine data, and the
534 ** system is arranged so nothing can be destroyed.
535 ****************************************************************************/
536 int LineCount(DEVICE_EXTENSION *pdx)
537 {
538         int iReturn = 0;        /*  will be count of line ends */
539
540         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
541         Allowi(pdx);            /*  Make sure char reads are running */
542         SendChars(pdx);         /*  and send any buffered chars */
543         spin_lock_irq(&pdx->charInLock);        /*  Get protection */
544
545         if (pdx->dwNumInput > 0) {      /*  worth looking? */
546                 unsigned int dwIndex = pdx->dwInBuffGet;        /*  start at first available */
547                 unsigned int dwEnd = pdx->dwInBuffPut;  /*  Position for search end */
548                 do {
549                         if (pdx->inputBuffer[dwIndex++] == CR_CHAR)
550                                 ++iReturn;      /*  inc count if CR */
551
552                         if (dwIndex >= INBUF_SZ)        /*  see if we fall off buff */
553                                 dwIndex = 0;
554                 } while (dwIndex != dwEnd);     /*  go to last available */
555         }
556
557         spin_unlock_irq(&pdx->charInLock);
558         dev_dbg(&pdx->interface->dev, "LineCount returned %d", iReturn);
559         mutex_unlock(&pdx->io_mutex);   /*  Protect disconnect from new i/o */
560         return iReturn;
561 }
562
563 /****************************************************************************
564 ** GetOutBufSpace
565 **
566 ** Gets the space in the output buffer. Called from user code.
567 *****************************************************************************/
568 int GetOutBufSpace(DEVICE_EXTENSION *pdx)
569 {
570         int iReturn;
571         mutex_lock(&pdx->io_mutex);     /*  Protect disconnect from new i/o */
572         SendChars(pdx);         /*  send any buffered chars */
573         iReturn = (int)(OUTBUF_SZ - pdx->dwNumOutput);  /*  no lock needed for single read */
574         dev_dbg(&pdx->interface->dev, "OutBufSpace %d", iReturn);
575         mutex_unlock(&pdx->io_mutex);   /*  Protect disconnect from new i/o */
576         return iReturn;
577 }
578
579 /****************************************************************************
580 **
581 ** ClearArea
582 **
583 ** Clears up a transfer area. This is always called in the context of a user
584 ** request, never from a call-back.
585 ****************************************************************************/
586 int ClearArea(DEVICE_EXTENSION *pdx, int nArea)
587 {
588         int iReturn = U14ERR_NOERROR;
589
590         if ((nArea < 0) || (nArea >= MAX_TRANSAREAS)) {
591                 iReturn = U14ERR_BADAREA;
592                 dev_err(&pdx->interface->dev, "%s Attempt to clear area %d",
593                         __func__, nArea);
594         } else {
595                 TRANSAREA *pTA = &pdx->rTransDef[nArea];        /*  to save typing */
596                 if (!pTA->bUsed)        /*  if not used... */
597                         iReturn = U14ERR_NOTSET;        /*  ...nothing to be done */
598                 else {
599                         /*  We must save the memory we return as we shouldn't mess with memory while */
600                         /*  holding a spin lock. */
601                         struct page **pPages = NULL; /*save page address list*/
602                         int nPages = 0; /*  and number of pages */
603                         int np;
604
605                         dev_dbg(&pdx->interface->dev, "%s area %d", __func__,
606                                 nArea);
607                         spin_lock_irq(&pdx->stagedLock);
608                         if ((pdx->StagedId == nArea)
609                             && (pdx->dwDMAFlag > MODE_CHAR)) {
610                                 iReturn = U14ERR_UNLOCKFAIL;    /*  cannot delete as in use */
611                                 dev_err(&pdx->interface->dev,
612                                         "%s call on area %d while active",
613                                         __func__, nArea);
614                         } else {
615                                 pPages = pTA->pPages;   /*  save page address list */
616                                 nPages = pTA->nPages;   /*  and page count */
617                                 if (pTA->dwEventSz)     /*  if events flagging in use */
618                                         wake_up_interruptible(&pTA->wqEvent);   /*  release anything that was waiting */
619
620                                 if (pdx->bXFerWaiting
621                                     && (pdx->rDMAInfo.wIdent == nArea))
622                                         pdx->bXFerWaiting = false;      /*  Cannot have pending xfer if area cleared */
623
624                                 /*  Clean out the TRANSAREA except for the wait queue, which is at the end */
625                                 /*  This sets bUsed to false and dwEventSz to 0 to say area not used and no events. */
626                                 memset(pTA, 0,
627                                        sizeof(TRANSAREA) -
628                                        sizeof(wait_queue_head_t));
629                         }
630                         spin_unlock_irq(&pdx->stagedLock);
631
632                         if (pPages) {   /*  if we decided to release the memory */
633                                 /*  Now we must undo the pinning down of the pages. We will assume the worst and mark */
634                                 /*  all the pages as dirty. Don't be tempted to move this up above as you must not be */
635                                 /*  holding a spin lock to do this stuff as it is not atomic. */
636                                 dev_dbg(&pdx->interface->dev, "%s nPages=%d",
637                                         __func__, nPages);
638
639                                 for (np = 0; np < nPages; ++np) {
640                                         if (pPages[np]) {
641                                                 SetPageDirty(pPages[np]);
642                                                 page_cache_release(pPages[np]);
643                                         }
644                                 }
645
646                                 kfree(pPages);
647                                 dev_dbg(&pdx->interface->dev,
648                                         "%s kfree(pPages) done", __func__);
649                         }
650                 }
651         }
652
653         return iReturn;
654 }
655
656 /****************************************************************************
657 ** SetArea
658 **
659 ** Sets up a transfer area - the functional part. Called by both
660 ** SetTransfer and SetCircular.
661 ****************************************************************************/
662 static int SetArea(DEVICE_EXTENSION *pdx, int nArea, char __user *puBuf,
663                    unsigned int dwLength, bool bCircular, bool bCircToHost)
664 {
665         /*  Start by working out the page aligned start of the area and the size */
666         /*  of the area in pages, allowing for the start not being aligned and the */
667         /*  end needing to be rounded up to a page boundary. */
668         unsigned long ulStart = ((unsigned long)puBuf) & PAGE_MASK;
669         unsigned int ulOffset = ((unsigned long)puBuf) & (PAGE_SIZE - 1);
670         int len = (dwLength + ulOffset + PAGE_SIZE - 1) >> PAGE_SHIFT;
671
672         TRANSAREA *pTA = &pdx->rTransDef[nArea];        /*  to save typing */
673         struct page **pPages = NULL;    /*  space for page tables */
674         int nPages = 0;         /*  and number of pages */
675
676         int iReturn = ClearArea(pdx, nArea);    /*  see if OK to use this area */
677         if ((iReturn != U14ERR_NOTSET) &&       /*  if not area unused and... */
678             (iReturn != U14ERR_NOERROR))        /*  ...not all OK, then... */
679                 return iReturn; /*  ...we cannot use this area */
680
681         if (!access_ok(VERIFY_WRITE, puBuf, dwLength))  /*  if we cannot access the memory... */
682                 return -EFAULT; /*  ...then we are done */
683
684         /*  Now allocate space to hold the page pointer and virtual address pointer tables */
685         pPages = kmalloc(len * sizeof(struct page *), GFP_KERNEL);
686         if (!pPages) {
687                 iReturn = U14ERR_NOMEMORY;
688                 goto error;
689         }
690         dev_dbg(&pdx->interface->dev, "%s %p, length=%06x, circular %d",
691                 __func__, puBuf, dwLength, bCircular);
692
693         /*  To pin down user pages we must first acquire the mapping semaphore. */
694         nPages = get_user_pages_fast(ulStart, len, 1, pPages);
695         dev_dbg(&pdx->interface->dev, "%s nPages = %d", __func__, nPages);
696
697         if (nPages > 0) {               /*  if we succeeded */
698                 /*  If you are tempted to use page_address (form LDD3), forget it. You MUST use */
699                 /*  kmap() or kmap_atomic() to get a virtual address. page_address will give you */
700                 /*  (null) or at least it does in this context with an x86 machine. */
701                 spin_lock_irq(&pdx->stagedLock);
702                 pTA->lpvBuff = puBuf;   /*  keep start of region (user address) */
703                 pTA->dwBaseOffset = ulOffset;   /*  save offset in first page to start of xfer */
704                 pTA->dwLength = dwLength;       /*  Size if the region in bytes */
705                 pTA->pPages = pPages;   /*  list of pages that are used by buffer */
706                 pTA->nPages = nPages;   /*  number of pages */
707
708                 pTA->bCircular = bCircular;
709                 pTA->bCircToHost = bCircToHost;
710
711                 pTA->aBlocks[0].dwOffset = 0;
712                 pTA->aBlocks[0].dwSize = 0;
713                 pTA->aBlocks[1].dwOffset = 0;
714                 pTA->aBlocks[1].dwSize = 0;
715                 pTA->bUsed = true;      /*  This is now a used block */
716
717                 spin_unlock_irq(&pdx->stagedLock);
718                 iReturn = U14ERR_NOERROR;       /*  say all was well */
719         } else {
720                 iReturn = U14ERR_LOCKFAIL;
721                 goto error;
722         }
723
724         return iReturn;
725
726 error:
727         kfree(pPages);
728         return iReturn;
729 }
730
731 /****************************************************************************
732 ** SetTransfer
733 **
734 ** Sets up a transfer area record. If the area is already set, we attempt to
735 ** unset it. Unsetting will fail if the area is booked, and a transfer to that
736 ** area is in progress. Otherwise, we will release the area and re-assign it.
737 ****************************************************************************/
738 int SetTransfer(DEVICE_EXTENSION *pdx, TRANSFERDESC __user *pTD)
739 {
740         int iReturn;
741         TRANSFERDESC td;
742
743         if (copy_from_user(&td, pTD, sizeof(td)))
744                 return -EFAULT;
745
746         mutex_lock(&pdx->io_mutex);
747         dev_dbg(&pdx->interface->dev, "%s area:%d, size:%08x", __func__,
748                 td.wAreaNum, td.dwLength);
749         /*  The strange cast is done so that we don't get warnings in 32-bit linux about the size of the */
750         /*  pointer. The pointer is always passed as a 64-bit object so that we don't have problems using */
751         /*  a 32-bit program on a 64-bit system. unsigned long is 64-bits on a 64-bit system. */
752         iReturn =
753             SetArea(pdx, td.wAreaNum,
754                     (char __user *)((unsigned long)td.lpvBuff), td.dwLength,
755                     false, false);
756         mutex_unlock(&pdx->io_mutex);
757         return iReturn;
758 }
759
760 /****************************************************************************
761 ** UnSetTransfer
762 ** Erases a transfer area record
763 ****************************************************************************/
764 int UnsetTransfer(DEVICE_EXTENSION *pdx, int nArea)
765 {
766         int iReturn;
767         mutex_lock(&pdx->io_mutex);
768         iReturn = ClearArea(pdx, nArea);
769         mutex_unlock(&pdx->io_mutex);
770         return iReturn;
771 }
772
773 /****************************************************************************
774 ** SetEvent
775 ** Creates an event that we can test for based on a transfer to/from an area.
776 ** The area must be setup for a transfer. We attempt to simulate the Windows
777 ** driver behavior for events (as we don't actually use them), which is to
778 ** pretend that whatever the user asked for was achieved, so we return 1 if
779 ** try to create one, and 0 if they ask to remove (assuming all else was OK).
780 ****************************************************************************/
781 int SetEvent(DEVICE_EXTENSION *pdx, TRANSFEREVENT __user *pTE)
782 {
783         int iReturn = U14ERR_NOERROR;
784         TRANSFEREVENT te;
785
786         /*  get a local copy of the data */
787         if (copy_from_user(&te, pTE, sizeof(te)))
788                 return -EFAULT;
789
790         if (te.wAreaNum >= MAX_TRANSAREAS)      /*  the area must exist */
791                 return U14ERR_BADAREA;
792         else {
793                 TRANSAREA *pTA = &pdx->rTransDef[te.wAreaNum];
794                 mutex_lock(&pdx->io_mutex);     /*  make sure we have no competitor */
795                 spin_lock_irq(&pdx->stagedLock);
796                 if (pTA->bUsed) {       /*  area must be in use */
797                         pTA->dwEventSt = te.dwStart;    /*  set area regions */
798                         pTA->dwEventSz = te.dwLength;   /*  set size (0 cancels it) */
799                         pTA->bEventToHost = te.wFlags & 1;      /*  set the direction */
800                         pTA->iWakeUp = 0;       /*  zero the wake up count */
801                 } else
802                         iReturn = U14ERR_NOTSET;
803                 spin_unlock_irq(&pdx->stagedLock);
804                 mutex_unlock(&pdx->io_mutex);
805         }
806         return iReturn ==
807             U14ERR_NOERROR ? (te.iSetEvent ? 1 : U14ERR_NOERROR) : iReturn;
808 }
809
810 /****************************************************************************
811 ** WaitEvent
812 ** Sleep the process with a timeout waiting for an event. Returns the number
813 ** of times that a block met the event condition since we last cleared it or
814 ** 0 if timed out, or -ve error (bad area or not set, or signal).
815 ****************************************************************************/
816 int WaitEvent(DEVICE_EXTENSION *pdx, int nArea, int msTimeOut)
817 {
818         int iReturn;
819         if ((unsigned)nArea >= MAX_TRANSAREAS)
820                 return U14ERR_BADAREA;
821         else {
822                 int iWait;
823                 TRANSAREA *pTA = &pdx->rTransDef[nArea];
824                 msTimeOut = (msTimeOut * HZ + 999) / 1000;      /*  convert timeout to jiffies */
825
826                 /*  We cannot wait holding the mutex, but we check the flags while holding */
827                 /*  it. This may well be pointless as another thread could get in between */
828                 /*  releasing it and the wait call. However, this would have to clear the */
829                 /*  iWakeUp flag. However, the !pTA-bUsed may help us in this case. */
830                 mutex_lock(&pdx->io_mutex);     /*  make sure we have no competitor */
831                 if (!pTA->bUsed || !pTA->dwEventSz)     /*  check something to wait for... */
832                         return U14ERR_NOTSET;   /*  ...else we do nothing */
833                 mutex_unlock(&pdx->io_mutex);
834
835                 if (msTimeOut)
836                         iWait =
837                             wait_event_interruptible_timeout(pTA->wqEvent,
838                                                              pTA->iWakeUp
839                                                              || !pTA->bUsed,
840                                                              msTimeOut);
841                 else
842                         iWait =
843                             wait_event_interruptible(pTA->wqEvent, pTA->iWakeUp
844                                                      || !pTA->bUsed);
845                 if (iWait)
846                         iReturn = -ERESTARTSYS; /*  oops - we have had a SIGNAL */
847                 else
848                         iReturn = pTA->iWakeUp; /*  else the wakeup count */
849
850                 spin_lock_irq(&pdx->stagedLock);
851                 pTA->iWakeUp = 0;       /*  clear the flag */
852                 spin_unlock_irq(&pdx->stagedLock);
853         }
854         return iReturn;
855 }
856
857 /****************************************************************************
858 ** TestEvent
859 ** Test the event to see if a WaitEvent would return immediately. Returns the
860 ** number of times a block completed since the last call, or 0 if none or a
861 ** negative error.
862 ****************************************************************************/
863 int TestEvent(DEVICE_EXTENSION *pdx, int nArea)
864 {
865         int iReturn;
866         if ((unsigned)nArea >= MAX_TRANSAREAS)
867                 iReturn = U14ERR_BADAREA;
868         else {
869                 TRANSAREA *pTA = &pdx->rTransDef[nArea];
870                 mutex_lock(&pdx->io_mutex);     /*  make sure we have no competitor */
871                 spin_lock_irq(&pdx->stagedLock);
872                 iReturn = pTA->iWakeUp; /*  get wakeup count since last call */
873                 pTA->iWakeUp = 0;       /*  clear the count */
874                 spin_unlock_irq(&pdx->stagedLock);
875                 mutex_unlock(&pdx->io_mutex);
876         }
877         return iReturn;
878 }
879
880 /****************************************************************************
881 ** GetTransferInfo
882 ** Puts the current state of the 1401 in a TGET_TX_BLOCK.
883 *****************************************************************************/
884 int GetTransfer(DEVICE_EXTENSION *pdx, TGET_TX_BLOCK __user *pTX)
885 {
886         int iReturn = U14ERR_NOERROR;
887         unsigned int dwIdent;
888
889         mutex_lock(&pdx->io_mutex);
890         dwIdent = pdx->StagedId;        /*  area ident for last xfer */
891         if (dwIdent >= MAX_TRANSAREAS)
892                 iReturn = U14ERR_BADAREA;
893         else {
894                 /*  Return the best information we have - we don't have physical addresses */
895                 TGET_TX_BLOCK *tx;
896
897                 tx = kzalloc(sizeof(*tx), GFP_KERNEL);
898                 if (!tx) {
899                         mutex_unlock(&pdx->io_mutex);
900                         return -ENOMEM;
901                 }
902                 tx->size = pdx->rTransDef[dwIdent].dwLength;
903                 tx->linear = (long long)((long)pdx->rTransDef[dwIdent].lpvBuff);
904                 tx->avail = GET_TX_MAXENTRIES;  /*  how many blocks we could return */
905                 tx->used = 1;   /*  number we actually return */
906                 tx->entries[0].physical =
907                     (long long)(tx->linear + pdx->StagedOffset);
908                 tx->entries[0].size = tx->size;
909
910                 if (copy_to_user(pTX, tx, sizeof(*tx)))
911                         iReturn = -EFAULT;
912                 kfree(tx);
913         }
914         mutex_unlock(&pdx->io_mutex);
915         return iReturn;
916 }
917
918 /****************************************************************************
919 ** KillIO1401
920 **
921 ** Empties the host i/o buffers
922 ****************************************************************************/
923 int KillIO1401(DEVICE_EXTENSION *pdx)
924 {
925         dev_dbg(&pdx->interface->dev, "%s", __func__);
926         mutex_lock(&pdx->io_mutex);
927         FlushOutBuff(pdx);
928         FlushInBuff(pdx);
929         mutex_unlock(&pdx->io_mutex);
930         return U14ERR_NOERROR;
931 }
932
933 /****************************************************************************
934 ** BlkTransState
935 ** Returns a 0 or a 1 for whether DMA is happening. No point holding a mutex
936 ** for this as it only does one read.
937 *****************************************************************************/
938 int BlkTransState(DEVICE_EXTENSION *pdx)
939 {
940         int iReturn = pdx->dwDMAFlag != MODE_CHAR;
941         dev_dbg(&pdx->interface->dev, "%s = %d", __func__, iReturn);
942         return iReturn;
943 }
944
945 /****************************************************************************
946 ** StateOf1401
947 **
948 ** Puts the current state of the 1401 in the Irp return buffer.
949 *****************************************************************************/
950 int StateOf1401(DEVICE_EXTENSION *pdx)
951 {
952         int iReturn;
953         mutex_lock(&pdx->io_mutex);
954
955         QuickCheck(pdx, false, false);  /*  get state up to date, no reset */
956         iReturn = pdx->sCurrentState;
957
958         mutex_unlock(&pdx->io_mutex);
959         dev_dbg(&pdx->interface->dev, "%s = %d", __func__, iReturn);
960
961         return iReturn;
962 }
963
964 /****************************************************************************
965 ** StartSelfTest
966 **
967 ** Initiates a self-test cycle. The assumption is that we have no interrupts
968 ** active, so we should make sure that this is the case.
969 *****************************************************************************/
970 int StartSelfTest(DEVICE_EXTENSION *pdx)
971 {
972         int nGot;
973         mutex_lock(&pdx->io_mutex);
974         dev_dbg(&pdx->interface->dev, "%s", __func__);
975
976         ced_draw_down(pdx);     /*  wait for, then kill outstanding Urbs */
977         FlushInBuff(pdx);       /*  Clear out input buffer & pipe */
978         FlushOutBuff(pdx);      /*  Clear output buffer & pipe */
979         /* so things stay tidy */
980         /* ReadWrite_Cancel(pDeviceObject); */
981         pdx->dwDMAFlag = MODE_CHAR;     /* Clear DMA mode flags here */
982
983         nGot = usb_control_msg(pdx->udev, usb_rcvctrlpipe(pdx->udev, 0),
984                                DB_SELFTEST, (H_TO_D | VENDOR | DEVREQ),
985                                0, 0, NULL, 0, HZ); /* allow 1 second timeout */
986         pdx->ulSelfTestTime = jiffies + HZ * 30;        /*  30 seconds into the future */
987
988         mutex_unlock(&pdx->io_mutex);
989         if (nGot < 0)
990                 dev_err(&pdx->interface->dev, "%s err=%d", __func__, nGot);
991         return nGot < 0 ? U14ERR_FAIL : U14ERR_NOERROR;
992 }
993
994 /****************************************************************************
995 ** CheckSelfTest
996 **
997 ** Check progress of a self-test cycle
998 ****************************************************************************/
999 int CheckSelfTest(DEVICE_EXTENSION *pdx, TGET_SELFTEST __user *pGST)
1000 {
1001         unsigned int state, error;
1002         int iReturn;
1003         TGET_SELFTEST gst;      /*  local work space */
1004         memset(&gst, 0, sizeof(gst));   /*  clear out the space (sets code 0) */
1005
1006         mutex_lock(&pdx->io_mutex);
1007
1008         dev_dbg(&pdx->interface->dev, "%s", __func__);
1009         iReturn = Get1401State(pdx, &state, &error);
1010         if (iReturn == U14ERR_NOERROR)  /*  Only accept zero if it happens twice */
1011                 iReturn = Get1401State(pdx, &state, &error);
1012
1013         if (iReturn != U14ERR_NOERROR) {        /*  Self-test can cause comms errors */
1014                                 /*  so we assume still testing */
1015                 dev_err(&pdx->interface->dev,
1016                         "%s Get1401State=%d, assuming still testing", __func__,
1017                         iReturn);
1018                 state = 0x80;   /*  Force still-testing, no error */
1019                 error = 0;
1020                 iReturn = U14ERR_NOERROR;
1021         }
1022
1023         if ((state == -1) && (error == -1)) {   /*  If Get1401State had problems */
1024                 dev_err(&pdx->interface->dev,
1025                         "%s Get1401State failed, assuming still testing",
1026                         __func__);
1027                 state = 0x80;   /*  Force still-testing, no error */
1028                 error = 0;
1029         }
1030
1031         if ((state & 0xFF) == 0x80) {   /*  If we are still in self-test */
1032                 if (state & 0x00FF0000) { /*  Have we got an error? */
1033                         gst.code = (state & 0x00FF0000) >> 16;  /*  read the error code */
1034                         gst.x = error & 0x0000FFFF;     /*  Error data X */
1035                         gst.y = (error & 0xFFFF0000) >> 16;     /*  and data Y */
1036                         dev_dbg(&pdx->interface->dev, "Self-test error code %d",
1037                                 gst.code);
1038                 } else {                /*  No error, check for timeout */
1039                         unsigned long ulNow = jiffies;  /*  get current time */
1040                         if (time_after(ulNow, pdx->ulSelfTestTime)) {
1041                                 gst.code = -2;  /*  Flag the timeout */
1042                                 dev_dbg(&pdx->interface->dev,
1043                                         "Self-test timed-out");
1044                         } else
1045                                 dev_dbg(&pdx->interface->dev,
1046                                         "Self-test on-going");
1047                 }
1048         } else {
1049                 gst.code = -1;  /*  Flag the test is done */
1050                 dev_dbg(&pdx->interface->dev, "Self-test done");
1051         }
1052
1053         if (gst.code < 0) {     /*  If we have a problem or finished */
1054                                 /*  If using the 2890 we should reset properly */
1055                 if ((pdx->nPipes == 4) && (pdx->s1401Type <= TYPEPOWER))
1056                         Is1401(pdx);    /*  Get 1401 reset and OK */
1057                 else
1058                         QuickCheck(pdx, true, true);    /*  Otherwise check without reset unless problems */
1059         }
1060         mutex_unlock(&pdx->io_mutex);
1061
1062         if (copy_to_user(pGST, &gst, sizeof(gst)))
1063                 return -EFAULT;
1064
1065         return iReturn;
1066 }
1067
1068 /****************************************************************************
1069 ** TypeOf1401
1070 **
1071 ** Returns code for standard, plus, micro1401, power1401 or none
1072 ****************************************************************************/
1073 int TypeOf1401(DEVICE_EXTENSION *pdx)
1074 {
1075         int iReturn = TYPEUNKNOWN;
1076         mutex_lock(&pdx->io_mutex);
1077         dev_dbg(&pdx->interface->dev, "%s", __func__);
1078
1079         switch (pdx->s1401Type) {
1080         case TYPE1401:
1081                 iReturn = U14ERR_STD;
1082                 break;          /*  Handle these types directly */
1083         case TYPEPLUS:
1084                 iReturn = U14ERR_PLUS;
1085                 break;
1086         case TYPEU1401:
1087                 iReturn = U14ERR_U1401;
1088                 break;
1089         default:
1090                 if ((pdx->s1401Type >= TYPEPOWER) && (pdx->s1401Type <= 25))
1091                         iReturn = pdx->s1401Type + 4;   /*  We can calculate types */
1092                 else            /*   for up-coming 1401 designs */
1093                         iReturn = TYPEUNKNOWN;  /*  Don't know or not there */
1094         }
1095         dev_dbg(&pdx->interface->dev, "%s %d", __func__, iReturn);
1096         mutex_unlock(&pdx->io_mutex);
1097
1098         return iReturn;
1099 }
1100
1101 /****************************************************************************
1102 ** TransferFlags
1103 **
1104 ** Returns flags on block transfer abilities
1105 ****************************************************************************/
1106 int TransferFlags(DEVICE_EXTENSION *pdx)
1107 {
1108         int iReturn = U14TF_MULTIA | U14TF_DIAG |       /*  we always have multiple DMA area */
1109             U14TF_NOTIFY | U14TF_CIRCTH;        /*  diagnostics, notify and circular */
1110         dev_dbg(&pdx->interface->dev, "%s", __func__);
1111         mutex_lock(&pdx->io_mutex);
1112         if (pdx->bIsUSB2)       /*  Set flag for USB2 if appropriate */
1113                 iReturn |= U14TF_USB2;
1114         mutex_unlock(&pdx->io_mutex);
1115
1116         return iReturn;
1117 }
1118
1119 /***************************************************************************
1120 ** DbgCmd1401
1121 ** Issues a debug\diagnostic command to the 1401 along with a 32-bit datum
1122 ** This is a utility command used for dbg operations.
1123 */
1124 static int DbgCmd1401(DEVICE_EXTENSION *pdx, unsigned char cmd,
1125                       unsigned int data)
1126 {
1127         int iReturn;
1128         dev_dbg(&pdx->interface->dev, "%s entry", __func__);
1129         iReturn = usb_control_msg(pdx->udev, usb_sndctrlpipe(pdx->udev, 0), cmd,
1130                                   (H_TO_D | VENDOR | DEVREQ),
1131                                   (unsigned short)data,
1132                                   (unsigned short)(data >> 16), NULL, 0, HZ);
1133                                                 /* allow 1 second timeout */
1134         if (iReturn < 0)
1135                 dev_err(&pdx->interface->dev, "%s fail code=%d", __func__,
1136                         iReturn);
1137
1138         return iReturn;
1139 }
1140
1141 /****************************************************************************
1142 ** DbgPeek
1143 **
1144 ** Execute the diagnostic peek operation. Uses address, width and repeats.
1145 ****************************************************************************/
1146 int DbgPeek(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB)
1147 {
1148         int iReturn;
1149         TDBGBLOCK db;
1150
1151         if (copy_from_user(&db, pDB, sizeof(db)))
1152                 return -EFAULT;
1153
1154         mutex_lock(&pdx->io_mutex);
1155         dev_dbg(&pdx->interface->dev, "%s @ %08x", __func__, db.iAddr);
1156
1157         iReturn = DbgCmd1401(pdx, DB_SETADD, db.iAddr);
1158         if (iReturn == U14ERR_NOERROR)
1159                 iReturn = DbgCmd1401(pdx, DB_WIDTH, db.iWidth);
1160         if (iReturn == U14ERR_NOERROR)
1161                 iReturn = DbgCmd1401(pdx, DB_REPEATS, db.iRepeats);
1162         if (iReturn == U14ERR_NOERROR)
1163                 iReturn = DbgCmd1401(pdx, DB_PEEK, 0);
1164         mutex_unlock(&pdx->io_mutex);
1165
1166         return iReturn;
1167 }
1168
1169 /****************************************************************************
1170 ** DbgPoke
1171 **
1172 ** Execute the diagnostic poke operation. Parameters are in the CSBLOCK struct
1173 ** in order address, size, repeats and value to poke.
1174 ****************************************************************************/
1175 int DbgPoke(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB)
1176 {
1177         int iReturn;
1178         TDBGBLOCK db;
1179
1180         if (copy_from_user(&db, pDB, sizeof(db)))
1181                 return -EFAULT;
1182
1183         mutex_lock(&pdx->io_mutex);
1184         dev_dbg(&pdx->interface->dev, "%s @ %08x", __func__, db.iAddr);
1185
1186         iReturn = DbgCmd1401(pdx, DB_SETADD, db.iAddr);
1187         if (iReturn == U14ERR_NOERROR)
1188                 iReturn = DbgCmd1401(pdx, DB_WIDTH, db.iWidth);
1189         if (iReturn == U14ERR_NOERROR)
1190                 iReturn = DbgCmd1401(pdx, DB_REPEATS, db.iRepeats);
1191         if (iReturn == U14ERR_NOERROR)
1192                 iReturn = DbgCmd1401(pdx, DB_POKE, db.iData);
1193         mutex_unlock(&pdx->io_mutex);
1194
1195         return iReturn;
1196 }
1197
1198 /****************************************************************************
1199 ** DbgRampData
1200 **
1201 ** Execute the diagnostic ramp data operation. Parameters are in the CSBLOCK struct
1202 ** in order address, default, enable mask, size and repeats.
1203 ****************************************************************************/
1204 int DbgRampData(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB)
1205 {
1206         int iReturn;
1207         TDBGBLOCK db;
1208
1209         if (copy_from_user(&db, pDB, sizeof(db)))
1210                 return -EFAULT;
1211
1212         mutex_lock(&pdx->io_mutex);
1213         dev_dbg(&pdx->interface->dev, "%s @ %08x", __func__, db.iAddr);
1214
1215         iReturn = DbgCmd1401(pdx, DB_SETADD, db.iAddr);
1216         if (iReturn == U14ERR_NOERROR)
1217                 iReturn = DbgCmd1401(pdx, DB_SETDEF, db.iDefault);
1218         if (iReturn == U14ERR_NOERROR)
1219                 iReturn = DbgCmd1401(pdx, DB_SETMASK, db.iMask);
1220         if (iReturn == U14ERR_NOERROR)
1221                 iReturn = DbgCmd1401(pdx, DB_WIDTH, db.iWidth);
1222         if (iReturn == U14ERR_NOERROR)
1223                 iReturn = DbgCmd1401(pdx, DB_REPEATS, db.iRepeats);
1224         if (iReturn == U14ERR_NOERROR)
1225                 iReturn = DbgCmd1401(pdx, DB_RAMPD, 0);
1226         mutex_unlock(&pdx->io_mutex);
1227
1228         return iReturn;
1229 }
1230
1231 /****************************************************************************
1232 ** DbgRampAddr
1233 **
1234 ** Execute the diagnostic ramp address operation
1235 ****************************************************************************/
1236 int DbgRampAddr(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB)
1237 {
1238         int iReturn;
1239         TDBGBLOCK db;
1240
1241         if (copy_from_user(&db, pDB, sizeof(db)))
1242                 return -EFAULT;
1243
1244         mutex_lock(&pdx->io_mutex);
1245         dev_dbg(&pdx->interface->dev, "%s", __func__);
1246
1247         iReturn = DbgCmd1401(pdx, DB_SETDEF, db.iDefault);
1248         if (iReturn == U14ERR_NOERROR)
1249                 iReturn = DbgCmd1401(pdx, DB_SETMASK, db.iMask);
1250         if (iReturn == U14ERR_NOERROR)
1251                 iReturn = DbgCmd1401(pdx, DB_WIDTH, db.iWidth);
1252         if (iReturn == U14ERR_NOERROR)
1253                 iReturn = DbgCmd1401(pdx, DB_REPEATS, db.iRepeats);
1254         if (iReturn == U14ERR_NOERROR)
1255                 iReturn = DbgCmd1401(pdx, DB_RAMPA, 0);
1256         mutex_unlock(&pdx->io_mutex);
1257
1258         return iReturn;
1259 }
1260
1261 /****************************************************************************
1262 ** DbgGetData
1263 **
1264 ** Retrieve the data resulting from the last debug Peek operation
1265 ****************************************************************************/
1266 int DbgGetData(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB)
1267 {
1268         int iReturn;
1269         TDBGBLOCK db;
1270         memset(&db, 0, sizeof(db));     /*  fill returned block with 0s */
1271
1272         mutex_lock(&pdx->io_mutex);
1273         dev_dbg(&pdx->interface->dev, "%s", __func__);
1274
1275         /*  Read back the last peeked value from the 1401. */
1276         iReturn = usb_control_msg(pdx->udev, usb_rcvctrlpipe(pdx->udev, 0),
1277                                   DB_DATA, (D_TO_H | VENDOR | DEVREQ), 0, 0,
1278                                   &db.iData, sizeof(db.iData), HZ);
1279         if (iReturn == sizeof(db.iData)) {
1280                 if (copy_to_user(pDB, &db, sizeof(db)))
1281                         iReturn = -EFAULT;
1282                 else
1283                         iReturn = U14ERR_NOERROR;
1284         } else
1285                 dev_err(&pdx->interface->dev, "%s failed, code %d", __func__,
1286                         iReturn);
1287
1288         mutex_unlock(&pdx->io_mutex);
1289
1290         return iReturn;
1291 }
1292
1293 /****************************************************************************
1294 ** DbgStopLoop
1295 **
1296 ** Stop any never-ending debug loop, we just call Get1401State for USB
1297 **
1298 ****************************************************************************/
1299 int DbgStopLoop(DEVICE_EXTENSION *pdx)
1300 {
1301         int iReturn;
1302         unsigned int uState, uErr;
1303
1304         mutex_lock(&pdx->io_mutex);
1305         dev_dbg(&pdx->interface->dev, "%s", __func__);
1306         iReturn = Get1401State(pdx, &uState, &uErr);
1307         mutex_unlock(&pdx->io_mutex);
1308
1309         return iReturn;
1310 }
1311
1312 /****************************************************************************
1313 ** SetCircular
1314 **
1315 ** Sets up a transfer area record for circular transfers. If the area is
1316 ** already set, we attempt to unset it. Unsetting will fail if the area is
1317 ** booked and a transfer to that area is in progress. Otherwise, we will
1318 ** release the area and re-assign it.
1319 ****************************************************************************/
1320 int SetCircular(DEVICE_EXTENSION *pdx, TRANSFERDESC __user *pTD)
1321 {
1322         int iReturn;
1323         bool bToHost;
1324         TRANSFERDESC td;
1325
1326         if (copy_from_user(&td, pTD, sizeof(td)))
1327                 return -EFAULT;
1328
1329         mutex_lock(&pdx->io_mutex);
1330         dev_dbg(&pdx->interface->dev, "%s area:%d, size:%08x", __func__,
1331                 td.wAreaNum, td.dwLength);
1332         bToHost = td.eSize != 0;        /*  this is used as the tohost flag */
1333
1334         /*  The strange cast is done so that we don't get warnings in 32-bit linux about the size of the */
1335         /*  pointer. The pointer is always passed as a 64-bit object so that we don't have problems using */
1336         /*  a 32-bit program on a 64-bit system. unsigned long is 64-bits on a 64-bit system. */
1337         iReturn =
1338             SetArea(pdx, td.wAreaNum,
1339                     (char __user *)((unsigned long)td.lpvBuff), td.dwLength,
1340                     true, bToHost);
1341         mutex_unlock(&pdx->io_mutex);
1342         return iReturn;
1343 }
1344
1345 /****************************************************************************
1346 ** GetCircBlock
1347 **
1348 ** Return the next available block of circularly-transferred data.
1349 ****************************************************************************/
1350 int GetCircBlock(DEVICE_EXTENSION *pdx, TCIRCBLOCK __user *pCB)
1351 {
1352         int iReturn = U14ERR_NOERROR;
1353         unsigned int nArea;
1354         TCIRCBLOCK cb;
1355
1356         dev_dbg(&pdx->interface->dev, "%s", __func__);
1357
1358         if (copy_from_user(&cb, pCB, sizeof(cb)))
1359                 return -EFAULT;
1360
1361         mutex_lock(&pdx->io_mutex);
1362
1363         nArea = cb.nArea;       /*  Retrieve parameters first */
1364         cb.dwOffset = 0;        /*  set default result (nothing) */
1365         cb.dwSize = 0;
1366
1367         if (nArea < MAX_TRANSAREAS) {   /*  The area number must be OK */
1368                 TRANSAREA *pArea = &pdx->rTransDef[nArea];      /*  Pointer to relevant info */
1369                 spin_lock_irq(&pdx->stagedLock);        /*  Lock others out */
1370
1371                 if ((pArea->bUsed) && (pArea->bCircular) &&     /*  Must be circular area */
1372                     (pArea->bCircToHost)) {     /*  For now at least must be to host */
1373                         if (pArea->aBlocks[0].dwSize > 0) {     /*  Got anything? */
1374                                 cb.dwOffset = pArea->aBlocks[0].dwOffset;
1375                                 cb.dwSize = pArea->aBlocks[0].dwSize;
1376                                 dev_dbg(&pdx->interface->dev,
1377                                         "%s return block 0: %d bytes at %d",
1378                                         __func__, cb.dwSize, cb.dwOffset);
1379                         }
1380                 } else
1381                         iReturn = U14ERR_NOTSET;
1382
1383                 spin_unlock_irq(&pdx->stagedLock);
1384         } else
1385                 iReturn = U14ERR_BADAREA;
1386
1387         if (copy_to_user(pCB, &cb, sizeof(cb)))
1388                 iReturn = -EFAULT;
1389
1390         mutex_unlock(&pdx->io_mutex);
1391         return iReturn;
1392 }
1393
1394 /****************************************************************************
1395 ** FreeCircBlock
1396 **
1397 ** Frees a block of circularly-transferred data and returns the next one.
1398 ****************************************************************************/
1399 int FreeCircBlock(DEVICE_EXTENSION *pdx, TCIRCBLOCK __user *pCB)
1400 {
1401         int iReturn = U14ERR_NOERROR;
1402         unsigned int nArea, uStart, uSize;
1403         TCIRCBLOCK cb;
1404
1405         dev_dbg(&pdx->interface->dev, "%s", __func__);
1406
1407         if (copy_from_user(&cb, pCB, sizeof(cb)))
1408                 return -EFAULT;
1409
1410         mutex_lock(&pdx->io_mutex);
1411
1412         nArea = cb.nArea;       /*  Retrieve parameters first */
1413         uStart = cb.dwOffset;
1414         uSize = cb.dwSize;
1415         cb.dwOffset = 0;        /*  then set default result (nothing) */
1416         cb.dwSize = 0;
1417
1418         if (nArea < MAX_TRANSAREAS) {   /*  The area number must be OK */
1419                 TRANSAREA *pArea = &pdx->rTransDef[nArea];      /*  Pointer to relevant info */
1420                 spin_lock_irq(&pdx->stagedLock);        /*  Lock others out */
1421
1422                 if ((pArea->bUsed) && (pArea->bCircular) &&     /*  Must be circular area */
1423                     (pArea->bCircToHost)) {     /*  For now at least must be to host */
1424                         bool bWaiting = false;
1425
1426                         if ((pArea->aBlocks[0].dwSize >= uSize) &&      /*  Got anything? */
1427                             (pArea->aBlocks[0].dwOffset == uStart)) {   /*  Must be legal data */
1428                                 pArea->aBlocks[0].dwSize -= uSize;
1429                                 pArea->aBlocks[0].dwOffset += uSize;
1430                                 if (pArea->aBlocks[0].dwSize == 0) {    /*  Have we emptied this block? */
1431                                         if (pArea->aBlocks[1].dwSize) { /*  Is there a second block? */
1432                                                 pArea->aBlocks[0] = pArea->aBlocks[1];  /*  Copy down block 2 data */
1433                                                 pArea->aBlocks[1].dwSize = 0;   /*  and mark the second block as unused */
1434                                                 pArea->aBlocks[1].dwOffset = 0;
1435                                         } else
1436                                                 pArea->aBlocks[0].dwOffset = 0;
1437                                 }
1438
1439                                 dev_dbg(&pdx->interface->dev,
1440                                         "%s free %d bytes at %d, return %d bytes at %d, wait=%d",
1441                                         __func__, uSize, uStart,
1442                                         pArea->aBlocks[0].dwSize,
1443                                         pArea->aBlocks[0].dwOffset,
1444                                         pdx->bXFerWaiting);
1445
1446                                 /*  Return the next available block of memory as well */
1447                                 if (pArea->aBlocks[0].dwSize > 0) {     /*  Got anything? */
1448                                         cb.dwOffset =
1449                                             pArea->aBlocks[0].dwOffset;
1450                                         cb.dwSize = pArea->aBlocks[0].dwSize;
1451                                 }
1452
1453                                 bWaiting = pdx->bXFerWaiting;
1454                                 if (bWaiting && pdx->bStagedUrbPending) {
1455                                         dev_err(&pdx->interface->dev,
1456                                                 "%s ERROR: waiting xfer and staged Urb pending!",
1457                                                 __func__);
1458                                         bWaiting = false;
1459                                 }
1460                         } else {
1461                                 dev_err(&pdx->interface->dev,
1462                                         "%s ERROR: freeing %d bytes at %d, block 0 is %d bytes at %d",
1463                                         __func__, uSize, uStart,
1464                                         pArea->aBlocks[0].dwSize,
1465                                         pArea->aBlocks[0].dwOffset);
1466                                 iReturn = U14ERR_NOMEMORY;
1467                         }
1468
1469                         /*  If we have one, kick off pending transfer */
1470                         if (bWaiting) { /*  Got a block xfer waiting? */
1471                                 int RWMStat =
1472                                     ReadWriteMem(pdx, !pdx->rDMAInfo.bOutWard,
1473                                                  pdx->rDMAInfo.wIdent,
1474                                                  pdx->rDMAInfo.dwOffset,
1475                                                  pdx->rDMAInfo.dwSize);
1476                                 if (RWMStat != U14ERR_NOERROR)
1477                                         dev_err(&pdx->interface->dev,
1478                                                 "%s rw setup failed %d",
1479                                                 __func__, RWMStat);
1480                         }
1481                 } else
1482                         iReturn = U14ERR_NOTSET;
1483
1484                 spin_unlock_irq(&pdx->stagedLock);
1485         } else
1486                 iReturn = U14ERR_BADAREA;
1487
1488         if (copy_to_user(pCB, &cb, sizeof(cb)))
1489                 iReturn = -EFAULT;
1490
1491         mutex_unlock(&pdx->io_mutex);
1492         return iReturn;
1493 }
This page took 0.118832 seconds and 4 git commands to generate.