Staging: rspiusb.c: break the huge piusb_ioctl function into several ones
[cascardo/linux.git] / drivers / staging / rspiusb / rspiusb.c
1 /*
2  * rspiusb.c
3  *
4  * Copyright (C) 2005, 2006 Princeton Instruments
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation version 2 of the License
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <linux/vmalloc.h>
21 #include <linux/kernel.h>
22 #include <linux/errno.h>
23 #include <linux/init.h>
24 #include <linux/slab.h>
25 #include <linux/module.h>
26 #include <linux/smp_lock.h>
27 #include <linux/completion.h>
28 #include <linux/scatterlist.h>
29 #include <linux/usb.h>
30 #include <linux/mm.h>
31 #include <linux/pagemap.h>
32 #include <linux/ioctl.h>
33 #include "rspiusb.h"
34
35 #ifdef CONFIG_USB_DEBUG
36 static int debug = 1;
37 #else
38 static int debug;
39 #endif
40 /* Use our own dbg macro */
41 #undef dbg
42 #define dbg(format, arg...) \
43         do { \
44                 if (debug) \
45                         printk(KERN_DEBUG __FILE__ ": " format "\n" , ##arg); \
46         } while (0)
47
48 /* Version Information */
49 #define DRIVER_VERSION "V1.0.1"
50 #define DRIVER_AUTHOR  "Princeton Instruments"
51 #define DRIVER_DESC    "PI USB2.0 Device Driver for Linux"
52
53 /* Define these values to match your devices */
54 #define VENDOR_ID   0x0BD7
55 #define ST133_PID   0xA010
56 #define PIXIS_PID   0xA026
57
58 /* Get a minor range for your devices from the usb maintainer */
59 #ifdef CONFIG_USB_DYNAMIC_MINORS
60 #define PIUSB_MINOR_BASE    0
61 #else
62 #define PIUSB_MINOR_BASE    192
63 #endif
64
65 /* prevent races between open() and disconnect() */
66 static DECLARE_MUTEX(disconnect_sem);
67
68 /* Structure to hold all of our device specific stuff */
69 struct device_extension {
70         struct usb_device *udev;         /* save off the usb device pointer */
71         struct usb_interface *interface; /* the interface for this device */
72         unsigned char minor;             /* the starting minor number
73                                           * for this device
74                                           */
75         size_t bulk_in_size_returned;
76         int bulk_in_byte_trk;
77         struct urb ***PixelUrb;
78         int frameIdx;
79         int urbIdx;
80         unsigned int *maplist_numPagesMapped;
81         int open;                 /* if the port is open or not */
82         int present;              /* if the device is not disconnected */
83         int userBufMapped;        /* has the user buffer been mapped ? */
84         struct scatterlist **sgl; /* scatter-gather list for user buffer */
85         unsigned int *sgEntries;
86         struct kref kref;
87         int gotPixelData;
88         int pendingWrite;
89         char **pendedPixelUrbs;
90         int iama;                /* PIXIS or ST133 */
91         int num_frames;          /* the number of frames that will fit
92                                   * in the user buffer
93                                   */
94         int active_frame;
95         unsigned long frameSize;
96         struct semaphore sem;
97         unsigned int hEP[8];     /* FX2 specific endpoints */
98 };
99
100 #define to_pi_dev(d) container_of(d, struct device_extension, kref)
101
102 /* Prototypes */
103 static int MapUserBuffer(struct ioctl_struct *, struct device_extension *);
104 static int UnMapUserBuffer(struct device_extension *);
105 static int piusb_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
106                        unsigned long arg);
107 static int piusb_output(struct ioctl_struct *, unsigned char *, int,
108                 struct device_extension *);
109 static struct usb_driver piusb_driver;
110
111 /* table of devices that work with this driver */
112 static struct usb_device_id pi_device_table[] = {
113         {USB_DEVICE(VENDOR_ID, ST133_PID)},
114         {USB_DEVICE(VENDOR_ID, PIXIS_PID)},
115         {0, } /* Terminating entry */
116 };
117
118 MODULE_DEVICE_TABLE(usb, pi_device_table);
119
120 static int lastErr;
121 static int errCnt;
122
123 static void piusb_delete(struct kref *kref)
124 {
125         struct device_extension *pdx = to_pi_dev(kref);
126
127         dev_dbg(&pdx->udev->dev, "%s\n", __func__);
128         usb_put_dev(pdx->udev);
129         kfree(pdx);
130 }
131
132 static int piusb_open(struct inode *inode, struct file *file)
133 {
134         struct device_extension *pdx = NULL;
135         struct usb_interface *interface;
136         int subminor;
137         int retval = 0;
138
139         dbg("Piusb_Open()");
140         subminor = iminor(inode);
141         interface = usb_find_interface(&piusb_driver, subminor);
142         if (!interface) {
143                 printk(KERN_ERR "%s - error, can't find device for minor %d\n",
144                        __func__, subminor);
145                 retval = -ENODEV;
146                 goto exit_no_device;
147         }
148
149         pdx = usb_get_intfdata(interface);
150         if (!pdx) {
151                 retval = -ENODEV;
152                 goto exit_no_device;
153         }
154         dbg("Alternate Setting = %d", interface->num_altsetting);
155
156         pdx->bulk_in_size_returned = 0;
157         pdx->bulk_in_byte_trk = 0;
158         pdx->PixelUrb = NULL;
159         pdx->frameIdx = 0;
160         pdx->urbIdx = 0;
161         pdx->maplist_numPagesMapped = NULL;
162         pdx->userBufMapped = 0;
163         pdx->sgl = NULL;
164         pdx->sgEntries = NULL;
165         pdx->gotPixelData = 0;
166         pdx->pendingWrite = 0;
167         pdx->pendedPixelUrbs = NULL;
168         pdx->num_frames = 0;
169         pdx->active_frame = 0;
170         pdx->frameSize = 0;
171
172         /* increment our usage count for the device */
173         kref_get(&pdx->kref);
174
175         /* save our object in the file's private structure */
176         file->private_data = pdx;
177
178 exit_no_device:
179         return retval;
180 }
181
182 static int piusb_release(struct inode *inode, struct file *file)
183 {
184         struct device_extension *pdx;
185         int retval = 0;
186
187         dbg("Piusb_Release()");
188         pdx = (struct device_extension *)file->private_data;
189         if (pdx == NULL) {
190                 dbg("%s - object is NULL", __func__);
191                 retval = -ENODEV;
192                 goto object_null;
193         }
194         /* decrement the count on our device */
195         kref_put(&pdx->kref, piusb_delete);
196
197 object_null:
198         return retval;
199 }
200
201 static int pixis_io(struct ioctl_struct *ctrl, struct device_extension *pdx,
202                 struct ioctl_struct *arg)
203 {
204         unsigned int numToRead = 0;
205         unsigned int totalRead = 0;
206         unsigned char *uBuf;
207         int numbytes;
208         int i;
209
210         uBuf = kmalloc(ctrl->numbytes, GFP_KERNEL);
211         if (!uBuf) {
212                 dbg("Alloc for uBuf failed");
213                 return 0;
214         }
215         numbytes = (int) ctrl->numbytes;
216         numToRead = (unsigned int) ctrl->numbytes;
217         dbg("numbytes to read = %d", numbytes);
218         dbg("endpoint # %d", ctrl->endpoint);
219
220         if (copy_from_user(uBuf, ctrl->pData, numbytes))
221                 dbg("copying ctrl->pData to dummyBuf failed");
222
223         do {
224                 i = usb_bulk_msg(pdx->udev, pdx->hEP[ctrl->endpoint],
225                                 (uBuf + totalRead),
226                                 /* EP0 can only handle 64 bytes at a time */
227                                 (numToRead > 64) ? 64 : numToRead,
228                                 &numbytes, HZ * 10);
229                 if (i) {
230                         dbg("CMD = %s, Address = 0x%02X",
231                                         ((uBuf[3] == 0x02) ? "WRITE" : "READ"),
232                                         uBuf[1]);
233                         dbg("Number of bytes Attempted to read = %d",
234                                         (int)ctrl->numbytes);
235                         dbg("Blocking ReadI/O Failed with status %d", i);
236                         kfree(uBuf);
237                         return -1;
238                 }
239                 dbg("Pixis EP0 Read %d bytes", numbytes);
240                 totalRead += numbytes;
241                 numToRead -= numbytes;
242         } while (numToRead);
243
244         memcpy(ctrl->pData, uBuf, totalRead);
245         dbg("Total Bytes Read from PIXIS EP0 = %d", totalRead);
246         ctrl->numbytes = totalRead;
247
248         if (copy_to_user(arg, ctrl, sizeof(struct ioctl_struct)))
249                 dbg("copy_to_user failed in IORB");
250
251         kfree(uBuf);
252         return ctrl->numbytes;
253 }
254
255 static int pixis_io2(struct ioctl_struct *ctrl, struct device_extension *pdx,
256                 struct ioctl_struct *arg)
257 {
258         unsigned char *uBuf;
259         int numbytes;
260         int i;
261
262         uBuf = kmalloc(ctrl->numbytes, GFP_KERNEL);
263         if (!uBuf) {
264                 dbg("Alloc for uBuf failed");
265                 return 0;
266         }
267         numbytes = (int) ctrl->numbytes;
268         /* dbg( "numbytes to read = %d", numbytes ); */
269         if (copy_from_user(uBuf, ctrl->pData, numbytes))
270                 dbg("copying ctrl->pData to dummyBuf failed");
271
272         i = usb_bulk_msg(pdx->udev, pdx->hEP[ctrl->endpoint],
273                         uBuf, numbytes, &numbytes, HZ * 10);
274         if (i) {
275                 dbg("Blocking ReadI/O Failed with status %d", i);
276                 kfree(uBuf);
277                 return -1;
278         }
279         ctrl->numbytes = numbytes;
280         memcpy(ctrl->pData, uBuf, numbytes);
281         if (copy_to_user(arg, ctrl, sizeof(struct ioctl_struct)))
282                 dbg("copy_to_user failed in IORB");
283         kfree(uBuf);
284         return ctrl->numbytes;
285 }
286
287 static int pixel_data(struct ioctl_struct *ctrl, struct device_extension *pdx)
288 {
289         int i;
290
291         if (!pdx->gotPixelData)
292                 return 0;
293
294         pdx->gotPixelData = 0;
295         ctrl->numbytes = pdx->bulk_in_size_returned;
296         pdx->bulk_in_size_returned -= pdx->frameSize;
297
298         for (i = 0; i < pdx->maplist_numPagesMapped[pdx->active_frame]; i++)
299                 SetPageDirty(pdx->sgl[pdx->active_frame][i].page_link);
300
301         pdx->active_frame = ((pdx->active_frame + 1) % pdx->num_frames);
302
303         return ctrl->numbytes;
304 }
305
306 /**
307  *      piusb_ioctl
308  */
309 static int piusb_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
310                        unsigned long arg)
311 {
312         struct device_extension *pdx;
313         char dummyCtlBuf[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
314         unsigned long devRB = 0;
315         int err = 0;
316         int retval = 0;
317         struct ioctl_struct ctrl;
318         unsigned short controlData = 0;
319
320         pdx = (struct device_extension *)file->private_data;
321         /* verify that the device wasn't unplugged */
322         if (!pdx->present) {
323                 dbg("No Device Present\n");
324                 return -ENODEV;
325         }
326         /* fill in your device specific stuff here */
327         if (_IOC_DIR(cmd) & _IOC_READ)
328                 err = !access_ok(VERIFY_WRITE, (void __user *)arg,
329                                 _IOC_SIZE(cmd));
330         else if (_IOC_DIR(cmd) & _IOC_WRITE)
331                 err = !access_ok(VERIFY_READ, (void __user *)arg,
332                                _IOC_SIZE(cmd));
333         if (err) {
334                 dev_err(&pdx->udev->dev, "return with error = %d\n", err);
335                 return -EFAULT;
336         }
337         switch (cmd) {
338         case PIUSB_GETVNDCMD:
339                 if (copy_from_user
340                     (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
341                         dev_err(&pdx->udev->dev, "copy_from_user failed\n");
342                 dbg("%s %x\n", "Get Vendor Command = ", ctrl.cmd);
343                 retval =
344                     usb_control_msg(pdx->udev, usb_rcvctrlpipe(pdx->udev, 0),
345                                     ctrl.cmd, USB_DIR_IN, 0, 0, &devRB,
346                                     ctrl.numbytes, HZ * 10);
347                 if (ctrl.cmd == 0xF1) {
348                         dbg("FW Version returned from HW = %ld.%ld",
349                             (devRB >> 8), (devRB & 0xFF));
350                 }
351                 if (retval >= 0)
352                         retval = (int)devRB;
353                 return retval;
354
355         case PIUSB_SETVNDCMD:
356                 if (copy_from_user
357                     (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
358                         dev_err(&pdx->udev->dev, "copy_from_user failed\n");
359                 /* dbg( "%s %x", "Set Vendor Command = ",ctrl.cmd ); */
360                 controlData = ctrl.pData[0];
361                 controlData |= (ctrl.pData[1] << 8);
362                 /* dbg( "%s %d", "Vendor Data =",controlData ); */
363                 retval = usb_control_msg(pdx->udev,
364                                 usb_sndctrlpipe(pdx->udev, 0),
365                                 ctrl.cmd,
366                                 (USB_DIR_OUT | USB_TYPE_VENDOR
367                                  /* | USB_RECIP_ENDPOINT */),
368                                 controlData, 0,
369                                 &dummyCtlBuf, ctrl.numbytes, HZ * 10);
370                 return retval;
371
372         case PIUSB_ISHIGHSPEED:
373                 return ((pdx->udev->speed == USB_SPEED_HIGH) ? 1 : 0);
374
375         case PIUSB_WRITEPIPE:
376                 if (copy_from_user(&ctrl, (void __user *)arg, _IOC_SIZE(cmd)))
377                         dev_err(&pdx->udev->dev,
378                                         "copy_from_user WRITE_DUMMY failed\n");
379                 if (!access_ok(VERIFY_READ, ctrl.pData, ctrl.numbytes)) {
380                         dbg("can't access pData");
381                         return 0;
382                 }
383                 piusb_output(&ctrl, ctrl.pData /* uBuf */, ctrl.numbytes, pdx);
384                 return ctrl.numbytes;
385
386         case PIUSB_USERBUFFER:
387                 if (copy_from_user
388                     (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
389                         dev_err(&pdx->udev->dev, "copy_from_user failed\n");
390                 return MapUserBuffer((struct ioctl_struct *) &ctrl, pdx);
391
392         case PIUSB_UNMAP_USERBUFFER:
393                 retval = UnMapUserBuffer(pdx);
394                 return retval;
395
396         case PIUSB_READPIPE:
397                 if (copy_from_user(&ctrl, (void __user *)arg,
398                                         sizeof(struct ioctl_struct)))
399                         dev_err(&pdx->udev->dev, "copy_from_user failed\n");
400
401                 switch (ctrl.endpoint) {
402                 case 0: /* ST133 Pixel Data or PIXIS IO */
403                         if (pdx->iama == PIXIS_PID) {
404                                 return pixis_io(&ctrl, pdx,
405                                                 (struct ioctl_struct *)arg);
406                         }
407                         /* ST133 Pixel Data */
408                         /* fall through */
409                 case 2: /* PIXIS Ping */
410                         /* fall through */
411                 case 3: /* PIXIS Pong */
412                         return pixel_data(&ctrl, pdx);
413
414                 case 1: /* ST133IO */
415                         /* fall through */
416                 case 4: /* PIXIS IO */
417                         return pixis_io2(&ctrl, pdx,
418                                         (struct ioctl_struct *)arg);
419                 default:
420                         break;
421                 }
422                 break;
423
424         case PIUSB_WHATCAMERA:
425                 return pdx->iama;
426
427         case PIUSB_SETFRAMESIZE:
428                 dbg("PIUSB_SETFRAMESIZE");
429                 if (copy_from_user
430                     (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
431                         dev_err(&pdx->udev->dev, "copy_from_user failed\n");
432                 pdx->frameSize = ctrl.numbytes;
433                 pdx->num_frames = ctrl.numFrames;
434                 if (!pdx->sgl)
435                         pdx->sgl =
436                             kmalloc(sizeof(struct scatterlist *) *
437                                     pdx->num_frames, GFP_KERNEL);
438                 if (!pdx->sgEntries)
439                         pdx->sgEntries =
440                             kmalloc(sizeof(unsigned int) * pdx->num_frames,
441                                     GFP_KERNEL);
442                 if (!pdx->PixelUrb)
443                         pdx->PixelUrb =
444                             kmalloc(sizeof(struct urb **) * pdx->num_frames,
445                                     GFP_KERNEL);
446                 if (!pdx->maplist_numPagesMapped)
447                         pdx->maplist_numPagesMapped =
448                             vmalloc(sizeof(unsigned int) * pdx->num_frames);
449                 if (!pdx->pendedPixelUrbs)
450                         pdx->pendedPixelUrbs =
451                             kmalloc(sizeof(char *) * pdx->num_frames,
452                                     GFP_KERNEL);
453                 return 0;
454
455         default:
456                 dbg("%s\n", "No IOCTL found");
457                 break;
458
459         }
460         /* return that we did not understand this ioctl call */
461         dbg("Returning -ENOTTY");
462         return -ENOTTY;
463 }
464
465 static void piusb_write_bulk_callback(struct urb *urb)
466 {
467         struct device_extension *pdx = urb->context;
468         int status = urb->status;
469
470         /* sync/async unlink faults aren't errors */
471         if (status && !(status == -ENOENT || status == -ECONNRESET))
472                 dev_dbg(&urb->dev->dev,
473                         "%s - nonzero write bulk status received: %d",
474                         __func__, status);
475
476         pdx->pendingWrite = 0;
477         usb_buffer_free(urb->dev, urb->transfer_buffer_length,
478                         urb->transfer_buffer, urb->transfer_dma);
479 }
480
481 int piusb_output(struct ioctl_struct *io, unsigned char *uBuf, int len,
482                  struct device_extension *pdx)
483 {
484         struct urb *urb = NULL;
485         int err = 0;
486         unsigned char *kbuf = NULL;
487
488         urb = usb_alloc_urb(0, GFP_KERNEL);
489         if (urb != NULL) {
490                 kbuf =
491                     usb_buffer_alloc(pdx->udev, len, GFP_KERNEL,
492                                      &urb->transfer_dma);
493                 if (!kbuf) {
494                         dev_err(&pdx->udev->dev, "buffer_alloc failed\n");
495                         return -ENOMEM;
496                 }
497                 memcpy(kbuf, uBuf, len);
498                 usb_fill_bulk_urb(urb, pdx->udev, pdx->hEP[io->endpoint], kbuf,
499                                   len, piusb_write_bulk_callback, pdx);
500                 urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
501                 err = usb_submit_urb(urb, GFP_KERNEL);
502                 if (err) {
503                         dev_err(&pdx->udev->dev,
504                                 "WRITE ERROR:submit urb error = %d\n", err);
505                 }
506                 pdx->pendingWrite = 1;
507                 usb_free_urb(urb);
508         }
509         return -EINPROGRESS;
510 }
511
512 static int UnMapUserBuffer(struct device_extension *pdx)
513 {
514         int i = 0;
515         int k = 0;
516         unsigned int epAddr;
517
518         for (k = 0; k < pdx->num_frames; k++) {
519                 dbg("Killing Urbs for Frame %d", k);
520                 for (i = 0; i < pdx->sgEntries[k]; i++) {
521                         usb_kill_urb(pdx->PixelUrb[k][i]);
522                         usb_free_urb(pdx->PixelUrb[k][i]);
523                         pdx->pendedPixelUrbs[k][i] = 0;
524                 }
525                 dbg("Urb error count = %d", errCnt);
526                 errCnt = 0;
527                 dbg("Urbs free'd and Killed for Frame %d", k);
528         }
529
530         for (k = 0; k < pdx->num_frames; k++) {
531                 if (pdx->iama == PIXIS_PID)
532                         /* which EP should we map this frame to ? */
533                         /* PONG, odd frames: hEP[3] */
534                         /* PING, even frames and zero hEP[2] */
535                         epAddr = (k % 2) ? pdx->hEP[3] : pdx->hEP[2];
536                 else
537                         /* ST133 only has 1 endpoint for Pixel data transfer */
538                         epAddr = pdx->hEP[0];
539
540                 usb_buffer_unmap_sg(pdx->udev, epAddr, pdx->sgl[k],
541                                     pdx->maplist_numPagesMapped[k]);
542                 for (i = 0; i < pdx->maplist_numPagesMapped[k]; i++)
543                         page_cache_release(pdx->sgl[k][i].page_link);
544                 kfree(pdx->sgl[k]);
545                 kfree(pdx->PixelUrb[k]);
546                 kfree(pdx->pendedPixelUrbs[k]);
547                 pdx->sgl[k] = NULL;
548                 pdx->PixelUrb[k] = NULL;
549                 pdx->pendedPixelUrbs[k] = NULL;
550         }
551
552         kfree(pdx->sgEntries);
553         vfree(pdx->maplist_numPagesMapped);
554         pdx->sgEntries = NULL;
555         pdx->maplist_numPagesMapped = NULL;
556         kfree(pdx->sgl);
557         kfree(pdx->pendedPixelUrbs);
558         kfree(pdx->PixelUrb);
559         pdx->sgl = NULL;
560         pdx->pendedPixelUrbs = NULL;
561         pdx->PixelUrb = NULL;
562
563         return 0;
564 }
565
566 static void piusb_readPIXEL_callback(struct urb *urb)
567 {
568         int i = 0;
569         struct device_extension *pdx = urb->context;
570         int status = urb->status;
571
572         if (status && !(status == -ENOENT || status == -ECONNRESET)) {
573                 dbg("%s - nonzero read bulk status received: %d", __func__,
574                     status);
575                 dbg("Error in read EP2 callback");
576                 dbg("FrameIndex = %d", pdx->frameIdx);
577                 dbg("Bytes received before problem occurred = %d",
578                     pdx->bulk_in_byte_trk);
579                 dbg("Urb Idx = %d", pdx->urbIdx);
580                 pdx->pendedPixelUrbs[pdx->frameIdx][pdx->urbIdx] = 0;
581         } else {
582                 pdx->bulk_in_byte_trk += urb->actual_length;
583                 i = usb_submit_urb(urb, GFP_ATOMIC);    /* resubmit the URB */
584                 if (i) {
585                         errCnt++;
586                         if (i != lastErr) {
587                                 dbg("submit urb in callback failed "
588                                                 "with error code %d", i);
589                                 lastErr = i;
590                         }
591                 } else {
592                         pdx->urbIdx++; /* point to next URB when we callback */
593                         if (pdx->bulk_in_byte_trk >= pdx->frameSize) {
594                                 pdx->bulk_in_size_returned =
595                                         pdx->bulk_in_byte_trk;
596                                 pdx->bulk_in_byte_trk = 0;
597                                 pdx->gotPixelData = 1;
598                                 pdx->frameIdx =
599                                         ((pdx->frameIdx +
600                                           1) % pdx->num_frames);
601                                 pdx->urbIdx = 0;
602                         }
603                 }
604         }
605 }
606
607 /* MapUserBuffer(
608         inputs:
609         struct ioctl_struct *io - structure containing user address,
610                                 frame #, and size
611         struct device_extension *pdx - the PIUSB device extension
612
613         returns:
614         int - status of the task
615
616         Notes:
617         MapUserBuffer maps a buffer passed down through an ioctl.
618         The user buffer is Page Aligned by the app and then passed down.
619         The function get_free_pages(...) does the actual mapping of the buffer
620         from user space to kernel space.
621         From there a scatterlist is created from all the pages.
622         The next function called is to usb_buffer_map_sg which allocated
623         DMA addresses for each page, even coalescing them if possible.
624         The DMA address is placed in the scatterlist structure.
625         The function returns the number of DMA addresses.
626         This may or may not be equal to the number of pages that
627         the user buffer uses.
628         We then build an URB for each DMA address and then submit them.
629 */
630
631 /*
632 int MapUserBuffer(unsigned long uaddr, unsigned long numbytes,
633                 unsigned long frameInfo, struct device_extension *pdx)
634 */
635 static int MapUserBuffer(struct ioctl_struct *io, struct device_extension *pdx)
636 {
637         unsigned long uaddr;
638         unsigned long numbytes;
639         int frameInfo;  /* which frame we're mapping */
640         unsigned int epAddr = 0;
641         unsigned long count = 0;
642         int i = 0;
643         int k = 0;
644         int err = 0;
645         struct page **maplist_p;
646         int numPagesRequired;
647
648         frameInfo = io->numFrames;
649         uaddr = (unsigned long)io->pData;
650         numbytes = io->numbytes;
651
652         if (pdx->iama == PIXIS_PID) {
653                 /* which EP should we map this frame to ? */
654                 /* PONG, odd frames: hEP[3] */
655                 /* PING, even frames and zero hEP[2] */
656                 epAddr = (frameInfo % 2) ? pdx->hEP[3] : pdx->hEP[2];
657                 dbg("Pixis Frame #%d: EP=%d", frameInfo,
658                     (epAddr == pdx->hEP[2]) ? 2 : 4);
659         } else { /* ST133 only has 1 endpoint for Pixel data transfer */
660                 epAddr = pdx->hEP[0];
661                 dbg("ST133 Frame #%d: EP=2", frameInfo);
662         }
663         count = numbytes;
664         dbg("UserAddress = 0x%08lX", uaddr);
665         dbg("numbytes = %d", (int)numbytes);
666
667         /* number of pages to map the entire user space DMA buffer */
668         numPagesRequired =
669             ((uaddr & ~PAGE_MASK) + count + ~PAGE_MASK) >> PAGE_SHIFT;
670         dbg("Number of pages needed = %d", numPagesRequired);
671         maplist_p = vmalloc(numPagesRequired * sizeof(struct page));
672         if (!maplist_p) {
673                 dbg("Can't Allocate Memory for maplist_p");
674                 return -ENOMEM;
675         }
676
677         /* map the user buffer to kernel memory */
678         down_write(&current->mm->mmap_sem);
679         pdx->maplist_numPagesMapped[frameInfo] = get_user_pages(current,
680                         current->mm, (uaddr & PAGE_MASK), numPagesRequired,
681                         WRITE, 0 /* Don't Force*/, maplist_p, NULL);
682         up_write(&current->mm->mmap_sem);
683         dbg("Number of pages mapped = %d",
684             pdx->maplist_numPagesMapped[frameInfo]);
685
686         for (i = 0; i < pdx->maplist_numPagesMapped[frameInfo]; i++)
687                 flush_dcache_page(maplist_p[i]);
688         if (!pdx->maplist_numPagesMapped[frameInfo]) {
689                 dbg("get_user_pages() failed");
690                 vfree(maplist_p);
691                 return -ENOMEM;
692         }
693
694         /* need to create a scatterlist that spans each frame
695          * that can fit into the mapped buffer
696          */
697         pdx->sgl[frameInfo] =
698             kmalloc((pdx->maplist_numPagesMapped[frameInfo] *
699                      sizeof(struct scatterlist)), GFP_ATOMIC);
700         if (!pdx->sgl[frameInfo]) {
701                 vfree(maplist_p);
702                 dbg("can't allocate mem for sgl");
703                 return -ENOMEM;
704         }
705         pdx->sgl[frameInfo][0].page_link = maplist_p[0];
706         pdx->sgl[frameInfo][0].offset = uaddr & ~PAGE_MASK;
707         if (pdx->maplist_numPagesMapped[frameInfo] > 1) {
708                 pdx->sgl[frameInfo][0].length =
709                     PAGE_SIZE - pdx->sgl[frameInfo][0].offset;
710                 count -= pdx->sgl[frameInfo][0].length;
711                 for (k = 1; k < pdx->maplist_numPagesMapped[frameInfo]; k++) {
712                         pdx->sgl[frameInfo][k].offset = 0;
713                         pdx->sgl[frameInfo][k].page_link = maplist_p[k];
714                         pdx->sgl[frameInfo][k].length =
715                             (count < PAGE_SIZE) ? count : PAGE_SIZE;
716                         count -= PAGE_SIZE; /* example had PAGE_SIZE here */
717                 }
718         } else {
719                 pdx->sgl[frameInfo][0].length = count;
720         }
721         pdx->sgEntries[frameInfo] =
722             usb_buffer_map_sg(pdx->udev, epAddr, pdx->sgl[frameInfo],
723                               pdx->maplist_numPagesMapped[frameInfo]);
724         dbg("number of sgEntries = %d", pdx->sgEntries[frameInfo]);
725         pdx->userBufMapped = 1;
726         vfree(maplist_p);
727
728         /* Create and Send the URB's for each s/g entry */
729         pdx->PixelUrb[frameInfo] =
730             kmalloc(pdx->sgEntries[frameInfo] * sizeof(struct urb *),
731                     GFP_KERNEL);
732         if (!pdx->PixelUrb[frameInfo]) {
733                 dbg("Can't Allocate Memory for Urb");
734                 return -ENOMEM;
735         }
736         for (i = 0; i < pdx->sgEntries[frameInfo]; i++) {
737                 /* 0 iso packets because we're using BULK transfers */
738                 pdx->PixelUrb[frameInfo][i] = usb_alloc_urb(0, GFP_KERNEL);
739                 usb_fill_bulk_urb(pdx->PixelUrb[frameInfo][i],
740                                   pdx->udev,
741                                   epAddr,
742                                   (dma_addr_t *) sg_dma_address(&pdx->
743                                                                 sgl[frameInfo]
744                                                                 [i]),
745                                   sg_dma_len(&pdx->sgl[frameInfo][i]),
746                                   piusb_readPIXEL_callback, (void *)pdx);
747                 pdx->PixelUrb[frameInfo][i]->transfer_dma =
748                     sg_dma_address(&pdx->sgl[frameInfo][i]);
749                 pdx->PixelUrb[frameInfo][i]->transfer_flags =
750                     URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT;
751         }
752         /* only interrupt when last URB completes */
753         pdx->PixelUrb[frameInfo][--i]->transfer_flags &= ~URB_NO_INTERRUPT;
754         pdx->pendedPixelUrbs[frameInfo] =
755             kmalloc((pdx->sgEntries[frameInfo] * sizeof(char)), GFP_KERNEL);
756         if (!pdx->pendedPixelUrbs[frameInfo])
757                 dbg("Can't allocate Memory for pendedPixelUrbs");
758         for (i = 0; i < pdx->sgEntries[frameInfo]; i++) {
759                 err = usb_submit_urb(pdx->PixelUrb[frameInfo][i], GFP_ATOMIC);
760                 if (err) {
761                         dbg("%s %d\n", "submit urb error =", err);
762                         pdx->pendedPixelUrbs[frameInfo][i] = 0;
763                         return err;
764                 }
765                 pdx->pendedPixelUrbs[frameInfo][i] = 1;
766         }
767         return 0;
768 }
769
770 static const struct file_operations piusb_fops = {
771         .owner = THIS_MODULE,
772         .ioctl = piusb_ioctl,
773         .open = piusb_open,
774         .release = piusb_release,
775 };
776
777 static struct usb_class_driver piusb_class = {
778         .name = "usb/rspiusb%d",
779         .fops = &piusb_fops,
780         .minor_base = PIUSB_MINOR_BASE,
781 };
782
783 /**
784  *      piusb_probe
785  *
786  *      Called by the usb core when a new device is connected that it thinks
787  *      this driver might be interested in.
788  */
789 static int piusb_probe(struct usb_interface *interface,
790                        const struct usb_device_id *id)
791 {
792         struct device_extension *pdx = NULL;
793         struct usb_host_interface *iface_desc;
794         struct usb_endpoint_descriptor *endpoint;
795         int i;
796         int retval = -ENOMEM;
797
798         dev_dbg(&interface->dev, "%s - Looking for PI USB Hardware", __func__);
799
800         pdx = kzalloc(sizeof(struct device_extension), GFP_KERNEL);
801         if (pdx == NULL) {
802                 dev_err(&interface->dev, "Out of memory\n");
803                 goto error;
804         }
805         kref_init(&pdx->kref);
806         pdx->udev = usb_get_dev(interface_to_usbdev(interface));
807         pdx->interface = interface;
808         iface_desc = interface->cur_altsetting;
809
810         /* See if the device offered us matches what we can accept */
811         if ((pdx->udev->descriptor.idVendor != VENDOR_ID)
812             || ((pdx->udev->descriptor.idProduct != PIXIS_PID)
813                 && (pdx->udev->descriptor.idProduct != ST133_PID)))
814                 return -ENODEV;
815
816         pdx->iama = pdx->udev->descriptor.idProduct;
817
818         if (debug) {
819                 if (pdx->udev->descriptor.idProduct == PIXIS_PID)
820                         dbg("PIUSB:Pixis Camera Found");
821                 else
822                         dbg("PIUSB:ST133 USB Controller Found");
823                 if (pdx->udev->speed == USB_SPEED_HIGH)
824                         dbg("Highspeed(USB2.0) Device Attached");
825                 else
826                         dbg("Lowspeed (USB1.1) Device Attached");
827
828                 dbg("NumEndpoints in Configuration: %d",
829                     iface_desc->desc.bNumEndpoints);
830         }
831         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
832                 endpoint = &iface_desc->endpoint[i].desc;
833                 if (debug) {
834                         dbg("Endpoint[%d]->bDescriptorType = %d", i,
835                             endpoint->bDescriptorType);
836                         dbg("Endpoint[%d]->bEndpointAddress = 0x%02X", i,
837                             endpoint->bEndpointAddress);
838                         dbg("Endpoint[%d]->bbmAttributes = %d", i,
839                             endpoint->bmAttributes);
840                         dbg("Endpoint[%d]->MaxPacketSize = %d\n", i,
841                             endpoint->wMaxPacketSize);
842                 }
843                 if (usb_endpoint_xfer_bulk(endpoint)) {
844                         if (usb_endpoint_dir_in(endpoint))
845                                 pdx->hEP[i] =
846                                     usb_rcvbulkpipe(pdx->udev,
847                                                     endpoint->bEndpointAddress);
848                         else
849                                 pdx->hEP[i] =
850                                     usb_sndbulkpipe(pdx->udev,
851                                                     endpoint->bEndpointAddress);
852                 }
853         }
854         usb_set_intfdata(interface, pdx);
855         retval = usb_register_dev(interface, &piusb_class);
856         if (retval) {
857                 err("Not able to get a minor for this device.");
858                 usb_set_intfdata(interface, NULL);
859                 goto error;
860         }
861         pdx->present = 1;
862
863         /* we can register the device now, as it is ready */
864         pdx->minor = interface->minor;
865         /* let the user know what node this device is now attached to */
866         dbg("PI USB2.0 device now attached to piusb-%d", pdx->minor);
867         return 0;
868
869 error:
870         if (pdx)
871                 kref_put(&pdx->kref, piusb_delete);
872         return retval;
873 }
874
875 /**
876  *      piusb_disconnect
877  *
878  *      Called by the usb core when the device is removed from the system.
879  *
880  *      This routine guarantees that the driver will not submit any more urbs
881  *      by clearing pdx->udev.  It is also supposed to terminate any currently
882  *      active urbs.  Unfortunately, usb_bulk_msg(), used in piusb_read(), does
883  *      not provide any way to do this.  But at least we can cancel an active
884  *      write.
885  */
886 static void piusb_disconnect(struct usb_interface *interface)
887 {
888         struct device_extension *pdx;
889         int minor = interface->minor;
890
891         lock_kernel();
892
893         pdx = usb_get_intfdata(interface);
894         usb_set_intfdata(interface, NULL);
895
896         /* give back our minor */
897         usb_deregister_dev(interface, &piusb_class);
898
899         unlock_kernel();
900
901         /* prevent device read, write and ioctl */
902         pdx->present = 0;
903         kref_put(&pdx->kref, piusb_delete);
904         dbg("PI USB2.0 device #%d now disconnected\n", minor);
905 }
906
907 static struct usb_driver piusb_driver = {
908         .name = "sub",
909         .probe = piusb_probe,
910         .disconnect = piusb_disconnect,
911         .id_table = pi_device_table,
912 };
913
914 /**
915  *      piusb_init
916  */
917 static int __init piusb_init(void)
918 {
919         int result;
920
921         lastErr = 0;
922         errCnt = 0;
923
924         /* register this driver with the USB subsystem */
925         result = usb_register(&piusb_driver);
926         if (result)
927                 printk(KERN_ERR KBUILD_MODNAME
928                                 ": usb_register failed. Error number %d\n",
929                                 result);
930         else
931                 printk(KERN_INFO KBUILD_MODNAME ":%s: %s\n", DRIVER_DESC,
932                                 DRIVER_VERSION);
933         return result;
934 }
935
936 /**
937  *      piusb_exit
938  */
939 static void __exit piusb_exit(void)
940 {
941         /* deregister this driver with the USB subsystem */
942         usb_deregister(&piusb_driver);
943 }
944
945 module_init(piusb_init);
946 module_exit(piusb_exit);
947
948 /* Module parameters */
949 module_param(debug, int, 0);
950 MODULE_PARM_DESC(debug, "Debug enabled or not");
951
952 MODULE_AUTHOR(DRIVER_AUTHOR);
953 MODULE_DESCRIPTION(DRIVER_DESC);
954 MODULE_LICENSE("GPL v2");